source: src/main.cc @ 84118d8

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 84118d8 was 0afffee, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

update stack trace on cfa error

  • Property mode set to 100644
File size: 13.2 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// main.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Fri May 15 23:12:02 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sun Oct 30 10:11:38 2016
13// Update Count     : 435
14//
15
16#include <iostream>
17#include <fstream>
18#include <signal.h>                                                                             // signal
19#include <getopt.h>                                                                             // getopt
20#include <execinfo.h>                                                                   // backtrace, backtrace_symbols
21#include <cxxabi.h>                                                                             // __cxa_demangle
22#include <cstring>                                                                              // index
23
24using namespace std;
25
26#include "Parser/lex.h"
27#include "Parser/parser.h"
28#include "Parser/TypedefTable.h"
29#include "GenPoly/Lvalue.h"
30#include "GenPoly/Specialize.h"
31#include "GenPoly/Box.h"
32#include "GenPoly/CopyParams.h"
33#include "GenPoly/InstantiateGeneric.h"
34#include "CodeGen/Generate.h"
35#include "CodeGen/FixNames.h"
36#include "ControlStruct/Mutate.h"
37#include "SymTab/Validate.h"
38#include "ResolvExpr/AlternativePrinter.h"
39#include "ResolvExpr/Resolver.h"
40#include "MakeLibCfa.h"
41#include "InitTweak/GenInit.h"
42#include "InitTweak/FixInit.h"
43#include "Common/UnimplementedError.h"
44#include "../config.h"
45
46using namespace std;
47
48#define OPTPRINT(x) if ( errorp ) cerr << x << endl;
49
50
51LinkageSpec::Spec linkage = LinkageSpec::Cforall;
52TypedefTable typedefTable;
53DeclarationNode * parseTree = nullptr;                                  // program parse tree
54
55extern int yydebug;                                                                             // set for -g flag (Grammar)
56bool
57        astp = false,
58        bresolvep = false,
59        bboxp = false,
60        ctorinitp = false,
61        exprp = false,
62        expraltp = false,
63        libcfap = false,
64        nopreludep = false,
65        noprotop = false,
66        parsep = false,
67        resolvep = false,                                                                       // used in AlternativeFinder
68        symtabp = false,
69        treep = false,
70        validp = false,
71        errorp = false,
72        codegenp = false;
73
74static void parse_cmdline( int argc, char *argv[], const char *& filename );
75static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
76static void dump( list< Declaration * > & translationUnit, ostream & out = cout );
77
78static void backtrace( int start ) {                                    // skip first N stack frames
79        enum { Frames = 50 };
80        void * array[Frames];
81        int size = ::backtrace( array, Frames );
82        char ** messages = ::backtrace_symbols( array, size ); // does not demangle names
83
84        *index( messages[0], '(' ) = '\0';                                      // find executable name
85        cerr << "Stack back trace for: " << messages[0] << endl;
86
87        // skip last 2 stack frames after main
88        for ( int i = start; i < size - 2 && messages != nullptr; i += 1 ) {
89                char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
90                for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
91                        if ( *p == '(' ) {
92                                mangled_name = p;
93                        } else if ( *p == '+' ) {
94                                offset_begin = p;
95                        } else if ( *p == ')' ) {
96                                offset_end = p;
97                                break;
98                        } // if
99                } // for
100
101                // if line contains symbol, attempt to demangle
102                int frameNo = i - start;
103                if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
104                        *mangled_name++ = '\0';                                         // delimit strings
105                        *offset_begin++ = '\0';
106                        *offset_end++ = '\0';
107
108                        int status;
109                        char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
110                        // bug in __cxa_demangle for single-character lower-case non-mangled names
111                        if ( status == 0 ) {                                            // demangling successful ?
112                                cerr << "(" << frameNo << ") " << messages[i] << " : "
113                                         << real_name << "+" << offset_begin << offset_end << endl;
114                        } else {                                                                        // otherwise, output mangled name
115                                cerr << "(" << frameNo << ") " << messages[i] << " : "
116                                         << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
117                        } // if
118
119                        free( real_name );
120                } else {                                                                                // otherwise, print the whole line
121                        cerr << "(" << frameNo << ") " << messages[i] << endl;
122                } // if
123        } // for
124
125        free( messages );
126} // backtrace
127
128void sigSegvBusHandler( int sig_num ) {
129        cerr << "*CFA runtime error* program cfa-cpp terminated with "
130                 <<     (sig_num == SIGSEGV ? "segment fault" : "bus error")
131                 << "." << endl;
132        backtrace( 2 );                                                                         // skip first 2 stack frames
133        exit( EXIT_FAILURE );
134} // sigSegvBusHandler
135
136void sigAbortHandler( int sig_num ) {
137        backtrace( 6 );                                                                         // skip first 6 stack frames
138        signal( SIGABRT, SIG_DFL);                                                      // reset default signal handler
139    raise( SIGABRT );                                                                   // reraise SIGABRT
140} // sigAbortHandler
141
142
143int main( int argc, char * argv[] ) {
144        FILE * input;                                                                           // use FILE rather than istream because yyin is FILE
145        ostream *output = & cout;
146        const char *filename = nullptr;
147        list< Declaration * > translationUnit;
148
149        signal( SIGSEGV, sigSegvBusHandler );
150        signal( SIGBUS, sigSegvBusHandler );
151        signal( SIGABRT, sigAbortHandler );
152
153        parse_cmdline( argc, argv, filename );                          // process command-line arguments
154
155        try {
156                // choose to read the program from a file or stdin
157                if ( optind < argc ) {                                                  // any commands after the flags ? => input file name
158                        input = fopen( argv[ optind ], "r" );
159                        assertf( input, "cannot open %s\n", argv[ optind ] );
160                        // if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
161                        if ( filename == nullptr ) filename = argv[ optind ];
162                        // prelude filename comes in differently
163                        if ( libcfap ) filename = "prelude.cf";
164                        optind += 1;
165                } else {                                                                                // no input file name
166                        input = stdin;
167                        // if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
168                        // a fake name along
169                        if ( filename == nullptr ) filename = "stdin";
170                } // if
171
172                if ( optind < argc ) {                                                  // any commands after the flags and input file ? => output file name
173                        output = new ofstream( argv[ optind ] );
174                } // if
175
176                // read in the builtins, extras, and the prelude
177                if ( ! nopreludep ) {                                                   // include gcc builtins
178                        // -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
179                        FILE * builtins = fopen( libcfap | treep ? "builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
180                        assertf( builtins, "cannot open builtins.cf\n" );
181                        parse( builtins, LinkageSpec::Compiler );
182
183                        // read the extra prelude in, if not generating the cfa library
184                        FILE * extras = fopen( libcfap | treep ? "extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
185                        assertf( extras, "cannot open extras.cf\n" );
186                        parse( extras, LinkageSpec::C );
187
188                        if ( ! libcfap ) {
189                                // read the prelude in, if not generating the cfa library
190                                FILE * prelude = fopen( treep ? "prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
191                                assertf( prelude, "cannot open prelude.cf\n" );
192                                parse( prelude, LinkageSpec::Intrinsic );
193                        } // if
194                } // if
195
196                parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );
197
198                if ( parsep ) {
199                        parseTree->printList( cout );
200                        delete parseTree;
201                        return 0;
202                } // if
203
204                buildList( parseTree, translationUnit );
205                delete parseTree;
206                parseTree = nullptr;
207
208                if ( astp ) {
209                        dump( translationUnit );
210                        return 0;
211                } // if
212
213                // add the assignment statement after the initialization of a type parameter
214                OPTPRINT( "validate" )
215                SymTab::validate( translationUnit, symtabp );
216                if ( symtabp ) {
217                        deleteAll( translationUnit );
218                        return 0;
219                } // if
220
221                if ( expraltp ) {
222                        ResolvExpr::AlternativePrinter printer( cout );
223                        acceptAll( translationUnit, printer );
224                        return 0;
225                } // if
226
227                if ( validp ) {
228                        dump( translationUnit );
229                        return 0;
230                } // if
231
232                OPTPRINT( "mutate" )
233                ControlStruct::mutate( translationUnit );
234                OPTPRINT( "fixNames" )
235                CodeGen::fixNames( translationUnit );
236                OPTPRINT( "tweakInit" )
237                InitTweak::genInit( translationUnit );
238
239                if ( libcfap ) {
240                        // generate the bodies of cfa library functions
241                        LibCfa::makeLibCfa( translationUnit );
242                } // if
243
244                if ( bresolvep ) {
245                        dump( translationUnit );
246                        return 0;
247                } // if
248
249                OPTPRINT( "resolve" )
250                ResolvExpr::resolve( translationUnit );
251                if ( exprp ) {
252                        dump( translationUnit );
253                        return 0;
254                } // if
255
256                // fix ObjectDecl - replaces ConstructorInit nodes
257                OPTPRINT( "fixInit" )
258                InitTweak::fix( translationUnit, filename, libcfap || treep );
259                if ( ctorinitp ) {
260                        dump ( translationUnit );
261                        return 0;
262                } // if
263
264                OPTPRINT("instantiateGenerics")
265                GenPoly::instantiateGeneric( translationUnit );
266                OPTPRINT( "copyParams" );
267                GenPoly::copyParams( translationUnit );
268                OPTPRINT( "convertSpecializations" )
269                GenPoly::convertSpecializations( translationUnit );
270                OPTPRINT( "convertLvalue" )
271                GenPoly::convertLvalue( translationUnit );
272
273                if ( bboxp ) {
274                        dump( translationUnit );
275                        return 0;
276                } // if
277                OPTPRINT( "box" )
278                GenPoly::box( translationUnit );
279
280                // print tree right before code generation
281                if ( codegenp ) {
282                        dump( translationUnit );
283                        return 0;
284                } // if
285
286                CodeGen::generate( translationUnit, *output, ! noprotop );
287
288                if ( output != &cout ) {
289                        delete output;
290                } // if
291        } catch ( SemanticError &e ) {
292                if ( errorp ) {
293                        cerr << "---AST at error:---" << endl;
294                        dump( translationUnit, cerr );
295                        cerr << endl << "---End of AST, begin error message:---\n" << endl;
296                } // if
297                e.print( cerr );
298                if ( output != &cout ) {
299                        delete output;
300                } // if
301                return 1;
302        } catch ( UnimplementedError &e ) {
303                cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
304                if ( output != &cout ) {
305                        delete output;
306                } // if
307                return 1;
308        } catch ( CompilerError &e ) {
309                cerr << "Compiler Error: " << e.get_what() << endl;
310                cerr << "(please report bugs to " << endl;
311                if ( output != &cout ) {
312                        delete output;
313                } // if
314                return 1;
315        } // try
316
317        deleteAll( translationUnit );
318        return 0;
319} // main
320
321void parse_cmdline( int argc, char * argv[], const char *& filename ) {
322        enum { Ast, Bbox, Bresolver, CtorInitFix, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, Validate, };
323
324        static struct option long_opts[] = {
325                { "ast", no_argument, 0, Ast },
326                { "before-box", no_argument, 0, Bbox },
327                { "before-resolver", no_argument, 0, Bresolver },
328                { "ctorinitfix", no_argument, 0, CtorInitFix },
329                { "expr", no_argument, 0, Expr },
330                { "expralt", no_argument, 0, ExprAlt },
331                { "grammar", no_argument, 0, Grammar },
332                { "libcfa", no_argument, 0, LibCFA },
333                { "no-preamble", no_argument, 0, Nopreamble },
334                { "parse", no_argument, 0, Parse },
335                { "no-prototypes", no_argument, 0, Prototypes },
336                { "resolver", no_argument, 0, Resolver },
337                { "symbol", no_argument, 0, Symbol },
338                { "tree", no_argument, 0, Tree },
339                { "validate", no_argument, 0, Validate },
340                { 0, 0, 0, 0 }
341        }; // long_opts
342        int long_index;
343
344        opterr = 0;                                                                                     // (global) prevent getopt from printing error messages
345
346        int c;
347        while ( (c = getopt_long( argc, argv, "abBcefglnpqrstvyzD:F:", long_opts, &long_index )) != -1 ) {
348                switch ( c ) {
349                  case Ast:
350                  case 'a':                                                                             // dump AST
351                        astp = true;
352                        break;
353                  case Bresolver:
354                  case 'b':                                                                             // print before resolver steps
355                        bresolvep = true;
356                        break;
357                  case 'B':                                                                             // print before resolver steps
358                        bboxp = true;
359                        break;
360                  case CtorInitFix:
361                  case 'c':
362                        ctorinitp = true;
363                        break;
364                  case Expr:
365                  case 'e':                                                                             // dump AST after expression analysis
366                        exprp = true;
367                        break;
368                  case ExprAlt:
369                  case 'f':                                                                             // print alternatives for expressions
370                        expraltp = true;
371                        break;
372                  case Grammar:
373                  case 'g':                                                                             // bison debugging info (grammar rules)
374                        yydebug = true;
375                        break;
376                  case LibCFA:
377                  case 'l':                                                                             // generate libcfa.c
378                        libcfap = true;
379                        break;
380                  case Nopreamble:
381                  case 'n':                                                                             // do not read preamble
382                        nopreludep = true;
383                        break;
384                  case Prototypes:
385                  case 'p':                                                                             // generate prototypes for preamble functions
386                        noprotop = true;
387                        break;
388                  case Parse:
389                  case 'q':                                                                             // dump parse tree
390                        parsep = true;
391                        break;
392                  case Resolver:
393                  case 'r':                                                                             // print resolver steps
394                        resolvep = true;
395                        break;
396                  case Symbol:
397                  case 's':                                                                             // print symbol table events
398                        symtabp = true;
399                        break;
400                  case Tree:
401                  case 't':                                                                             // build in tree
402                        treep = true;
403                        break;
404                  case 'v':                                                                             // dump AST after decl validation pass
405                        validp = true;
406                        break;
407                  case 'y':
408                        errorp = true;
409                        break;
410                  case 'z':
411                        codegenp = true;
412                        break;
413                  case 'D':                                                                             // ignore -Dxxx
414                        break;
415                  case 'F':                                                                             // source file-name without suffix
416                        filename = optarg;
417                        break;
418                  case '?':
419                        assertf( false, "Unknown option: '%c'\n", (char)optopt );
420                  default:
421                        abort();
422                } // switch
423        } // while
424} // parse_cmdline
425
426static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
427        extern int yyparse( void );
428        extern FILE * yyin;
429        extern int yylineno;
430
431        ::linkage = linkage;                                                            // set globals
432        yyin = input;
433        yylineno = 1;
434        typedefTable.enterScope();
435        int parseStatus = yyparse();
436
437        fclose( input );
438        if ( shouldExit || parseStatus != 0 ) {
439                exit( parseStatus );
440        } // if
441} // parse
442
443static bool notPrelude( Declaration * decl ) {
444        return ! LinkageSpec::isBuiltin( decl->get_linkage() );
445} // notPrelude
446
447static void dump( list< Declaration * > & translationUnit, ostream & out ) {
448        list< Declaration * > decls;
449
450        if ( noprotop ) {
451                filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
452        } else {
453                decls = translationUnit;
454        } // if
455
456        printAll( decls, out );
457        deleteAll( translationUnit );
458} // dump
459
460// Local Variables: //
461// tab-width: 4 //
462// mode: c++ //
463// compile-command: "make install" //
464// End:  //
Note: See TracBrowser for help on using the repository browser.