1 //: The bedrock level 1 of abstraction is now done, and we're going to start
  2 //: building levels above it that make programming in x86 machine code a
  3 //: little more ergonomic.
  4 //:
  5 //: All levels will be "pass through by default". Whatever they don't
  6 //: understand they will silently pass through to lower levels.
  7 //:
  8 //: Since raw hex bytes of machine code are always possible to inject, SubX is
  9 //: not a language, and we aren't building a compiler. This is something
 10 //: deliberately leakier. Levels are more for improving auditing, checks and
 11 //: error messages rather than for hiding low-level details.
 12 
 13 //: Translator workflow: read 'source' file. Run a series of transforms on it,
 14 //: each passing through what it doesn't understand. The final program should
 15 //: be just machine code, suitable to write to an ELF binary.
 16 //:
 17 //: Higher levels usually transform code on the basis of metadata.
 18 
 19 :(before "End Main")
 20 if (is_equal(argv[1], "translate")) {
 21   START_TRACING_UNTIL_END_OF_SCOPE;
 22   assert(argc > 3);
 23   reset();
 24   program p;
 25   ifstream fin(argv[2]);
 26   if (!fin) {
 27     cerr << "could not open " << argv[2] << '\n';
 28     return 1;
 29   }
 30   parse(fin, p);
 31   if (trace_contains_errors()) return 1;
 32   transform(p);
 33   if (trace_contains_errors()) return 1;
 34   save_elf(p, argv[3]);
 35   if (trace_contains_errors()) unlink(argv[3]);
 36   return 0;
 37 }
 38 
 39 :(code)
 40 // write out a program to a bare-bones ELF file
 41 void save_elf(const program& p, const char* filename) {
 42   ofstream out(filename, ios::binary);
 43   write_elf_header(out, p);
 44   for (size_t i = 0;  i < p.segments.size();  ++i)
 45     write_segment(p.segments.at(i), out);
 46   out.close();
 47 }
 48 
 49 void write_elf_header(ostream& out, const program& p) {
 50   char c = '\0';
 51 #define O(X)  c = (X); out.write(&c, sizeof(c))
 52 // host is required to be little-endian
 53 #define emit(X)  out.write(reinterpret_cast<const char*>(&X), sizeof(X))
 54   //// ehdr
 55   // e_ident
 56   O(0x7f); O(/*E*/0x45); O(/*L*/0x4c); O(/*F*/0x46);
 57     O(0x1);  // 32-bit format
 58     O(0x1);  // little-endian
 59     O(0x1); O(0x0);
 60   for (size_t i = 0;  i < 8;  ++i) { O(0x0); }
 61   // e_type
 62   O(0x02); O(0x00);
 63   // e_machine
 64   O(0x03); O(0x00);
 65   // e_version
 66   O(0x01); O(0x00); O(0x00); O(0x00);
 67   // e_entry
 68   int e_entry = p.segments.at(0).start;  // convention
 69   emit(e_entry);
 70   // e_phoff -- immediately after ELF header
 71   int e_phoff = 0x34;
 72   emit(e_phoff);
 73   // e_shoff; unused
 74   int dummy32 = 0;
 75   emit(dummy32);
 76   // e_flags; unused
 77   emit(dummy32);
 78   // e_ehsize
 79   uint16_t e_ehsize = 0x34;
 80   emit(e_ehsize);
 81   // e_phentsize
 82   uint16_t e_phentsize = 0x20;
 83   emit(e_phentsize);
 84   // e_phnum
 85   uint16_t e_phnum = SIZE(p.segments);
 86   emit(e_phnum);
 87   // e_shentsize
 88   uint16_t dummy16 = 0x0;
 89   emit(dummy16);
 90   // e_shnum
 91   emit(dummy16);
 92   // e_shstrndx
 93   emit(dummy16);
 94 
 95   uint32_t p_offset = /*size of ehdr*/0x34 + SIZE(p.segments)*0x20/*size of each phdr*/;
 96   for (int i = 0;  i < SIZE(p.segments);  ++i) {
 97     //// phdr
 98     // p_type
 99     uint32_t p_type = 0x1;
100     emit(p_type);
101     // p_offset
102     emit(p_offset);
103     // p_vaddr
104     uint32_t p_start = p.segments.at(i).start;
105     emit(p_start);
106     // p_paddr
107     emit(p_start);
108     // p_filesz
109     uint32_t size = num_words(p.segments.at(i));
110     assert(p_offset + size < SEGMENT_SIZE);
111     emit(size);
112     // p_memsz
113     emit(size);
114     // p_flags
115     uint32_t p_flags = (i == 0) ? /*r-x*/0x5 : /*rw-*/0x6;  // convention: only first segment is code
116     emit(p_flags);
117 
118     // p_align
119     // "As the system creates or augments a process image, it logically copies
120     // a file's segment to a virtual memory segment.  When—and if— the system
121     // physically reads the file depends on the program's execution behavior,
122     // system load, and so on.  A process does not require a physical page
123     // unless it references the logical page during execution, and processes
124     // commonly leave many pages unreferenced. Therefore delaying physical
125     // reads frequently obviates them, improving system performance. To obtain
126     // this efficiency in practice, executable and shared object files must
127     // have segment images whose file offsets and virtual addresses are
128     // congruent, modulo the page size." -- http://refspecs.linuxbase.org/elf/elf.pdf (page 95)
129     uint32_t p_align = 0x1000;  // default page size on linux
130     emit(p_align);
131     if (p_offset % p_align != p_start % p_align) {
132       raise << "segment starting at 0x" << HEXWORD << p_start << " is improperly aligned; alignment for p_offset " << p_offset << " should be " << (p_offset % p_align) << " but is " << (p_start % p_align) << '\n' << end();
133       return;
134     }
135 
136     // prepare for next segment
137     p_offset += size;
138   }
139 #undef O
140 #undef emit
141 }
142 
143 void write_segment(const segment& s, ostream& out) {
144   for (int i = 0;  i < SIZE(s.lines);  ++i) {
145     const vector<word>& w = s.lines.at(i).words;
146     for (int j = 0;  j < SIZE(w);  ++j) {
147       uint8_t x = hex_byte(w.at(j).data);  // we're done with metadata by this point
148       out.write(reinterpret_cast<const char*>(&x), /*sizeof(byte)*/1);
149     }
150   }
151 }
152 
153 uint32_t num_words(const segment& s) {
154   uint32_t sum = 0;
155   for (int i = 0;  i < SIZE(s.lines);  ++i)
156     sum += SIZE(s.lines.at(i).words);
157   return sum;
158 }
159 
160 :(before "End Includes")
161 using std::ios;