473,385 Members | 1,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Executing bytecode from a string.

I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function. I'm thinking of a database that contains compiled
objects that I can load and execute. I'm also curious as to what level of
grainularity this would work - module, class, class method, function?
Anyone tried to do this before? Obviously dependencies are a consideration
but I'm more interested in the mechanics of this. Appreciate ideas &
pointers you might have...

Ben Scherrey
Jul 18 '05 #1
6 4881
"Benjamin Scherrey" <sc******@proteus-tech.com> writes:
I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function.
Fairly hard: you'd need to guess or work out all the other parameters
to new.code such as argcount, stacksize,...
I'm thinking of a database that contains compiled objects that I can
load and execute.
You'd likely be much better off storing marshalled code objects than
raw code strings. Whether that would suffice is hard to say from your
description, but it's probably a good start.

Or just Python source...
I'm also curious as to what level of grainularity this would work -
module, class, class method, function?
I think "it depends".
Anyone tried to do this before?


Almost certainly :-)

Cheers,
mwh

--
Ignoring the rules in the FAQ: 1" slice in spleen and prevention
of immediate medical care.
-- Mark C. Langston, asr
Jul 18 '05 #2
Michael Hudson wrote:
"Benjamin Scherrey" <sc******@proteus-tech.com> writes:

I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function.


Fairly hard: you'd need to guess or work out all the other parameters
to new.code such as argcount, stacksize,...


I seem to recall doing this, and it wasn't hard for my particular
case because it wasn't an arbitrary function. It took no arguments,
returned nothing, etc...

I was doing this as an experiment to see whether it was feasible
to use evolutionary programming to evolve Python bytecode that
would solve some problem.

The idea worked in principle (I was able to get the bytecode to
execute) but unfortunately there were numerous instances where the
effectively random bytecode would lead to the interpreter crashing
fatally.

I still think it's a neat idea, but it won't work well with Python
in its current form.

Might be useful for doing some kind of stress testing on the
interpreter though, if someone was interested in making it
bullet-proof even for psychotic code (as part of a new security
initiative, perhaps?).

And sorry, but this was a quickie experiment and I don't have the
code any more. Just wanted to say it was doable for the simplest
case.

-Peter
Jul 18 '05 #3

"Benjamin Scherrey" <sc******@proteus-tech.com> wrote in message
news:pa****************************@proteus-tech.com...
I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function. I'm thinking of a database that contains compiled
objects that I can load and execute. I'm also curious as to what level of
grainularity this would work - module, class, class method, function?
Anyone tried to do this before? Obviously dependencies are a consideration
but I'm more interested in the mechanics of this. Appreciate ideas &
pointers you might have...

Ben Scherrey


Look at the 'new' module. It's in the Library Reference under
Python Runtime Services. You'll need to wrap the byte string
with 'code', and then wrap that with 'function'.

As someone else pointed out, there are a number of other
parameters you'll need to supply, and some of them aren't
at all obvious. You may find the disassembler (documented
under Python language services) to be helpful in figuring
some of them out.

John Roth
Jul 18 '05 #4
John Roth wrote:
Look at the 'new' module. It's in the Library Reference under
Python Runtime Services. You'll need to wrap the byte string
with 'code', and then wrap that with 'function'.


that's insane, though. use marshal on code objects, and keep your
sanity.

see page 4-10 in this document for a small sample:

http://www.effbot.org/zone/librarybo...esentation.pdf

to avoid chaos when you upgrade Python, it's a good idea to attach
imp.get_magic() to the marshalled string, and verify it before you un-
marshall the code; see:

http://mail.python.org/pipermail/pyt...er/196230.html

</F>

Jul 18 '05 #5
Benjamin Scherrey wrote:
I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function. I'm thinking of a database that contains compiled
objects that I can load and execute. I'm also curious as to what level of
grainularity this would work - module, class, class method, function?
Anyone tried to do this before? Obviously dependencies are a consideration
but I'm more interested in the mechanics of this. Appreciate ideas &
pointers you might have...

Ben Scherrey


