Skip to content

Instantly share code, notes, and snippets.

@tango238
Created November 4, 2012 10:03
Show Gist options
  • Save tango238/4011144 to your computer and use it in GitHub Desktop.
Save tango238/4011144 to your computer and use it in GitHub Desktop.
dump a.out
// http://www.iecc.com/linker/linker03.html
// Figure 2: a.out header
// int a_magic; -- magic number
// int a_text; -- text segment size
// int a_data; -- initialized data size
// int a_bss; -- uninitialized data size
// int a_syms; -- symbol table size
// int a_entry; -- entry point
// int a_trsize; -- text relocation size
// int a_drsize; -- data relocation size
aout = new Aout()
headerSize = 16
def printDump(List hexStrs, int pc) {
if(hexStrs[pc] == "15" && hexStrs[pc+1] == "C0") {
// MOV
println Integer.toHexString(pc) + ": 15c0 " + hexStrs[pc+2] + hexStrs[pc+3] + " mov \$" + Integer.parseInt(hexStrs[pc+3], 16) + ", r" + Integer.parseInt(hexStrs[pc+2], 16)
return pc + 4
}
if(hexStrs[pc] == "89") {
// SYS
println Integer.toHexString(pc) + ": 89" + hexStrs[pc+1] + " sys " + Integer.parseInt(hexStrs[pc+1], 16)
return pc + 2
}
if(hexStrs[pc] == "00" && hexStrs[pc+1] == "10") {
// .WORD
println Integer.toHexString(pc) + ": 0010 .word 20"
return pc + 2
}
if(hexStrs[pc] == "00" && hexStrs[pc+1] == "06") {
// RTT
println Integer.toHexString(pc) + ": 0006 rtt"
return pc + 2
}
}
def dump = { prog ->
bytes = []
String tmp = ""
prog.toList().eachWithIndex { str, idx ->
tmp += str
if((idx + 1) % 2 == 0) {
bytes += tmp
tmp = ""
}
}
int nextPc = 0
bytes.eachWithIndex { b, pc ->
if(pc == nextPc) {
nextPc = printDump(bytes, pc)
}
}
}
def analyze = {
InputStream input = new BufferedInputStream(new FileInputStream(new File('a.out')));
int counter = 0
String tmp = ""
while ((c = input.read()) != -1) {
String hex = Integer.toHexString(c).toUpperCase().padLeft(2, "0")
// a_text
if(counter == 2 || counter == 3) {
aout.header.atext = hex + aout.header.atext
}
// a_data
if(counter == 4 || counter == 5) {
aout.header.adata = hex + aout.header.adata
}
// program
if(counter >= headerSize) {
def pc = headerSize + aout.header.atextAsInt()
if(counter < pc){
if(counter % 2 == 1) {
tmp = hex + tmp
aout.program += tmp
} else {
tmp = hex
}
}
}
counter++
}
}
class Aout {
Header header = new Header()
String program = ""
String data = ""
}
class Header {
String atext = ""
String adata = ""
def atextAsInt(){
(this.atext != "") ? Integer.parseInt(this.atext, 16) : 0
}
def adataAsInt(){
(this.adata != "") ? Integer.parseInt(this.adata, 16) : 0
}
}
analyze()
dump(aout.program)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment