1import binascii
2import logging
3import struct
4
5
6class Process(object):
7    """Base interface for process being debugged. Provides basic functions for gdbserver to interact.
8       Create a class object for your backing system to provide functionality
9
10       Here is the list of must implement functions:
11        + please update hinfo['ostype'] and hinfo['vendor'] if its not in (macosx, ios)
12        + please populate threads_ids_list with ids of threads.
13        - getThreadStopInfo
14        - getProcessInfo
15        - getRegisterDataForThread
16        - getRegisterInfo
17        - readMemory
18    """
19    def __init__(self, cputype, cpusubtype, ptrsize):
20        super().__init__()
21        self.hinfo = {
22            'cputype': cputype, 'cpusubtype': cpusubtype,
23            'triple': None, 'vendor': 'apple', 'ostype': 'macosx',
24            'endian': 'little', 'ptrsize': ptrsize, 'hostname': None, 'os_build': None,
25            'os_kernel': None, 'os_version': None, 'watchpoint_exceptions_received': None,
26            'default_packet_timeout': '10', 'distribution_id': None
27        }
28
29        ## if cputype is arm assume its ios
30        if (cputype & 0xc) != 0xc:
31            self.hinfo['ostype'] = 'ios'
32        self.ptrsize = ptrsize
33        self.threads = {}
34        self.threads_ids_list = []
35
36    def getHostInfo(self):
37        retval = ''
38        for i in list(self.hinfo.keys()):
39            if self.hinfo[i] is None:
40                continue
41            retval += '%s:%s;' % (str(i), str(self.hinfo[i]))
42        return retval
43
44    def getRegisterDataForThread(self, th_id, reg_num):
45        logging.critical("Not Implemented: getRegisterDataForThread")
46        return ''
47
48    def readMemory(self, address, size):
49        logging.critical("readMemory: Not Implemented: readMemory")
50        #E08 means read failed
51        return 'E08'
52
53    def writeMemory(self, address, data, size):
54        """ Unimplemented. address in ptr to save data to. data is native endian stream of bytes,
55        """
56        return 'E09'
57
58    def getRegisterInfo(regnum):
59        #something similar to
60        #"name:x1;bitsize:64;offset:8;encoding:uint;format:hex;gcc:1;dwarf:1;set:General Purpose Registers;"
61        logging.critical("getRegisterInfo: Not Implemented: getRegisterInfo")
62        return 'E45'
63
64    def getProcessInfo(self):
65        logging.critical("Not Implemented: qProcessInfo")
66        return ''
67
68    def getFirstThreadInfo(self):
69        """ describe all thread ids in the process.
70        """
71        thinfo_str = self.getThreadsInfo()
72        if not thinfo_str:
73            logging.warning('getFirstThreadInfo: Process has no threads')
74            return ''
75        return 'm' + thinfo_str
76
77    def getSubsequestThreadInfo(self):
78        """ return 'l' for last because all threads are listed in getFirstThreadInfo call.
79        """
80        return 'l'
81
82    def getSharedLibInfoAddress(self):
83        """ return int data of a hint where shared library is loaded.
84        """
85        logging.critical("Not Implemented: qShlibInfoAddr")
86        raise NotImplementedError('getSharedLibInfoAddress is not Implemented')
87
88    def getSignalInfo(self):
89        # return the signal info in required format.
90        return "T02" + "threads:" + self.getThreadsInfo() + ';'
91
92    def getThreadsInfo(self):
93        """ returns ',' separeted values of thread ids """
94        retval = ''
95        first = True
96        for tid in self.threads_ids_list:
97            if first is True:
98                first = False
99                retval += self.encodeThreadID(tid)
100            else:
101                retval += ',%s' % self.encodeThreadID(tid)
102        return retval
103
104    def getCurrentThreadID(self):
105        """ returns int thread id of the first stopped thread
106            if subclass supports thread switching etc then
107            make sure to re-implement this funciton
108        """
109        if self.threads_ids_list:
110            return self.threads_ids_list[0]
111        return 0
112
113    def getThreadStopInfo(self, th_id):
114        """ returns stop signal and some thread register info.
115        """
116        logging.critical("getThreadStopInfo: Not Implemented. returning basic info.")
117
118        return 'T02thread:%s' % self.encodeThreadID(th_id)
119
120    def encodeRegisterData(self, intdata, bytesize=None):
121        """ return an encoded string for unsigned int intdata
122            based on the bytesize and endianness value
123        """
124        if not bytesize:
125            bytesize = self.ptrsize
126
127        format = '<I'
128        if bytesize > 4:
129            format = '<Q'
130        packed_data = struct.pack(format, intdata)
131        return binascii.hexlify(packed_data).decode()
132
133    def encodePointerRegisterData(self, ptrdata):
134        """ encodes pointer data based on ptrsize defined for the target """
135        return self.encodeRegisterData(ptrdata, bytesize=self.ptrsize)
136
137    def encodeThreadID(self, intdata):
138        format = '>Q'
139        return binascii.hexlify(struct.pack(format, intdata)).decode()
140
141    def encodeByteString(self, bytestr):
142        return binascii.hexlify(bytestr).decode()
143