Generates random Python functions using Markov chains
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

210 行
6.6 KiB

  1. from code import interact
  2. import imp
  3. import opcode
  4. import os
  5. import random
  6. import re
  7. import sys
  8. import types
  9. OPMAP = opcode.opmap
  10. OP_HASCALL = [OPMAP[n] for n in ("CALL_FUNCTION", "CALL_FUNCTION_VAR",
  11. "CALL_FUNCTION_KW", "CALL_FUNCTION_VAR_KW")]
  12. OP_HASMAKE = [OPMAP[n] for n in ("MAKE_FUNCTION", "MAKE_CLOSURE")]
  13. MARKOV_START = -1
  14. MARKOV_END = -2
  15. def make_chain(funcs):
  16. chain = {}
  17. for func in funcs:
  18. _parse_func(func, chain)
  19. return chain
  20. def make_function(chain, name, argcount=1):
  21. codes, constants, names, varnames = _make_codes(chain)
  22. codestring = "".join([chr(code) for code in codes])
  23. lnotab = ""
  24. code = types.CodeType(argcount, len(varnames), 1024, 0, codestring,
  25. constants, names, varnames, "<smash>", name, 1,
  26. lnotab)
  27. func = types.FunctionType(code, globals(), name)
  28. return func
  29. def print_chain(chain):
  30. print "{"
  31. for code in sorted(chain.keys()):
  32. name = _opcode_to_opname(code)
  33. target_counts = {}
  34. for tcode in chain[code]:
  35. target = _opcode_to_opname(tcode[0])
  36. if tcode[0] >= opcode.HAVE_ARGUMENT:
  37. target = "{0}({1!r})".format(target, tcode[1])
  38. try:
  39. target_counts[target] += 1
  40. except KeyError:
  41. target_counts[target] = 1
  42. targets = []
  43. for target, count in target_counts.iteritems():
  44. if count == 1:
  45. targets.append(target)
  46. else:
  47. targets.append("{0}x {1}".format(count, target))
  48. targets.sort()
  49. print name.rjust(20), "=> [{0}]".format(", ".join(targets))
  50. print "}"
  51. def print_function(func):
  52. codeobj = func.__code__
  53. codestring = codeobj.co_code
  54. length = len(codestring)
  55. i = 0
  56. while i < length:
  57. code = ord(codestring[i])
  58. i += 1
  59. print opcode.opname[code].rjust(20),
  60. if code >= opcode.HAVE_ARGUMENT:
  61. arg = _get_argument(codeobj, codestring, i, code)
  62. i += 2
  63. if code in opcode.hascompare:
  64. print " ({0})".format(arg)
  65. elif code in opcode.hasjabs:
  66. print " (to {0})".format(arg)
  67. elif code in opcode.hasjrel:
  68. print " (+{0})".format(arg)
  69. elif code in OP_HASCALL:
  70. print " ({0} args, {1} kwargs)".format(*arg)
  71. elif code in OP_HASMAKE:
  72. print " ({0} defaults)".format(arg)
  73. else:
  74. print " ({0!r})".format(arg)
  75. else:
  76. print
  77. def run():
  78. try:
  79. path, name = os.path.split(sys.argv[1])
  80. name = re.sub("\.pyc?$", "", name)
  81. except IndexError:
  82. raise RuntimeError("Needs a filename as a command-line argument")
  83. file_obj, path, desc = imp.find_module(name, [path])
  84. try:
  85. module = imp.load_module(name, file_obj, path, desc)
  86. finally:
  87. file_obj.close()
  88. _demo(module.corpus)
  89. def _parse_func(func, chain):
  90. codeobj = func.__code__
  91. codestring = codeobj.co_code
  92. length = len(codestring)
  93. i = 0
  94. prevcode = MARKOV_START
  95. while i < length:
  96. code = ord(codestring[i])
  97. i += 1
  98. if code >= opcode.HAVE_ARGUMENT:
  99. arg = _get_argument(codeobj, codestring, i, code)
  100. i += 2
  101. else:
  102. arg = None
  103. _chain_append(chain, prevcode, (code, arg))
  104. prevcode = code
  105. _chain_append(chain, code, (MARKOV_END, None))
  106. def _get_argument(codeobj, codestring, i, code):
  107. arg = ord(codestring[i]) + ord(codestring[i + 1]) * 256
  108. if code in opcode.hasconst:
  109. return codeobj.co_consts[arg]
  110. elif code in opcode.hasname:
  111. return codeobj.co_names[arg]
  112. elif code in opcode.haslocal:
  113. return codeobj.co_varnames[arg]
  114. elif code in opcode.hascompare:
  115. return opcode.cmp_op[arg]
  116. elif code in opcode.hasjabs:
  117. return arg
  118. elif code in opcode.hasjrel:
  119. return arg - i - 2
  120. elif code in OP_HASCALL:
  121. return (ord(codestring[i]), ord(codestring[i + 1]))
  122. elif code in OP_HASMAKE:
  123. return arg
  124. raise NotImplementedError(code, opcode.opname[code])
  125. def _chain_append(chain, first, second):
  126. try:
  127. chain[first].append(second)
  128. except KeyError:
  129. chain[first] = [second]
  130. def _make_codes(chain):
  131. codes = []
  132. instruction = random.choice(chain[MARKOV_START])
  133. constants, names, varnames = [], [], []
  134. i = 0
  135. while 1:
  136. i += 1
  137. code, arg = instruction
  138. if code == MARKOV_END:
  139. break
  140. codes.append(code)
  141. if code >= opcode.HAVE_ARGUMENT:
  142. i += 2
  143. if code in opcode.hasconst:
  144. if arg not in constants:
  145. constants.append(arg)
  146. _coerce_arg_into_codes(codes, constants.index(arg))
  147. elif code in opcode.hasname:
  148. if arg not in names:
  149. names.append(arg)
  150. _coerce_arg_into_codes(codes, names.index(arg))
  151. elif code in opcode.haslocal:
  152. if arg not in varnames:
  153. varnames.append(arg)
  154. _coerce_arg_into_codes(codes, varnames.index(arg))
  155. elif code in opcode.hascompare:
  156. _coerce_arg_into_codes(codes, opcode.cmp_op.index(arg))
  157. elif code in opcode.hasjabs:
  158. _coerce_arg_into_codes(codes, arg)
  159. elif code in opcode.hasjrel:
  160. _coerce_arg_into_codes(codes, arg + i)
  161. elif code in OP_HASCALL:
  162. codes.append(arg[0])
  163. codes.append(arg[1])
  164. elif code in OP_HASMAKE:
  165. _coerce_arg_into_codes(codes, arg)
  166. else:
  167. raise NotImplementedError(code, opcode.opname[code])
  168. instruction = random.choice(chain[code])
  169. return codes, tuple(constants), tuple(names), tuple(varnames)
  170. def _opcode_to_opname(code):
  171. if code == MARKOV_START:
  172. return "START"
  173. elif code == MARKOV_END:
  174. return "END"
  175. return opcode.opname[code]
  176. def _coerce_arg_into_codes(codes, arg):
  177. codes.append(arg % 256)
  178. codes.append(arg // 256)
  179. def _demo(corpus, arg=12.0):
  180. chain = make_chain(corpus)
  181. func = make_function(chain, "func")
  182. print "Using {0}-function corpus.".format(len(corpus))
  183. print "Smashed function disassembly:"
  184. print_function(func)
  185. print
  186. print "func({0}) =".format(arg), func(arg)
  187. if len(sys.argv) > 2 and sys.argv[2] == "-i":
  188. variables = dict(globals().items() + locals().items())
  189. interact(banner="", local=variables)
  190. if __name__ == "__main__":
  191. run()