void output() #endif { free_itemsets(); free_shifts(); free_reductions(); output_stored_text(); output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); output_stype(); if (rflag) write_section(tables); write_section(header); if (language == C) output_trailing_text(); write_section(body); output_semantic_actions(); write_section(trailer); if ((language == PERL) || (language == PYTHON)) output_trailing_text(); free_derives(); free_nullable(); }
void output(void) { const_array = jflag ? "private final static " : ""; free_itemsets(); free_shifts(); free_reductions(); output_prefix(); output_stored_text(); output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); if (!jflag) { output_stype(); if (rflag) write_section(tables); write_section(header); output_trailing_text(); } write_section(jflag ? jbody : body); output_semantic_actions(); write_section(jflag ? jtrailer : trailer); if (jflag) output_trailing_text(); }
int quota_get (quota_t *myquota) { struct dqblk sysquota; int retval; output_debug ("fetching quotas: device='%s',id='%d'", myquota->_qfile, myquota->_id); retval = quotactl (myquota->_qfile, QCMD(Q_GETQUOTA, myquota->_id_type), myquota->_id, (caddr_t) &sysquota); if ( retval < 0 ) { output_error ("Failed fetching quotas: %s", strerror (errno)); return 0; } /* here, linux.c does a memcpy(), it should also work for darwin, * but it's better to be on the safe side */ myquota->block_hard = sysquota.dqb_bhardlimit; myquota->block_soft = sysquota.dqb_bsoftlimit; myquota->diskspace_used = sysquota.dqb_curbytes; myquota->inode_hard = sysquota.dqb_ihardlimit; myquota->inode_soft = sysquota.dqb_isoftlimit; myquota->inode_used = sysquota.dqb_curinodes ; myquota->block_time = (time_t) sysquota.dqb_btime; myquota->inode_time = (time_t) sysquota.dqb_itime; // FIXME: remove debug //output_info ("BLOCK_SIZE: %d\n", BLOCK_SIZE); //output_info ("Getting quota soft/hard: %llu, %llu\n", myquota->block_soft, myquota->block_hard); return 1; }
void output(void) { free_itemsets(); free_shifts(); free_reductions(); output_stored_text(); if (jflag) /*rwj*/ { write_section(jheader); output_stype(); } output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); if (!jflag) /*rwj*/ output_stype(); if (rflag) write_section(tables); if (!jflag) /*rwj*/ write_section(header); output_trailing_text(); if (jflag) /*rwj*/ write_section(jbody); else write_section(body); output_semantic_actions(); if (jflag) /*rwj*/ write_section(jtrailer); else write_section(trailer); }
void dlload_error(const char *filename) { #ifndef MINGW #if defined WIN32 LPTSTR error; LPTSTR end; DWORD result = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &error, 0, NULL); if (!result) error = TEXT("[FormatMessage failed]"); else for (end = error + strlen(error) - 1; end >= error && isspace(*end); end--) *end = 0; #else char *error = dlerror(); #endif #else char *error = "unknown error"; #endif output_debug("%s: %s (LD_LIBRARY_PATH=%s)", filename, error,getenv("LD_LIBRARY_PATH")); #if defined WIN32 && ! defined MINGW if (result) LocalFree(error); #endif }
quota_t *quota_new (int q_type, int id, char *fs_spec) { quota_t *myquota; fs_t *fs; char *qfile; char *q_filename; if (q_type > MAXQUOTAS) { output_error ("Unknown quota type: %d", q_type); return 0; } if (q_type == QUOTA_USER) q_filename = Q_USER_FILENAME; else q_filename = Q_GROUP_FILENAME; --q_type; /* see defs in quota.h */ myquota = (quota_t *) malloc (sizeof(quota_t)); if (! myquota) { output_error ("Insufficient memory"); exit (ERR_MEM); } fs = system_getfs (fs_spec); if ( ! fs ) { return NULL; } qfile = malloc (strlen(fs->mount_pt) + strlen(q_filename) + 1); if (! qfile) { output_error ("Insufficient memory"); exit (ERR_MEM); } #if HAVE_STRLCPY strlcpy(qfile, fs->mount_pt, strlen(fs->mount_pt) + 1); #else strcpy (qfile, fs->mount_pt); #endif /* HAVE_STRLCPY */ #if HAVE_STRLCAT strlcat(qfile, q_filename, strlen(qfile) + strlen(q_filename) + 1); #else strcat (qfile, q_filename); #endif /* HAVE_STRLCAT */ // skip duplicated / at start of qfile while (strlen(qfile) > 1 && qfile[0] == '/' && qfile[1] == '/') qfile++; output_debug ("qfile is \"%s\"\n", qfile); myquota->_id = id; myquota->_id_type = q_type; myquota->_qfile = qfile; free (fs); return myquota; }
size_t stream(FILE *fileptr,int opts) { stream_pos = 0; fp = fileptr; flags = opts; output_debug("starting stream on file %d with options %x", fileno(fp), flags); try { // header stream("GLD30"); // runtime classes try { stream(class_get_first_runtime()); } catch (int) {}; // modules try { stream(module_get_first()); } catch (int) {} // objects try { stream(object_get_first()); } catch (int) {}; // globals try { stream(global_getnext(NULL)); } catch (int) {}; // module data struct s_stream *s; for ( s=stream_list ; s!=NULL ; s=s->next ) { s->call((int)flags,(STREAMCALLBACK)stream_callback); } output_debug("done processing stream on file %d with options %x", fileno(fp), flags); return stream_pos; } catch (const char *msg) { output_error("stream() unexpected %s at offset %lld", msg, (int64)stream_pos); return -1; } catch (...) { output_error("stream() failed as offset %lld", (int64)stream_pos); return -1; } }
int link_termall(void) { bool ok = true; glxlink *mod; for ( mod=glxlink::get_first() ; mod!=NULL ; mod=mod->get_next() ) { output_debug("link_initall(): terminating %s link...",mod->get_target()); if ( !mod->do_term() ) ok = false; } return ok; }
// Other include files, declarations, and non-Xerces-C++ initializations. XERCES_CPP_NAMESPACE_USE /*int main(int argc, char** argv){ char* xmlFile = "well-formatted-new.xml"; //char *xmlFile = "GridLABD_Multi_Example.xml"; return loadall_xml(xmlFile); }*/ int loadall_xml(char *filename){ if(filename == NULL) return 0; try{ XMLPlatformUtils::Initialize(); } catch(const XMLException& /*toCatch*/){ output_error("Load_XML: Xerces Initialization failed."); output_debug(" * something really spectacularly nasty happened inside Xerces and outside our control."); return 0; } SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(); parser->setFeature(XMLUni::fgXercesDynamic, true); //parser->setFeature(XMLUni::fgSAX2CoreValidation, true); //parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); // optional gld_loadHndl *defaultHandler = new gld_loadHndl(); parser->setContentHandler(defaultHandler); parser->setErrorHandler(defaultHandler); try { parser->parse(filename); } catch (const XMLException& toCatch){ char* message = XMLString::transcode(toCatch.getMessage()); output_error("Load_XML: XMLException from Xerces: %s", message); XMLString::release(&message); return 0; } catch (const SAXParseException& toCatch){ char* message = XMLString::transcode(toCatch.getMessage()); output_error("Load_XML: SAXParseException from Xerces: %s", message); XMLString::release(&message); return 0; } catch (...) { output_error("Load_XML: unexpected exception from Xerces."); return 0; } if(!defaultHandler->did_load()){ output_error("Load_XML: loading failed."); return 0; } delete parser; delete defaultHandler; return 1; }
void output(void) { free_itemsets(); free_shifts(); free_reductions(); output_stored_text(); if (jflag) /*rwj*/ { write_section(jheader); output_stype(); } output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); if (!jflag) /*rwj*/ output_stype(); if (rflag) write_section(tables); if (!jflag) /*rwj*/ write_section(header); output_trailing_text(); if (jflag) { /*rwj*/ /* yio 20020304: nodebug and throws options */ if (jdebug == TRUE) { write_section(jbody_a); if (strlen(jyyparse_throws)>0) fprintf(code_file,"throws %s\n",jyyparse_throws); write_section(jbody_b); } else { write_section(jbody_nodebug_a); if (strlen(jyyparse_throws)>0) fprintf(code_file,"throws %s\n",jyyparse_throws); write_section(jbody_nodebug_b); } } else write_section(body); output_semantic_actions(); if (jflag) { /*rwj*/ /* yio 20020304: nodebug option */ if (jdebug == TRUE) write_section(jtrailer); else write_section(jtrailer_nodebug); } else write_section(trailer); }
void inc_files(const char *name) { if ( global_debug_mode || global_verbose_mode ) output_debug("processing %s", name); else { static size_t len = 0; char blank[1024]; memset(blank,32,len); blank[len]='\0'; len = output_raw("%s\rProcessing %s...\r",blank,name)-len; } wlock(); n_files++; wunlock(); };
int quota_get (quota_t *myquota) { int retval; output_debug ("fetching quotas: device='%s',id='%d'", myquota->_qfile, myquota->_id); if (QF_IS_XFS(quota_format)) { retval = xfs_quota_get(myquota); } else if (IF_GENERIC) { retval = generic_quota_get(myquota); } else if (QF_IS_V0(quota_format)) { retval = v0_quota_get(myquota); } else { retval = old_quota_get(myquota); } return retval; }
void output() { free_itemsets(); free_shifts(); free_reductions(); output_stored_text(); output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); output_stype(); if (rflag) write_section("tables"); write_section("header"); output_trailing_text(); write_section("body"); output_semantic_actions(); write_section("trailer"); }
output() { free_itemsets(); free_shifts(); free_reductions(); output_prefix(); output_stored_text(); output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); output_stype(); if (rflag) write_section(tables); write_section(header); output_trailing_text(); write_section(body); output_semantic_actions(); write_section(trailer); }
int kern_quota_format(fs_t *fs, int q_type) { u_int32_t version; struct v0_dqstats v0_stats; FILE *f; int ret = 0; struct stat st; if (strcasecmp(fs->mnt_type, "xfs") == 0) { if (stat("/proc/fs/xfs/stat", &st) == 0) { quota_format |= (1 << QF_XFS); return ret; } else { output_error("%s is mounted as XFS but no kernel support for XFS quota!", fs->device); exit(ERR_SYS); } } if ((f = fopen("/proc/fs/quota", "r"))) { if (fscanf(f, "Version %u", &version) != 1) { fclose(f); return QF_TOONEW; } fclose(f); } else if (stat("/proc/sys/fs/quota", &st) == 0) { /* Either QF_VFSOLD or QF_VFSV0 or QF_VFSV1 */ int actfmt, retval; kernel_iface = IFACE_GENERIC; retval = quotactl(QCMD(Q_GETFMT, q_type), fs->device, 0, (void *) &actfmt); if (retval < 0) { if (! QF_IS_XFS(quota_format)) { if (errno == 3) { output_error("Quotatool cannot function while quotas are disabled. " "Please enable quotas by running `quotaon -a`.\n"); } else { output_error("Error while detecting kernel quota version: %i, %s\n", errno, strerror(errno)); } exit(ERR_SYS); } } else { if (actfmt == 1) /* Q_GETFMT retval for QF_VFSOLD */ quota_format |= (1 << QF_VFSOLD); else if (actfmt == 2) /* Q_GETFMT retval for QF_VFSV0 */ quota_format |= (1 << QF_VFSV0); else if (actfmt == 4) /* Q_GETFMT retval for QF_VFSV1 */ quota_format |= (1 << QF_VFSV1); else { output_debug("Unknown Q_GETFMT: %d\n", actfmt); return QF_ERROR; } } return ret; } else if (quotactl(QCMD(Q_V0_GETSTATS, 0), NULL, 0, (void *) &v0_stats) >= 0) { version = v0_stats.version; /* Copy the version */ } else { if (errno == ENOSYS || errno == ENOTSUP) /* Quota not compiled? */ return QF_ERROR; if (errno == EINVAL || errno == EFAULT || errno == EPERM) { /* Old quota compiled? */ /* RedHat 7.1 (2.4.2-2) newquota check * Q_V0_GETSTATS in it's old place, Q_GETQUOTA in the new place * (they haven't moved Q_GETSTATS to its new value) */ int err_stat = 0; int err_quota = 0; char tmp[1024]; /* Just temporary buffer */ if (quotactl(QCMD(Q_OLD_GETSTATS, 0), NULL, 0, tmp)) err_stat = errno; if (quotactl(QCMD(Q_OLD_GETQUOTA, 0), "/dev/null", 0, tmp)) err_quota = errno; /* On a RedHat 2.4.2-2 we expect 0, EINVAL * On a 2.4.x we expect 0, ENOENT * On a 2.4.x-ac we wont get here */ if (err_stat == 0 && err_quota == EINVAL) { quota_format |= (1 << QF_VFSV0); /* New format supported */ kernel_iface = IFACE_VFSV0; } else { quota_format |= (1 << QF_VFSOLD); kernel_iface = IFACE_VFSOLD; } return ret; } output_error("Error while detecting kernel quota version: %s\n", strerror(errno)); exit(ERR_SYS); } if (version > KERN_KNOWN_QUOTA_VERSION) /* Newer kernel than we know? */ quota_format = QF_TOONEW; if (version <= 6*10000+4*100+0) { /* Old quota format? */ quota_format |= (1 << QF_VFSOLD); kernel_iface = IFACE_VFSOLD; } else { quota_format |= (1 << QF_VFSV0); /* New format supported */ kernel_iface = IFACE_VFSOLD; } return ret; }
quota_t *quota_new (int q_type, int id, char *fs_spec) { quota_t *myquota; fs_t *fs; char *qfile; q_type--; /* see defs in quota.h */ if ( q_type >= MAXQUOTAS ) { output_error ("Unknown quota type: %d", q_type); return 0; } myquota = (quota_t *) malloc (sizeof(quota_t)); if ( ! myquota ) { output_error ("Insufficient memory"); exit (ERR_MEM); } fs = system_getfs (fs_spec); if ( ! fs ) { return NULL; } /* * Detect quota format */ output_debug("Detecting quota format"); if (kern_quota_format(fs, q_type) == QF_ERROR) { output_error("Cannot determine quota format!"); exit (ERR_SYS); } if (QF_IS_TOO_NEW(quota_format)) { output_error("Quota format too new (?)"); exit (ERR_SYS); } if (QF_IS_XFS(quota_format)) { output_debug("Detected quota format: XFS"); } if (QF_IS_V0(quota_format)) { output_debug("Detected quota format: VFSV0"); if (IF_GENERIC) { output_debug("Detected quota interface: GENERIC"); } else { myquota->_v0_quotainfo = (struct v0_kern_dqinfo *) 0; myquota->_v0_quotainfo = (struct v0_kern_dqinfo *) malloc (sizeof(struct v0_kern_dqinfo)); if ( ! myquota->_v0_quotainfo ) { output_error ("Insufficient memory"); exit (ERR_MEM); } } } else if (QF_IS_V1(quota_format)) { output_debug("Detected quota format: VFSV1"); if (IF_GENERIC) { output_debug("Detected quota interface: GENERIC"); } else { output_error("Unsupported quota format: VFSV1 but not GENERIC, please report Issue on github: https://github.com/ekenberg/quotatool"); exit(ERR_SYS); } } else if (QF_IS_OLD(quota_format)) { output_debug("Detected quota format: OLD"); if (IF_GENERIC) { output_debug("Detected quota interface: GENERIC"); } } else if (! QF_IS_XFS(quota_format)) { output_error("Unknown quota format!"); exit(ERR_SYS); } if (IF_GENERIC) { myquota->_generic_quotainfo = (struct if_dqinfo *) 0; myquota->_generic_quotainfo = (struct if_dqinfo *) malloc (sizeof(struct if_dqinfo)); if ( ! myquota->_generic_quotainfo ) { output_error ("Insufficient memory"); exit (ERR_MEM); } } qfile = strdup (fs->device); myquota->_id = id; myquota->_id_type = q_type; myquota->_qfile = qfile; free (fs); return myquota; }
void inc_access(const char *name) { output_debug("%s folder access failure", name); wlock(); n_access++; wunlock(); };
/** Initialize the delta mode code This call must be completed before the first call to any delta mode code. If the call fails, no delta mode code can be executed. Failure does not affect whether event mode code can run. @return SUCCESS or FAILED **/ STATUS delta_init(void) { OBJECT *obj, **pObj; char temp_name_buff[64]; unsigned int n, toprank = 0; OBJECT ***ranklist; int *rankcount; MODULE *module; clock_t t = clock(); /* count qualified modules */ for ( module=module_get_first() ; module!=NULL ; module=module_get_next(module) ) { if ( 0 != module->deltadesired ){ // this could probably be counted in module_init()... delta_modulecount++; if (profile.module_list[0]!=0) strcat(profile.module_list,","); strcat(profile.module_list,module->name); } } /* if none, stop here */ if ( delta_modulecount==0 ){ goto Success; } /* allocate memory for qualified module list */ delta_modulelist = (MODULE**)malloc(sizeof(MODULE**)*delta_modulecount); if(0 == delta_modulelist){ output_error("unable to allocate memory for deltamode module list"); /* TROUBLESHOOT Deltamode operation requires more memory than is available. Try freeing up memory by making more heap available or making the model smaller. */ return FAILED; } /* build qualified module list */ delta_modulecount = 0; global_deltamode_updateorder[0]='\0'; for ( module=module_get_first() ; module!=NULL ; module=module_get_next(module) ) { if ( 0 != module->deltadesired ) { if ( delta_modulecount>0 ) strcat(global_deltamode_updateorder,","); strcat(global_deltamode_updateorder,module->name); delta_modulelist[delta_modulecount++] = module; } } /* count qualified objects */ for ( obj=object_get_first() ; obj!=NULL ; obj=object_get_next(obj) ) { if ( obj->flags&OF_DELTAMODE ) { if ( !obj->oclass->update ) output_debug("object '%s' requested deltamode updates but the class '%s' does not export the update function", object_name(obj, temp_name_buff, 63), obj->oclass->name); delta_objectcount++; if ( obj->rank > toprank ){ toprank = obj->rank; } } } /* if none, stop here */ if ( delta_objectcount==0 ){ goto Success; } /* allocate final object list */ delta_objectlist = (OBJECT**)malloc(sizeof(OBJECT*)*delta_objectcount); if ( delta_objectlist==NULL) { output_error("unable to allocate memory for deltamode object list"); /* TROUBLESHOOT Deltamode operation requires more memory than is available. Try freeing up memory by making more heap available or making the model smaller. */ return FAILED; } /* allocate rank lists */ ranklist = (OBJECT***)malloc(sizeof(OBJECT**)*(toprank+1)); if ( 0 == ranklist ){ output_error("unable to allocate memory for deltamode ranklist"); /* TROUBLESHOOT Deltamode operation requires more memory than is available. Try freeing up memory by making more heap available or making the model smaller. */ return FAILED; } memset(ranklist,0,sizeof(OBJECT**)*(toprank+1)); /* allocate rank counts */ rankcount = (int*)malloc(sizeof(int)*(toprank+1)); if ( 0 == rankcount ){ output_error("unable to allocate memory for deltamode rankcount"); /* TROUBLESHOOT Deltamode operation requires more memory than is available. Try freeing up memory by making more heap available or making the model smaller. */ return FAILED; } memset(rankcount,0,sizeof(int)*(toprank+1)); /* count qualified objects in each rank */ for ( obj=object_get_first() ; obj!=NULL ; obj=object_get_next(obj) ) { if ( obj->flags&OF_DELTAMODE ){ rankcount[obj->rank]++; } } /* allocate rank lists */ for ( n=0 ; n<=toprank ; n++) { if ( rankcount[n]>0 ) { ranklist[n] = (OBJECT**)malloc(sizeof(OBJECT*)*rankcount[n]); if ( !ranklist[n] ){ output_error("unable to allocate memory for deltamode rankcount %i", n); /* TROUBLESHOOT Deltamode operation requires more memory than is available. Try freeing up memory by making more heap available or making the model smaller. */ return FAILED; } rankcount[n] = 0; /* clear for index recount */ } else ranklist[n] = NULL; } /* assign qualified objects to rank lists */ for ( obj=object_get_first() ; obj!=NULL ; obj=object_get_next(obj) ) { if ( obj->flags&OF_DELTAMODE ){ ranklist[obj->rank][rankcount[obj->rank]++] = obj; } } /* build final object list */ pObj = delta_objectlist; for ( n=0 ; n<=toprank ; n++) { int m; for ( m=0 ; m<rankcount[n] ; m++ ){ *pObj++ = ranklist[n][m]; } if ( ranklist[n]!=NULL ){ free(ranklist[n]); ranklist[n] = NULL; } } /* release memory */ free(rankcount); rankcount = NULL; free(ranklist); ranklist = NULL; Success: profile.t_init += clock() - t; return SUCCESS; }
glxlink::glxlink(char *filename) { bool ok = true; globals = NULL; imports = NULL; exports = NULL; objects = NULL; handle = NULL; settag = NULL; init = NULL; sync = NULL; term = NULL; glxflags = 0; valid_to = 0; last_t = 0; FILE *fp = fopen(filename,"rt"); if ( fp==NULL ) throw "file open failed"; output_debug("opened link '%s'", filename); char line[1024]; int linenum=0; while ( fgets(line,sizeof(line),fp)!=NULL ) { linenum++; if ( line[0]=='#' ) continue; char tag[64], data[1024]=""; if ( sscanf(line,"%s %[^\r\n]",tag,data)>0 ) { output_debug("%s(%d): %s %s", filename, linenum, tag,data); if ( settag!=NULL ) { if ( strcmp(tag,"global")==0 ) { add_global(data); } else if ( strcmp(tag,"object")==0 ) { add_object(data); } else if ( strcmp(tag,"export")==0 ) { add_export(data); } else if ( strcmp(tag,"import")==0 ) { add_import(data); } else if ( !(*settag)(this,tag,data) ) output_error("%s(%d): tag '%s' not accepted", filename, linenum, tag); } else if ( strcmp(tag,"target")==0) { if ( !set_target(data) ) { output_error("%s(%d): target '%s' is not valid", filename, linenum, data); ok = false; } } else output_warning("%s(%d): tag '%s' cannot be processed until target module is loaded", filename, linenum, tag); } } fclose(fp); // append to link list next = first; first = this; if ( ok ) output_verbose("link '%s' ok", filename); else throw "cannot establish link"; }
/** Load and process the command-line arguments @return a STATUS value Arguments are processed immediately as they are seen. This means that models are loaded when they are encountered, and in relation to the other flags. Thus @code gridlabd --warn model1 --warn model2 @endcode will load \p model1 with warnings on, and \p model2 with warnings off. **/ STATUS cmdarg_load(int argc, /**< the number of arguments in \p argv */ char *argv[]) /**< a list pointers to the argument string */ { int test_mod_num = 1; unsigned int pos=0; int i; char *pd1, *pd2; /* capture the execdir */ strcpy(global_execname,argv[0]); strcpy(global_execdir,argv[0]); pd1 = strrchr(global_execdir,'/'); pd2 = strrchr(global_execdir,'\\'); if (pd1>pd2) *pd1='\0'; else if (pd2>pd1) *pd2='\0'; /* capture the command line */ for (i=0; i<argc; i++) { if (pos<sizeof(global_command_line)-strlen(argv[i])) pos += sprintf(global_command_line+pos,"%s%s",pos>0?" ":"",argv[i]); } while (argv++,--argc>0) { if (strcmp(*argv,"--copyright")==0) legal_notice(); else if (strcmp(*argv,"-w")==0 || strcmp(*argv,"--warn")==0) global_warn_mode=!global_warn_mode; else if (strcmp(*argv,"--bothstdout")==0) output_both_stdout(); else if (strcmp(*argv,"-c")==0 || strcmp(*argv,"--check")==0) global_runchecks=!global_runchecks; else if (strcmp(*argv,"--debug")==0) global_debug_output=!global_debug_output; else if (strcmp(*argv,"--debugger")==0){ global_debug_mode=1; global_debug_output=!global_debug_output; } else if (strcmp(*argv,"--dumpall")==0) global_dumpall=!global_dumpall; else if (strcmp(*argv,"-q")==0 || strcmp(*argv,"--quiet")==0) global_quiet_mode=!global_quiet_mode; else if (strcmp(*argv,"-v")==0 || strcmp(*argv,"--verbose")==0){ global_verbose_mode=!global_verbose_mode; } else if (strcmp(*argv,"--profile")==0) global_profiler=!global_profiler; else if (strcmp(*argv,"--pause")==0) global_pauseatexit=!global_pauseatexit; else if (strcmp(*argv,"--compile")==0) global_compileonly = !global_compileonly; else if (strcmp(*argv,"--license")==0) legal_license(); else if (strcmp(*argv,"--server_portnum")==0 || strcmp(*argv,"-P")==0) { if (argc-1>0) global_server_portnum = (argc--,atoi(*++argv)); else { output_fatal("missing server port number"); /* TROUBLESHOOT The <b>-P</b> or <b>--server_portnum</b> command line directive was not followed by a valid number. The correct syntax is <b>-P <i>number</i></b> or <b>--server_portnum <i>number</i></b>. */ } } else if (strcmp(*argv, "-V")==0 ||strcmp(*argv, "--version")==0) { char *buildinfo = strstr(BUILD,":"); int build = buildinfo ? atoi(strstr(BUILD,":")+1) : 0; output_message("Revision major: %d", REV_MAJOR); output_message("Revision minor: %d", REV_MINOR); output_message("Patch number : %d", REV_PATCH); output_message("Branch name : %s", BRANCH); if (build>0) output_message("Build number : %d", build); else output_message("Build number : %s", #ifdef WIN32 #ifdef _DEBUG #ifdef _M_X64 "WIN64-DEBUG" #else "WIN32-DEBUG" #endif #else #ifdef _M_X64 "WIN64-RELEASE" #else "WIN32-RELEASE" #endif #endif #else "DEV" #endif ); } else if (strcmp(*argv,"--dsttest")==0) timestamp_test(); else if (strcmp(*argv,"--randtest")==0) random_test(); else if (strcmp(*argv,"--unitstest")==0) unit_test(); else if (strcmp(*argv,"--scheduletest")==0) schedule_test(); else if (strcmp(*argv,"--loadshapetest")==0) loadshape_test(); else if (strcmp(*argv,"--endusetest")==0) enduse_test(); else if (strcmp(*argv,"--xmlstrict")==0) global_xmlstrict = !global_xmlstrict; else if (strcmp(*argv,"--globaldump")==0) { global_dump(); exit(0); } else if (strcmp(*argv,"--relax")==0) global_strictnames = FALSE; else if (strncmp(*argv,"--pidfile",9)==0) { char *filename = strchr(*argv,'='); if (filename==NULL) strcpy(global_pidfile,"gridlabd.pid"); else strcpy(global_pidfile,filename+1); } else if (strncmp(*argv,"--kml",5)==0) { char *filename = strchr(*argv,'='); if (filename) strcpy(global_kmlfile,filename+1); else strcpy(global_kmlfile,"gridlabd.kml"); } else if (strcmp(*argv, "--avlbalance") == 0){ global_no_balance = !global_no_balance; } else if (strcmp(*argv,"--testall")==0){ FILE *fd = NULL; if(*++argv != NULL) fd = fopen(*argv,"r"); else { output_fatal("no filename for testall"); /* TROUBLESHOOT The --testall parameter was found on the command line, but if was not followed by a filename containing the test description file. */ return FAILED; } argc--; global_test_mode=TRUE; if(fd == NULL) { output_fatal("incorrect module list file name"); /* TROUBLESHOOT The --testall parameter was found on the command line, but if was not followed by a valid filename containing the test description file. */ return FAILED; } if(load_module_list(fd,&test_mod_num) == FAILED) return FAILED; } else if (strcmp(*argv,"--modhelp")==0) { if(argc-1 > 0){ MODULE *mod = NULL; CLASS *oclass = NULL; argv++; argc--; if(strchr(argv[0], ':') == 0){ // no class mod = module_load(argv[0],0,NULL); } else { GLOBALVAR *var=NULL; char *cname; cname = strchr(argv[0], ':')+1; mod = module_load(strtok(argv[0],":"),0,NULL); oclass = class_get_class_from_classname(cname); if(oclass == NULL){ output_fatal("Unable to find class '%s' in module '%s'", cname, argv[0]); /* TROUBLESHOOT The <b>--modhelp</b> parameter was found on the command line, but if was followed by a class specification that isn't valid. Verify that the class exists in the module you specified. */ return FAILED; } /* dump module globals */ printf("module %s {\n", mod->name); while ((var=global_getnext(var))!=NULL) { PROPERTY *prop = var->prop; char *proptype = class_get_property_typename(prop->ptype); if (strncmp(var->prop->name,mod->name,strlen(mod->name))!=0) continue; if (proptype!=NULL){ if(prop->unit != NULL) { printf("\t%s %s[%s];", proptype, strrchr(prop->name,':')+1, prop->unit->name); } else if (prop->ptype==PT_set || prop->ptype==PT_enumeration) { KEYWORD *key; printf("\t%s {", proptype); for (key=prop->keywords; key!=NULL; key=key->next) printf("%s=%"FMT_INT64"u%s", key->name, (int64)key->value, key->next==NULL?"":", "); printf("} %s;", strrchr(prop->name,':')+1); } else { printf("\t%s %s;", proptype, strrchr(prop->name,':')+1); } if (prop->description!=NULL) printf(" // %s%s",prop->flags&PF_DEPRECATED?"(DEPRECATED) ":"",prop->description); printf("\n"); } } printf("}\n"); } if(mod == NULL){ output_fatal("module %s is not found",*argv); /* TROUBLESHOOT The <b>--modhelp</b> parameter was found on the command line, but if was followed by a module specification that isn't valid. Verify that the module exists in GridLAB-D's <b>lib</b> folder. */ return FAILED; } if(oclass != NULL) { print_class(oclass); } else { CLASS *oclass; pntree *ctree; /* lexographically sort all elements from class_get_first_class & oclass->next */ oclass=class_get_first_class(); ctree = (pntree *)malloc(sizeof(pntree)); if(ctree == NULL){ throw_exception("--modhelp: malloc failure"); /* TROUBLESHOOT The memory allocation needed for module help to function has failed. Try freeing up system memory and try again. */ } ctree->name = oclass->name; ctree->oclass = oclass; ctree->left = ctree->right = 0; for(; oclass != NULL; oclass = oclass->next){ modhelp_alpha(&ctree, oclass); //print_class(oclass); } /* flatten tree */ print_modhelp_tree(ctree); } } } else if (strcmp(*argv,"--modtest")==0) { if (argc-1>0) { MODULE *mod = module_load(argv[1],0,NULL); if (mod==NULL) output_fatal("module %s is not found",argv[1]); /* TROUBLESHOOT The <b>--modtest</b> parameter was found on the command line, but if was followed by a module specification that isn't valid. Verify that the module exists in GridLAB-D's <b>lib</b> folder. */ else { argv++;argc--; if (mod->test==NULL) output_fatal("module %s does not implement a test routine", argv[0]); /* TROUBLESHOOT The <b>--modtest</b> parameter was found on the command line, but if was followed by a specification for a module that doesn't implement any test procedures. See the <b>--libinfo</b> command line parameter for information on which procedures the module supports. */ else { output_test("*** modtest of %s beginning ***", argv[0]); mod->test(0,NULL); output_test("*** modtest of %s ended ***", argv[0]); } } } else { output_fatal("definition is missing"); /* TROUBLESHOOT The <b>--modtest</b> parameter was found on the command line, but if was not followed by a module specification. The correct syntax is <b>gridlabd --modtest <i>module_name</i></b>. */ return FAILED; } } else if (strcmp(*argv,"--test")==0){ global_test_mode=TRUE; global_strictnames = FALSE; output_debug("disabling strict naming for tests"); if (argc-1>0) { char mod_test[100]; sprintf(mod_test,"mod_test%d=%s",test_mod_num++,*++argv); if (global_setvar(mod_test)==SUCCESS) argc--; } else { output_fatal("test module name is missing"); /* TROUBLESHOOT The <b>--test</b> parameter was found on the command line, but if was not followed by a module specification that is valid. The correct syntax is <b>gridlabd --test <i>module_name</i></b>. */ return FAILED; } } else if (strcmp(*argv,"-D")==0 || strcmp(*argv,"--define")==0) { if (argc-1>0) { bool namestate = global_strictnames; global_strictnames = FALSE; if (global_setvar(*++argv,NULL)==SUCCESS){ argc--; } global_strictnames = namestate; } else { output_fatal("definition is missing"); /* TROUBLESHOOT The <b>-D</b> or <b>--define</b> command line parameters was given, but it was not followed by a variable definition. The correct syntax <b>-D </i>variable</i>=<i>value</i></b> or <b>--define </i>variable</i>=<i>value</i></b> */ return FAILED; } } else if (strcmp(*argv,"--globals")==0) { char *list[65536]; int i, n=0; GLOBALVAR *var = NULL; /* load the list into the array */ while ((var=global_getnext(var))!=NULL) { if (n<sizeof(list)/sizeof(list[0])) list[n++] = var->prop->name; else { output_fatal("--globals has insufficient buffer space to sort globals list"); return FAILED; } } /* sort the array */ qsort(list,n,sizeof(list[0]),compare); /* output sorted array */ for (i=0; i<n; i++) { char buffer[1024]; var = global_find(list[i]); printf("%s=%s;",var->prop->name,global_getvar(var->prop->name,buffer,sizeof(buffer))?buffer:"(error)"); if (var->prop->description || var->prop->flags&PF_DEPRECATED) printf(" // %s%s", (var->prop->flags&PF_DEPRECATED)?"DEPRECATED ":"", var->prop->description?var->prop->description:""); printf("\n"); } } else if (strcmp(*argv,"--redirect")==0) { if (argc-1>0) { char buffer[1024]; char *p; strcpy(buffer,*++argv); argc--; if (strcmp(buffer,"all")==0) { if (output_redirect("output",NULL)==NULL || output_redirect("error",NULL)==NULL || output_redirect("warning",NULL)==NULL || output_redirect("debug",NULL)==NULL || output_redirect("verbose",NULL)==NULL || output_redirect("profile",NULL)==NULL || output_redirect("progress",NULL)==NULL) { output_fatal("redirection of all failed"); /* TROUBLESHOOT An attempt to close all standard stream from the command line using <b>--redirect all</b> has failed. One of the streams cannot be closed. Try redirecting each stream separately until the problem stream is identified and the correct the problem with that stream. */ return FAILED; } } else if ((p=strchr(buffer,':'))!=NULL) { *p++='\0'; if (output_redirect(buffer,p)==NULL) { output_fatal("redirection of %s to '%s' failed: %s",buffer,p, strerror(errno)); /* TROUBLESHOOT An attempt to redirect a standard stream from the command line using <b>--redirect <i>stream</i>:<i>destination</i></b> has failed. The message should provide an indication of why the attempt failed. The remedy will depend on the nature of the problem. */ return FAILED; } } else if (output_redirect(buffer,NULL)==NULL) { output_fatal("default redirection of %s failed: %s",buffer, strerror(errno)); /* TROUBLESHOOT An attempt to close a standard stream from the command line using <b>--redirect <i>stream</i></b> has failed. The message should provide an indication of why the attempt failed. The remedy will depend on the nature of the problem. */ return FAILED; } } else { output_fatal("redirection is missing"); /* TROUBLESHOOT A <b>--redirect</b> directive on the command line is missing its redirection specification. The correct syntax is <b>--redirect <i>stream</i>[:<i>destination</i>]</b>. */ return FAILED; } } else if (strcmp(*argv,"-L")==0 || strcmp(*argv,"--libinfo")==0) { if (argc-1>0) { argc--; module_libinfo(*++argv); exit(0); } else { output_fatal("missing library name"); /* TROUBLESHOOT The <b>-L</b> or <b>--libinfo</b> command line directive was not followed by a module name. The correct syntax is <b>-L <i>module_name</i></b> or <b>--libinfo <i>module_name</i></b>. */ return FAILED; } } else if (strcmp(*argv,"-T")==0 || strcmp(*argv,"--threadcount")==0) { if (argc-1>0) global_threadcount = (argc--,atoi(*++argv)); else { output_fatal("missing thread count"); /* TROUBLESHOOT The <b>-T</b> or <b>--threadcount</b> command line directive was not followed by a valid number. The correct syntax is <b>-T <i>number</i></b> or <b>--threadcount <i>number</i></b>. */ return FAILED; } } else if (strcmp(*argv,"-o")==0 || strcmp(*argv,"--output")==0) { if (argc-1>0) strcpy(global_savefile,(argc--,*++argv)); else { output_fatal("missing output file"); /* TROUBLESHOOT The <b>-o</b> or <b>--output</b> command line directive was not followed by a valid filename. The correct syntax is <b>-o <i>file</i></b> or <b>--output <i>file</i></b>. */ return FAILED; } } else if (strcmp(*argv,"-e")==0 || strcmp(*argv,"--environment")==0) { if (argc-1>0) strcpy(global_environment,(argc--,*++argv)); else { output_fatal("environment not specified"); /* TROUBLESHOOT The <b>-e</b> or <b>--environment</b> command line directive was not followed by a valid environment specification. The correct syntax is <b>-e <i>keyword</i></b> or <b>--environment <i>keyword</i></b>. */ return FAILED; } } else if (strcmp(*argv,"--xmlencoding")==0) { if (argc-1>0) { global_xml_encoding = atoi(*++argv); argc--; } else { output_fatal("xml encoding not specified"); /* TROUBLESHOOT The <b>--xmlencoding</b> command line directive was not followed by a encoding specification. The correct syntax is <b>--xmlencoding <i>keyword</i></b>. */ return FAILED; } } else if (strcmp(*argv,"--xsd")==0) { if (argc-1>0) { argc--; exit(output_xsd(*++argv)); } else { MODULE *mod; for (mod=module_get_first(); mod!=NULL; mod=mod->next) output_xsd(mod->name); return SUCCESS; } } else if (strcmp(*argv,"--xsl")==0) { if (argc-1>0) { char fname[1024]; char *p_arg = *++argv; char n_args=1; char **p_args; argc--; while (*p_arg++!='\0') if (*p_arg==',') n_args++; p_args = (char**)malloc(sizeof(char*)*n_args); p_arg = strtok(*argv,","); n_args=0; while (p_arg!=NULL) { p_args[n_args++] = p_arg; p_arg = strtok(NULL,","); } sprintf(fname,"gridlabd-%d_%d.xsl",global_version_major,global_version_minor); exit(output_xsl(fname,n_args,p_args)); } else { output_fatal("module list not specified"); /* TROUBLESHOOT The <b>--xsl</b> command line directive was not followed by a validlist of modules. The correct syntax is <b>--xsl <i>module1</i>[,<i>module2</i>[,...]]</b>. */ return FAILED; } } else if (strcmp(*argv,"--stream")==0) global_streaming_io_enabled = !global_streaming_io_enabled; else if (strcmp(*argv,"--server")==0) strcpy(global_environment,"server"); else if (strcmp(*argv,"-h")==0 || strcmp(*argv,"--help")==0) { printf("Syntax: gridlabd [OPTIONS ...] <file> ... \nOptions:\n" " --avlbalance toggles AVL tree balancing\n" " -c|--check toggles module checks after model loads\n" " -D|--define <def> defines a macro value\n" " --debug toggles debug output (prints internal messages)\n" " --debugger toggles debugger mode (generates internal messages)\n" " --dumpall toggles module data dump after run completes\n" " -e|--environment <name> specifies user environment (default none)\n" " --license print license information\n" " -L|--libinfo <module> print module library information\n" " -o|--output <file> specifies model should be output after run\n" " --profile toggles profilers\n" " -q|--quiet toggles quiet mode (suppresses startup banner)\n" " --test toggles test mode (activate testing procedures)\n" " -T|--threadcount <n> specifies the number of processor threads to use\n" " -v|--verbose toggles verbose mode (active verbose messages)\n" " -V|--version prints the GridlabD version information\n" " -w|--warn toggles warning mode (generates warning messages)\n" " --xmlencoding <num> set the XML encoding (8, 16, or 32)\n" " --xmlstrict toggles XML encoding to be strict\n" " --xsd <module>[:<object>] prints the xsd of an object\n" " --xsl <modlist> prints the xsl for the modules listed\n" ); exit(0); } else if (**argv!='-') { if (global_test_mode) output_warning("file '%s' ignored in test mode", *argv); /* TROUBLESHOOT This warning is caused by an attempt to read an input file in self-test mode. The use of self-test model precludes reading model files. Try running the system in normal more or leaving off the model file name. */ else { if (!loadall(*argv)) return FAILED; /* preserve name of first model only */ if (strcmp(global_modelname,"")==0) strcpy(global_modelname,*argv); } } else { int n = module_cmdargs(argc,argv); if (n==0) { output_error("command line option '%s' is not recognized",*argv); /* TROUBLESHOOT The command line option given is not valid where it was found. Check the command line for correct syntax and order of options. */ return FAILED; } } } /*debug_traverse_tree(NULL);*/ /* for checking the name tree & getting a test file. -mh */ return SUCCESS; }
/* * parse_commandline * read our args, parse them * and return a struct of the data */ argdata_t *parse_commandline (int argc, char **argv) { argdata_t *data; extern char *optarg; extern int optind, opterr, optopt; int done, fail; int quota_type; int opt; if (argc == 1) { output_help (); return NULL; } data = (argdata_t *) calloc (1,sizeof(argdata_t)); if ( ! data ) { output_error ("Insufficient memory"); exit (ERR_MEM); } quota_type = _PARSE_UNDEF; optarg = NULL; opterr = 0; done = fail = 0; while ( ! done && ! fail ) { opt = getopt(argc, argv, OPTSTRING); if (opt > 0) output_debug ("option: '%c', argument: '%s'", opt, optarg); switch (opt) { case EOF: done = 1; break; case 'h': output_help (); exit (0); case 'V': output_version(); exit (0); case 'v': output_level++; break; case 'n': data->noaction = 1; break; case 'u': /* set username */ if ( data->id_type ) { output_error("Only one quota (user or group) can be set"); fail = 1; continue; } data->id_type = QUOTA_USER; #if HAVE_GNU_GETOPT /* -uuser */ if ( optarg ) { output_debug ("not mangling: optarg='%s', next='%s'", optarg, argv[optind]); data->id = optarg; } /* -u [-next-opt] */ else if ( ! argv[optind] || argv[optind][0] == '-' ) { output_debug ("not mangling: NULL user"); data->id = NULL; } /* -u user */ else { output_debug ("mangling everything: next='%s'", argv[optind]); data->id = argv[optind]; optind++; } #else if (optarg && ((data->block_grace || data->inode_grace) || (optarg[0] == '-'))) { /* -u [-next-opt] */ optind--; data->id = NULL; } else { /* -u user */ data->id = optarg; } #endif output_info ("using uid %s", data->id); break; case 'g': /* set groupname */ if ( data->id_type ) { output_error("Only one quota (user or group) can be set"); fail = 1; continue; } data->id_type = QUOTA_GROUP; #if HAVE_GNU_GETOPT if ( optarg ) { output_debug ("not mangling: optarg='%s', next='%s'", optarg, argv[optind]); data->id = optarg; } else if ( ! argv[optind] || argv[optind][0] == '-' ) { output_debug ("not mangling: NULL user"); data->id = NULL; } else { output_debug ("mangling everything: next='%s', argv[optind]"); data->id = argv[optind]; optind++; } #else data->id = optarg; #endif output_info ("using gid %s", data->id); break; case 'b': // Work with block limits output_info ("working with block limits"); quota_type = _PARSE_BLOCK; break; case 'i': // Work with inode limits output_info ("working with inode limits"); quota_type = _PARSE_INODE; break; case 'q': // soft limit switch ( quota_type ) { case _PARSE_UNDEF: output_error ("Must specify either block (-b) or inode (-i) before -q"); fail = 1; break; case _PARSE_BLOCK: data->block_soft = optarg; break; case _PARSE_INODE: data->inode_soft = optarg; break; default: output_error ("Impossible error #42q: evacuate the building!"); break; } output_info ("setting soft limit to %s", optarg); break; case 'l': // hard limit switch ( quota_type ) { case _PARSE_UNDEF: output_error ("Must specify either block (-b) or inode (-i) before -l"); fail = 1; break; case _PARSE_BLOCK: data->block_hard = optarg; break; case _PARSE_INODE: data->inode_hard = optarg; break; default: output_error ("Impossible error #42l: evacuate the building!"); break; } output_info ("setting hard limit to %s", optarg); break; case 't': // set grace period data->id = NULL; switch ( quota_type ) { case _PARSE_UNDEF: output_error ("Must specify either block (-b) or inode (-i) before -t"); fail = 1; break; case _PARSE_BLOCK: data->block_grace = optarg; break; case _PARSE_INODE: data->inode_grace = optarg; break; default: output_error ("Impossible error #42t: evacuate the building!"); break; } break; case 'r': // reset grace time switch ( quota_type ) { case _PARSE_UNDEF: output_error ("Must specify either block (-b) or inode (-i) before -r"); fail = 1; break; case _PARSE_BLOCK: data->block_reset = 1; break; case _PARSE_INODE: data->inode_reset = 1; break; default: output_error ("Impossible error #42r: evacuate the building!"); break; } break; case 'd': data->dump_info = 1; break; case 'R': data->raise_only = 1; break; case ':': output_error ("Option '%c' requires an argument", optopt); break; case '?': output_error ("Unrecognized option: '%c'", optopt); __attribute__ ((fallthrough)); default: output_help(); fail = 1; break; } } if ( fail ) { free (data); return NULL; } if ( ! data->id_type ) { output_error ("Must specify either user or group quota"); return NULL; } if ( data->dump_info) { output_info("Option 'd' => just dumping quota-info for %s", data->id_type == QUOTA_USER ? "user" : "group"); } /* the remaining arg is the filesystem */ data->qfile = argv[optind]; if ( ! data->qfile || strlen(data->qfile) == 0) { output_error ("No filesystem specified"); return NULL; } /* remove trailing slash(es) except for / filesystem */ while (strlen(data->qfile) > 1) { if (data->qfile[strlen(data->qfile) - 1] != '/') break; data->qfile[strlen(data->qfile) - 1] = '\0'; } /* check for mixing -t with other options in the wrong way */ if (data->block_grace || data->inode_grace) { if (data->block_hard || data->block_soft || data->inode_hard || data->inode_soft || data->id) { output_error("Wrong options for -t, please see manpage for usage instructions!"); return NULL; } } /* check for mixing -r with other options in the wrong way */ if (data->block_reset || data->inode_reset) { if (data->block_hard || data->block_soft || data->inode_hard || data->inode_soft) { output_error("Wrong options for -r, please see manpage for usage instructions!"); return NULL; } } output_info ("using filesystem %s", data->qfile); return data; }
/* initialize modules */ int link_initall(void) { output_debug("link_initall(): link startup in progress..."); glxlink *mod; for ( mod=glxlink::get_first() ; mod!=NULL ; mod=mod->get_next() ) { LINKLIST *item; output_debug("link_initall(): setting up %s link", mod->get_target()); // set default global list (if needed) if ( mod->get_globals()==NULL ) { GLOBALVAR *var = NULL; while ( (var=global_getnext(var))!=NULL ) { if ( var->prop!=NULL && var->prop->name!=NULL ) { LINKLIST *item = mod->add_global(var->prop->name); if ( item!=NULL ) item->data = (void*)var; else output_error("link_initall(): unable to link %s", var->prop->name); } else output_warning("link_initall(): a variable property definition is null"); } } else { // link global variables for ( item=mod->get_globals() ; item!=NULL ; item=mod->get_next(item) ) { if ( strcmp(item->name,"")==0 ) continue; item->data = (void*)global_find(item->name); if ( item->data==NULL ) output_error("link_initall(target='%s'): global '%s' is not found", mod->get_target(), item->name); } } // link objects if ( mod->get_objects()==NULL ) { // set default object list OBJECT *obj = NULL; for ( obj=object_get_first() ; obj!=NULL ; obj=object_get_next(obj) ) { // add named objects LINKLIST *item = NULL; if ( obj->name!=NULL ) item = mod->add_object(obj->name); else { char id[256]; sprintf(id,"%s:%d",obj->oclass->name,obj->id); item = mod->add_object(id); } item->data = (void*)obj; } } else { LINKLIST *item; // link global variables for ( item=mod->get_objects() ; item!=NULL ; item=mod->get_next(item) ) { if ( strcmp(item->name,"")==0 ) continue; OBJECT *obj = NULL; item->data = (void*)object_find_name(item->name); if ( item->data==NULL) output_error("link_initall(target='%s'): object '%s' is not found", mod->get_target(), item->name); } } // link exports for ( item=mod->get_exports() ; item!=NULL ; item=mod->get_next(item) ) { char objname[64], propname[64], varname[64]; if ( sscanf(item->name,"%[^.].%s %s",objname,propname,varname)==3 ) { OBJECTPROPERTY *objprop = (OBJECTPROPERTY*)malloc(sizeof(OBJECTPROPERTY)); objprop->obj = object_find_name(objname); if ( objprop->obj ) { objprop->prop = class_find_property(objprop->obj->oclass,propname); if ( objprop->prop==NULL ) output_error("link_initall(target='%s'): export '%s' property not found", mod->get_target(), item->name); else { item->data = objprop; strcpy(item->name,varname); } } else output_error("link_initall(target='%s'): export '%s' object not found", mod->get_target(), item->name); } else output_error("link_initall(target='%s'): '%s' is not a valid export specification", mod->get_target(), item->name); } // link imports for ( item=mod->get_imports() ; item!=NULL ; item=mod->get_next(item) ) { char objname[64], propname[64], varname[64]; if ( sscanf(item->name,"%[^.].%s %s",objname,propname,varname)==3 ) { OBJECTPROPERTY *objprop = (OBJECTPROPERTY*)malloc(sizeof(OBJECTPROPERTY)); objprop->obj = object_find_name(objname); if ( objprop->obj ) { objprop->prop = class_find_property(objprop->obj->oclass,propname); if ( objprop->prop==NULL ) output_error("link_initall(target='%s'): import '%s' property not found", mod->get_target(), item->name); else { item->data = objprop; strcpy(item->name,varname); } } else output_error("link_initall(target='%s'): import '%s' object not found", mod->get_target(), item->name); } else output_error("link_initall(target='%s'): '%s' is not a valid import specification", mod->get_target(), item->name); } // initialize link module if ( !mod->do_init() ) { output_error("link_initall(): link startup failed"); link_termall(); return 0; } } output_debug("link_initall(): link startup done ok"); atexit((void(*)(void))link_termall); return 1; }
HTTP* hopen(char *url, int maxlen) { struct sockaddr_in serv_addr; struct hostent *server; char protocol[64]; char hostname[1024]; char filespec[1024]; HTTP *http; char request[1024]; int len; #ifdef WIN32 /* init sockets */ WORD wsaVersion = MAKEWORD(2,2); WSADATA wsaData; if ( WSAStartup(wsaVersion,&wsaData)!=0 ) { output_error("hopen(char *url='%s', int maxlen=%d): unable to initialize Windows sockets", url, maxlen); return NULL; } #endif /* extract URL parts */ if ( sscanf(url,"%63[^:]://%1023[^/]%1023s", protocol,hostname, filespec)!=3 ) { output_error("hopen(char *url='%s', int maxlen=%d): badly formed URL", url, maxlen); return NULL; } /* setup handle */ http = (HTTP*)malloc(sizeof(HTTP)); if ( http==NULL ) { output_error("hopen(char *url='%s', int maxlen=%d): memory allocation failure", url, maxlen); return NULL; } /* initialize http */ http->buf = NULL; http->len = 0; http->pos = 0; /* setup socket */ http->sd = socket(AF_INET, SOCK_STREAM, 0); if ( http->sd < 0 ) { output_error("hopen(char *url='%s', int maxlen=%d): unable to create socket", url, maxlen); goto Error; } /* find server */ server = gethostbyname(hostname); if ( server==NULL ) { output_error("hopen(char *url='%s', int maxlen=%d): server not found", url, maxlen); goto Error; } /* extract server address */ memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; memcpy((char*)&serv_addr.sin_addr.s_addr,(char*)server->h_addr,server->h_length); serv_addr.sin_port = htons(80); /* open connection */ if ( connect(http->sd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0 ) { output_error("hopen(char *url='%s', maxlen=%d): unable to connect to server", url, maxlen); goto Error; } /* format/send request */ len = sprintf(request,"GET %s HTTP/1.1\r\nHost: %s:80\r\nUser-Agent: GridLAB-D/%d.%d\r\nConnection: close\r\n\r\n",filespec,hostname,REV_MAJOR,REV_MINOR); output_debug("sending HTTP message \n%s", request); if ( send(http->sd,request,len,0)<len ) { output_error("hopen(char *url='%s', maxlen=%d): unable to send request", url, maxlen); goto Error; } /* read response header */ http->buf = (char*)malloc(maxlen+1); http->len = 0; do { len = recv(http->sd,http->buf+http->len,(int)(maxlen-http->len),0x00); if ( len==0 ) { output_debug("hopen(char *url='%s', maxlen=%d): connection closed", url, maxlen); } else if ( len<0 ) { output_error("hopen(char *url='%s', maxlen=%d): unable to read response", url, maxlen); goto Error; } else { http->len += len; http->buf[http->len] = '\0'; } } while ( len>0 ); if ( http->len>0 ) output_debug("received HTTP message \n%s", http->buf); else output_debug("no HTTP response received"); return http; Error: #ifdef WIN32 output_error("hopen(char *url='%s', int maxlen=%d): WSA error code %d", url, maxlen, WSAGetLastError()); #endif return NULL; }
MODULE *module_load(const char *file, /**< module filename, searches \p PATH */ int argc, /**< count of arguments in \p argv */ char *argv[]) /**< arguments passed from the command line */ { /* check for already loaded */ MODULE *mod = module_find((char *)file); char buffer[FILENAME_MAX+1]; char *fmod; bool isforeign = false; char pathname[1024]; char *tpath = NULL; #ifdef WIN32 char from='/', to='\\'; #else char from='\\', to='/'; #endif char *p = NULL; void *hLib = NULL; LIBINIT init = NULL; int *pMajor = NULL, *pMinor = NULL; CLASS *previous = NULL; CLASS *c; #ifdef NEVER /* this shouldn't ever be necessary but sometimes for debugging purposes it is helpful */ /* if LD_LIBRARY_PATH is not set, default to current directory */ if (getenv("LD_LIBRARY_PATH")==NULL) { putenv("LD_LIBRARY_PATH=."); output_verbose("Setting default LD_LIBRARY_DEFAULT to current directory"); } #endif if (mod!=NULL) { output_verbose("%s(%d): module '%s' already loaded", __FILE__, __LINE__, file); return mod; } else { output_verbose("%s(%d): module '%s' not yet loaded", __FILE__, __LINE__, file); } /* check for foreign modules */ strcpy(buffer,file); fmod = strtok(buffer,"::"); if (fmod!=NULL && strcmp(fmod, file) != 0) { char *modname = strtok(NULL,"::"); MODULE *parent_mod = module_find(fmod); if(parent_mod == NULL) parent_mod = module_load(fmod, 0, NULL); previous = class_get_last_class(); if(parent_mod != NULL && parent_mod->subload != NULL) { /* if we've defined a subload routine and already loaded the parent module*/ MODULE *child_mod; if(module_find(fmod) == NULL) module_load(fmod, 0, NULL); child_mod = parent_mod->subload(modname, &mod, (previous ? &(previous->next) : &previous), argc, argv); if(child_mod == NULL) { /* failure */ output_error("module_load(file='%s::%s'): subload failed", fmod, modname); return NULL; } if (mod != NULL) { /* if we want to register another module */ last_module->next = mod; last_module = mod; mod->oclass = previous ? previous->next : class_get_first_class(); } return last_module; } else { struct { char *name; LOADER loader; } fmap[] = { {"matlab",NULL}, {"java",load_java_module}, {"python",load_python_module}, {NULL,NULL} /* DO NOT DELETE THIS TERMINATOR ENTRY */ }, *p; for (p=fmap; p->name!=NULL; p++) { if (strcmp(p->name, fmod)==0) { static char *args[1]; isforeign = true; if (p->loader!=NULL) /* use external loader */ return p->loader(modname,argc,argv); /* use a module with command args */ argv = args; argc=1; argv[0] = modname; file=buffer; break; } } if (p==NULL) { output_error("module_load(file='%s',...): foreign module type %s not recognized or supported", fmod); return NULL; } } } /* create a new module entry */ mod = (MODULE *)malloc(sizeof(MODULE)); if (mod==NULL) { output_verbose("%s(%d): module '%s' memory allocation failed", __FILE__, __LINE__, file); errno=ENOMEM; return NULL; } else output_verbose("%s(%d): module '%s' memory allocated", __FILE__, __LINE__, file); /* locate the module */ snprintf(pathname, 1024, "%s" DLEXT, file); tpath = find_file(pathname, NULL, X_OK|R_OK); if(tpath == NULL) { output_verbose("unable to locate %s in GLPATH, using library loader instead", pathname); tpath=pathname; } else { #ifndef WIN32 /* if the path is a relative path */ struct stat buf; if (tpath[0]!='/' && stat(tpath,&buf)==0) { char buffer[1024]; /* add ./ to the beginning of the path */ sprintf(buffer,"./%s", tpath); strcpy(tpath,buffer); } #endif output_verbose("full path to library '%s' is '%s'", file, tpath); } /* convert path delims based on OS preference */ for (p=strchr(tpath,from); p!=NULL; p=strchr(p,from)) *p=to; /* ok, let's do it */ hLib = DLLOAD(tpath); if (hLib==NULL) { #if defined WIN32 && ! defined MINGW output_error("%s(%d): module '%s' load failed - %s (error code %d)", __FILE__, __LINE__, file, strerror(errno), GetLastError()); #else output_error("%s(%d): module '%s' load failed - %s", __FILE__, __LINE__, file, dlerror()); output_debug("%s(%d): path to module is '%s'", __FILE__, __LINE__, tpath); #endif dlload_error(pathname); errno = ENOENT; free(mod); return NULL; } else output_verbose("%s(%d): module '%s' loaded ok", __FILE__, __LINE__, file); /* get the initialization function */ init = (LIBINIT)DLSYM(hLib,"init"); if (init==NULL) { output_error("%s(%d): module '%s' does not export init()", __FILE__, __LINE__, file); dlload_error(pathname); errno = ENOEXEC; free(mod); return NULL; } else output_verbose("%s(%d): module '%s' exports init()", __FILE__, __LINE__, file); /* connect the module's exported data & functions */ mod->hLib = (void*)hLib; pMajor = (int*)DLSYM(hLib, "major"); pMinor = (int*)DLSYM(hLib, "minor"); mod->major = pMajor?*pMajor:0; mod->minor = pMinor?*pMinor:0; mod->import_file = (int(*)(char*))DLSYM(hLib,"import_file"); mod->export_file = (int(*)(char*))DLSYM(hLib,"export_file"); mod->setvar = (int(*)(char*,char*))DLSYM(hLib,"setvar"); mod->getvar = (void*(*)(char*,char*,unsigned int))DLSYM(hLib,"getvar"); mod->check = (int(*)())DLSYM(hLib,"check"); #ifndef _NO_CPPUNIT mod->module_test = (int(*)(TEST_CALLBACKS*,int,char*[]))DLSYM(hLib,"module_test"); #endif mod->cmdargs = (int(*)(int,char**))DLSYM(hLib,"cmdargs"); mod->kmldump = (int(*)(FILE*,OBJECT*))DLSYM(hLib,"kmldump"); mod->subload = (MODULE *(*)(char *, MODULE **, CLASS **, int, char **))DLSYM(hLib, "subload"); mod->test = (void(*)(int,char*[]))DLSYM(hLib,"test"); mod->globals = NULL; strcpy(mod->name,file); mod->next = NULL; /* call the initialization function */ mod->oclass = (*init)(&callbacks,(void*)mod,argc,argv); if (mod->oclass==NULL) return NULL; /* connect intrinsic functions */ for (c=mod->oclass; c!=NULL; c=c->next) { char fname[1024]; struct { FUNCTIONADDR *func; char *name; int optional; } map[] = { {&c->create,"create",FALSE}, {&c->init,"init",TRUE}, {&c->sync,"sync",TRUE}, {&c->commit,"commit",TRUE}, {&c->notify,"notify",TRUE}, {&c->isa,"isa",TRUE}, {&c->plc,"plc",TRUE}, {&c->recalc,"recalc",TRUE}, }; int i; for (i=0; i<sizeof(map)/sizeof(map[0]); i++) { snprintf(fname, 1024,"%s_%s",map[i].name,isforeign?fmod:c->name); if ((*(map[i].func) = (FUNCTIONADDR)DLSYM(hLib,fname))==NULL && !map[i].optional) { output_fatal("intrinsic %s is not defined in class %s", fname,file); /* TROUBLESHOOT A required intrinsic function was not found. Please review and modify the class definition. */ errno=EINVAL; return NULL; } else if(!map[i].optional) output_verbose("%s(%d): module '%s' intrinsic %s found", __FILE__, __LINE__, file, fname); } } /* attach to list of known modules */ if (first_module==NULL) first_module = mod; else last_module->next = mod; last_module = mod; return last_module; }
/** stream_compress Format of compressed stream [US/len] [bit15 runlen flag, bit 0-14 data len] Bit 15 clear : raw data follows for len given [UC/data ... ] Bit 15 set : compressed data [SC/delta] differential to apply to each value [SC/value] initial value **/ size_t stream_compress(FILE *fp, char *buf, size_t len) { size_t count = 0, original = len; char *p = buf; // current position in input buffer char *raw = p; // start of raw buffer unsigned short rawlen = 0; // len of raw buffer char *run = p; // start of run buffer unsigned short runlen = 0; // len of run buffer char diff = 0; // current differential run value enum {RAW=0, RUNLEN=1} state = RAW; // state of compression for ( p = buf ; len-->0 ; p++ ) { int dp = p[1]-p[0]; if (state == RAW) { if (dp==diff) // pattern repeats runlen++; else runlen=0; // if raw buffer in progress and run is long enough to use if (runlen==8) { // dump raw buffer if (rawlen>runlen) { rawlen -= runlen; // don't include new run data if (fwrite(&rawlen,1,sizeof(rawlen),fp)<0) return -1; if (fwrite(raw,1,rawlen,fp)<0) return -1; count += rawlen+2; } // change to run buffer state = RUNLEN; rawlen = 0; run = p-runlen; } else if (rawlen==32767) // long raw buffer { // dump raw buffer if (fwrite(&rawlen,1,sizeof(rawlen),fp)<0) return -1; if (fwrite(raw,1,rawlen,fp)<0) return -1; count += rawlen+2; // restart raw buffer rawlen = 0; raw = p; } else rawlen++; } else if (state==RUNLEN) { if (dp==diff) // run continues { runlen++; // if run buffer is too long if (runlen==32767) { // mark run buffer runlen |= 0x8000; // dump run buffer if (fwrite(&runlen,1,sizeof(runlen),fp)<0) return -1; if (fwrite(&diff,1,sizeof(diff),fp)<0) return -1; if (fputc(*run,fp)<0) return -1; count+=4; // start over with a new run runlen = 0; run = p; } } else // run ends { // mark run buffer runlen |= 0x8000; // dump run buffer if (fwrite(&runlen,1,sizeof(runlen),fp)<0) return -1; if (fwrite(&diff,1,sizeof(diff),fp)<0) return -1; if (fputc(*run,fp)<0) return -1; count+=4; // change to a raw buffer state = RAW; raw = p; rawlen = 0; // get run candidate runlen = 0; } } // get next run candidate diff = dp; } // terminate compressed stream rawlen=0; if (fwrite(&rawlen,sizeof(rawlen),1,fp)<0) return -1; else count+=2; // stream len confirmation code if (fwrite(&count,sizeof(count),1,fp)<0) return -1; else count+=2; output_debug("stream_compress(): %d kB -> %d kB (%.1f%%)", original/1000+1, count/1000+1, (double)count*100/(double)original); return count; }
void output(void) { FILE *fp; free_itemsets(); free_shifts(); free_reductions(); if (iflag) { ++outline; fprintf(code_file, "#include \"%s\"\n", externs_file_name); fp = externs_file; } else fp = code_file; output_prefix(iflag ? externs_file : output_file); output_pure_parser(fp); output_stored_text(fp); output_stype(fp); output_parse_decl(fp); output_lex_decl(fp); output_error_decl(fp); write_section(fp, xdecls); if (iflag) { output_externs(externs_file, global_vars); if (!pure_parser) output_externs(externs_file, impure_vars); } if (iflag) { ++outline; fprintf(code_file, "#include \"%s\"\n", defines_file_name); if (!dflag) output_defines(externs_file); } else { putc_code(code_file, '\n'); output_defines(code_file); } if (dflag) output_defines(defines_file); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); if (rflag) { output_prefix(code_file); write_section(code_file, xdecls); write_section(code_file, tables); } write_section(code_file, global_vars); if (!pure_parser) { write_section(code_file, impure_vars); } write_section(code_file, hdr_defs); if (!pure_parser) { write_section(code_file, hdr_vars); } output_trailing_text(); write_section(code_file, body_1); if (pure_parser) { write_section(code_file, body_vars); } write_section(code_file, body_2); output_yyerror_call("syntax error"); write_section(code_file, body_3); output_semantic_actions(); write_section(code_file, trailer); output_yyerror_call("yacc stack overflow"); write_section(code_file, trailer_2); }
STATUS server_startup(int argc, char *argv[]) { static int started = 0; int portNumber = global_server_portnum; SOCKET sockfd; struct sockaddr_in serv_addr; #ifdef WIN32 static WSADATA wsaData; #endif if (started) return SUCCESS; #ifdef WIN32 output_debug("starting WS2"); if (WSAStartup(MAKEWORD(2,0),&wsaData)!=0) { output_error("socket library initialization failed: %s",strerror(GetLastError())); return FAILED; } #endif /* create a new socket */ if ((sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == INVALID_SOCKET) { output_error("can't create stream socket: %s",strerror(GetLastError())); return FAILED; } atexit(shutdown_now); memset(&serv_addr,0,sizeof(serv_addr)); Retry: serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(portNumber); /* bind socket to server address */ if (bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) { if (portNumber<global_server_portnum+1000) { portNumber++; output_warning("server port not available, trying port %d...", portNumber); goto Retry; } #ifdef WIN32 output_error("can't bind to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4); #else output_error("can't bind address: %s",strerror(GetLastError())); #endif return FAILED; } #ifdef WIN32 output_verbose("bind ok to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4); #else output_verbose("bind ok to address"); #endif /* listen for connection */ listen(sockfd,5); output_verbose("server listening to port %d", portNumber); global_server_portnum = portNumber; /* start the server thread */ if (pthread_create(&thread,NULL,server_routine,(void*)sockfd)) { output_error("server thread startup failed: %s",strerror(GetLastError())); return FAILED; } started = 1; return SUCCESS; }