File: Poser.py

package info (click to toggle)
pose 3.5-7
  • links: PTS
  • area: contrib
  • in suites: sarge
  • size: 14,136 kB
  • ctags: 29,490
  • sloc: cpp: 93,990; ansic: 62,838; sh: 27,519; perl: 1,891; python: 1,242; makefile: 652
file content (471 lines) | stat: -rw-r--r-- 16,119 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# ======================================================================================
#	Copyright (c) 1999-2001 Palm, Inc. or its subsidiaries.
#	All rights reserved.
# ======================================================================================
#
# File:    Poser.py
# Author:  David Creemer
# Created: Thu Jul 29 17:05:33 PDT 1999

""" This module implements a connection to the PalmOS Emulator
POSER. It provides a socket for client - poser communications, and an
hierarchy of classes for formatting poser RPC and other SysPackets
calls. """

import sys
import socket
from struct import pack, unpack
from string import upper,atoi

# -----------------------------------------------------------------------------
# Utility functions

def _memdump( baseaddr, len, data ):
    """return a string that is a nicely formatted hex and ascii dump of a range of bytes"""

    base = "Addr=0x%08X " % (baseaddr)
    base = base + "Len=0x%04X (%d) " % (len, len)
    for i in range(len):
	if (i % 8) == 0:
	    base = base +  "\n  %08X " % (baseaddr + i)
	base = base + " %02X" % ( ord(data[i]) )
    return base

# -----------------------------------------------------------------------------
class ProtocolException:

    def __init__( self, msg ):
        self._message = msg

# -----------------------------------------------------------------------------

class Socket:
    """defines the interface by which an application talks with a running poser"""

    # packet header signatures
    _HeaderSignature1 = 0xBEEF
    _HeaderSignature2 = 0xED

    def __init__( self ):
	self._sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
	self._transid = 1
        self._src = 1
        self._type = 0

    # ----------------------------------------------------------------
    # public API
    # ----------------------------------------------------------------

    def connect( self, addr="localhost", port=6414 ):
	"""connect to the running poser at the given host and port"""
	self._sock.connect( addr, port )

    def close( self ):
	"""terminate communication with the connected poser"""
	self._sock.close()

    def call( self, pkt ):
	"""call the connected poser with the given sysCall packet"""
	# get the raw packet data
	pkt._marshal()
	# prepare the header
	shdr = pack( ">HBBBBHB", Socket._HeaderSignature1, Socket._HeaderSignature2,
                     pkt._dest, self._src, self._type, len( pkt._data ), self._transid );
	shdr = shdr + pack( ">B", self._calcHeaderChecksum( shdr ) )
	# send the packet pieces
	spkt = shdr + pkt._data + pack( ">H", self._calcFooterChecksum( pkt._data ) )
	self._sock.send( spkt )
	# read the header
	rhdr = self._sock.recv( 10 )
	( h1, b1, rsrc, rdest, rtype, rlen, rtid, rhcs ) = unpack( ">HBBBBHBB", rhdr )
	# read in the body
	pkt._data = self._sock.recv( rlen )
	# read in the footer
	rftr = self._sock.recv( 2 )
	(rbcs) = unpack( ">H", rftr )
	# bump the transaction id
	self._transid = self._transid + 1
	pkt._unmarshal()

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _calcHeaderChecksum( self, bytes ):
	"""calculate the checksum for the packet header"""
	cs = 0
	for c in bytes:
	    cs = cs + ord( c )
	    if ( cs > 255 ):
		cs = cs - 256
	return cs

    def _calcFooterChecksum( self, body ):
	"""calculate the checksum for the packet body"""
	# TBD
	return 0

    def __repr__( self ):
	return "<poser socket, tid=" + str( self._transid ) + ", sock=" + \
	       str( self._sock ) + ">"

#-----------------------------------------------------------------------------
# Abstract base class for all SysPackets
#-----------------------------------------------------------------------------

class SysPacket:
    """abstract base class for all poser SysPacket messages"""

    def __init__( self ):
	self._data = None
	self._command = 0x00
        self._dest = 0

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _marshal( self ):
	"""pack the packet data into a binary stream"""
	return pack( ">BB", self._command, 0 )

    def _unmarshal( self ):
	"""pull the packet data from the binary stream"""
	( self._command, dummy ) = unpack( ">BB", self._data[0:2] )
	self._data = self._data[2:]

    def __repr__( self ):
	return "cmd=0x%02X" % ( self._command )



#-----------------------------------------------------------------------------
# Memory Reading and Writing SysPackets
#-----------------------------------------------------------------------------

class SysPacketMem( SysPacket ):
    """ abstract parent class of mem read/write packet classes"""

    def __init__( self, addr, length ):
	"""instantiate generic memory sys packet"""
	SysPacket.__init__( self )
        self._dest = 1
	self._memAddr = addr
	self._memLength = length
	self._memory = None

    # ----------------------------------------------------------------
    # public API
    # ----------------------------------------------------------------

    def getMemory( self ):
	"""return the memory read"""
	return self._memory

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def __repr__( self ):
	return SysPacket.__repr__( self ) + ", " + _memdump( self._memAddr, self._memLength, self._memory )