The following was written just for fun with no pretension that it will work
in the "real world". I've only manipulated co_consts and co_code of my
custom code object - you can investigate the other parameters one after
another and replace them with something at your choice.
The question that remains - how do you want to create the bytecode strings?
If from actual functions, why not store their source code, if from
codeobjects, why not marshal.dump()/load() them?

Peter

<code>
# get hold of the function and code types
def f(): pass
function = type(f)
del f
code = type(compile("def f(): pass", "noname", "exec"))

template = compile("def f(): pass", "noname", "exec")

def makeFunc(bytecode, consts):
""" create a new function from a bytecode string and a consts tuple """

# instead of inventing all code-attributes ourselves
# copy those we are not interested in from an existing template
co = template
codeobj = code(co.co_argcount, co.co_nlocals, co.co_stacksize,
co.co_flags, bytecode, consts, co.co_names,
co.co_varnames, co.co_filename, co.co_name,
co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)

return function(codeobj, globals(), "f", None, None)

# get hold of a valid bytecode string
# (I could have pasted the string literal from the interpreter,
# but I chose not to cheat :-)
def prototype():
print "so what"
bytecode = prototype.func_code.co_code

# test what we have so far
g = makeFunc(bytecode, consts=(None, "it takes more than the byte-code",))
h = makeFunc(bytecode, consts=(None, "to make a function"))
g()
h()
</code>
Jul 18 '05 #6
Benjamin Scherrey schrieb:
I'm curious as to how difficult it would be to take a string that contains
compiled bytecode, load it into memory, give it a function name then
execute that function. I'm thinking of a database that contains compiled
objects that I can load and execute. I'm also curious as to what level of
grainularity this would work - module, class, class method, function?
Anyone tried to do this before? Obviously dependencies are a consideration
but I'm more interested in the mechanics of this. Appreciate ideas &
pointers you might have...

Ben Scherrey


I am just writing my Macro/Script in python sourcecode.
In the program I'm doing:

f = open('segment.py','r')
str = f.read()
f.close()

segment_code = compile(str, '<string>', 'exec')

exec(segment_code)

Markus
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

46
by: Jon Perez | last post by:
Can one run a 1.5 .pyc file with the 2.x version interpreters and vice versa? How about running a 2.x .pyc using a 2.y interpreter?
1
by: Bo Jacobsen | last post by:
I have a number of files compiled to bytecode using py_compile.compile(). The .pyc files can be invoked by python directly ($python file.pyc), but "loading" them by execfile just throws an...
33
by: Maurice LING | last post by:
Hi, I've been using Python for about 2 years now, for my honours project and now my postgrad project. I must say that I am loving it more and more now. From my knowledge, Python bytecodes are...
0
by: Andrew Lambert | last post by:
Hi, I've been trying to compile perl scripts into bytecode. Now, from what I understand I can use either perlcc -B script.pl or perl -MO=bytecode script.pl to do this (whats the difference...
4
by: Ben | last post by:
Does anyone have any experience using the TrueType bytecode interpreter to display fonts in PHP under Windows? I'm running Windows XP, PHP 4.3.11, GD 2.0.28 with FreeType enabled. It all works...
0
by: sxanth | last post by:
>What puzzles me, though, are bytecodes 17, 39 and 42 - surely these aren't >reachable? Does the compiler just throw in a default 'return None' >epilogue, with routes there from every code path,...
3
by: Rob De Almeida | last post by:
Hi, I would like to compile an AST to bytecode, so I can eval it later. I tried using parse.compileast, but it fails: Traceback (most recent call last): File "<stdin>", line 1, in ?...
4
by: kwatch | last post by:
Hi, It is possible to get bytecode from code object. Reversely, is it possible to create code object from bytecode? ex. ## python code (not a module) pycode = '''\ print "<ul>\n" for item...
3
by: schwarz | last post by:
As part of some research I am doing a Python Virtual Machine in Java, and the exact semantics of the STORE_NAME bytecode is unclear to be, so I was hoping somebody here could clarify it. The...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.