| 1 |
structure X86_64Elf = |
| 2 |
struct |
| 3 |
|
| 4 |
(* get all the bytes off the input stream *) |
| 5 |
fun input inStrm = let |
| 6 |
fun lp (line, lines) = |
| 7 |
if BinIO.endOfStream inStrm |
| 8 |
then List.rev lines |
| 9 |
else lp (BinIO.inputN(inStrm, 8), line :: lines) |
| 10 |
val lines = lp(BinIO.inputN(inStrm, 8), []) |
| 11 |
in |
| 12 |
BinIO.closeIn inStrm; |
| 13 |
lines |
| 14 |
end |
| 15 |
|
| 16 |
(* input the entire file *) |
| 17 |
val inputFile = input o BinIO.openIn |
| 18 |
|
| 19 |
(* extract the text segment from an obj file *) |
| 20 |
fun extractTextSegment bytes = let |
| 21 |
val bytesBeforeInsn = List.take(bytes, 8) |
| 22 |
val insn = List.nth(bytes, 8) |
| 23 |
val bytesAfterInsn = List.drop(bytes, 9) |
| 24 |
in |
| 25 |
(bytesBeforeInsn, insn, bytesAfterInsn) |
| 26 |
end |
| 27 |
|
| 28 |
(* send a list of bytes to the output stream *) |
| 29 |
fun output (bytes, outStrm) = let |
| 30 |
fun lp [] = BinIO.closeOut outStrm |
| 31 |
| lp (l :: ls) = ( |
| 32 |
BinIO.output(outStrm, l); |
| 33 |
lp ls) |
| 34 |
in |
| 35 |
lp bytes |
| 36 |
end |
| 37 |
|
| 38 |
(* take a byte-encoding of an instruction and pad it out to 8 bytes *) |
| 39 |
fun encodeInstr bs = |
| 40 |
Word8Vector.fromList(bs @ List.tabulate(8-(List.length bs), fn _ => 0wx00)) |
| 41 |
|
| 42 |
fun instrToElf (instr, obj) = let |
| 43 |
(* copy in bytes from the object file *) |
| 44 |
val bytes = inputFile obj |
| 45 |
val (bs1, _, bs2) = extractTextSegment bytes |
| 46 |
in |
| 47 |
bs1 @ [encodeInstr instr] @ bs2 |
| 48 |
end |
| 49 |
|
| 50 |
(* copy bytes to an object file *) |
| 51 |
fun outputObjFile (objOut, objBytes) = output(objBytes, BinIO.openOut objOut) |
| 52 |
|
| 53 |
(* takes an elf object file and an instruction, and outputs that instruction to its own elf object file *) |
| 54 |
fun outputInstrToObj (elfObj, instr) = |
| 55 |
outputObjFile("out."^elfObj, instrToElf(instr, elfObj)) |
| 56 |
|
| 57 |
fun doit () = outputInstrToObj("asm1.o", [0wxff, 0wxc2]) |
| 58 |
|
| 59 |
end |