about summary refs log blame commit diff stats
path: root/001help.cc
blob: 87466acd976f667182609834ff223e598a9aaf8f (plain) (tree)
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#!/bin/sh

./configure CFLAGS='-g3 -O0' CXXFLAGS='-g3 -O0'
re>
6e1eeeeb ^
9e5e87ca ^
6e1eeeeb ^
9e5e87ca ^
6e1eeeeb ^

9e5e87ca ^
6e1eeeeb ^
9e5e87ca ^
300aa167 ^




6e1eeeeb ^

55628fb6 ^

d260b017 ^


6e1eeeeb ^




9e5e87ca ^
6e1eeeeb ^



b39ceb27 ^
49ed062c ^



b39ceb27 ^

d4030624 ^
ae08e30e ^
6c96a437 ^
ae08e30e ^

d4030624 ^

5a702544 ^















































863f52e8 ^

b24eb476 ^
863f52e8 ^




ac0e9db5 ^
b24eb476 ^
c58e2368 ^
23679883 ^
5b5ef63b ^

6573fe1f ^
5b5ef63b ^






df37108f ^
5b5ef63b ^



5b5ef63b ^
1a33d221 ^
5b5ef63b ^


6e1eeeeb ^
5b5ef63b ^








5b5ef63b ^





c58e2368 ^
795f5244 ^




6e1eeeeb ^



795f5244 ^

91abd257 ^

6e1eeeeb ^



91abd257 ^

795f5244 ^
6e1eeeeb ^

795f5244 ^
f3760b0f ^





6e1eeeeb ^




f3760b0f ^

c58e2368 ^
08cf048f ^


c58e2368 ^
08cf048f ^


ac0e9db5 ^
b39ceb27 ^
385ff136 ^
d98e1a18 ^
385ff136 ^
b39ceb27 ^





385ff136 ^
b39ceb27 ^
10f415a6 ^
385ff136 ^
b39ceb27 ^
fd72ec75 ^
514f0e34 ^


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


                                                                             

                                               
                                                         
                                                             
                             


           


                                                                         






                                                                                              
                          

 




































                                                     



                                                                        
        
                                   
                           
                            

                                                                                
                                                                                  
                                                                          
                                      




                                                       

                         

                                                                                    


                                                                                




                                                                                 
                        



                   
       



                                               

 
                                                      
                                                    
                                                        

                               

 















































                                                                                                                                

                                                                                 
   




                                                                            
                        
                                                                                             
 
                                                                            

                                                                             
                         






                                                                              
                                 



                                                                                                     
 
                                                                      


                       
                                                                                           








                                                                   





                        
 




                                                                                            



                                                      

                      

                                                                                                        



                                                      

                      
                                                                                                                                        

                   
 





                                                                                                      




                                                                                                                                            

                                                                              
 


                                                                              
       


                            
 
                        
                   
 
                   





                    
                  
 
                   
                 
                  
 


                    
//: Everything this project/binary supports.
//: This should give you a sense for what to look forward to in later layers.

:(before "End Commandline Parsing")
if (argc <= 1 || is_equal(argv[1], "--help")) {
  //: this is the functionality later layers will provide
  // currently no automated tests for commandline arg parsing
  cerr << get(Help, "usage");
  return 0;
}

//: Support for option parsing.
//: Options always begin with '--' and are always the first arguments. An
//: option will never follow a non-option.
char** arg = &argv[1];
while (argc > 1 && starts_with(*arg, "--")) {
  if (false)
    ;  // no-op branch just so any further additions can consistently always start with 'else'
  // End Commandline Options(*arg)
  else
    cerr << "skipping unknown option " << *arg << '\n';
  --argc;  ++argv;  ++arg;
}

if (is_equal(argv[1], "help")) {
  if (argc == 2) {
    cerr << "help on what?\n";
    help_contents();
    return 0;
  }
  string key(argv[2]);
  // End Help Special-cases(key)
  if (contains_key(Help, key)) {
    cerr << get(Help, key);
    return 0;
  }
  else {
    cerr << "No help found for '" << key << "'\n";
    help_contents();
    cerr << "Please check your command for typos.\n";
    return 1;
  }
}

