1 //: Since we're tagging operands with their types, let's start checking these
  2 //: operand types for each instruction.
  3 
  4 :(scenario check_missing_imm8_operand)
  5 % Hide_errors = true;
  6 == 0x1
  7 # instruction                     effective address                                                   operand     displacement    immediate
  8 # op          subop               mod             rm32          base        index         scale       r32
  9 # 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
 10   cd                                                                                                                                                # int ??
 11 +error: 'cd' (software interrupt): missing imm8 operand
 12 
 13 :(before "Pack Operands(segment code)")
 14 check_operands(code);
 15 if (trace_contains_errors()) return;
 16 
 17 :(code)
 18 void check_operands(const segment& code) {
 19   trace(99, "transform") << "-- check operands" << end();
 20   for (int i = 0;  i < SIZE(code.lines);  ++i) {
 21     check_operands(code.lines.at(i));
 22     if (trace_contains_errors()) return;  // stop at the first mal-formed instruction
 23   }
 24 }
 25 
 26 void check_operands(const line& inst) {
 27   word op = preprocess_op(inst.words.at(0));
 28   if (op.data == "0f") {
 29     check_operands_0f(inst);
 30     return;
 31   }
 32   if (op.data == "f3") {
 33     check_operands_f3(inst);
 34     return;
 35   }
 36   check_operands(inst, op);
 37 }
 38 
 39 word preprocess_op(word/*copy*/ op) {
 40   op.data = tolower(op.data.c_str());
 41   // opcodes can't be negative
 42   if (starts_with(op.data, "0x"))
 43     op.data = op.data.substr(2);
 44   if (SIZE(op.data) == 1)
 45     op.data = string("0")+op.data;
 46   return op;
 47 }
 48 
 49 void test_preprocess_op() {
 50   word w1;  w1.data = "0xf";
 51   word w2;  w2.data = "0f";
 52   CHECK_EQ(preprocess_op(w1).data, preprocess_op(w2).data);
 53 }
 54 
 55 //: To check the operands for an opcode, we'll track the permitted operands
 56 //: for each supported opcode in a bitvector. That way we can often compute the
 57 //: bitvector for each instruction's operands and compare it with the expected.
 58 
 59 :(before "End Types")
 60 enum operand_type {
 61   // start from the least significant bit
 62   MODRM,  // more complex, may also involve disp8 or disp32
 63   SUBOP,
 64   DISP8,
 65   DISP16,
 66   DISP32,
 67   IMM8,
 68   IMM32,
 69   NUM_OPERAND_TYPES
 70 };
 71 :(before "End Globals")
 72 vector<string> Operand_type_name;
 73 map<string, operand_type> Operand_type;
 74 :(before "End One-time Setup")
 75 init_op_types();
 76 :(code)
 77 void init_op_types() {
 78   assert(NUM_OPERAND_TYPES <= /*bits in a uint8_t*/8);
 79   Operand_type_name.resize(NUM_OPERAND_TYPES);
 80   #define DEF(type) Operand_type_name.at(type) = tolower(#type), put(Operand_type, tolower(#type), type);
 81   DEF(MODRM);
 82   DEF(SUBOP);
 83   DEF(DISP8);
 84   DEF(DISP16);
 85   DEF(DISP32);
 86   DEF(IMM8);
 87   DEF(IMM32);
 88   #undef DEF
 89 }
 90 
 91 :(before "End Globals")
 92 map</*op*/string, /*bitvector*/uint8_t> Permitted_operands;
 93 const uint8_t INVALID_OPERANDS = 0xff;  // no instruction uses all the operand types
 94 :(before "End One-time Setup")
 95 init_permitted_operands();
 96 :(code)
 97 void init_permitted_operands() {
 98   //// Class A: just op, no operands
 99   // halt
100   put(Permitted_operands, "f4", 0x00);
101   // inc
102   put(Permitted_operands, "40", 0x00);
103   put(Permitted_operands, "41", 0x00);
104   put(Permitted_operands, "42", 0x00);
105   put(Permitted_operands, "43", 0x00);
106   put(Permitted_operands, "44", 0x00);
107   put(Permitted_operands, "45", 0x00);
108   put(Permitted_operands, "46", 0x00);
109   put(Permitted_operands, "47", 0x00);
110   // dec
111   put(Permitted_operands, "48", 0x00);
112   put(Permitted_operands, "49", 0x00);
113   put(Permitted_operands, "4a", 0x00);
114   put(Permitted_operands, "4b", 0x00);
115   put(Permitted_operands, "4c", 0x00);
116   put(Permitted_operands, "4d", 0x00);
117   put(Permitted_operands, "4e", 0x00);
118   put(Permitted_operands, "4f", 0x00);
119   // push
120   put(Permitted_operands, "50", 0x00);
121   put(Permitted_operands, "51", 0x00);
122   put(Permitted_operands, "52", 0x00);
123   put(Permitted_operands, "53", 0x00);
124   put(Permitted_operands, "54", 0x00);
125   put(Permitted_operands, "55", 0x00);
126   put(Permitted_operands, "56", 0x00);
127   put(Permitted_operands, "57", 0x00);
128   // pop
129   put(Permitted_operands, "58", 0x00);
130   put(Permitted_operands, "59", 0x00);
131   put(Permitted_operands, "5a", 0x00);
132   put(Permitted_operands, "5b", 0x00);
133   put(Permitted_operands, "5c", 0x00);
134   put(Permitted_operands, "5d", 0x00);
135   put(Permitted_operands, "5e", 0x00);
136   put(Permitted_operands, "5f", 0x00);
137   // return
138   put(Permitted_operands, "c3", 0x00);
139 
140   //// Class B: just op and disp8
141   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
142   //  0     0     0      |0       1     0     0
143 
144   // jump
145   put(Permitted_operands, "eb", 0x04);
146   put(Permitted_operands, "74", 0x04);
147   put(Permitted_operands, "75", 0x04);
148   put(Permitted_operands, "7c", 0x04);
149   put(Permitted_operands, "7d", 0x04);
150   put(Permitted_operands, "7e", 0x04);
151   put(Permitted_operands, "7f", 0x04);
152 
153   //// Class C: just op and disp16
154   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
155   //  0     0     0      |1       0     0     0
156   put(Permitted_operands, "e9", 0x08);  // jump
157 
158   //// Class D: just op and disp32
159   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
160   //  0     0     1      |0       0     0     0
161   put(Permitted_operands, "e8", 0x10);  // call
162 
163   //// Class E: just op and imm8
164   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
165   //  0     1     0      |0       0     0     0
166   put(Permitted_operands, "cd", 0x20);  // software interrupt
167 
168   //// Class F: just op and imm32
169   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
170   //  1     0     0      |0       0     0     0
171   put(Permitted_operands, "05", 0x40);  // add
172   put(Permitted_operands, "2d", 0x40);  // subtract
173   put(Permitted_operands, "25", 0x40);  // and
174   put(Permitted_operands, "0d", 0x40);  // or
175   put(Permitted_operands, "35", 0x40);  // xor
176   put(Permitted_operands, "3d", 0x40);  // compare
177   put(Permitted_operands, "68", 0x40);  // push
178   // copy
179   put(Permitted_operands, "b8", 0x40);
180   put(Permitted_operands, "b9", 0x40);
181   put(Permitted_operands, "ba", 0x40);
182   put(Permitted_operands, "bb", 0x40);
183   put(Permitted_operands, "bc", 0x40);
184   put(Permitted_operands, "bd", 0x40);
185   put(Permitted_operands, "be", 0x40);
186   put(Permitted_operands, "bf", 0x40);
187 
188   //// Class M: using ModR/M byte
189   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
190   //  0     0     0      |0       0     0     1
191 
192   // add
193   put(Permitted_operands, "01", 0x01);
194   put(Permitted_operands, "03", 0x01);
195   // subtract
196   put(Permitted_operands, "29", 0x01);
197   put(Permitted_operands, "2b", 0x01);
198   // and
199   put(Permitted_operands, "21", 0x01);
200   put(Permitted_operands, "23", 0x01);
201   // or
202   put(Permitted_operands, "09", 0x01);
203   put(Permitted_operands, "0b", 0x01);
204   // xor
205   put(Permitted_operands, "31", 0x01);
206   put(Permitted_operands, "33", 0x01);
207   // compare
208   put(Permitted_operands, "39", 0x01);
209   put(Permitted_operands, "3b", 0x01);
210   // copy
211   put(Permitted_operands, "88", 0x01);
212   put(Permitted_operands, "89", 0x01);
213   put(Permitted_operands, "8a", 0x01);
214   put(Permitted_operands, "8b", 0x01);
215   // swap
216   put(Permitted_operands, "87", 0x01);
217   // pop
218   put(Permitted_operands, "8f", 0x01);
219 
220   //// Class O: op, ModR/M and subop (not r32)
221   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
222   //  0     0     0      |0       0     1     1
223   put(Permitted_operands, "f7", 0x03);  // test/not/mul/div
224   put(Permitted_operands, "ff", 0x03);  // jump/push/call
225 
226   //// Class N: op, ModR/M and imm32
227   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
228   //  1     0     0      |0       0     0     1
229   put(Permitted_operands, "c7", 0x41);  // copy
230 
231   //// Class P: op, ModR/M, subop (not r32) and imm32
232   //  imm32 imm8  disp32 |disp16  disp8 subop modrm
233   //  1     0     0      |0       0     1     1
234   put(Permitted_operands, "81", 0x43);  // combine
235 
236   // End Init Permitted Operands
237 }
238 
239 :(code)
240 #define HAS(bitvector, bit)  ((bitvector) & (1 << (bit)))
241 #define SET(bitvector, bit)  ((bitvector) | (1 << (bit)))
242 #define CLEAR(bitvector, bit)  ((bitvector) & (~(1 << (bit))))
243 
244 void check_operands(const line& inst, const word& op) {
245   if (!is_hex_byte(op)) return;
246   uint8_t expected_bitvector = get(Permitted_operands, op.data);
247   if (HAS(expected_bitvector, MODRM)) {
248     check_operands_modrm(inst, op);
249     compare_bitvector_modrm(inst, expected_bitvector, op);
250   }
251   else {
252     compare_bitvector(inst, expected_bitvector, op);
253   }
254 }
255 
256 //: Many instructions can be checked just by comparing bitvectors.
257 
258 void compare_bitvector(const line& inst, uint8_t expected, const word& op) {
259   if (all_hex_bytes(inst) && has_operands(inst)) return;  // deliberately programming in raw hex; we'll raise a warning elsewhere
260   uint8_t bitvector = compute_operand_bitvector(inst);
261   if (trace_contains_errors()) return;  // duplicate operand type
262   if (bitvector == expected) return;  // all good with this instruction
263   for (int i = 0;  i < NUM_OPERAND_TYPES;  ++i, bitvector >>= 1, expected >>= 1) {
264 //?     cerr << "comparing " << HEXBYTE << NUM(bitvector) << " with " << NUM(expected) << '\n';
265     if ((bitvector & 0x1) == (expected & 0x1)) continue;  // all good with this operand
266     const string& optype = Operand_type_name.at(i);
267     if ((bitvector & 0x1) > (expected & 0x1))
268       raise << "'" << to_string(inst) << "'" << maybe_name(op) << ": unexpected " << optype << " operand\n" << end();
269     else
270       raise << "'" << to_string(inst) << "'" << maybe_name(op) << ": missing " << optype << " operand\n" << end();
271     // continue giving all errors for a single instruction
272   }
273   // ignore settings in any unused bits
274 }
275 
276 string maybe_name(const word& op) {
277   if (!is_hex_byte(op)) return "";
278   if (!contains_key(name, op.data)) return "";
279   return " ("+get(name, op.data)+')';
280 }
281 
282 uint32_t compute_operand_bitvector(const line& inst) {
283   uint32_t bitvector = 0;
284   for (int i = /*skip op*/1;  i < SIZE(inst.words);  ++i) {
285     bitvector = bitvector | bitvector_for_operand(inst.words.at(i));
286     if (trace_contains_errors()) return INVALID_OPERANDS;  // duplicate operand type
287   }
288   return bitvector;
289 }
290 
291 bool has_operands(const line& inst) {
292   return SIZE(inst.words) > first_operand(inst);
293 }
294 
295 int first_operand(const line& inst) {
296   if (inst.words.at(0).data == "0f") return 2;
297   if (inst.words.at(0).data == "f2" || inst.words.at(0).data == "f3") {
298     if (inst.words.at(1).data == "0f")
299       return 3;
300     else
301       return 2;
302   }
303   return 1;
304 }
305 
306 // Scan the metadata of 'w' and return the bit corresponding to any operand type.
307 // Also raise an error if metadata contains multiple operand types.
308 uint32_t bitvector_for_operand(const word& w) {
309   uint32_t bv = 0;
310   bool found = false;
311   for (int i = 0;  i < SIZE(w.metadata);  ++i) {
312     const string& curr = w.metadata.at(i);
313     if (!contains_key(Operand_type, curr)) continue;  // ignore unrecognized metadata
314     if (found) {
315       raise << "'" << w.original << "' has conflicting operand types; it should have only one\n" << end();
316       return INVALID_OPERANDS;
317     }
318     bv = (1 << get(Operand_type, curr));
319     found = true;
320   }
321   return bv;
322 }
323 
324 :(scenario conflicting_operand_type)
325 % Hide_errors = true;
326 == 0x1
327 cd/software-interrupt 80/imm8/imm32
328 +error: '80/imm8/imm32' has conflicting operand types; it should have only one
329 
330 //: Instructions computing effective addresses have more complex rules, so
331 //: we'll hard-code a common set of instruction-decoding rules.
332 
333 :(scenario check_missing_mod_operand)
334 % Hide_errors = true;
335 == 0x1
336 81 0/add/subop       3/rm32/ebx 1/imm32
337 +error: '81 0/add/subop 3/rm32/ebx 1/imm32' (combine rm32 with imm32 based on subop): missing mod operand
338 
339 :(code)
340 void check_operands_modrm(const line& inst, const word& op) {
341   if (all_hex_bytes(inst)) return;  // deliberately programming in raw hex; we'll raise a warning elsewhere
342   check_operand_metadata_present(inst, "mod", op);
343   check_operand_metadata_present(inst, "rm32", op);
344   // no check for r32; some instructions don't use it; just assume it's 0 if missing
345   if (op.data == "81" || op.data == "8f" || op.data == "ff") {  // keep sync'd with 'help subop'
346     check_operand_metadata_present(inst, "subop", op);
347     check_operand_metadata_absent(inst, "r32", op, "should be replaced by subop");
348   }
349   if (trace_contains_errors()) return;
350   if (metadata(inst, "rm32").data != "4") return;
351   // SIB byte checks
352   uint8_t mod = hex_byte(metadata(inst, "mod").data);
353   if (mod != /*direct*/3) {
354     check_operand_metadata_present(inst, "base", op);
355     check_operand_metadata_present(inst, "index", op);  // otherwise why go to SIB?
356   }
357   else {
358     check_operand_metadata_absent(inst, "base", op, "direct mode");
359     check_operand_metadata_absent(inst, "index", op, "direct mode");
360   }
361   // no check for scale; 0 (2**0 = 1) by default
362 }
363 
364 // same as compare_bitvector, with a couple of exceptions for modrm-based instructions
365 //   exception 1: ignore modrm bit since we already checked it above
366 //   exception 2: modrm instructions can use a displacement on occasion
367 void compare_bitvector_modrm(const line& inst, uint8_t expected, const word& op) {
368   if (all_hex_bytes(inst) && has_operands(inst)) return;  // deliberately programming in raw hex; we'll raise a warning elsewhere
369   uint8_t bitvector = compute_operand_bitvector(inst);
370   if (trace_contains_errors()) return;  // duplicate operand type
371   expected = CLEAR(expected, MODRM);  // exception 1
372   if (bitvector == expected) return;  // all good with this instruction
373   for (int i = 0;  i < NUM_OPERAND_TYPES;  ++i, bitvector >>= 1, expected >>= 1) {
374 //?     cerr << "comparing for modrm " << HEXBYTE << NUM(bitvector) << " with " << NUM(expected) << '\n';
375     if ((bitvector & 0x1) == (expected & 0x1)) continue;  // all good with this operand
376     if (i == DISP8 || i == DISP32) continue;  // exception 2
377     const string& optype = Operand_type_name.at(i);
378     if ((bitvector & 0x1) > (expected & 0x1))
379       raise << "'" << to_string(inst) << "'" << maybe_name(op) << ": unexpected " << optype << " operand\n" << end();
380     else
381       raise << "'" << to_string(inst) << "'" << maybe_name(op) << ": missing " << optype << " operand\n" << end();
382     // continue giving all errors for a single instruction
383   }
384   // ignore settings in any unused bits
385 }
386 
387 void check_operand_metadata_present(const line& inst, const string& type, const word& op) {
388   if (!has_operand_metadata(inst, type))
389     raise << "'" << to_string(inst) << "' (" << get(name, op.data) << "): missing " << type << " operand\n" << end();
390 }
391 
392 void check_operand_metadata_absent(const line& inst, const string& type, const word& op, const string& msg) {
393   if (has_operand_metadata(inst, type))
394     raise << "'" << to_string(inst) << "' (" << get(name, op.data) << "): unexpected " << type << " operand (" << msg << ")\n" << end();
395 }
396 
397 :(scenarios transform)
398 :(scenario modrm_with_displacement)
399 % Reg[EAX].u = 0x1;
400 == 0x1
401 # just avoid null pointer
402 8b/copy 1/mod/lookup+disp8 0/rm32/EAX 2/r32/EDX 4/disp8  # copy *(EAX+4) to EDX
403 $error: 0
404 :(scenarios run)
405 
406 :(scenario conflicting_operands_in_modrm_instruction)
407 % Hide_errors = true;
408 == 0x1
409 01/add 0/mod 3/mod
410 +error: '01/add 0/mod 3/mod' has conflicting mod operands
411 
412 :(scenario conflicting_operand_type_modrm)
413 % Hide_errors = true;
414 == 0x1
415 01/add 0/mod 3/rm32/r32
416 +error: '3/rm32/r32' has conflicting operand types; it should have only one
417 
418 :(scenario check_missing_rm32_operand)
419 % Hide_errors = true;
420 == 0x1
421 81 0/add/subop 0/mod            1/imm32
422 +error: '81 0/add/subop 0/mod 1/imm32' (combine rm32 with imm32 based on subop): missing rm32 operand
423 
424 :(scenario check_missing_subop_operand)
425 % Hide_errors = true;
426 == 0x1
427 81             0/mod 3/rm32/ebx 1/imm32
428 +error: '81 0/mod 3/rm32/ebx 1/imm32' (combine rm32 with imm32 based on subop): missing subop operand
429 
430 :(scenario check_missing_base_operand)
431 % Hide_errors = true;
432 == 0x1
433 81 0/add/subop 0/mod/indirect 4/rm32/use-sib 1/imm32
434 +error: '81 0/add/subop 0/mod/indirect 4/rm32/use-sib 1/imm32' (combine rm32 with imm32 based on subop): missing base operand
435 
436 :(scenario check_missing_index_operand)
437 % Hide_errors = true;
438 == 0x1
439 81 0/add/subop 0/mod/indirect 4/rm32/use-sib 0/base 1/imm32
440 +error: '81 0/add/subop 0/mod/indirect 4/rm32/use-sib 0/base 1/imm32' (combine rm32 with imm32 based on subop): missing index operand
441 
442 :(scenario check_missing_base_operand_2)
443 % Hide_errors = true;
444 == 0x1
445 81 0/add/subop 0/mod/indirect 4/rm32/use-sib 2/index 3/scale 1/imm32
446 +error: '81 0/add/subop 0/mod/indirect 4/rm32/use-sib 2/index 3/scale 1/imm32' (combine rm32 with imm32 based on subop): missing base operand
447 
448 :(scenario check_base_operand_not_needed_in_direct_mode)
449 == 0x1
450 81 0/add/subop 3/mod/indirect 4/rm32/use-sib 1/imm32
451 $error: 0
452 
453 //:: similarly handle multi-byte opcodes
454 
455 :(code)
456 void check_operands_0f(const line& inst) {
457   assert(inst.words.at(0).data == "0f");
458   if (SIZE(inst.words) == 1) {
459     raise << "opcode '0f' requires a second opcode\n" << end();
460     return;
461   }
462   word op = preprocess_op(inst.words.at(1));
463   if (!contains_key(name_0f, op.data)) {
464     raise << "unknown 2-byte opcode '0f " << op.data << "'\n" << end();
465     return;
466   }
467   check_operands_0f(inst, op);
468 }
469 
470 void check_operands_f3(const line& /*unused*/) {
471   raise << "no supported opcodes starting with f3\n" << end();
472 }
473 
474 :(scenario check_missing_disp16_operand)
475 % Hide_errors = true;
476 == 0x1
477 # instruction                     effective address                                                   operand     displacement    immediate
478 # op          subop               mod             rm32          base        index         scale       r32
479 # 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
480   0f 84                                                                                                                                             # jmp if ZF to ??
481 +error: '0f 84' (jump disp16 bytes away if ZF is set): missing disp16 operand
482 
483 :(before "End Globals")
484 map</*op*/string, /*bitvector*/uint8_t> Permitted_operands_0f;
485 :(before "End Init Permitted Operands")
486 //// Class C: just op and disp16
487 //  imm32 imm8  disp32 |disp16  disp8 subop modrm
488 //  0     0     0      |1       0     0     0
489 put(Permitted_operands_0f, "84", 0x08);
490 put(Permitted_operands_0f, "85", 0x08);
491 put(Permitted_operands_0f, "8c", 0x08);
492 put(Permitted_operands_0f, "8d", 0x08);
493 put(Permitted_operands_0f, "8e", 0x08);
494 put(Permitted_operands_0f, "8f", 0x08);
495 
496 //// Class M: using ModR/M byte
497 //  imm32 imm8  disp32 |disp16  disp8 subop modrm
498 //  0     0     0      |0       0     0     1
499 put(Permitted_operands_0f, "af", 0x01);
500 
501 :(code)
502 void check_operands_0f(const line& inst, const word& op) {
503   uint8_t expected_bitvector = get(Permitted_operands_0f, op.data);
504   if (HAS(expected_bitvector, MODRM))
505     check_operands_modrm(inst, op);
506   compare_bitvector_0f(inst, CLEAR(expected_bitvector, MODRM), op);
507 }
508 
509 void compare_bitvector_0f(const line& inst, uint8_t expected, const word& op) {
510   if (all_hex_bytes(inst) && has_operands(inst)) return;  // deliberately programming in raw hex; we'll raise a warning elsewhere
511   uint8_t bitvector = compute_operand_bitvector(inst);
512   if (trace_contains_errors()) return;  // duplicate operand type
513   if (bitvector == expected) return;  // all good with this instruction
514   for (int i = 0;  i < NUM_OPERAND_TYPES;  ++i, bitvector >>= 1, expected >>= 1) {
515 //?     cerr << "comparing " << HEXBYTE << NUM(bitvector) << " with " << NUM(expected) << '\n';
516     if ((bitvector & 0x1) == (expected & 0x1)) continue;  // all good with this operand
517     const string& optype = Operand_type_name.at(i);
518     if ((bitvector & 0x1) > (expected & 0x1))
519       raise << "'" << to_string(inst) << "' (" << get(name_0f, op.data) << "): unexpected " << optype << " operand\n" << end();
520     else
521       raise << "'" << to_string(inst) << "' (" << get(name_0f, op.data) << "): missing " << optype << " operand\n" << end();
522     // continue giving all errors for a single instruction
523   }
524   // ignore settings in any unused bits
525 }
526 
527 string tolower(const char* s) {
528   ostringstream out;
529   for (/*nada*/;  *s;  ++s)
530     out << static_cast<char>(tolower(*s));
531   return out.str();
532 }
533 
534 #undef HAS
535 #undef SET
536 #undef CLEAR
537 
538 :(before "End Includes")
539 #include<cctype>