#-----------------------------------------------------------------------------

class SysPacketReadMem( SysPacketMem ):
    """A poser sysPacket which reads PalmOS memory"""

    def __init__( self, addr, length ):
	"""instantiate read memory packet"""
	SysPacketMem.__init__( self, addr, length )
	self._command = 0x01

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _marshal( self ):
	"""marshal the RPC information & parameters into a flat byte stream"""
	self._data = SysPacket._marshal( self ) + pack( ">LH",
							 self._memAddr,
							 self._memLength )

    def _unmarshal( self ):
	"""unmarshal the RPC information & parameters from the flat byte stream"""
	SysPacket._unmarshal( self )
	self._memory = self._data[0:self._memLength]

#-----------------------------------------------------------------------------

class SysPacketWriteMem( SysPacketMem ):
    """A poser sysPacket which writes PalmOS memory"""

    def __init__( self, addr, data, length ):
	"""instantiate write memory"""
	SysPacketMem.__init__( self, addr, length )
	self._command = 0x02
	self._memory = data

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _marshal( self ):
	"""marshal the RPC information & parameters into a flat byte stream"""
	fmt = ">LH" + str(self._memLength) + "s"
	self._data = SysPacket._marshal( self ) + pack( fmt,
							 self._memAddr,
							 self._memLength,
							 self._memory )

#-----------------------------------------------------------------------------
# OS Trap RPC SysPackets
#-----------------------------------------------------------------------------

class SysPacketRPC( SysPacket ):
    """A poser sysPacket which implements a RPC call/respone PalmOS Trap call"""

    def __init__( self, trap ):
	"""instantiate new RPC call with the trap word to be called"""
	SysPacket.__init__( self )
        self._dest = 1
	self._command = 0x0A
	self._trap = trap
	self._params = {}
        self._paramnames = [] # used to preserver order
	self._a0 = 0
	self._d0 = 0

    # ----------------------------------------------------------------
    # public API
    # ----------------------------------------------------------------

    def __len__( self ):
        # return # of params + A0 and D0 registers
        return len( self._paramnames ) + 2

    def keys( self ):
        return self._paramnames + [ 'A0' , 'D0' ]
    
    def __setitem__( self, key, param ):
        if upper( key ) == 'A0':
            self._a0 = param
        elif upper( key ) == 'D0':
            self._d0 = param
        else:
            self._params[ key ] = param
            self._paramnames.insert( 0, key )
        
    def __getitem__( self, key ):
        if upper( key ) == 'A0':
            return self._a0
        elif upper( key ) == 'D0':
            return self._d0
        else:
            return self._params[ key ]._getvalue()
        
    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _marshal( self ):
	"""marshal the RPC information & parameters into a flat byte stream"""
	self._data = SysPacket._marshal( self ) + pack( ">HLLH",
							self._trap,
							self._d0,
							self._a0,
							len( self._params ) )
	for pname in self._paramnames:
	    self._data = self._data + self._params[ pname ]._data

    def _unmarshal( self ):
	"""unmarshal the RPC information & parameters from the flat byte stream"""
	SysPacket._unmarshal( self )

	( self._trap, self._d0, self._a0, pcount ) = unpack( ">HLLH", self._data[0:12] )
	self._data = self._data[12:]

        if pcount != len( self._paramnames ):
            raise ProtocolException, "Unexpected number of return parameters"
        
	for i in range( pcount ):
            pname = self._paramnames[i]
	    ( dummy, size ) = unpack( ">BB", self._data[0:2] )
	    self._params[ pname ]._data = self._data[0:size+2]
	    self._data = self._data[size+2:]
	    self._params[ pname ]._unmarshal()

    def __repr__( self ):
	base = "<sysPacketRPC, " + SysPacket.__repr__( self )
	base = base + ", trap=0x%04X, " % ( self._trap )
	base = base + "a0=0x%08X, " % (self._a0)
	base = base + "d0=0x%08X(%d), " % (self._d0, self._d0)
        base = base + "Params("
	for pname in self._paramnames:
	    base = base + " " + pname + "=" + str( self._params[ pname ] )
	return base + " ) >"

#-----------------------------------------------------------------------------

