1

I have a python snippet as follows

5 + 6 * 8

Compiling this to AST gives:

>>> ast.dump(compile('5+6*8', '', 'eval', ast.PyCF_ONLY_AST))    
Expression(body=BinOp(left=Num(n=5), op=Add(), right=BinOp(left=Num(n=6), op=Mult(), right=Num(n=8))))

Note that in the generated AST 6 * 8 is not optimized into 48.

However, if I compile this generated AST and disassemble, 6 * 8 is replaced by 48.

>>> astree = compile('5+6*8', '', 'eval', ast.PyCF_ONLY_AST)
>>> dis.disco(compile(astree, '', 'eval'))
  1           0 LOAD_CONST               0 (5)
              3 LOAD_CONST               3 (48)
              6 BINARY_ADD          
              7 RETURN_VALUE 

My question

How to compile the code to bytecode without the constant folding optimization? I need to do this for developing an obfuscator.

Extreme Coders
  • 3,441
  • 2
  • 39
  • 55
  • Maybe finding out why `5 + 48` wasn’t folded to `53` will guide to a solution. However, I don’t think that avoiding constant folding can be considered a strong obfuscation. Actually, it’s the opposite. The information that the constant `53` was derived from `5 + 6 * 8` (perhaps using named constants) in the source, is an information that is lost after folding and no decompiler can ever reconstitute… – Holger Jan 06 '17 at 11:58

0 Answers0