Package Libs :: Module immutils
[hide private]
[frames] | no frames]

Source Code for Module Libs.immutils

  1  #!/usr/bin/env python 
  2   
  3  """ 
  4  (c) Immunity, Inc. 2004-2007 
  5   
  6   
  7  U{Immunity Inc.<http://www.immunityinc.com>} 
  8   
  9   
 10  MOSDEF utils for non-CANVAS users 
 11   
 12  """ 
 13   
 14   
 15  __VERSION__ = '1.0' 
 16   
 17  # TODO check: 
 18  # ----------- 
 19  # cparse: dInt 
 20  # spark: prettyprint 
 21  # x86opcodes: issignedbyte, intel_byte, intel_2byte 
 22  # pelib: hexdump 
 23  # mosdef: isprint, strisprint 
 24  # makeexe: binstring? 
 25   
 26  import sys, os 
 27  sys.path.append('.') 
 28   
 29  #try: 
 30  #    from internal import * 
 31  #except: 
32 -def __ignore(*args, **kargs):
33 return False
34 -def __retsamearg(arg):
35 return arg
36 devlog = __ignore 37 isdebug = __ignore 38 warnings_safely_ignore = __ignore 39 warning_restore = __ignore 40 deprecate = __ignore 41 uniqlist = __retsamearg 42 43 44 # -------------------- 45 # 46 # __MOSDEFimport__ 47 # 48 # -------------------- 49 # 50 # global options: (set it to False to desactivate) 51 _MOSDEFimport_hook = True # desactivate the current hook 52 _MOSDEFimport_cachefailedimport = True # cache can be dangerous (breaks reload()?) 53 # 54 # normally you DONT want to hack in the <MOSDEFimport> tag. 55 # NOTE: can we optimize speed here? 56 # 57 # <MOSDEFimport> begin 58 from traceback import format_exc
59 -def __MOSDEFimport__(*args):
60 global _failed_imported_module_table 61 def mod_hash(modname): 62 return hash(str(hash(str(sys.path))) + modname)
63 modname = args[0] 64 if __debug__: 65 if len(args) < 4 or args[3] == None: 66 devlog('MOSDEFimport', "IMPORT %s" % modname) 67 else: 68 if len(args[3]) == 1: 69 val = args[3][0] 70 else: 71 val = str(args[3])[1:-1] 72 devlog('MOSDEFimport', "FROM %s IMPORT %s" % (modname, val), nofile = True) 73 if _MOSDEFimport_cachefailedimport: 74 modhash = mod_hash(modname) 75 if modhash in _failed_imported_module_table: 76 devlog('MOSDEFimport', "already failed to import <%s>" % modname, nofile = True) 77 raise ImportError 78 cwd = os.getcwd() 79 filepath = os.path.dirname(globals()['__file__']) 80 mosdefpath = filepath.replace(cwd, ".") 81 #print "[!] mosdef cwd: %s"%cwd 82 #print "[!] filepath: %s"%filepath 83 #print "[!] mosdefpath: %s"%mosdefpath 84 sys.path = uniqlist(sys.path) 85 if cwd != mosdefpath and mosdefpath not in sys.path: 86 sys.path.insert(0, mosdefpath) 87 import_time = time.time() 88 try: 89 return sys.modules['__builtin__'].__import__orig(*args) 90 except: 91 if _MOSDEFimport_cachefailedimport: 92 _failed_imported_module_table += [modhash] 93 devlog('all', "failed to import <%s> (lost %ss)" % (modname, time.time() - import_time), nofile = True) 94 devlog('ImportError', format_exc(0).split('\n')[1], nodesc = True) 95 if isdebug('ImportErrorTrace'): 96 backtrace() 97 raise 98 import __builtin__ 99 if _MOSDEFimport_hook and not hasattr(__builtin__, '__import__orig'): 100 import time 101 __builtin__.__import__orig = __builtin__.__import__ 102 __builtin__.__import__ = __MOSDEFimport__ 103 _MOSDEFimport_hook = False 104 _failed_imported_module_table = [] 105 devlog('all', "__import__ hooked with __MOSDEFimport__") 106 del __builtin__ 107 # </MOSDEFimport> end 108 109 110 ##################################################### 111 # 112 # 113 # dictionary class that hold floats as integers 114 # 115 # 116 ##################################################### 117 118 import types 119
120 -class antifloatdict(types.DictType):
121
122 - def __init__(self, arg = {}):
123 if type(arg) == types.DictType: 124 d = {} 125 for item in arg.items(): 126 d.__setitem__(item[0], item[1]) 127 arg = d 128 return types.DictType.__init__(self, arg)
129
130 - def __setitem__(self, itemname, itemvalue):
131 if type(itemvalue) == types.FloatType: 132 itemvalue = int(itemvalue) 133 return types.DictType.__setitem__(self, itemname, itemvalue)
134
135 - def __getitem__(self, itemname):
136 item = types.DictType.__getitem__(self, itemname) 137 if type(item) == types.FloatType: 138 item = int(item) 139 return item
140
141 - def copy(self):
142 return antifloatdict(self)
143
144 -def hasbadchar(word,badchars):
145 try: 146 wordstr=intel_order(word) 147 except: 148 wordstr=str(word) 149 for ch in badchars: 150 if wordstr.count(ch): 151 return 1 152 return 0
153 154 155 156 ##################################################### 157 # 158 # 159 # little/big endian management functions 160 # 161 # 162 ##################################################### 163
164 -def check_bits_consistancy(bits):
165 assert not bits % 8, "bits should be sizeof(char) aligned, got %d" % bits
166
167 -def check_string_len(s, l, assertmsg=""):
168 if assertmsg != "": 169 assertmsg += "\n" 170 assert len(s) >= l, "%sexpecting a at_least_%d_chars string, got %d_chars instead.\nstring is: %s" % \ 171 (assertmsg, l, len(s), prettyprint(s))
172
173 -def split_int_bits(bits, i):
174 check_bits_consistancy(bits) 175 # we cast to uint_bits here to be sure to return (bits/8) x uint8 176 u = uint_bits(bits, i) 177 r = [] 178 for b in range(0, bits, 8): 179 r += [ (u >> (bits - (b + 8))) & 0xff ] 180 return r
181 182 # 0x12345678 -> [0x12, 0x34, 0x56, 0x78]
183 -def split_int32(int32):
184 return split_int_bits(32, int32)
185
186 -def int2list_bits(bits, i, swap=0):
187 check_bits_consistancy(bits) 188 l = split_int_bits(bits, i) 189 #devlog("int2list: l = %s" % l) 190 lc = [] 191 for n in l: 192 #devlog("int2list: n = 0x%x" % n) 193 lc += [chr(n)] 194 if swap: 195 lc.reverse() 196 return lc
197
198 -def int2list32(int32, swap=0):
199 return int2list_bits(32, int32, swap=swap)
200 201 #def int2list(int32): 202 # deprecate("use int2list32 instead") 203 # return int2list32(int32) 204
205 -def int2str_bits(bits, i, swap=0):
206 check_bits_consistancy(bits) 207 return "".join(int2list_bits(bits, i, swap=swap))
208
209 -def int2str32(int32, swap=0):
210 return int2str_bits(32, int32, swap=swap)
211
212 -def int2str16(int16, swap=0):
213 return int2str_bits(16, int16, swap=swap)
214
215 -def int2str32_swapped(int32):
216 return int2str_bits(32, int32, swap=1)
217
218 -def int2str16_swapped(int16):
219 return int2str_bits(16, int16, swap=1)
220 221 #def int2str(int32): 222 # deprecate("use int2str32 instead") 223 # return int2str32(int32) 224
225 -def str2int_bits(bits, s):
226 check_bits_consistancy(bits) 227 assert type(s) == type(""), "str2int_bits() expects a string argument, got %s" % type(s) 228 nchars = bits / 8 229 check_string_len(s, nchars, "str2int_bits(%d, s): string=<%s> len=%d" % (bits, s, len(s))) 230 r = 0 231 warnings_safely_ignore(FutureWarning) 232 for i in range(0, nchars): 233 #print "%d = %x << %d" % (ord(s[i]) << 8*i, ord(s[i]), 8*i) 234 r += ord(s[nchars-i-1]) << 8*i 235 warning_restore() 236 return r
237
238 -def str2int_bits_swapped(bits, s):
239 check_string_len(s, bits/8) 240 return byteswap_bits(bits, str2int_bits(bits, s))
241
242 -def str2int16(s):
243 return str2int_bits(16, s)
244
245 -def str2int32(s):
246 return str2int_bits(32, s)
247
248 -def str2int64(s):
249 return str2int_bits(64, s)
250
251 -def str2int16_swapped(s):
252 return str2int_bits_swapped(16, s)
253
254 -def str2int32_swapped(s):
255 return str2int_bits_swapped(32, s)
256
257 -def str2int64_swapped(s):
258 return str2int_bits_swapped(64, s)
259 260 # "\x12\x34\x56\x78" -> 0x12345678 261 #def str2int32_old(s): 262 # #return str2int_bits(32, s) 263 # assert type(s) == type(""), "str2int32() expects a string argument, got %s" % type(s) 264 # if len(s) < 4: 265 # devlog("str2int32: string=<%s> len=%d" % (s, len(s))) 266 # raise AssertionError, "str2int32 called with a less_than_4_chars string (%d chars)" % len(s) 267 # (a,b,c,d)=(ord(s[0]),ord(s[1]),ord(s[2]),ord(s[3])) 268 # return sint32((a << 24) + (b << 16) + (c << 8) + d) 269 270 #returns the integer that the 4 byte string represents 271 #Note: If you are getting OverflowError in this function, you need to upgrade to Python 272 #2.2. !! 273
274 -def str2bigendian(astring):
275 """ 276 oppposite of istr2int 277 """ 278 return str2int32(astring)
279 280 # >>> print "0x%x" % str2littleendian("\x12\x34\x56\x78") 281 # 0x78563412
282 -def str2littleendian(astring):
283 return byteswap_32(str2int32(astring))
284
285 -def byteswap_bits(bits, i):
286 check_bits_consistancy(bits) 287 r = 0 288 warnings_safely_ignore(FutureWarning) 289 for b in range(0, bits, 8): 290 r += (((i >> b) & 0xff) << (bits - (b + 8))) 291 warning_restore() 292 return r
293
294 -def byteswap_64(int64):
295 return byteswap_bits(64, int64)
296
297 -def byteswap_32(int32):
298 return byteswap_bits(32, int32)
299
300 -def byteswap_16(int16):
301 return byteswap_bits(16, int16)
302 303 """ 304 istr2halfword(halfword2bstr(dInt(x))) == byteswap_16(x) 305 """ 306 307 ##################################################### 308 # 309 # 310 # print crap nicely 311 # 312 # 313 ##################################################### 314 315 #wee little function for printing strings nicely
316 -def hexprint(s):
317 if not type(s) == type(""): 318 return "can not hexdump %s" % type(s) 319 tmp="" 320 for c in s: 321 tmp+="[0x%2.2x]"%ord(c) 322 return tmp
323 324 goodchars=".()~!#$%^&*()-=_/\\:<>" 325 #let's not mess up our tty
326 -def prettyprint(instring):
327 import string 328 if not type(instring) == type(""): 329 devlog("prettyprint got %s and not string" % type(instring)) 330 instring = str(instring) 331 #return "can not prettyprint %s" % type(instring) 332 tmp="" 333 for ch in instring: 334 #if (ch.isalnum() or ch in goodchars) and ord(ch)<127: 335 if ch in string.printable and ch not in ["\x0c"]: 336 tmp+=ch 337 else: 338 value="%2.2x" % ord(ch) 339 tmp+="["+value+"]" 340 341 return tmp
342
343 -def c_array(data, desc = None):
344 if not type(data) == type(""): 345 devlog("c_array() got %s and not string" % type(data)) 346 return "c_array() can not dump %s" % type(data) 347 if not len(data): 348 return "c_array() got void buffer" 349 350 ucharbuf = "unsigned char buf[] = \"" 351 for uchar in data: 352 ucharbuf += "\\x%02x" % ord(uchar) 353 ucharbuf += "\"; // %d byte" % len(data) 354 if len(data) > 1: 355 ucharbuf += "s" 356 if desc: 357 ucharbuf += ", %s" % desc 358 359 return ucharbuf
360
361 -def shellcode_dump(sc, align=0, alignpad=" ", alignmax=16, mode=None):
362 import types 363 assert type(align) == type(0), "error in arguments, expecting an int for 'align'" 364 if not type(sc) in [types.StringType, types.BufferType]: 365 devlog("shellcode_dump() got %s and not string" % type(sc)) 366 return type(sc) 367 if not len(sc): 368 return "void buffer" 369 if mode and mode.upper() == "RISC": 370 align=4 371 alignmax=4 372 if align: 373 alignmax *= align 374 buf = "" 375 i = 0 376 for c in sc: 377 buf += "%02x " % ord(c) 378 if align and (i % align) == (align - 1): 379 buf += alignpad 380 if alignmax and (i % alignmax) == (alignmax - 1): 381 buf += "\n" 382 i += 1 383 if buf[-1] == "\n": 384 buf = buf[:-1] 385 return buf
386
387 -def dummywrite(fd, data):
388 """ 389 we just want to write some data on any fd, opened or closed. 390 """ 391 import os 392 try: 393 os.write(fd, data) 394 except OSError, errargs: 395 import errno 396 if errargs.errno != errno.EBADF: 397 raise
398
399 -def warnmsg(msg):
400 sys.stderr.write("WARNING: %s\n" % msg)
401 402 ##################################################### 403 # 404 # 405 # return a binary representation of an integer 406 # 407 # 408 ##################################################### 409
410 -def binary_string_bits(bits, i):
411 binstr = "" 412 for bit in range(0, bits): 413 if i & (long(1) << bit): 414 binstr = "1" + binstr 415 else: 416 binstr = "0" + binstr 417 return binstr
418
419 -def binary_string_int8(int8):
420 return binary_string_bits(8, int8)
421
422 -def binary_string_int16(int16):
423 return binary_string_bits(16, int16)
424
425 -def binary_string_int32(int32):
426 return binary_string_bits(32, int32)
427
428 -def binary_string_int64(int64):
429 return binary_string_bits(64, int64)
430
431 -def binary_string_char(c):
432 return binary_string_int8(c)
433
434 -def binary_string_short(s):
435 return binary_string_int16(s)
436
437 -def binary_string_int(i):
438 return binary_string_int32(i)
439 440 ##################################################### 441 # 442 # 443 # how to handle python fucking integers 444 # 445 # 446 ##################################################### 447
448 -def dInt(sint):
449 """ 450 Turns sint into an int, hopefully 451 python's int() doesn't handle negatives with base 0 well 452 """ 453 if sint==None or type(sint) in [type( (1,1) ), type( [1]), type( {} ) ]: 454 devlog("Type ERROR: dInt(%s)!"%str(sint)) 455 #should we call bugcheck here? 456 raise TypeError, "type %s for dInt(%s)" % (type(sint), str(sint)) 457 458 s=str(sint) 459 if s[0:2]=="0x": 460 return long(s,0) 461 else: 462 #if you have long("5.0") it throws a horrible exception 463 #so we convert to float and then back to long to avoid this 464 return long(float(s))
465
466 -def binary_from_string(astr,bits=None):
467 """ returns [1,0,0,0,0,0,0,0] from "\x80" 468 """ 469 if not bits: 470 #print "Setting bits to 8*length" 471 bits=len(astr)*8 472 ret=[] 473 474 for c in astr: 475 #for each character 476 mask=0x80 477 for i in range(0,8): 478 #for each bit in the character 479 if mask & ord(c): 480 bit=1 481 else: 482 bit=0 483 ret+=[bit] 484 if len(ret)==bits: 485 break 486 mask=mask >> 1 487 return ret
488
489 -def b(mystr):
490 mydict={"1":1,"0":0} 491 tmp=0 492 for c in mystr: 493 value=mydict[c] 494 tmp=(tmp<<1)+value 495 return tmp
496 497 # Note: this is a 5m lame function
498 -def hexdump(buf):
499 tbl=[] 500 tmp="" 501 hex="" 502 i=0 503 for a in buf: 504 hex+="%02X "% ord(a) 505 i+=1 506 if ord(a) >=0x20 and ord(a) <0x7f: 507 tmp+=a 508 else: 509 tmp+="." 510 if i%16 == 0: 511 tbl.append((hex, tmp)) 512 hex="" 513 tmp="" 514 tbl.append((hex, tmp)) 515 return tbl
516
517 -def prettyhexprint(s,length=8):
518 """ 519 A nicely displayed hexdump as a string 520 """ 521 # we are expecting a string here 522 if not type(s) == type(""): 523 return "can not hexdump %s" % type(s) 524 tmp=[] 525 i=1 526 for c in s: 527 tmp+=["%2.2x "%ord(c)] 528 if i%length==0: 529 tmp+=["\n"] 530 i+=1 531 return "".join(tmp)
532 533 # generic functions for integers 534
535 -def sint_is_signed(bits, c):
536 return uint_bits(bits, c) >> (bits - 1)
537
538 -def uint_bits(bits, c):
539 # WARNING i dunno if dInt is safe here 540 c=dInt(c) 541 # [Python < 2.4] FutureWarning: x<<y losing bits or changing sign will return a long in Python 2.4 and up 542 # [Python < 2.4] 1 << 32 = 0 543 # so we force python < 2.4 to use a long. 544 return c & ((long(1) << bits) - 1)
545
546 -def sint_bits(bits, c):
547 u = uint_bits(bits, c) 548 if sint_is_signed(bits, c): 549 return u - (long(1) << bits) 550 else: 551 return u
552
553 -def fmt_bits(bits):
554 n = 1 << 3 555 while True: 556 if bits <= n: 557 break 558 n <<= 1 559 n /= 4 560 return "0x%%0%dx" % n
561 562 # what do we expect if arg is None? (to track upper level bug/failure)
563 -def uintfmt_bits(bits, c):
564 # XXX assert c is not type number? 565 #if c is None: 566 # return "None" 567 return fmt_bits(bits) % uint_bits(bits, c)
568
569 -def sintfmt_bits(bits, c):
570 # XXX assert c is not type number? 571 #if c is None: 572 # return "None" 573 sign = "" 574 if sint_is_signed(bits, c): 575 sign = '-' 576 c = abs(c) 577 return sign + uintfmt_bits(bits, c)
578
579 -def bits(myint, maxbits=32):
580 """counts the number of bits in an integer the slow way""" 581 b = 0 582 myint = uint_bits(maxbits, myint) 583 while myint >> b: 584 b += 1 585 return b
586 587 # a.k.a. MACROS for integers 588
589 -def uint8(c):
590 return uint_bits(8, c)
591
592 -def uint16(c):
593 return uint_bits(16, c)
594
595 -def uint32(c):
596 return uint_bits(32, c)
597
598 -def uint64(c):
599 return uint_bits(64, c)
600
601 -def sint16(c):
602 return sint_bits(16, c)
603
604 -def sint32(c):
605 return sint_bits(32, c)
606
607 -def sint64(c):
608 return sint_bits(64, c)
609
610 -def uint8fmt(c):
611 return uintfmt_bits(8, c)
612
613 -def uint16fmt(c):
614 return uintfmt_bits(16, c)
615
616 -def uint32fmt(c):
617 return uintfmt_bits(32, c)
618
619 -def uint64fmt(c):
620 return uintfmt_bits(64, c)
621
622 -def sint16fmt(c):
623 return sintfmt_bits(16, c)
624
625 -def sint32fmt(c):
626 return sintfmt_bits(32, c)
627
628 -def sint64fmt(c):
629 return sintfmt_bits(64, c)
630
631 -def IsInt(str):
632 """ 633 Checks for integer, hex or no 634 """ 635 try: 636 num = int(str,0) 637 return 1 638 except ValueError: 639 return 0
640 641 ##################################################### 642 # 643 # 644 # old functions [ now deprecated ] 645 # 646 # 647 ##################################################### 648 649 # <transition> 650
651 -def signedshort(i):
652 deprecate("use sint16() instead") 653 return sint16(i)
654
655 -def big2int(big):
656 deprecate("use sint32() instead") 657 return sint32(big)
658
659 -def int2uns(small):
660 assert sys.version_info[0] >= 2 and (sys.version_info[0] == 2 and sys.version_info[1] >= 4), \ 661 "\nyou tried to call int2uns() but your python %d.%d is too old to handle it correctly\n" \ 662 "Python versions before 2.4 are fucked up with integers, rely on 2.4 only!" % \ 663 (sys.version_info[0], sys.version_info[1]) 664 deprecate("use uint32() instead") 665 return uint32(small)
666
667 -def istr2halfword(astring):
668 #deprecate("use str2int16_swapped() instead") 669 return str2int16_swapped(astring)
670
671 -def nstr2halfword(astring):
672 #deprecate("use str2int16() instead") 673 return str2int16(astring)
674 675 #def intel_str2int_old(astring): 676 # if len(astring) < 4: 677 # devlog("intel_str2int: astring=<%s> len=%d" % (astring, len(astring))) 678 # raise AssertionError, "intel_str2int called with a less_than_4_chars string" 679 # 680 # (a,b,c,d)=(ord(astring[0]),ord(astring[1]),ord(astring[2]),ord(astring[3])) 681 # #print "%x:%x:%x:%x"%(a,b,c,d) 682 # result=a 683 # result=result+b*256 684 # result=result+c*65536 685 # result=result+d*16777216 686 # #change 2 int type, if long 687 # result=uint32(result) 688 # return result 689 #
690 -def intel_str2int(astring):
691 deprecate("use str2littleendian instead") 692 return str2littleendian(astring)
693 694 #just a nice short wrapper
695 -def istr2int(astring):
696 #devlog("istr2int(%s)" % astring) 697 return str2littleendian(astring)
698 699 #def halfword2istr(halfword): 700 # data="" 701 # a=halfword & 0xff 702 # b=halfword/256 & 0xff 703 # data+=chr(a)+chr(b) 704 # return data 705 # 706 #def halfword2bstr(halfword): 707 # data="" 708 # a=halfword & 0xff 709 # b=halfword/256 & 0xff 710 # data+=chr(b)+chr(a) 711 # return data 712 # 713 #def short2bigstr(short): 714 # """ 715 # changes an int to a two byte big endian string 716 # """ 717 # data="" 718 # #short=uint16(short) 719 # #print "short=%x /256=%x"%(short,short/256) 720 # data+=chr(short / 256) 721 # data+=chr(short & 0xff) 722 # return data 723 724 """ 725 >>> print hexprint(halfword2bstr(0x1234)) 726 [0x12][0x34] 727 >>> print hexprint(short2bigstr(0x1234)) 728 [0x12][0x34] 729 >>> print hexprint("".join(int2list(uint16(0x1234))[2:4])) 730 [0x12][0x34] 731 732 >>> print hexprint(halfword2istr(0x1234)) 733 [0x34][0x12] 734 >>> print hexprint("".join(int2list(byteswap_16(uint16(0x1234)))[2:4])) 735 [0x34][0x12] 736 737 >>> print uint16fmt(istr2halfword(halfword2bstr(dInt(0x1234)))) 738 0x3412 739 >>> print uint16fmt(byteswap_16(0x1234)) 740 0x3412 741 742 >>> print hexprint(halfword2bstr(0x1234)) 743 [0x12][0x34] 744 >>> print hexprint(int2str_bits(16, 0x1234)) 745 [0x12][0x34] 746 >>> print hexprint(halfword2bstr(0x12345678)) 747 [0x56][0x78] 748 >>> print hexprint(int2str_bits(16, 0x12345678)) 749 [0x56][0x78] 750 >>> print hexprint(int2str16(0x1234)) 751 [0x12][0x34] 752 >>> print hexprint(int2str16(0x1234, swap=1)) 753 [0x34][0x12] 754 >>> print hexprint(int2str16_swapped(0x1234)) 755 [0x34][0x12] 756 """ 757
758 -def halfword2istr(halfword):
759 #deprecate("use int2str16_swapped instead") 760 return int2str16_swapped(halfword)
761
762 -def halfword2bstr(halfword):
763 #deprecate("use int2str16 instead") 764 return int2str16(halfword)
765
766 -def short2bigstr(short):
767 return halfword2bstr(short)
768
769 -def intel_short(halfword):
770 return halfword2istr(halfword)
771
772 -def big_short(short):
773 return short2bigstr(short)
774 775 #def big_order_old(myint): 776 # """ 777 # Opposite of str2bigendian 778 # """ 779 # str="" 780 # a=chr(myint % 256) 781 # myint=myint >> 8 782 # b=chr(myint % 256) 783 # myint=myint >> 8 784 # c=chr(myint % 256) 785 # myint=myint >> 8 786 # d=chr(myint % 256) 787 # 788 # str+="%c%c%c%c" % (d,c,b,a) 789 # return str 790 791 ##int to intelordered string conversion 792 #def intel_order_old(myint): 793 # #struct.pack is non-intuitive for non-python programers, which is why I do this sort of thing. 794 # #it's for people who wish they were using perl, imo. <LH@$! :> 795 # str="" 796 # a=chr(myint % 256) 797 # myint=myint >> 8 798 # b=chr(myint % 256) 799 # myint=myint >> 8 800 # c=chr(myint % 256) 801 # myint=myint >> 8 802 # d=chr(myint % 256) 803 # 804 # str+="%c%c%c%c" % (a,b,c,d) 805 # 806 # return str 807
808 -def big_order(int32):
809 """ 810 Opposite of str2bigendian 811 """ 812 #deprecated("use int2str32() instead") 813 return int2str32(int32)
814
815 -def intel_order(int32):
816 """ 817 bijection of str2littleendian() 818 """ 819 #deprecated("use int2str32_swapped() instead") 820 return int2str32_swapped(int32)
821 822 #def binary_string_long(l): 823 # return binary_string_int64(l) 824 825 #def print_binary_old(myint): 826 # tmp="" 827 # for i in range(0,32): 828 # if (long(1)<<i) & myint: 829 # tmp="1"+tmp 830 # else: 831 # tmp="0"+tmp 832 # return tmp 833 837
838 -def decimal2binary(num):
839 if num == 0: 840 return '0'*32 841 if num < 0 : 842 return '' 843 ret='' 844 # while num > 0: 845 for a in range(0,32): 846 ret = str(num&0x1) + ret 847 num = num >> 1 848 849 return ret
850 851 # </transition> 852 853 ##################################################### 854 # 855 # 856 # test ... 857 # 858 # 859 ##################################################### 860 861 if __name__=="__main__": 862 863 warnings_safely_ignore(FutureWarning) 864
865 - def test(funcname):
866 print "testing %s() ..." % funcname
867 868 print "running tests..." 869 870 test("split_int32") 871 assert split_int32(0x12345678) == [0x12, 0x34, 0x56, 0x78] 872 873 test("str2int16") 874 assert str2int16('\x12\x34\x56') == 0x1234 875 assert nstr2halfword('\x12\x34\x56\x78') == 0x1234 #DEPRECATED 876 877 test("str2int16_swapped") 878 assert str2int16_swapped('\x12\x34') == 0x3412 879 assert istr2halfword('\x12\x34') == 0x3412 #DEPRECATED 880 assert str2int16_swapped('\x12\x34\x56\x78') == 0x3412 881 882 test("str2littleendian") 883 assert str2littleendian('\x12\x34\x56\x78') == 0x78563412 884 assert intel_str2int('\x12\x34\x56\x78') == 0x78563412 #DEPRECATED 885 assert istr2int('\x12\x34\x56\x78') == 0x78563412 #DEPRECATED 886 887 test("str2bigendian/str2int32") 888 assert str2int32('\x12\x34\x56\x78') == 0x12345678 889 assert str2bigendian('\x12\x34\x56\x78') == 0x12345678 890 891 test("int2str16") 892 assert int2str16(0x1234) == '\x12\x34' 893 assert halfword2bstr(0x1234) == '\x12\x34' #DEPRECATED 894 assert short2bigstr(0x1234) == '\x12\x34' #DEPRECATED 895 assert big_short(0x1234) == '\x12\x34' #DEPRECATED 896 897 test("int2str16_swapped") 898 assert int2str16_swapped(0x1234) == '\x34\x12' 899 assert halfword2istr(0x1234) == '\x34\x12' #DEPRECATED 900 assert intel_short(0x1234) == '\x34\x12' #DEPRECATED 901 assert intel_short(0x12345678) == '\x78\x56' #DEPRECATED 902 903 test("int2str32") 904 assert int2str32(0x12345678) == '\x12\x34\x56\x78' 905 assert big_order(0x12345678) == '\x12\x34\x56\x78' #DEPRECATED 906 907 test("int2str32_swapped") 908 assert int2str32_swapped(0x12345678) == '\x78\x56\x34\x12' 909 assert intel_order(0x12345678) == '\x78\x56\x34\x12' #DEPRECATED 910 911 test("binary_string_int") 912 assert print_binary(0x12345678) == '00010010001101000101011001111000' 913 914 test("binary_string_int") 915 assert binary_string_short(0x12345678) == '0101011001111000' 916 917 try: 918 assert int2uns(-1) == 0xffffffffL #DEPRECATED 919 except AssertionError: 920 print "[!] failed: int2uns(-1) == 0xffffffff" 921 assert sys.version_info[0] >= 2, "word, what an old Python you have :/" 922 if sys.version_info[0] == 2 and sys.version_info[1] < 4: 923 print "Python 2.3 integers are fucked up, rely on 2.4 only!" 924 print "your version can not handle int2uns() correctly" 925 pass 926 else: 927 raise 928 929 test("uint16") 930 assert uint16(0xffff) == 0xffff 931 assert uint16(0x12345678) == 0x5678 932 933 test("sint16") 934 assert sint16(0xffff) == -1 935 assert sint16(0xffff) == sint16(-1) 936 assert signedshort(0xffff) == -1 #DEPRECATED 937 938 test("sint32") 939 assert sint32(-1) == -1 940 assert big2int(0x123456789) == 0x23456789 #DEPRECATED 941 942 test("uintfmt_bits") 943 assert uintfmt_bits(32, 0x12345678) == '0x12345678' 944 assert uintfmt_bits(32, 0x1234) == '0x00001234' 945 assert uintfmt_bits(24, 0x1234) == '0x00001234' 946 assert uintfmt_bits(16, 0x1234) == '0x1234' 947 948 test("uint16fmt") 949 assert uint16fmt(0x123456) == '0x3456' 950 assert uint16fmt(-0x123456) == '0xcbaa' 951 952 test("uint32fmt") 953 assert uint32fmt(0x1234) == '0x00001234' 954 955 test("uint64fmt") 956 assert uint64fmt(0x12345678) == '0x0000000012345678' 957 assert uint64fmt(-1) == '0xffffffffffffffff' 958 959 test("sint16fmt") 960 assert sint16fmt(0x1234) == '0x1234' 961 assert sint16fmt(-0x1234) == '-0x1234' 962 assert sint16fmt(-0x12345678) == '-0x5678' 963 # TODO check that 964 #assert sint16fmt(0xffff) == '-0x0001' 965 966 test("sint32fmt") 967 assert sint32fmt(0x1234) == '0x00001234' 968 assert sint32fmt(-0x1234) == '-0x00001234' 969 970 test("sint64fmt") 971 assert sint64fmt(-1) == '-0x0000000000000001' 972 973 test("byteswap_32") 974 assert byteswap_32(0x12345678) == 0x78563412 975 976 test("byteswap_64") 977 assert byteswap_64(0x1234567890123456) == 0x5634129078563412 978 979 #print "0f=%s"%uint8fmt(0xf) 980 assert uint8fmt(0x0f) == '0x0f' 981 982 print "done." 983