class SysPacketRPC2( SysPacketRPC ):

    def __init__( self, trap ):
	"""instantiate a new RPC2 call with the trap word to be called"""
	SysPacketRPC.__init__( self, trap )
        self._dest = 14
	self._command = 0x70
        self._registers = {} # for A0,A1...,D0,D1...
        self._exception = 0

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    # register list. order is important: don't change it
    _reglist = [ 'D7','D6','D5','D4','D3','D2','D1','D0','A7','A6','A5','A4','A3','A2','A1','A0' ]
    _reglistrev = [ 'A0','A1','A2','A3','A4','A5','A6','A7','D0','D1','D2','D3','D4','D5','D6','D7' ]
    
    def _isRegister( self, key ):
        return upper( key ) in SysPacketRPC2._reglist

    def _makeRegMask( self ):
        mask = 0
        for r in SysPacketRPC2._reglist:
            mask = mask << 1
            if self._registers.has_key( r ):
                mask = mask | 1
        return mask
    
    def __setitem__( self, key, param ):
        if self._isRegister( key ):
            self._registers[ upper( key ) ] = param
        else:
            self._params[ key ] = param
            self._paramnames.insert( 0, key )
    
    def __getitem__( self, key ):
        if upper( key ) == 'A0':
            return self._a0
        elif upper( key ) == 'D0':
            return self._d0
        elif self._isRegister( key ):
            # this may throw an exception. That's ok.
            return self._registers[ upper( key ) ]
        elif upper( key ) == 'exception':
            return self._exception
        else:
            return self._params[ key ]._getvalue()

    def _marshal( self ):
	"""marshal the RPC information & parameters into a flat byte stream"""
	self._data = SysPacket._marshal( self ) + pack( ">HLLHH",
							self._trap,
							self._d0,
							self._a0,
                                                        self._exception,
                                                        self._makeRegMask() )
        # add registers
        for r in self._registers.keys():
            self._data = self._data + pack( ">L", self._registers[ r ] )
            
        # add parameters
        self._data = self._data + pack( ">H", len( self._params ) )
	for pname in self._paramnames:
	    self._data = self._data + self._params[ pname ]._data

    def _unmarshal( self ):
	"""unmarshal the RPC information & parameters from the flat byte stream"""
        SysPacket._unmarshal( self )
        ( self._trap, self._d0, self._a0, self._exception, regmask ) = unpack( ">HLLHH",
                                                                               self._data[0:14] )
	self._data = self._data[14:]

        # extract the registers ( if any )
        for r in SysPacketRPC2._reglistrev:
            # if the mask bit is set
            if regmask & 0x0001:
                # extract register value & trim unmarshalled data
                ( self._registers[ r ], ) = unpack( ">L", self._data )
                self._data = self._data[4:]
            # go onto next bit in mask
            regmask = regmask >> 1
        
        # extract parameter count
        ( pcount, ) = unpack( ">H", self._data[0:2] )
        self._data = self._data[2:]

        # extract paramters
        if pcount != len( self._paramnames ):
            raise ProtocolException, "Unexpected number of return parameters"
        
	for i in range( pcount ):
            pname = self._paramnames[i]
	    ( dummy, size ) = unpack( ">BB", self._data[0:2] )
	    self._params[ pname ]._data = self._data[0:size+2]
	    self._data = self._data[size+2:]
	    self._params[ pname ]._unmarshal()

    def __repr__( self ):
	base = "<sysPacketRPC2, " + SysPacket.__repr__( self )
	base = base + ", trap=0x%04X, " % ( self._trap )
	base = base + "a0=0x%08X, " % (self._a0)
	base = base + "d0=0x%08X(%d), " % (self._d0, self._d0)
	base = base + "exception=0x%04X, " % (self._exception)
	base = base + "registers=" + str(self._registers)
        base = base + "Params("
	for pname in self._paramnames:
	    base = base + " " + pname + "=" + str( self._params[ pname ] )
	return base + " ) >"

#-----------------------------------------------------------------------------

class RPCParam:
    """a parameter to a poser SysPacketRPC(2) call"""

    def __init__( self, byref, type, value ):
	"""instantiate new RPC parameter of a given type and value"""
	self._type = type
	self._value = value
	if byref:
	    self._byref = 1
	else:
	    self._byref = 0
	self._data = None
	self._calcSize()
	self._marshal()

    # ----------------------------------------------------------------
    # implementation methods
    # ----------------------------------------------------------------

    def _getvalue( self ):
	"""return the value of the param as received from the wire"""
	self._unmarshal()
	return self._value

    def _calcSize( self ):
	"""calculate the size of the parameter based on its type"""
	t = upper( self._type[ -1 ] )
	if t == 'B':
	    self._size = 1
	elif t == 'H':
	    self._size = 2
	elif t == 'L':
	    self._size = 4	
	elif t == 'S':
	    # string with specified size ('32s')
	    self._size = atoi( self._type[:-1] )

    def _marshal( self ):
	"""flatten the RPC param into a binary stream"""
	self._data = pack( ">BB" + self._type,
			   self._byref, self._size, self._value )

    def _unmarshal( self ):
	"""pull the RPC param data from the binary stream"""
	( self._byref, self._size ) = unpack( ">BB", self._data[0:2] )
	( self._value, ) = unpack( ">" + self._type, self._data[2:] )

    def __repr__( self ):
	return "<sysPacketRPC param, byref=" + str( self._byref ) + ", type=" + \
	       str( self._type ) + ", size=" + str( self._size ) + ", value=" + \
	       str( self._value ) + ">"