Wednesday, December 17, 2008

De-anonymizer for Javascript


Here is a snippet of Ruby code to de-anonymize anonymous functions in Javascript files. It could, for example, be used in a rake file of a rails project, or a Capistrano script.
It will make your debugging and stack tracing experience a lot more fruitful:



def deanonymize(file_name)
content = ""
line_counter = 1
File.open(file_name).each_line do |line|
content += line.gsub(/(\w*)(\.?)(\w*)\s*(=?)\s*function\s*\(/) {
$1 + $2 + $3 + ' ' + $4 + ' function sbrew_' + $1 + '_' + $3 + '_' +
file_name.split('/').last.sub(/.js$/i, '_js') + '_' + line_counter.to_s + '('
}
line_counter += 1
end
content
end


Note that it tries to put as much information as possible into a function name, but not all de-anonymized functions will look the same. The information it uses is:


  • The file name

  • Line number of the function declaration (note: this will make the stack traces look a bit unusual, as you might expect to see the execution line in that stack trace but it is the function declaration line)

  • Enclosing object



No comments: