Created
May 21, 2015 07:41
-
-
Save alex8224/e77e6bce6cf10884475d to your computer and use it in GitHub Desktop.
inject bytecode into python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import dis | |
import inspect | |
from byteplay import * | |
def wearedcode(fcode): | |
c = Code.from_code(fcode) | |
if c.code[1] == (LOAD_CONST, 'alex'): | |
return fcode | |
c.code[1:1] = [ | |
(LOAD_CONST, u'alex'), (STORE_FAST, 'name'), | |
(LOAD_FAST, 'name'), | |
(PRINT_ITEM, None), (PRINT_NEWLINE, None), | |
] | |
return c.to_code() | |
def trace(frame, event, arg): | |
if event != 'call': | |
return | |
co = frame.f_code | |
func_name = co.co_name | |
if func_name == "write": | |
return | |
if func_name == "get": | |
import tornado.web | |
args = inspect.getargvalues(frame) | |
if 'self' in args.locals: | |
if isinstance(args.locals['self'], tornado.web.RequestHandler): | |
getmethod = args.locals['self'].get | |
print(dis.dis(getmethod.__func__.__code__)) | |
code = getmethod.__func__.__code__ | |
getmethod.__func__.__code__ = wearedcode(code) | |
return | |
sys.settrace(trace) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment