Puyb Inside

mercredi 10 mars 2010

Gna!


Je ne suis pas sûr que je puisse aller à Solution Linux avec ce badge !

Pour ceux qui ne voient pas pourquoi, il y a juste un joli message d'ereur à la place du code barre !

mercredi 3 mars 2010

Build a call tree in Javascript

Disclaimer: This is my first post in english (or at least, the first that try to). So if my writings makes your eyes bleed, please leave a comment about it !

Yesterday, at work, i had to debug an old Internet Explorer only javascript application. This software was made by dumb monkeys who had no clue about how to write maintainable code. I had to go through something close to two thousand line of code and more than an hundred of carefully nested functions... In less than an hour, I was completely lost !
This application was carefully designed to run only under Internet Explorer. There's no hope to be able to used a decent debugger like Firebug. So as usual with this project, i decided to start to build my own tool.

I made a little script that fetches all functions to wrap them in a new function that log the function name, the caller name, the current time, the arguments and the returned value... I hoped this was enough to help me debug the code !

function build_calltree() {
    var call_log = [];
    function log_wrapper(func, name) {
        func.function_name = name;
        function wrapped_func() {
            var caller = arguments.callee.caller || wrapped_func.caller;
            var data = {
                name: name,
                caller: caller,
                caller_name: caller && caller.function_name || '__unknown__',
                'date': new Date(),
                'arguments': arguments
            };
            call_log.push(data);
            var ret = func.apply(this, arguments);
            data['return'] = ret;
            return ret;
        }
        wrapped_func.original = func;
        wrapped_func.function_name = name;
        return wrapped_func;
    }
    for(var k in window) {
        if(typeof window[k] == 'function') {
            window[k] = log_wrapper(window[k], k);
        }
    }
    return call_log;
}
var call_log = build_calltree();

I wrote and test this code in Firefox. But when i tried to test it in IE, it didn't worked...

I found that in IE, global objects (those who aren't declared in the scope of a function) are not attached to the window object. I found a good article that describes the problem.
So I can't iterate through the window object in order to get all the functions. Again, this an IE bug ! The only solution I found is to parse all the js files to extract all the functions names. Crazy, inefficient, and error prone ! Isn't that a good description of IE ?

So i gave up, walked through the code manually, took some paracetamol, and after several hours, find the bug ! But, i want to publish the code above to think that i didn't wrote it for nothing.