javascript profile in Firefox - javascript

(I know some people already asked questions about js profile, but that's not what I need if I understand them correctly.)
I'd like to trace the execution of javascript to collect the information of 1) which function is invoked, 2) the time when the function is invoked, and 3) the execution time of the function.
I want to collect the information online (on deployed code) but not in-house. So, the trade-off has to be light. Also, I don't want to manually add a line before and after where a function is invoked. However, it would be great if there's a way that can dynamically instrument the code.
Thanks in advance!

I don't think that there is any system whereby JavaScript will automatically track the time a function starts and the time a function stops. That is likely something you will have to add yourself. If this is what you need, you may want to consider using PHP to serve up your JavaScript and use a regular expression to find the beginnings and ends of each function with a regex or something like that.
Your RegExp might look like this (completely untested, so you'll have to experiment):
/function [A-Za-z_$][A-Za-z0-9_$]*{(.*?)}/i
Once you have access to the inside of the function, you could replace that value with the function to track its beginning and end wrapped around the original function definition.
This has the benefit of doing exactly what you want, without worrying about modifying how your js code functions. It is then something the server will handle entirely.
Either that or, instead of calling the function directly, use a wrapper function:
function wrapFunction( func, context, argList )
{
// Replace with however you are storing this.
console.log( new Date().getTime() );
func.apply( context, argList );
console.log( new Date().getTime() );
}
This has the benefit of being a lot cleaner than having the server update your JS for you. Unfortunately, it also means having to re-write the JS manually.
My recommendation would be to simply adapt a logging syntax and use that. Most loggers will output a timestamp, a context, a level, and a specific message. If you simply call the logger at the beginning and end of the function, it will do exactly what you're looking for. Further, since many are configurable, you would be able to have it display to the JS console in Firefox, send information to the server, or completely disabled if you so chose.
There are a list of JS loggers here:
JavaScript loggers
This would unfortunately require you to manually update everything, but it seems like the simplest way to get 90% of what you're looking for out of the box.

Perhaps the profiler in FireBug can help you track down slow functions.
Here's a video detailing the profiling options. (Index: 3:20).

console.profile([title])
//also see
console.trace()
http://getfirebug.com/wiki/index.php/Console_API

Related

How can I check if a function is a pure function?

I'm working on react-metaform, and one of my challenges is that I need to allow the end-user to define metadata as functions. Example:
socialSecurityNumber.required: (m) => m.type == 'person'
The problem is obvious: I cannot trust the user. So, these are the precautions i'm planning to make:
User-defined functions should be pure function. In the sense that, these functions can only access their parameter, nothing else.
User-defined functions will run in an environment that is resilient to exceptions, too long execution times and infinite loops. (I'm not worried about this right now).
The question is: How do I make sure a user-defined function only accesses it's parameters and nothing else?
I would use esprima to parse users' JavaScript functions that are stored in files or in a database. And I would allow to run only code that passes the parsing test (only whitelisted features - using local variables, parameters, ...).
You can start with a very simple checking code that only allows very limited scripts and progressively improve it. However, I guess you will put a lot of effort to the solution over time because your users will always want more.
Note: Angular.js uses for its dependency injection this kind of 'trick': https://jsfiddle.net/987Lwezy/
function test() {
console.log("This is my secret!");
}
function parser(f) {
document.body.innerHTML = test.toString();
}
parser(test);
You could use https://github.com/lcrespom/purecheck. It hasn't been updated in a while, but seems to support what you need.

Node JS - executing a string of code in a new process

Let's say I have a string of NodeJS code I want to execute, but it's untrusted, and thus I must sandbox it, using vm.runInNewContext(stringOfCode). Two questions arise:
If I do have some objects I want to use within the executed code, how may that bee achieved?
Let's say I want to limit the execution time of the code to 5 seconds, how may I do that?
How may I run this code on a new process? I now I can use child_process.fork(), but how exactly will I do that?
Thank you!!
The sandbox argument you provide to vm.runInNewContext() is the object which will be available to the sandboxed code. Put there anything you need to use from inside. It's described in the docs:
http://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_sandbox_filename
But as the documentation says, you should better put the untrusted code into a separate process. Otherwise the code could simply hang with while(true);. As you mentioned yourself, the chlid_process.fork() shoudl be used for that. The docs are here:
http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options
But in this case you cannot transfer the objects to the new process, the messaging should be used instead.
Finally there's a library which simplifies everything above:
https://github.com/asvd/jailed

check if javascript variable has been changed from console

I am developing a JS game and wish to prevent cheating as much as possible. I understand that this is near impossible but I would like to prevent users from going into the console and changing their lives by saying something like game.lives = 99;
Is there a way I can detect if a variable such as lives has been changed from the console thus marking the game hacked and stopping the execution of my code? I understand I could do server side checking but I want to avoid lag. I am looking for a JS answer if there is one.
You won't be able to completely stop a user from changing the javascript code or variable values. You only can make it more difficult. Fisch mentioned using closure so as all variables will be private. Look into the immediately invoked function expression (IIFE) pattern. It's used in a lot of plugin style code and helps prevent modifications.
If a user wants to change a variables value, nothing will stop them from running the game in debug mode and modifying values at breakpoints.
You could use a closure which would essentially make all your variables private and thus not accessible from the console. If you need to have some public variables and methods, you could use a revealing module pattern. you can read more about them here: http://www.joezimjs.com/javascript/javascript-closures-and-the-module-pattern/

Faking a VbScript Array with JavaScript

I'm using and testing a VbScript API using JavaScript. One part of the VbScript API has a construct, that I must assume is an array, that you can read and write from. I do not have the source code for the VbScript API, nor do I even have access to the system in which it runs for the time being. In my JavaScript test code, which mocks myObj and myFunc, assignments throw an error, not surprisingly, since I'm mocking it as a function.
myObj.myFunc("xyz") = 1
Mocking as an array would not work, since JavaScript uses [] as the accessor.
One solution would be to wrap calls to myFunc with JavaScript, but I was wondering if there might be a more ingenious solution, JavaScript being the pliable language that it is.
I think I've answered my own question here... I only need to set and read one value, which is why it was not already wrapped and mocked as an array. The answer is to go ahead and wrap it.
Thanks,
Mike
How about this?
myObj.setValue("xyz", 1);
Really it makes no sense trying to simulate the syntax of another language.
I don't exactly understand the question, but if you're trying to create a JS construct that can set an array element using that format, that's pretty easy
Array.prototype.setValue = function(key,value) {
this[key]=value;
};
http://jsfiddle.net/gcVSq/

Javascript eval limits

Is there a limit to javascript's eval, like in lenght?
I'm trying to build an app where you can store JS code in the DB, which you can later load and eval in order to execute it, but i'm reaching a limit.
First of all, the code has to all be in one line. Any multiline statements are not executed.
Next, i'm reaching a limit in length (i guess). If i execute the code manually, it works, but put that same code in the db, load it via ajax, and try to execute it, and it fails.
Any ideas why?
You don't need to use eval and its not exactly a good thing to use. You could just have it print out to the page and it will run.
Here is the accepted answer on why you should not use eval:
Improper use of eval opens up your code for injection attacks
Debugging can be more challenging (no line numbers, etc.)
eval'd code executes more slowly (no opportunity to compile/cache eval'd code)
I have run into this also. As others have said here - eval comes in handy when you are generating the Javascript on the fly and then want to have it execute on the browser. My usages of this technique are to go small things like a simple function that will just make a call back to the server when a button is pressed. Depending upon the circumstances there might be two functions or just one. I've also used it to display information that changes from a database. The information is always just plain text. So no injection attack can be done.
Anyway, I too have run in to this limitation of the Javascript EVAL statement and it seems to me that there is a 1024 character limit. When I go over this I start getting weird things like eval just spitting out the original text. This is really evident because I hex everything before sending it to the browser so I can have things like single and double quotes in the text without it causing eval any problems. (And hexing everything helps prevent injection attacks.)
I also side with the person who said to use getscript in jQuery. It works just as well as the eval without the size limitations. The only extra step you have to take is to create the Javascript file first.
I hope this helps and answers the original poster's question. That being I believe the size limitation is 1024 bytes.
You could create a javascript function that creates a script-tag dynamically (createElement('script') and append it to the head- or bodytag) and point the source to your app. The src can contain parameters, used like a get request, like for example: src="jsapp.aspx?script=myscript&includefunction=loadfn" No eval needed. You can even define an onload handler for your new script tag. Plenty of documentation on the net for that.
You wouldn't even have to use XHR (AKA Ajax) for that.

Categories

Resources