Created
October 3, 2012 06:13
-
-
Save suresk/3825355 to your computer and use it in GitHub Desktop.
Part of my Java Class file parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Typedef(bytes) { | |
this.bytes = bytes; | |
}; | |
Typedef.prototype.getData = function(data, start){ | |
var values = data.slice(start, start + this.bytes); | |
var c = 0; | |
for(i = 0; i < values.length; i++) { | |
var offset = this.bytes - (i + 1); | |
c += values[i] * Math.pow(2, offset); | |
} | |
return c; | |
}; | |
var uint8 = new Typedef(1); | |
var uint16 = new Typedef(2); | |
var uint32 = new Typedef(4); | |
toHexString = function(bytes) { | |
return bytes.toString(16); | |
}; | |
function readUTF8String(data, start, n) { | |
var str = ""; | |
for (j = 0; j < n; j++) { | |
str += String.fromCharCode(uint8.getData(data, start + j)); | |
} | |
return str; | |
}; | |
var klazz = new klass.Klass(); | |
var p1 = uint8.getData(data, 0); | |
var p2 = uint8.getData(data, 1); | |
var p3 = uint8.getData(data, 2); | |
var p4 = uint8.getData(data, 3); | |
var maybeCafeBabe = toHexString(p1) + toHexString(p2) + toHexString(p3) + toHexString(p4); | |
if (maybeCafeBabe == "cafebabe") { | |
console.log("java class file"); | |
} else { | |
console.log("not a java class file"); | |
} | |
var minorVersion = uint16.getData(data, 4); | |
var majorVersion = uint16.getData(data, 6); | |
console.log("Major: " + majorVersion); | |
console.log("Minor: " + minorVersion); | |
var constPoolSize = uint16.getData(data, 8); | |
console.log("Constant Pool Size: " + constPoolSize); | |
console.log("First type: " + uint8.getData(data, 10)); | |
console.log("additional: " + uint16.getData(data, 11)); | |
console.log("next byte: " + uint8.getData(data, 13)); | |
console.log("next byte: " + uint16.getData(data, 14)); | |
klazz.name = readUTF8String(data, 16, 11); | |
console.log("name: " + klazz.name); | |
console.log("next byte: " + uint8.getData(data, 27)); | |
console.log("next byte: " + uint16.getData(data, 28)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment