1
2
3 :(scenario check_bitfield_sizes)
4 % Hide_errors = true;
5 == 0x1
6 01/add 4/mod
7 +error: '4/mod' too large to fit in bitfield mod
8
9 :(before "End Globals")
10 map<string, uint32_t> Operand_bound;
11 :(before "End One-time Setup")
12 put(Operand_bound, "subop", 1<<3);
13 put(Operand_bound, "mod", 1<<2);
14 put(Operand_bound, "rm32", 1<<3);
15 put(Operand_bound, "base", 1<<3);
16 put(Operand_bound, "index", 1<<3);
17 put(Operand_bound, "scale", 1<<2);
18 put(Operand_bound, "r32", 1<<3);
19 put(Operand_bound, "disp8", 1<<8);
20 put(Operand_bound, "disp16", 1<<16);
21
22 put(Operand_bound, "imm8", 1<<8);
23
24
25 :(before "End Transforms")
26 Transform.push_back(check_operand_bounds);
27 :(code)
28 void check_operand_bounds( program& p) {
29 trace(99, "transform") << "-- check operand bounds" << end();
30 if (p.segments.empty()) return;
31 const segment& code = p.segments.at(0);
32 for (int i = 0; i < SIZE(code.lines); ++i) {
33 const line& inst = code.lines.at(i);
34 for (int j = first_operand(inst); j < SIZE(inst.words); ++j)
35 check_operand_bounds(inst.words.at(j));
36 if (trace_contains_errors()) return;
37 }
38 }
39
40 void check_operand_bounds(const word& w) {
41 for (map<string, uint32_t>::iterator p = Operand_bound.begin(); p != Operand_bound.end(); ++p) {
42 if (!has_metadata(w, p->first)) continue;
43 if (!is_hex_int(w.data)) continue;
44 int32_t x = parse_int(w.data);
45 if (x >= 0) {
46 if (static_cast<uint32_t>(x) >= p->second)
47 raise << "'" << w.original << "' too large to fit in bitfield " << p->first << '\n' << end();
48 }
49 else {
50
51 if (x < -1*static_cast<int32_t>(p->second/2))
52 raise << "'" << w.original << "' too large to fit in bitfield " << p->first << '\n' << end();
53 }
54 }
55 }
56
57 bool is_hex_int(const string& s) {
58 if (s.empty()) return false;
59 size_t pos = 0;
60 if (s.at(0) == '-' || s.at(0) == '+') pos++;
61 if (s.substr(pos, pos+2) == "0x") pos += 2;
62 return s.find_first_not_of("0123456789abcdefABCDEF", pos) == string::npos;
63 }
64
65 int32_t parse_int(const string& s) {
66 istringstream in(s);
67 int32_t result = 0;
68 in >> std::hex >> result;
69 if (!in || !in.eof()) {
70 raise << "not a number: " << s << '\n' << end();
71 return 0;
72 }
73 return result;
74 }