1 //: Labels are defined by ending names with a ':'. This layer will compute
  2 //: displacements for labels, and compute the offset for instructions using them.
  3 //:
  4 //: We won't check this, but our convention will be that jump targets will
  5 //: start with a '$', while functions will not. Function names will never be
  6 //: jumped to, and jump targets will never be called.
  7 
  8 //: We're introducing non-number names for the first time, so it's worth
  9 //: laying down some ground rules all transforms will follow, so things don't
 10 //: get too confusing:
 11 //:   - if it starts with a digit, it's treated as a number. If it can't be
 12 //:     parsed as hex it will raise an error.
 13 //:   - if it starts with '-' it's treated as a number.
 14 //:   - if it starts with '0x' it's treated as a number.
 15 //:   - if it's two characters long, it can't be a name. Either it's a hex
 16 //:     byte, or it raises an error.
 17 //: That's it. Names can start with any non-digit that isn't a dash. They can
 18 //: be a single character long. 'a' is not a hex number, it's a variable.
 19 //: Later layers may add more conventions partitioning the space of names. But
 20 //: the above rules will remain inviolate.
 21 void check_valid_name(const string& s) {
 22   if (s.empty()) {
 23     raise << "empty name!\n" << end();
 24     return;
 25   }
 26   if (s.at(0) == '-')
 27     raise << "'" << s << "' starts with '-', which can be confused with a negative number; use a different name\n" << end();
 28   if (s.substr(0, 2) == "0x") {
 29     raise << "'" << s << "' looks like a hex number; use a different name\n" << end();
 30     return;
 31   }
 32   if (isdigit(s.at(0)))
 33     raise << "'" << s << "' starts with a digit, and so can be confused with a negative number; use a different name.\n" << end();
 34   if (SIZE(s) == 2)
 35     raise << "'" << s << "' is two characters long which can look like raw hex bytes at a glance; use a different name\n" << end();
 36 }
 37 
 38 :(scenarios transform)
 39 :(scenario map_label)
 40 == 0x1
 41           # instruction                     effective address                                                   operand     displacement    immediate
 42           # op          subop               mod             rm32          base        index         scale       r32
 43           # 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes
 44 loop:
 45             05                                                                                                                              0x0d0c0b0a/imm32  # add to EAX
 46 +transform: label 'loop' is at address 1
 47 
 48 :(before "End Level-2 Transforms")
 49 Transform.push_back(rewrite_labels);
 50 :(code)
 51 void rewrite_labels(program& p) {
 52   trace(99, "transform") << "-- rewrite labels" << end();
 53   if (p.segments.empty()) return;
 54   segment& code = p.segments.at(0);
 55   map<string, int32_t> byte_index;  // values are unsigned, but we're going to do subtractions on them so they need to fit in 31 bits
 56   compute_byte_indices_for_labels(code, byte_index);
 57   if (trace_contains_errors()) return;
 58   drop_labels(code);
 59   if (trace_contains_errors()) return;
 60   replace_labels_with_displacements(code, byte_index);
 61 }
 62 
 63 void compute_byte_indices_for_labels(const segment& code, map<string, int32_t>& byte_index) {
 64   int current_byte = 0;
 65   for (int i = 0;  i < SIZE(code.lines);  ++i) {
 66     const line& inst = code.lines.at(i);
 67     for (int j = 0;  j < SIZE(inst.words);  ++j) {
 68       const word& curr = inst.words.at(j);
 69       // hack: if we have any operand metadata left after previous transforms,
 70       // deduce its size
 71       // Maybe we should just move this transform to before instruction
 72       // packing, and deduce the size of *all* operands. But then we'll also
 73       // have to deal with bitfields.
 74       if (has_operand_metadata(curr, "disp32") || has_operand_metadata(curr, "imm32")) {
 75         if (*curr.data.rbegin() == ':')
 76           raise << "'" << to_string(inst) << "': don't use ':' when jumping to labels\n" << end();
 77         current_byte += 4;
 78       }
 79       // automatically handle /disp8 and /imm8 here
 80       else if (*curr.data.rbegin() != ':') {
 81         ++current_byte;
 82       }
 83       else {
 84         string label = drop_last(curr.data);
 85         // ensure labels look sufficiently different from raw hex
 86         check_valid_name(label);
 87         if (trace_contains_errors()) return;
 88         if (contains_any_operand_metadata(curr))
 89           raise << "'" << to_string(inst) << "': label definition (':') not allowed in operand\n" << end();
 90         if (j > 0)
 91           raise << "'" << to_string(inst) << "': labels can only be the first word in a line.\n" << end();
 92         if (Dump_map)
 93           cerr << "0x" << HEXWORD << (code.start + current_byte) << ' ' << label << '\n';
 94         put(byte_index, label, current_byte);
 95         trace(99, "transform") << "label '" << label << "' is at address " << (current_byte+code.start) << end();
 96         // no modifying current_byte; label definitions won't be in the final binary
 97       }
 98     }
 99   }
100 }
101 
102 :(before "End Globals")
103 bool Dump_map = false;  // currently used only by 'subx translate'
104 :(before "End Commandline Options")
105 else if (is_equal(*arg, "--map")) {
106   Dump_map = true;
107 }
108 
109 :(code)
110 void drop_labels(segment& code) {
111   for (int i = 0;  i < SIZE(code.lines);  ++i) {
112     line& inst = code.lines.at(i);
113     vector<word>::iterator new_end = remove_if(inst.words.begin(), inst.words.end(), is_label);
114     inst.words.erase(new_end, inst.words.end());
115   }
116 }
117 
118 bool is_label(const word& w) {
119   return *w.data.rbegin() == ':';
120 }
121 
122 void replace_labels_with_displacements(segment& code, const map<string, int32_t>& byte_index) {
123   int32_t byte_index_next_instruction_starts_at = 0;
124   for (int i = 0;  i < SIZE(code.lines);  ++i) {
125     line& inst = code.lines.at(i);
126     byte_index_next_instruction_starts_at += num_bytes(inst);
127     line new_inst;
128     for (int j = 0;  j < SIZE(inst.words);  ++j) {
129       const word& curr = inst.words.at(j);
130       if (contains_key(byte_index, curr.data)) {
131         int32_t displacement = static_cast<int32_t>(get(byte_index, curr.data)) - byte_index_next_instruction_starts_at;
132         if (has_operand_metadata(curr, "disp8")) {
133           if (displacement > 0xff || displacement < -0x7f)
134             raise << "'" << to_string(inst) << "': label too far away for displacement " << std::hex << displacement << " to fit in 8 bits\n" << end();
135           else
136             emit_hex_bytes(new_inst, displacement, 1);
137         }
138         else if (has_operand_metadata(curr, "disp16")) {
139           if (displacement > 0xffff || displacement < -0x7fff)
140             raise << "'" << to_string(inst) << "': label too far away for displacement " << std::hex << displacement << " to fit in 16 bits\n" << end();
141           else
142             emit_hex_bytes(new_inst, displacement, 2);
143         }
144         else if (has_operand_metadata(curr, "disp32")) {
145           emit_hex_bytes(new_inst, displacement, 4);
146         }
147       }
148       else {
149         new_inst.words.push_back(curr);
150       }
151     }
152     inst.words.swap(new_inst.words);
153     trace(99, "transform") << "instruction after transform: '" << data_to_string(inst) << "'" << end();
154   }
155 }
156 
157 string data_to_string(const line& inst) {
158   ostringstream out;
159   for (int i = 0;  i < SIZE(inst.words);  ++i) {
160     if (i > 0) out << ' ';
161     out << inst.words.at(i).data;
162   }
163   return out.str();
164 }
165 
166 string drop_last(const string& s) {
167   return string(s.begin(), --s.end());
168 }
169 
170 //: Label definitions must be the first word on a line. No jumping inside
171 //: instructions.
172 //: They should also be the only word on a line.
173 //: However, you can absolutely have multiple labels map to the same address,
174 //: as long as they're on separate lines.
175 
176 :(scenario multiple_labels_at)
177 == 0x1
178           # instruction                     effective address                                                   operand     displacement    immediate
179           # op          subop               mod             rm32          base        index         scale       r32
180           # 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes
181 # address 1
182 loop:
183  $loop2:
184 # address 1 (labels take up no space)
185             05                                                                                                                              0x0d0c0b0a/imm32  # add to EAX
186 # address 6
187             eb                                                                                                              $loop2/disp8
188 # address 8
189             eb                                                                                                              $loop3/disp8
190 # address 0xa
191  $loop3:
192 +transform: label 'loop' is at address 1
193 +transform: label '$loop2' is at address 1
194 +transform: label '$loop3' is at address a
195 # first jump is to -7
196 +transform: instruction after transform: 'eb f9'
197 # second jump is to 0 (fall through)
198 +transform: instruction after transform: 'eb 00'
199 
200 :(scenario label_too_short)
201 % Hide_errors = true;
202 == 0x1
203           # instruction                     effective address                                                   operand     displacement    immediate
204           # op          subop               mod             rm32          base        index         scale       r32
205           # 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes
206 xz:
207             05                                                                                                                              0x0d0c0b0a/imm32  # add to EAX
208 +error: 'xz' is two characters long which can look like raw hex bytes at a glance; use a different name
209 
210 :(scenario label_hex)
211 % Hide_errors = true;
212 == 0x1
213           # instruction                     effective address                                                   operand     displacement    immediate
214           # op          subop               mod             rm32          base        index         scale       r32
215           # 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes
216 0xab:
217             05                                                                                                                              0x0d0c0b0a/imm32  # add to EAX
218 +error: '0xab' looks like a hex number; use a different name
219 
220 :(scenario label_negative_hex)
221 % Hide_errors = true;
222 == 0x1
223           # instruction                     effective address                                                   operand     displacement    immediate
224           # op          subop               mod             rm32          base        index         scale       r32
225           # 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes
226  -a:  # indent to avoid looking like a trace_should_not_contain command for this scenario
227             05                                                                                                                              0x0d0c0b0a/imm32  # add to EAX
228 +error: '-a' starts with '-', which can be confused with a negative number; use a different name
229 
230 //: now that we have labels, we need to adjust segment size computation to
231 //: ignore them.
232 
233 :(scenario segment_size_ignores_labels)
234 % Mem_offset = CODE_START;
235 == code  # 0x08048074
236 05/add 0x0d0c0b0a/imm32  # 5 bytes
237 foo:                     # 0 bytes
238 == data  # 0x08049079
239 bar:
240 00
241 +transform: segment 1 begins at address 0x08049079
242 
243 :(before "End num_bytes(curr) Special-cases")
244 else if (is_label(curr))
245   ;  // don't count it