Question

Is it possible to have some function that increments a counter run upon each instruction within a function, and does some behavior if a number is reached?

To explain, I want to be able to raise an exception if a function ends up taking up past a certain number of bytecode instructions in the virtual machine. So, if someone creates a list comprehension that will make an infinite loop, or creates an infinite while loop, it will force a break out early.

Can this be done in Python?

Was it helpful?

Solution

I doubt it. Usually, the only robust way to do this is to run the untrusted code in a separate process, properly sandboxed.

Consider what happens if the untrusted code acquires some critical resource (e.g. a lock), and then gets killed because it's taking too long. The entire process will deadlock if anyone will try to acquire that same lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top