Skip to content
Advertisement

Hooking Function Constructor (JavaScript)

Does anyone know of a way to detect when a new function is created?

I know you can hook the function class constructor but that will only detect new Function() calls, not function func(){} declarations.

I assume the JS engine just creates a default function class when it sees a function declaration instead of looking at the global Function class.

Does anyone know if this is the case or if you can intercept function declarations.

Example function to hook :

function add(x,y){return x+y}

A hook should get the function when it is defined and hopefully redefine it to be able to capture the arguments, this, and return value.

Advertisement

Answer

(V8 developer here.)

No, there is no way to intercept all function declarations.

FWIW, this isn’t up to individual engines to decide; the JavaScript language provides no way to accomplish this, and engines aim to implement the language without any custom deviations (i.e. neither adding nor removing features).

I can offer two alternative ideas that may or may not serve your purposes:
(1) V8 has a --trace flag which logs all function entries and returns to stdout. Be warned: this tends to produce a lot of output.
(2) You could feed the source of the app you are interested in to a JavaScript parser, and then run whatever analysis (and/or transformation) you want over the AST it produces. This won’t catch dynamically generated and eval-ed functions, but it will find all function func() {...} declarations.


The need is game hacking.

In the interest of helping you ask better questions (so that you may get more helpful answers), I’d like to point out that that’s not the level of detail that @Bergi was asking for: the general area in which you are active does not provide any hints for possible alternative approaches. Wanting to hook function declarations so that you can capture their arguments and return values is a search for a specific solution. @Bergi’s question is: what is the specific problem that you are trying to solve by intercepting all functions?

That said, “game hacking”, while being very vague, does sound sufficiently shady that I’d like to humbly suggest that you not only think about whether you could, but alse give sufficient thought to whether you should.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement