When should I use eval (taking a string and executing it as code at runtime)?

I've often heard the argument (in javascript, but many languages ​​have the same function) that using eval is "bad". The arguments are that most of the things you could use to use eval can be done in other ways: the fact that eval is very slow in most cases, and that it can allow users to enter code to be executed (if proper precautions). We know that most functions are not just "bad", but allow, but the spotlight on eval,

What are some of the valid uses of eval? (besides offering a great opportunity for developers to debug an application)

+2


source to share


7 replies


eval () has good points and bad points. The worst aspect of eval in any language that supports it is that it opens the door to security holes. If an exploiter can figure out how to get any custom code that he writes to an eval statement in your application, then he probably has the ability to do all sorts of dishonest things, such as stealing identity or disabling services provided by your application. Performance is another issue you already talked about.



Eval really shines in areas where your code might need to dynamically generate other code to complete a complex task. I can't think of an example right now, but any case where you needed to do this probably won't be trivial. I would recommend doing this only when absolutely necessary to minimize the risk of the point made in the previous paragraph. If possible, never trust user input as safe enough to use eval with.

+6


source


A read-eval-print loop will usually be implemented using eval.



+7


source


The eval hook is the same as in SQL injection. If you build a string dynamically in your code and call eval in that order. But if your code is blindly concatenating user input into a string to be evaluated, then you are asking for it. There are many cases where eval can be useful, but people tend to avoid it because there are other ways to get around the need for eval.

+2


source


He does metaprogramming cinch. Great if you want to analyze the program in some way (i.e. for debugging or profiling).

+1


source


Decoding json from trusted source. Evaluate an expression entered by the user, just like a graphing calculator. I can't think of too many others, although in the late 90s many of them were abused by people who didn't want to learn the correct ways to access page elements.

0


source


I once wrote a perl CGI script, the output of which was Perl code that was received by another script on a different machine and eval () 'd. It was only safe because I was in control of both ends, but it certainly solved a problem that would otherwise require me to invent some kind of serialization format in an era before XML was widely known.

0


source


The only valid use for eval

is executing code that you have no control over (which you should never do unless you create a javascript sandbox ).

0


source







All Articles