Javascript Eval and Function constructor usage - javascript

I'm currently experimenting on self replicating code. Out of love for the language I'd like to write it in javascript.
I'm working on a program that writes a function's code which in turn writes its function own code and so on. Basically, the desired process is this:
I manually create A function which returns code (which includes some randomness) and a numeric value (proposed solution to a problem).
I call this function a number of times, evaluate the results of each of those returned functions, and continue the process until I have code that is sufficiently good for what I'm trying to do.
Now, I have always been told how eval is evil, how never to use it and so on. However for my specific use case it seems like the Function constructor or eval are exactly what I'm looking for.
So, in short the question is:
Are eval/Function constructor indeed the best tools to use in my case? If so, I figured I'd use the Function constructor to scope the code executed, but is there a way to truly limit it from accessing the global scope? Also, what are some good practices for eval usage in my case?

I think I just figured out something I could use:
If I run my javascript code using node.js I can use the vm module which allows me to execute javascript code safely in a new context, and without letting the executed code have any access to the local or global scopes.
vm.runInNewContext compiles code, then runs it in sandbox and returns the result.
Running code does not have access to local scope. The object sandbox will be used as
the global object for code. sandbox and filename are optional, filename is only used in
stack traces.
You can see a full example here: vm.runInNewContext
This will allow me to eval code safely, and seems to be the safest way (I found) currently available. I think this is a much better solution than eval or calling the Function constructor.
Thank you everyone who helped.

Unfortunately I believe there is no way to prevent it from accessing the global scope. Suppose for example that in a web browser i evaled some code like this :
(function(window) {
eval(script);
)(null));
Any time the script tries to access window - it will get an error, since window is null. However someone who knew what they were doing could always do this :
var global = (function() {
return this;
}());
Since when you invoke a function in what Crockford calls the "function invocation style" then the this is always bound to the global variable.

Related

Javascript hooking

If I wanted to hook calls to functions like eval and settimeout in Javascript to get things like the code eval is going to execute and through function settimeout is going to call, where would I start?
Scenario is, I go to a webpage in chrome and i want a breakpoint set at each of these points. They may however be obsfuscated (potentially malicious) so i can't just search the source for those kinds of calls.
Wouldn't i be able to use chrome directly to do this or would i really need to create a hook into v8 to capture these calls to specific js functions?
There is no way to intercept all code execution events. You would have to modify the sources.
That said, both eval and setTimeout are just functions, installed as configurable properties on the global object. You can overwrite them with wrappers:
var original_eval = eval;
eval = function(str) {
console.log("eval was called with: " + str);
return original_eval(str);
}
Note that there is a big conceptual difference between eval and setTimeout: the former takes fresh source code, the latter can only schedule calls to existing functions (that might have been created with eval).
There is also the Function constructor, which is similar to eval.

Accessing/Intercepting Nashorn's Global Object Variables

This is along the same lines as the question titled "Capturing Nashorn's Global Variables". I'm finding it very limiting not being able to intercept the assignment of variables to the global object.
For instance, say I eval the script "a = 10". Perhaps I want to call a listener to notify something that 'a' was added to the scope. The only way I could do this is to investigate the global object after the script is eval'd.
Or say i want to intercept an object being assigned to the global scope and substitute it for another; if it was using Bindings I could implement put, and delegate off to some other bindings:
public Object put(String name, Object value) {
//put a toStringed version of the object in scope
return delegate.put(name, value+"");
}
This way, when the code 'a=10' is evalled, it would put "10" in scope instead of 10.
It's handy having a Bindings interface to implement, but frustrating that I can't provide something like this implementation for the global object. ScriptObjectMirror is final, so I can't even overload this and hijack the subsequent call to the internal ScriptObject. Am I missing something?
So basically what you want to do is to intercept/trap assignments to arbitrary properties on some object. In your case, the global object.
Afaik, this was never really possible without some pretty hacky code indeed. A search for 'observables javascript' might help you with that, but be warned that you'll get into some muddy territory.
If this is meant for testing (as opposed to production code), a setTimeout / setInterval with some listener that periodically enumerates all properties of the global object and logs a warning if one was added might be good enough for you.
In the future, we'll have the Javascript Proxy standard to help us with this but I seriously doubt it is there yet in Nashorn. It's been a while since I worked with Nashorn but after the initial burst on the scene it has been quiet on the Nashorn front afaict...

Why do we wrap Angular app inside a function?

