https://github.com/akkartik/mu/blob/master/subx/001help.cc
  1 //: Everything this project/binary supports.
  2 //: This should give you a sense for what to look forward to in later layers.
  3 
  4 :(before "End Commandline Parsing")
  5 if (argc <= 1 || is_equal(argv[1], "--help")) {
  6   //: this is the functionality later layers will provide
  7   // currently no automated tests for commandline arg parsing
  8   cerr << get(Help, "usage");
  9   return 0;
 10 }
 11 
 12 //: Support for option parsing.
 13 //: Options always begin with '--' and are always the first arguments. An
 14 //: option will never follow a non-option.
 15 char** arg = &argv[1];
 16 while (argc > 1 && starts_with(*arg, "--")) {
 17   if (false)
 18     ;  // no-op branch just so any further additions can consistently always start with 'else'
 19   // End Commandline Options(*arg)
 20   else
 21     cerr << "skipping unknown option " << *arg << '\n';
 22   --argc;  ++argv;  ++arg;
 23 }
 24 
 25 if (is_equal(argv[1], "help")) {
 26   if (argc == 2) {
 27     cerr << "help on what?\n";
 28     help_contents();
 29     return 0;
 30   }
 31   string key(argv[2]);
 32   // End Help Special-cases(key)
 33   if (contains_key(Help, key)) {
 34     cerr << get(Help, key);
 35     return 0;
 36   }
 37   else {
 38     cerr << "No help found for '" << key << "'\n";
 39     help_contents();
 40     cerr << "Please check your command for typos.\n";
 41     return 1;
 42   }
 43 }
 44 
 45 :(code)
 46 void help_contents() {
 47   cerr << "Available top-level topics:\n";
 48   cerr << "  usage\n";
 49   // End Help Contents
 50 }
 51 
 52 :(before "End Globals")
 53 map<string, string> Help;
 54 :(before "End Includes")
 55 #include <map>
 56 using std::map;
 57 :(before "End One-time Setup")
 58 init_help();
 59 :(code)
 60 void init_help() {
 61   put(Help, "usage",
 62     "Welcome to SubX, a better way to program in machine code.\n"
 63     "SubX uses a subset of the x86 instruction set. SubX programs will run\n"
 64     "without modification on Linux computers.\n"
 65     "It provides a better experience and better error messages than\n"
 66     "programming directly in machine code, but you have to stick to the\n"
 67     "instructions it supports.\n"
 68     "\n"
 69     "== Ways to invoke subx\n"
 70     "- Run tests:\n"
 71     "    subx test\n"
 72     "- See this message:\n"
 73     "    subx --help\n"
 74     "- Convert a textual SubX program into a standard ELF binary that you can\n"
 75     "  run on your computer:\n"
 76     "    subx translate input1.subx intput2.subx ... -o <output ELF binary>\n"
 77     "- Run a SubX binary using SubX itself (for better error messages):\n"
 78     "    subx run <ELF binary>\n"
 79     "\n"
 80     "== Debugging aids\n"
 81     "- Add '--trace' to any of these commands to print a trace to stderr\n"
 82     "  for debugging purposes.\n"
 83     "- Add '--map' to add information to traces. 'subx --map translate' will save\n"
 84     "  (to a file called 'map') the mapping from labels to addresses that it computes\n"
 85     "  during translation. This file is then available to 'subx --map --trace run'\n"
 86     "  which prints out label names in the trace as it encounters them.\n"
 87     "\n"
 88     "Options starting with '--' must always come before any other arguments.\n"
 89     "\n"
 90     "To start learning how to write SubX programs, see Readme.md (particularly\n"
 91     "the section on the x86 instruction set) and then run:\n"
 92     "  subx help\n"
 93   );
 94   // End Help Texts
 95 }
 96 
 97 :(code)
 98 bool is_equal(char* s, const char* lit) {
 99   return strncmp(s, lit, strlen(lit)) == 0;
100 }
101 
102 bool starts_with(const string& s, const string& pat) {
103   string::const_iterator a=s.begin(), b=pat.begin();
104   for (/*nada*/;  a!=s.end() && b!=pat.end();  ++a, ++b)
105     if (*a != *b) return false;
106   return b == pat.end();
107 }
108 
109 //: I'll throw some style conventions here for want of a better place for them.
110 //: As a rule I hate style guides. Do what you want, that's my motto. But since
111 //: we're dealing with C/C++, the one big thing we want to avoid is undefined
112 //: behavior. If a compiler ever encounters undefined behavior it can make
113 //: your program do anything it wants.
114 //:
115 //: For reference, my checklist of undefined behaviors to watch out for:
116 //:   out-of-bounds access
117 //:   uninitialized variables
118 //:   use after free
119 //:   dereferencing invalid pointers: null, a new of size 0, others
120 //:
121 //:   casting a large number to a type too small to hold it
122 //:
123 //:   integer overflow
124 //:   division by zero and other undefined expressions
125 //:   left-shift by negative count
126 //:   shifting values by more than or equal to the number of bits they contain
127 //:   bitwise operations on signed numbers
128 //:
129 //:   Converting pointers to types of different alignment requirements
130 //:     T* -> void* -> T*: defined
131 //:     T* -> U* -> T*: defined if non-function pointers and alignment requirements are same
132 //:     function pointers may be cast to other function pointers
133 //:
134 //:       Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast)
135 //:
136 //: To guard against these, some conventions:
137 //:
138 //: 0. Initialize all primitive variables in functions and constructors.
139 //:
140 //: 1. Minimize use of pointers and pointer arithmetic. Avoid 'new' and
141 //: 'delete' as far as possible. Rely on STL to perform memory management to
142 //: avoid use-after-free issues (and memory leaks).
143 //:
144 //: 2. Avoid naked arrays to avoid out-of-bounds access. Never use operator[]
145 //: except with map. Use at() with STL vectors and so on.
146 //:
147 //: 3. Valgrind all the things.
148 //:
149 //: 4. Avoid unsigned numbers. Not strictly an undefined-behavior issue, but
150 //: the extra range doesn't matter, and it's one less confusing category of
151 //: interaction gotchas to worry about.
152 //:
153 //: Corollary: don't use the size() method on containers, since it returns an
154 //: unsigned and that'll cause warnings about mixing signed and unsigned,
155 //: yadda-yadda. Instead use this macro below to perform an unsafe cast to
156 //: signed. We'll just give up immediately if a container's ever too large.
157 //: Basically, Mu is not concerned about this being a little slower than it
158 //: could be. (https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759de5a7)
159 //:
160 //: Addendum to corollary: We're going to uniformly use int everywhere, to
161 //: indicate that we're oblivious to number size, and since Clang on 32-bit
162 //: platforms doesn't yet support multiplication over 64-bit integers, and
163 //: since multiplying two integers seems like a more common situation to end
164 //: up in than integer overflow.
165 :(before "End Includes")
166 #define SIZE(X) (assert((X).size() < (1LL<<(sizeof(int)*8-2))), static_cast<int>((X).size()))
167 
168 //: 5. Integer overflow is guarded against at runtime using the -ftrapv flag
169 //: to the compiler, supported by Clang (GCC version only works sometimes:
170 //: http://stackoverflow.com/questions/20851061/how-to-make-gcc-ftrapv-work).
171 :(before "atexit(reset)")
172 initialize_signal_handlers();  // not always necessary, but doesn't hurt
173 //? cerr << INT_MAX+1 << '\n';  // test overflow
174 //? assert(false);  // test SIGABRT
175 :(code)
176 // based on https://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c
177 void initialize_signal_handlers() {
178   struct sigaction action;
179   bzero(&action, sizeof(action));
180   action.sa_sigaction = dump_and_exit;
181   sigemptyset(&action.sa_mask);
182   sigaction(SIGABRT, &action, NULL);  // assert() failure or integer overflow on linux (with -ftrapv)
183   sigaction(SIGILL,  &action, NULL);  // integer overflow on OS X (with -ftrapv)
184 }
185 void dump_and_exit(int sig, siginfo_t* /*unused*/, void* /*unused*/) {
186   switch (sig) {
187     case SIGABRT:
188       #ifndef __APPLE__
189         cerr << "SIGABRT: might be an integer overflow if it wasn't an assert() failure\n";
190         _Exit(1);
191       #endif
192       break;
193     case SIGILL:
194       #ifdef __APPLE__
195         cerr << "SIGILL: most likely caused by integer overflow\n";
196         _Exit(1);
197       #endif
198       break;
199     default:
200       break;
201   }
202 }
203 :(before "End Includes")
204 #include <signal.h>
205 
206 //: For good measure we'll also enable SIGFPE.
207 :(before "atexit(reset)")
208 feenableexcept(FE_OVERFLOW | FE_UNDERFLOW);
209 //? assert(sizeof(int) == 4 && sizeof(float) == 4);
210 //? //                          | exp   |  mantissa
211 //? int smallest_subnormal = 0b00000000000000000000000000000001;
212 //? float smallest_subnormal_f = *reinterpret_cast<float*>(&smallest_subnormal);
213 //? cerr << "ε: " << smallest_subnormal_f << '\n';
214 //? cerr << "ε/2: " << smallest_subnormal_f/2 << " (underflow)\n";  // test SIGFPE
215 :(before "End Includes")
216 #include <fenv.h>
217 :(code)
218 #ifdef __APPLE__
219 // Public domain polyfill for feenableexcept on OS X
220 // http://www-personal.umich.edu/~williams/archive/computation/fe-handling-example.c
221 int feenableexcept(unsigned int excepts) {
222   static fenv_t fenv;
223   unsigned int new_excepts = excepts & FE_ALL_EXCEPT;
224   unsigned int old_excepts;
225   if (fegetenv(&fenv)) return -1;
226   old_excepts = fenv.__control & FE_ALL_EXCEPT;
227   fenv.__control &= ~new_excepts;
228   fenv.__mxcsr &= ~(new_excepts << 7);
229   return fesetenv(&fenv) ? -1 : old_excepts;
230 }
231 #endif
232 
233 //: 6. Map's operator[] being non-const is fucking evil.
234 :(before "Globals")  // can't generate prototypes for these
235 // from http://stackoverflow.com/questions/152643/idiomatic-c-for-reading-from-a-const-map
236 template<typename T> typename T::mapped_type& get(T& map, typename T::key_type const& key) {
237   typename T::iterator iter(map.find(key));
238   if (iter == map.end()) {
239     cerr << "get couldn't find key '" << key << "'\n";
240     assert(iter != map.end());
241   }
242   return iter->second;
243 }
244 template<typename T> typename T::mapped_type const& get(const T& map, typename T::key_type const& key) {
245   typename T::const_iterator iter(map.find(key));
246   if (iter == map.end()) {
247     cerr << "get couldn't find key '" << key << "'\n";
248     assert(iter != map.end());
249   }
250   return iter->second;
251 }
252 template<typename T> typename T::mapped_type const& put(T& map, typename T::key_type const& key, typename T::mapped_type const& value) {
253   map[key] = value;
254   return map[key];
255 }
256 template<typename T> bool contains_key(T& map, typename T::key_type const& key) {
257   return map.find(key) != map.end();
258 }
259 template<typename T> typename T::mapped_type& get_or_insert(T& map, typename T::key_type const& key) {
260   return map[key];
261 }
262 template<typename T> typename T::mapped_type const& put_new(T& map, typename T::key_type const& key, typename T::mapped_type const& value) {
263   assert(map.find(key) == map.end());
264   map[key] = value;
265   return map[key];
266 }
267 //: The contract: any container that relies on get_or_insert should never call
268 //: contains_key.
269 
270 //: 7. istreams are a royal pain in the arse. You have to be careful about
271 //: what subclass you try to putback into. You have to watch out for the pesky
272 //: failbit and badbit. Just avoid eof() and use this helper instead.
273 :(code)
274 bool has_data(istream& in) {
275   return in && !in.eof();
276 }
277 
278 :(before "End Includes")
279 #include <assert.h>
280 
281 #include <iostream>
282 using std::istream;
283 using std::ostream;
284 using std::iostream;
285 using std::cin;
286 using std::cout;
287 using std::cerr;
288 #include <iomanip>
289 
290 #include <string.h>
291 #include <string>
292 using std::string;
293 
294 #include <algorithm>
295 using std::min;
296 using std::max;