:(code)
void help_contents() {
  cerr << "Available top-level topics:\n";
  cerr << "  usage\n";
  // End Help Contents
}

:(before "End Globals")
map<string, string> Help;
:(before "End Includes")
#include <map>
using std::map;
:(before "End One-time Setup")
init_help();
:(code)
void init_help() {
  put(Help, "usage",
    "bootstrap: the bootstrap translator for SubX.\n"
    "This program also wraps some miscellaneous useful functionality:\n"
    "  - an x86 emulator: `bootstrap run`\n"
    "  - online help: `bootstrap help`\n"
    "\n"
    "== Ways to invoke bootstrap\n"
    "- See this message:\n"
    "    bootstrap --help\n"
    "- Convert a textual SubX program into a standard ELF binary that you can\n"
    "  run on your computer:\n"
    "    bootstrap translate input1.subx input2.subx ... -o <output ELF binary>\n"
    "- Run a SubX binary using SubX itself (for better error messages):\n"
    "    bootstrap run <ELF binary>\n"
    "- Run all bootstrap's unit tests:\n"
    "    bootstrap test\n"
    "- Run a single unit test:\n"
    "    bootstrap test <test name>\n"
    "     e.g. bootstrap test test_copy_imm32_to_EAX\n"
    "\n"
    "== Debugging aids\n"
    "- Add '--trace' to any of these commands to save a trace to disk at the end.\n"
    "  This can run out of memory for long-running commands.\n"
    "- Add '--debug' to emit additional debug information during translation.\n"
    "  'bootstrap --debug translate' will save metadata to disk that\n"
    "  'bootstrap --trace run' uses to make traces more informative.\n"
    "\n"
    "Options starting with '--' must always come before any other arguments.\n"
    "\n"
    "To start learning how to write SubX programs, see Readme.md (particularly\n"
    "the section on the x86 instruction set) and then run:\n"
    "  bootstrap help\n"
  );
  // End Help Texts
}

:(code)
bool is_equal(const char* s, const char* lit) {
  size_t len = strlen(lit);
  if (strlen(s) != len) return false;
  return strncmp(s, lit, len) == 0;
}

bool starts_with(const string& s, const string& pat) {
  string::const_iterator a=s.begin(), b=pat.begin();
  for (/*nada*/;  a!=s.end() && b!=pat.end();  ++a, ++b)
    if (*a != *b) return false;
  return b == pat.end();
}

//: I'll throw some style conventions here for want of a better place for them.
//: As a rule I hate style guides. Do what you want, that's my motto. But since
//: we're dealing with C/C++, the one big thing we want to avoid is undefined
//: behavior. If a compiler ever encounters undefined behavior it can make
//: your program do anything it wants.
//:
//: For reference, my checklist of undefined behaviors to watch out for:
//:   out-of-bounds access
//:   uninitialized variables
//:   use after free
//:   dereferencing invalid pointers: null, a new of size 0, others
//:
//:   casting a large number to a type too small to hold it
//:
//:   integer overflow
//:   division by zero and other undefined expressions
//:   left-shift by negative count
//:   shifting values by more than or equal to the number of bits they contain
//:   bitwise operations on signed numbers
//:
//:   Converting pointers to types of different alignment requirements
//:     T* -> void* -> T*: defined
//:     T* -> U* -> T*: defined if non-function pointers and alignment requirements are same
//:     function pointers may be cast to other function pointers
//:
//:       Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast)
//:
//: To guard against these, some conventions:
//:
//: 0. Initialize all primitive variables in functions and constructors.
//:
//: 1. Minimize use of pointers and pointer arithmetic. Avoid 'new' and
//: 'delete' as far as possible. Rely on STL to perform memory management to
//: avoid use-after-free issues (and memory leaks).
//:
//: 2. Avoid naked arrays to avoid out-of-bounds access. Never use operator[]
//: except with map. Use at() with STL vectors and so on.
//:
//: 3. Valgrind all the things.
//:
//: 4. Avoid unsigned numbers. Not strictly an undefined-behavior issue, but
//: the extra range doesn't matter, and it's one less confusing category of
//: interaction gotchas to worry about.
//:
//: Corollary: don't use the size() method on containers, since it returns an
//: unsigned and that'll cause warnings about mixing signed and unsigned,
//: yadda-yadda. Instead use this macro below to perform an unsafe cast to
//: signed. We'll just give up immediately if a container's ever too large.
//: Basically, Mu is not concerned about this being a little slower than it
//: could be. (https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759de5a7)
//:
//: Addendum to corollary: We're going to uniformly use int everywhere, to
//: indicate that we're oblivious to number size, and since Clang on 32-bit
//: platforms doesn't yet support multiplication over 64-bit integers, and
//: since multiplying two integers seems like a more common situation to end
//: up in than integer overflow.
:(before "End Includes")
#define SIZE(X) (assert((X).size() < (1LL<<(sizeof(int)*8-2))), static_cast<int>((X).size()))