I'm learning Angular and in all the resources I've used so far I saw this in the app.js file:
(function () {
\\\myAngularModules
})();
The most commonl explainantion is an unhelpful "it's just good practice".
Questions:
Is wrapping our Angular JS code in a function really good practice? Why?
What sort of function is it and what does it do?
Please give examples where possible.
This is what is known as an immediately invoked anonymous function (IIFE). It allows us to create a new function scope and immediately run the code so that no variable or other items we create "leak" out and manipulate the global scope.
Leaking of your code into the global can impact other modules or 3rd party code. This also helps protect your code by making you think about what objects you are using that are not declared in your local scope.
http://gregfranko.com/blog/i-love-my-iife/ as a more detailed explanation that covers the general idea other esoteric things like minification benefits.
Is wrapping our Angular JS code in a function really good practice?
Why?
This is good practice and is called module pattern. As a pattern has it advantages and it disadvantages. However, it is one of the most used patterns in the JS world. In a few words, it allows you to declare as you want your variables, your functions etc. without having any conflict with any js code you use in your app.
For further information on the above, please have a look here.
What sort of function is it and what does it do?
It is a classic function. Nothing more nothing less. Using the invoking operator () at the end, we call the function, to be executed. The latter is also known as IIFE, immediately invoked anonymous function.

What is the purpose of passing arguments to anonymous functions in this manner? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do JavaScript closures work?
I was playing around with the Google Closure Compiler, putting in random code to see what it would do.
It rewrote one of my functions to look something like this:
(function(msg) { console.log(msg); })("Hello World!");​​​​​​​
Where it appears that "Hello World" is the argument passed as msg to the anonymous function preceding it. I was looking at it for a moment, and had thought that I had seen something similar in jQuery plugins that look something like:
(function( $ ) {
...
})(jQuery);
Which now makes more sense to me, in the scope of conflicts with $. But what is the primary reason or purpose for passing arguments into an anonymous function like this? Why wouldn't you simply define the arguments as variables within the function? Is there any performance or flexibility advantage to writing functions like this?
There is one significant difference connected also to scope. The following code:
(function(msg) { console.log(msg); })("Hello World!");​​​​​​​
is in some circumstances cleaner in terms of namespace pollution than this:
var msg = "Hello World!";
console.log(msg);
because the second code leaves variable after it is no longer needed, but may interfere with other parts of the code.
This is especially important when you execute the mentioned code outside any other function: in such case msg variable would be available everywhere on the page, as global variable.
Basically, it's always a good idea to keep your code wrapped in this: (function(){/*code*/}()); to prevent your vars from colliding with other peoples vars.
I think the main thing closure compiler is getting at is saving the 5 characters:var and =.
It depends a bit on the context. There are some conditions where the compiler won't try to inline any function at all (if the scoping function contains "eval" for instance). If this is a in global scope and you are running in ADVANCED mode, it is simply that the inlining opportunity appeared after the compiler stop trying to inline functions (or there is a bug in the inlining code and it missed the opportunity). If you run your sample output through the compiler in ADVANCED mode, you get this:
console.log("Hello World!");

Possible to enumerate or access module-level function declarations in NodeJs?

In Node.js, if I load a module which contains code in module-scope like:
this["foo"] = function() { console.log("foo"); }
...then I appear to get a globally available function that I can call just by saying foo() from any code using the module. It can be seen as one of the printed items with Object.getOwnPropertyNames(this).
However, if I put the following in module scope instead:
function foo() { console.log("foo"); }
...then it produces a function which can similarly be called within that module as foo(), but is invisible outside of it (e.g. does not show up as one of the items with Object.getOwnPropertyNames(this)).
I gather this is a change in runtime behavior from what's done in browsers. A browser seems to poke everything into global scope by default (and for years people have had to consciously avoid this by wrapping things up in anonymous functions/etc.)
My question is whether NodeJs has some secret way of interacting with these declarations outside of the module in which they are declared BESIDES using exports.(...) = (...). Can they be enumerated somehow, or are they garbage collected as soon as they are declared if they're not called by a module export? If I knew what the name of such a function was going to be in advance of loading a module...could I tell Node.js to "capture it" when it was defined?
I'm not expecting any such capabilities to be well-documented...but perhaps there's a debugger feature or other system call. One of the best pointers would be to the specific code in the Node.js project where this kind of declaration is handled, to see if there are any loopholes.
Note: In researching a little into V8 I saw that a "function definition" doesn't get added to the context. It's put into an "activation object" of the "execution context", and cannot be programmatically accessed. If you want some "light reading" I found:
http://coachwei.sys-con.com/node/676031/mobile
http://perfectionkills.com/understanding-delete/
if you fill in exports.foo = foo; at the end of your file it will be available in other files in node, assuming that you do var myFile = require('myFile.js') with the file name and you call the function via myFile.foo(); You can even rename the function for outside use in exports and set whatever you want to call the package when you use require.
BTW you can enumerate these functions just like you do on any JSON object (ie for k in ...)
This is impossible in node without more advanced reflection tools like the debugger.
The only way to do this would be to use __parent__ which was removed due to security issues and other things (hard to optimize, not standard to begin with) . When you run the script those variables become closed under the module. You can not access them elsewhere without explicitly exporting them.
This is not a bug, it's by design. It's just how node works. see this closely related question.
If this sort of reflection was available without tools like the debugger it would have been extremely hard to optimize the source code (at least the way v8 works) , meaning the answer to your question is no. Sorry.

Categories