2

Is there any way to safely override eval? Have tried directly overriding:

var oldEval = global.eval;
global.eval = function(){
    // my logic
    global.a+=1;
    return oldEval.apply(this, arguments);
}

This somehow gives the following reference err:

ReferenceError: createCallback is not defined

NOTE: Error here is not generated while overriding, but rather on some occurrences of call to eval. In other cases this works exactly as expected.

Please find the issue reproduction code here: https://runkit.com/embed/8hv0yp94on8s

Anupam Juniwal
  • 309
  • 1
  • 3
  • 11
  • *on some occurrences of call to eval* Like what? – CertainPerformance Nov 14 '19 at 06:09
  • In case of rendering ejs, for example, eval is called, this throws the above stated error. The case can be observed in other 3rd party library such as koa-send. – Anupam Juniwal Nov 14 '19 at 06:14
  • Can you give a concrete example of code in which a call to `eval` throws, so we have a [MCVE] to look at and debug? It might be as simple as returning the `oldEval` call – CertainPerformance Nov 14 '19 at 06:15
  • As stated, the problem observed is in case of some 3rd party libraries. Following have been extracted from koa-ejs: `(function readFile() { var self = this var len = arguments.length var multiArgs = true var lastType = typeof arguments[len - 1] if (lastType === "function") return $$__fn__$$.apply(self, arguments) var args = new Array(len + 1) for (var i = 0; i < len; ++i) args[i] = arguments[i] var lastIndex = i return new Promise(function (resolve, reject) { args[lastIndex] = createCallback(resolve, reject, multiArgs) $$__fn__$$.apply(self, args) }) }) ` – Anupam Juniwal Nov 14 '19 at 06:19
  • Unfortunately, `eval` looks to be nowhere in there... – CertainPerformance Nov 14 '19 at 06:23
  • Sorry, my bad try reproducing with this: `var fs = require('mz/fs') await fs.readFile('index', 'utf8');` – Anupam Juniwal Nov 14 '19 at 06:30
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202311/discussion-between-anupam-juniwal-and-certainperformance). – Anupam Juniwal Nov 14 '19 at 06:55
  • is there any issue related to scope of eval function? As eval runs in global scope. – sumit_suthar Nov 25 '19 at 11:26
  • 1
    yes @sumit_suthar it indeed is, on a lot of research, I came to the conclusion that monkey patching eval is not viable, this is because eval internally calls the interpreter and re constructs the lexical scope. – Anupam Juniwal Nov 26 '19 at 14:21

0 Answers0