0

To make it more clear, I will put what I want to do in code.

var functionsafe = "function plus(a,b){c=a+b; return c}";

and we can directly call function add ()= functionsafe;

I wonder if there is a possible language which is capable of doing this. This is inspired by SQL injection attack method, which means inject some code into SQL to mess up database, which makes me thinking if it's possible to do this to general code, which is modify the code while executing. It probably sounds crazy, since codes need to pass the compiler to be recognized by computer, but imagine if it's possible to use similar technique for machine learning. Please tell me if and why it would be impossible to do such thing.

adiga
  • 34,372
  • 9
  • 61
  • 83
  • 1
    `eval(functionsafe)` – adiga Jul 13 '19 at 06:38
  • `new Function()` will also do the trick. Also remember that you don't need the `Function` keyword: `"".constructor.constructor` also retrieves the `Function` object. – SOFe Jul 13 '19 at 06:53
  • I have previously asked a similar question on security.SE: https://security.stackexchange.com/q/204315/125315 – SOFe Jul 13 '19 at 06:54
  • 1
    Are you asking how to do this in Java or in JavaScript? They are two entirely different languages, so please don't tag both. – Andreas Jul 13 '19 at 07:28

1 Answers1

0

The closest thing in JavaScript is the eval function. The syntax doesn't work exactly as you propose, but the functionality is pretty close.

If you make one small change (the addition of enclosing parentheses) like this:

var functionsafe = "(function plus(a,b){c=a+b; return c})";

You can then invoke the function like this:

eval(functionsafe)(2, 3)

Which will give you the result 5.

The use of the eval function is generally frowned upon, however. (See here: https://www.sitepoint.com/call-javascript-function-string-without-using-eval/)

kshetline
  • 12,547
  • 4
  • 37
  • 73