//: 5. Integer overflow is guarded against at runtime using the -ftrapv flag
//: to the compiler, supported by Clang (GCC version only works sometimes:
//: http://stackoverflow.com/questions/20851061/how-to-make-gcc-ftrapv-work).
:(before "atexit(reset)")
initialize_signal_handlers();  // not always necessary, but doesn't hurt
//? cerr << INT_MAX+1 << '\n';  // test overflow
//? assert(false);  // test SIGABRT
:(code)
// based on https://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c
void initialize_signal_handlers() {
  struct sigaction action;
  bzero(&action, sizeof(action));
  action.sa_sigaction = dump_and_exit;
  sigemptyset(&action.sa_mask);
  sigaction(SIGABRT, &action, NULL);  // assert() failure or integer overflow on linux (with -ftrapv)
  sigaction(SIGILL,  &action, NULL);  // integer overflow on OS X (with -ftrapv)
}
void dump_and_exit(int sig, siginfo_t* /*unused*/, void* /*unused*/) {
  switch (sig) {
    case SIGABRT:
      #ifndef __APPLE__
        cerr << "SIGABRT: might be an integer overflow if it wasn't an assert() failure\n";
        _Exit(1);
      #endif
      break;
    case SIGILL:
      #ifdef __APPLE__
        cerr << "SIGILL: most likely caused by integer overflow\n";
        _Exit(1);
      #endif
      break;
    default:
      break;
  }
}
:(before "End Includes")
#include <signal.h>

//: 6. Map's operator[] being non-const is fucking evil.
:(before "Globals")  // can't generate prototypes for these
// from http://stackoverflow.com/questions/152643/idiomatic-c-for-reading-from-a-const-map
template<typename T> typename T::mapped_type& get(T& map, typename T::key_type const& key) {
  typename T::iterator iter(map.find(key));
  if (iter == map.end()) {
    cerr << "get couldn't find key '" << key << "'\n";
    assert(iter != map.end());
  }
  return iter->second;
}
template<typename T> typename T::mapped_type const& get(const T& map, typename T::key_type const& key) {
  typename T::const_iterator iter(map.find(key));
  if (iter == map.end()) {
    cerr << "get couldn't find key '" << key << "'\n";
    assert(iter != map.end());
  }
  return iter->second;
}
template<typename T> typename T::mapped_type const& put(T& map, typename T::key_type const& key, typename T::mapped_type const& value) {
  map[key] = value;
  return map[key];
}
template<typename T> bool contains_key(T& map, typename T::key_type const& key) {
  return map.find(key) != map.end();
}
template<typename T> typename T::mapped_type& get_or_insert(T& map, typename T::key_type const& key) {
  return map[key];
}
template<typename T> typename T::mapped_type const& put_new(T& map, typename T::key_type const& key, typename T::mapped_type const& value) {
  assert(map.find(key) == map.end());
  map[key] = value;
  return map[key];
}
//: The contract: any container that relies on get_or_insert should never call
//: contains_key.

//: 7. istreams are a royal pain in the arse. You have to be careful about
//: what subclass you try to putback into. You have to watch out for the pesky
//: failbit and badbit. Just avoid eof() and use this helper instead.
:(code)
bool has_data(istream& in) {
  return in && !in.eof();
}

:(before "End Includes")
#include <assert.h>

#include <iostream>
using std::istream;
using std::ostream;
using std::iostream;
using std::cin;
using std::cout;
using std::cerr;
#include <iomanip>

#include <string.h>
#include <string>
using std::string;

#include <algorithm>
using std::min;
using std::max;