void hcache_readfile(HCACHEFILE *file) { HCACHEDATA cachedata, *c, *last = 0; FILE *f; int bad_cache = 1, ch; const char *version; BUFFER buff; long buffsize; /* if( ! (hcachename = hcache_filename()) ) return;*/ if( ! (f = fopen( file->cachefilename, "rb" )) ) return; fseek( f, 0, SEEK_END ); buffsize = ftell( f ); fseek( f, 0, SEEK_SET ); buffer_init( &buff ); buffer_resize( &buff, buffsize + 1 ); if ( fread( buffer_ptr( &buff ), buffsize, 1, f ) != 1 ) { fclose( f ); goto bail; } buffer_ptr( &buff )[buffsize] = 0; fclose( f ); version = read_string( &buff ); ch = buffer_getchar( &buff ); if (!version || strcmp( version, CACHE_FILE_VERSION ) || ch != '\n' ) { goto bail; } for(;;) { int i, count, ch; LIST *l; c = &cachedata; c->boundname = read_string( &buff ); if( !c->boundname ) /* Test for eof */ break; c->time = read_int( &buff ); c->age = read_int( &buff ) + 1; /* we're getting older... */ #ifdef OPT_BUILTIN_MD5CACHE_EXT c->mtime = read_int( &buff ); read_md5sum( &buff, c->rulemd5sum ); memcpy( &c->currentrulemd5sum, &c->rulemd5sum, MD5_SUMSIZE ); read_md5sum( &buff, c->contentmd5sum ); memcpy( &c->currentcontentmd5sum, &c->contentmd5sum, MD5_SUMSIZE ); #endif if( !c->boundname ) goto bail; /* headers */ count = read_int( &buff ); for( l = 0, i = 0; i < count; ++i ) { const char *s = read_string( &buff ); if( !s ) goto bail; l = list_append( l, s, 0 ); } c->includes = l; /* hdrscan */ count = read_int( &buff ); for( l = 0, i = 0; i < count; ++i ) { const char *s = read_string( &buff ); if( !s ) goto bail; l = list_append( l, s, 0 ); } c->hdrscan = l; /* Read the newline */ ch = skip_spaces( &buff ); if( ch != '!' ) goto bail; ch = skip_spaces( &buff ); if( ch != '\n' ) goto bail; if( !hashenter( file->hcachehash, (HASHDATA **)&c ) ) { printf( "jam: can't insert header cache item, bailing on %s\n", file->cachefilename ); goto bail; } c->next = 0; if( last ) last->next = c; else file->hcachelist = c; last = c; } bad_cache = 0; if( DEBUG_HEADER ) printf( "hcache read from file %s\n", file->cachefilename ); bail: /* If its bad, no worries, it'll be overwritten in hcache_done() */ if( bad_cache ) printf( "jam: warning: the cache was invalid: %s\n", file->cachefilename ); buffer_free( &buff ); }
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth) { if (depth >= 100) { err = true; return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } switch (*in) { // ---------------------------------------------- // integer case 'i': { ++in; // 'i' std::string val = read_until(in, end, 'e', err); if (err) return; TORRENT_ASSERT(*in == 'e'); ++in; // 'e' ret = entry(entry::int_t); char* end_pointer; ret.integer() = strtoll(val.c_str(), &end_pointer, 10); #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif if (end_pointer == val.c_str()) { err = true; return; } } break; // ---------------------------------------------- // list case 'l': { ret = entry(entry::list_t); ++in; // 'l' while (*in != 'e') { ret.list().push_back(entry()); entry& e = ret.list().back(); bdecode_recursive(in, end, e, err, depth + 1); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // dictionary case 'd': { ret = entry(entry::dictionary_t); ++in; // 'd' while (*in != 'e') { entry key; bdecode_recursive(in, end, key, err, depth + 1); if (err || key.type() != entry::string_t) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } entry& e = ret[key.string()]; bdecode_recursive(in, end, e, err, depth + 1); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // string default: if (is_digit((unsigned char)*in)) { std::string len_s = read_until(in, end, ':', err); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } TORRENT_ASSERT(*in == ':'); ++in; // ':' int len = atoi(len_s.c_str()); ret = entry(entry::string_t); read_string(in, end, len, ret.string(), err); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } else { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif } }
static int llex(LexState *ls, SemInfo *seminfo) { luaZ_resetbuffer(ls->buff); for (;;) { switch (ls->current) { case '\n': case '\r': { /* line breaks */ inclinenumber(ls); break; } case ' ': case '\f': case '\t': case '\v': { /* spaces */ next(ls); break; } case '-': { /* '-' or '--' (comment) */ next(ls); if (ls->current != '-') return '-'; /* else is a comment */ next(ls); if (ls->current == '[') { /* long comment? */ int sep = skip_sep(ls); luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ if (sep >= 0) { read_long_string(ls, NULL, sep); /* skip long comment */ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ break; } } /* else short comment */ while (!currIsNewline(ls) && ls->current != EOZ) next(ls); /* skip until end of line (or end of file) */ break; } case '[': { /* long string or simply '[' */ int sep = skip_sep(ls); if (sep >= 0) { read_long_string(ls, seminfo, sep); return TK_STRING; } else if (sep != -1) /* '[=...' missing second bracket */ lexerror(ls, "invalid long string delimiter", TK_STRING); return '['; } case '=': { next(ls); if (check_next1(ls, '=')) return TK_EQ; else return '='; } case '<': { next(ls); if (check_next1(ls, '=')) return TK_LE; else if (check_next1(ls, '<')) return TK_SHL; else return '<'; } case '>': { next(ls); if (check_next1(ls, '=')) return TK_GE; else if (check_next1(ls, '>')) return TK_SHR; else return '>'; } case '/': { next(ls); if (check_next1(ls, '/')) return TK_IDIV; else return '/'; } case '~': { next(ls); if (check_next1(ls, '=')) return TK_NE; else return '~'; } case ':': { next(ls); if (check_next1(ls, ':')) return TK_DBCOLON; else return ':'; } case '"': case '\'': { /* short literal strings */ read_string(ls, ls->current, seminfo); return TK_STRING; } case '.': { /* '.', '..', '...', or number */ save_and_next(ls); if (check_next1(ls, '.')) { if (check_next1(ls, '.')) return TK_DOTS; /* '...' */ else return TK_CONCAT; /* '..' */ } else if (!lisdigit(ls->current)) return '.'; else return read_numeral(ls, seminfo); } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { return read_numeral(ls, seminfo); } case EOZ: { return TK_EOS; } default: { if (lislalpha(ls->current)) { /* identifier or reserved word? */ TString *ts; do { save_and_next(ls); } while (lislalnum(ls->current)); ts = luaX_newstring(ls, luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff)); seminfo->ts = ts; if (isreserved(ts)) /* reserved word? */ return ts->extra - 1 + FIRST_RESERVED; else { return TK_NAME; } } else { /* single-char tokens (+ - / ...) */ int c = ls->current; next(ls); return c; } } } } }
static const char* process_fields(lsb_heka_field *f, const char *p, const char *e) { int tag = 0; int wiretype = 0; long long vi = 0; p = lsb_pb_read_varint(p, e, &vi); if (!p || vi < 0 || p + vi > e) { return NULL; } e = p + vi; // only process to the end of the current field record do { p = lsb_pb_read_key(p, &tag, &wiretype); switch (tag) { case LSB_PB_NAME: p = read_string(wiretype, p, e, &f->name); break; case LSB_PB_VALUE_TYPE: p = process_varint(wiretype, p, e, &vi); if (p) { f->value_type = (int)vi; } break; case LSB_PB_REPRESENTATION: p = read_string(wiretype, p, e, &f->representation); break; // don't bother with the value(s) until we actually need them // since this stream is created by Hindsight // - tags are guaranteed to be properly ordered (values at the end) // - there won't be repeated tags for packed values case LSB_PB_VALUE_STRING: case LSB_PB_VALUE_BYTES: if (wiretype != 2) { p = NULL; break; } f->value.s = p - 1; f->value.len = e - f->value.s; p = e; break; case LSB_PB_VALUE_INTEGER: case LSB_PB_VALUE_BOOL: if (wiretype != 0 && wiretype != 2) { p = NULL; break; } // fall thru case LSB_PB_VALUE_DOUBLE: if (tag == 7 && wiretype != 1 && wiretype != 2) { p = NULL; break; } if (wiretype == 2) { p = lsb_pb_read_varint(p, e, &vi); if (!p || vi < 0 || p + vi > e) { p = NULL; break; } } f->value.s = p; f->value.len = e - f->value.s; p = e; break; default: p = NULL; // don't allow unknown tags break; } } while (p && p < e); return p && f->name.s ? p : NULL; }
int luaX_lex (LexState *LS, SemInfo *seminfo) { for (;;) { switch (LS->current) { case '\n': { inclinenumber(LS); continue; } case '-': { next(LS); if (LS->current != '-') return '-'; /* else is a comment */ next(LS); if (LS->current == '[' && (next(LS), LS->current == '[')) read_long_string(LS, NULL); /* long comment */ else /* short comment */ while (LS->current != '\n' && LS->current != EOZ) next(LS); continue; } case '[': { next(LS); if (LS->current != '[') return '['; else { read_long_string(LS, seminfo); return TK_STRING; } } case '=': { next(LS); if (LS->current != '=') return '='; else { next(LS); return TK_EQ; } } case '<': { next(LS); if (LS->current != '=') return '<'; else { next(LS); return TK_LE; } } case '>': { next(LS); if (LS->current != '=') return '>'; else { next(LS); return TK_GE; } } case '~': { next(LS); if (LS->current != '=') return '~'; else { next(LS); return TK_NE; } } case '"': case '\'': { read_string(LS, LS->current, seminfo); return TK_STRING; } case '.': { next(LS); if (LS->current == '.') { next(LS); if (LS->current == '.') { next(LS); return TK_DOTS; /* ... */ } else return TK_CONCAT; /* .. */ } else if (!isdigit(LS->current)) return '.'; else { read_numeral(LS, 1, seminfo); return TK_NUMBER; } } case EOZ: { return TK_EOS; } default: { if (isspace(LS->current)) { next(LS); continue; } else if (isdigit(LS->current)) { read_numeral(LS, 0, seminfo); return TK_NUMBER; } else if (isalpha(LS->current) || LS->current == '_') { /* identifier or reserved word */ size_t l = readname(LS); TString *ts = luaS_newlstr(LS->L, luaZ_buffer(LS->buff), l); if (ts->tsv.reserved > 0) /* reserved word? */ return ts->tsv.reserved - 1 + FIRST_RESERVED; seminfo->ts = ts; return TK_NAME; } else { int c = LS->current; if (iscntrl(c)) luaX_error(LS, "invalid control char", luaO_pushfstring(LS->L, "char(%d)", c)); next(LS); return c; /* single-char tokens (+ - / ...) */ } } } } }
void Tool::read(char *& st, char *& k, bool new_format) { if (new_format && at_end(st)) { ntools = 0; return; } unsigned rank = 0; k = read_keyword(st); already_read = TRUE; for (;;) { if (strcmp(k, "tool")) { if (new_format) { ntools = rank; wrong_keyword(k, "tool"); } else if (strcmp(k, "end")) wrong_keyword(k, "end"); else k = read_keyword(st); return; } if (rank == ntools) { // too small table ATool * t = new ATool[ntools + 16]; for (rank = 0; rank != ntools; rank += 1) t[rank] = tools[rank]; if (tools) delete [] tools; tools = t; ntools += 16; } ATool & tool = tools[rank++]; tool.display = read_string(st); tool.cmd = read_string(st); // fixe ghtml default conf bug int index = tool.cmd.indexOf("ghtml - flat"); if (index != -1) tool.cmd.remove(index + 7, 1); if (new_format && at_end(st)) { ntools = rank; return; } k = read_keyword(st); if (!strcmp(k, "Project")) { tool.applicable[UmlProject] = TRUE; if (new_format && at_end(st)) { ntools = rank; return; } k = read_keyword(st); } for (;;) { // old format const char * kc; if (!strcmp(k, "Attribut")) kc = "Attribute"; else if (((index = strlen(k)) > 4) && !strcmp(k + index - 4, "Icon")) { k[index - 4] = 0; kc = k; } else kc = k; for (index = 0; index != sizeof(ToolCase) / sizeof(*ToolCase); index += 1) { if (!strcmp(kc, ToolCase[index].key)) break; } if (index != sizeof(ToolCase) / sizeof(*ToolCase)) tool.applicable[ToolCase[index].kind] = TRUE; else break; if (new_format && at_end(st)) { ntools = rank; return; } k = read_keyword(st); } } }
void c_get_string (struct value *value, gdb_byte **buffer, int *length, struct type **char_type, const char **charset) { int err, width; unsigned int fetchlimit; struct type *type = check_typedef (value_type (value)); struct type *element_type = TYPE_TARGET_TYPE (type); int req_length = *length; enum bfd_endian byte_order = gdbarch_byte_order (get_type_arch (type)); enum c_string_type kind; if (element_type == NULL) goto error; if (TYPE_CODE (type) == TYPE_CODE_ARRAY) { /* If we know the size of the array, we can use it as a limit on the number of characters to be fetched. */ if (TYPE_NFIELDS (type) == 1 && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_RANGE) { LONGEST low_bound, high_bound; get_discrete_bounds (TYPE_FIELD_TYPE (type, 0), &low_bound, &high_bound); fetchlimit = high_bound - low_bound + 1; } else fetchlimit = UINT_MAX; } else if (TYPE_CODE (type) == TYPE_CODE_PTR) fetchlimit = UINT_MAX; else /* We work only with arrays and pointers. */ goto error; if (! c_textual_element_type (element_type, 0)) goto error; kind = classify_type (element_type, get_type_arch (element_type), charset); width = TYPE_LENGTH (element_type); /* If the string lives in GDB's memory instead of the inferior's, then we just need to copy it to BUFFER. Also, since such strings are arrays with known size, FETCHLIMIT will hold the size of the array. */ if ((VALUE_LVAL (value) == not_lval || VALUE_LVAL (value) == lval_internalvar) && fetchlimit != UINT_MAX) { int i; const gdb_byte *contents = value_contents (value); /* If a length is specified, use that. */ if (*length >= 0) i = *length; else /* Otherwise, look for a null character. */ for (i = 0; i < fetchlimit; i++) if (extract_unsigned_integer (contents + i * width, width, byte_order) == 0) break; /* I is now either a user-defined length, the number of non-null characters, or FETCHLIMIT. */ *length = i * width; *buffer = xmalloc (*length); memcpy (*buffer, contents, *length); err = 0; } else { err = read_string (value_as_address (value), *length, width, fetchlimit, byte_order, buffer, length); if (err) { xfree (*buffer); error (_("Error reading string from inferior: %s"), safe_strerror (err)); } } /* If the LENGTH is specified at -1, we want to return the string length up to the terminating null character. If an actual length was specified, we want to return the length of exactly what was read. */ if (req_length == -1) /* If the last character is null, subtract it from LENGTH. */ if (*length > 0 && extract_unsigned_integer (*buffer + *length - width, width, byte_order) == 0) *length -= width; /* The read_string function will return the number of bytes read. If length returned from read_string was > 0, return the number of characters read by dividing the number of bytes by width. */ if (*length != 0) *length = *length / width; *char_type = element_type; return; error: { char *type_str; type_str = type_to_string (type); if (type_str) { make_cleanup (xfree, type_str); error (_("Trying to read string with inappropriate type `%s'."), type_str); } else error (_("Trying to read string with inappropriate type.")); } }
int read_scan(const char *fmt, ...) { assert(fmt != NULL); int return_code = 0; int *out_int = NULL; char *out_char = NULL; char **out_string = NULL; int max_buffer = 0; va_list argp; va_start(argp, fmt); // @TODO better error handling everywhere (goto error) // @TODO buffer overflow check & limit checking for (int i = 0; fmt[i] != '\0'; i++) { if (fmt[i] == '%') { i++; switch (fmt[i]) { case '\0': printf("Invalid format, you ended with %%.\n"); break; case 'd': out_int = va_arg(argp, int *); int read_int_rc = read_int(out_int); if (read_int_rc != 0) { return_code = -1; goto cleanup; } break; case 'c': out_char = va_arg(argp, char *); int read_char_rc = read_char(out_char, CHOMP_NEWLINE); if (read_char_rc != 0) { return_code = -1; goto cleanup; } break; case 's': out_string = va_arg(argp, char **); max_buffer = va_arg(argp, int); if (out_string == NULL) { return_code = -1; goto cleanup; } if (max_buffer <= 0) { return_code = -1; goto cleanup; } int read_string_rc = read_string(out_string, max_buffer); if (read_string_rc != 0) { return_code = -1; goto cleanup; } break; default: printf("Invalid format.\n"); break; } } // @TODO hier sollte nur feof geprüft werden // ferror() eigentlich nach jedem read? assert(!feof(stdin) && !ferror(stdin)); }
Value *Parser::parse_string() { return new String(read_string()); }
int parse_command_line(sym_environment *env, int argc, char **argv) { int i; char line[MAX_LINE_LENGTH +1], tmp, c; char key[MAX_LINE_LENGTH +1], value[MAX_LINE_LENGTH +1]; FILE *f = NULL, *f1 = NULL; // str_int colgen_str[COLGEN_STR_SIZE] = COLGEN_STR_ARRAY; tm_params *tm_par = &env->par.tm_par; lp_params *lp_par = &env->par.lp_par; cg_params *cg_par = &env->par.cg_par; cp_params *cp_par = &env->par.cp_par; dg_params *dg_par = &env->par.dg_par; if (argc < 2){ usage(); exit(0); } printf("SYMPHONY was called with the following arguments:\n"); printf("%s ", argv[0]); for (i = 1; i < argc; i++){ sscanf(argv[i], "%c", &tmp); if (tmp == '-') printf("\n"); printf("%s ", argv[i]); } printf("\n\n"); for (i = 0; i < argc; i++){ if (!strcmp(argv[i], "-f")) break; } if (i == argc){ goto EXIT; }else{ strncpy(env->par.param_file, argv[i+1], MAX_FILE_NAME_LENGTH); } if ((f = fopen(env->par.param_file, "r")) == NULL){ (void) fprintf(stderr, "Readparams: file '%s' can't be opened\n\n", env->par.param_file); return(ERROR__OPENING_PARAM_FILE); } printf("============= Other Parameter Settings =============\n\n"); while (NULL != fgets(line, MAX_LINE_LENGTH, f)){ /* read in parameters */ set_param(env, line); printf("%s", line); strcpy(key,""); sscanf(line,"%s%s", key, value); if (strcmp(key, "lp_mach_num") == 0 || strcmp(key, "TM_lp_mach_num") == 0){ if (tm_par->lp_mach_num){ char *lp_machs = (char *) malloc (tm_par->lp_mach_num * (MACH_NAME_LENGTH + 1)); tm_par->lp_machs = (char **) malloc(tm_par->lp_mach_num * sizeof(char *)); for (i=0; i<tm_par->lp_mach_num; i++) tm_par->lp_machs[i] = lp_machs + i * (MACH_NAME_LENGTH+1); for (i=0; i<tm_par->lp_mach_num; i++){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ fprintf(stderr, "\nio: error reading lp_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "TM_lp_machine") != 0){ fprintf(stderr, "\nio: error reading lp_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } read_string(tm_par->lp_machs[i], line, MACH_NAME_LENGTH); printf("%s", line); } } } else if (strcmp(key, "cg_mach_num") == 0 || strcmp(key, "TM_cg_mach_num") == 0){ if (tm_par->cg_mach_num){ char *cg_machs = (char *) malloc (tm_par->cg_mach_num * (MACH_NAME_LENGTH + 1)); tm_par->cg_machs = (char **) malloc(tm_par->cg_mach_num * sizeof(char *)); for (i=0; i<tm_par->cg_mach_num; i++) tm_par->cg_machs[i] = cg_machs + i * (MACH_NAME_LENGTH+1); for (i=0; i<tm_par->cg_mach_num; i++){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ fprintf(stderr, "\nio: error reading cg_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "TM_cg_machine") != 0){ fprintf(stderr, "\nio: error reading cg_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } read_string(tm_par->cg_machs[i], line, MACH_NAME_LENGTH); printf("%s", line); } } } else if (strcmp(key, "cp_mach_num") == 0 || strcmp(key, "TM_cp_mach_num") == 0){ if (tm_par->cp_mach_num){ char *cp_machs = (char *) malloc (tm_par->cp_mach_num * (MACH_NAME_LENGTH + 1)); tm_par->cp_machs = (char **) malloc(tm_par->cp_mach_num * sizeof(char *)); for (i=0; i<tm_par->cp_mach_num; i++) tm_par->cp_machs[i] = cp_machs + i * (MACH_NAME_LENGTH+1); for (i=0; i<tm_par->cp_mach_num; i++){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ fprintf(stderr, "\nio: error reading cp_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "TM_cp_machine") != 0){ fprintf(stderr, "\nio: error reading cp_machine list\n\n"); return(ERROR__PARSING_PARAM_FILE); } read_string(tm_par->cp_machs[i], line, MACH_NAME_LENGTH); printf("%s", line); } } } else if (strcmp(key, "keep_description_of_pruned") == 0 || strcmp(key, "TM_keep_description_of_pruned") == 0){ if (tm_par->keep_description_of_pruned == KEEP_ON_DISK_FULL || tm_par->keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No pruned node file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "pruned_node_file_name") != 0){ printf("Need pruned_node_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->pruned_node_file_name, value); if (!(f1 = fopen(tm_par->pruned_node_file_name, "w"))){ printf("\nError opening pruned node file\n\n"); }else{ if (tm_par->keep_description_of_pruned == KEEP_ON_DISK_FULL){ fprintf(f1, "******* Pruned Node Log File *******\n\n"); }else{ fprintf(f1, "#TYPE: COMPLETE TREE\n"); fprintf(f1, "#TIME: NOT\n"); fprintf(f1, "#BOUNDS: NONE\n"); fprintf(f1, "#INFORMATION: EXCEPTION\n"); fprintf(f1, "#NODE_NUMBER: NONE\n"); } fclose(f1); } } } else if (strcmp(key, "warm_start") == 0 || strcmp(key, "TM_warm_start") == 0){ if ((env->par.warm_start = tm_par->warm_start)){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No warm start tree file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "warm_start_tree_file_name") != 0){ printf("Need warm_start_tree_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->warm_start_tree_file_name, value); if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No warm start cut file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "warm_start_cut_file_name") != 0){ printf("Need warm_start_cut_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->warm_start_cut_file_name, value); } } else if (strcmp(key, "vbc_emulation") == 0 || strcmp(key, "TM_vbc_emulation") == 0){ if (tm_par->vbc_emulation == VBC_EMULATION_FILE){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No vbc emulation file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "vbc_emulation_file_name") != 0){ printf("Need vbc_emulation_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->vbc_emulation_file_name, value); if (!(f1 = fopen(tm_par->vbc_emulation_file_name, "w"))){ printf("\nError opening vbc emulation file\n\n"); }else{ fprintf(f1, "#TYPE: COMPLETE TREE\n"); fprintf(f1, "#TIME: SET\n"); fprintf(f1, "#BOUNDS: NONE\n"); fprintf(f1, "#INFORMATION: STANDARD\n"); fprintf(f1, "#NODE_NUMBER: NONE\n"); fprintf(f1, "00:00:00.00 N 0 1 %i\n", VBC_CAND_NODE); fclose(f1); } }else if (tm_par->vbc_emulation == VBC_EMULATION_LIVE){ printf("$#TYPE: COMPLETE TREE\n"); printf("$#TIME: SET\n"); printf("$#BOUNDS: NONE\n"); printf("$#INFORMATION: STANDARD\n"); printf("$#NODE_NUMBER: NONE\n"); printf("$N 0 1 %i\n", VBC_CAND_NODE); } } else if (strcmp(key, "logging") == 0 || strcmp(key, "TM_logging") == 0){ if (tm_par->logging){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No tree log file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "tree_log_file_name") != 0){ printf("tree_log_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->tree_log_file_name, value); if (tm_par->logging != VBC_TOOL){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No cut log file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "cut_log_file_name") != 0){ printf("Need cut_log_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(tm_par->cut_log_file_name, value); } } } else if (strcmp(key, "cp_warm_start") == 0 || strcmp(key, "CP_warm_start") == 0){ if (cp_par->warm_start){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No cut pool warm start file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "cp_warm_start_file_name") != 0){ printf("Need cp_warm_start_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(cp_par->warm_start_file_name, value); } } else if (strcmp(key, "cp_logging") == 0 || strcmp(key, "CP_logging") == 0){ if ((tm_par->cp_logging = cp_par->logging)){ if (fgets(line, MAX_LINE_LENGTH, f) == NULL){ printf("No cut pool log file!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(key, ""); sscanf(line, "%s%s", key, value); if (strcmp(key, "cp_log_file_name") != 0){ printf("Need cp_log_file_name next!!!\n\n"); return(ERROR__PARSING_PARAM_FILE); } strcpy(cp_par->log_file_name, value); } } } printf("\n====================================================\n\n"); EXIT: for (i = 1; i < argc; i++){ sscanf(argv[i], "%c %c", &tmp, &c); if (tmp != '-') continue; switch (c) { case 'h': usage(); exit(0); case 'H': #ifdef USE_SYM_APPLICATION user_usage(); #else printf("master [ -H ] [ -F file ] \n\n\t%s\n\t%s\n\t%s\n\t%s\n\n", "-H: help (solver-specific switches)", "-F model: model should be read in from file 'model'", " (MPS format is assumed unless -D is also present)", "-D data: model is in AMPL format and data is in file 'data'"); #endif exit(0); case 'a': lp_par->first_lp.first_cut_time_out = 0; lp_par->first_lp.all_cuts_time_out = 0; lp_par->later_lp.first_cut_time_out = 0; lp_par->later_lp.all_cuts_time_out = 0; break; case 'd': env->par.do_draw_graph = TRUE; break; case 'g': lp_par->use_cg = tm_par->use_cg = TRUE; break; case 'r': tm_par->price_in_root = TRUE; break; case 't': tm_par->trim_search_tree = TRUE; break; case 'b': env->par.do_branch_and_cut = FALSE; break; case 'u': sscanf(argv[++i], "%lf", &env->ub); env->has_ub = TRUE; break; case 'p': sscanf(argv[++i], "%i", &tm_par->max_active_nodes); break; case 'n': sscanf(argv[++i], "%i", &tm_par->node_selection_rule); break; case 'v': sscanf(argv[++i], "%i", &env->par.verbosity); tm_par->verbosity = lp_par->verbosity = cg_par->verbosity = cp_par->verbosity = env->par.verbosity; break; case 's': sscanf(argv[++i], "%i", &lp_par->strong_branching_cand_num_max); lp_par->strong_branching_cand_num_min = lp_par->strong_branching_cand_num_max; lp_par->strong_branching_red_ratio = 0; break; case 'c': sscanf(argv[++i], "%i", &lp_par->compare_candidates_default); break; case 'k': sscanf(argv[++i], "%i", &lp_par->select_child_default); break; case 'm': sscanf(argv[++i], "%i", &lp_par->max_cut_num_per_iter); break; case 'e': sscanf(argv[++i], "%i", &tm_par->max_cp_num); break; case 'l': sscanf(argv[++i], "%i", &lp_par->load_balance_level); sscanf(argv[++i], "%i", &lp_par->load_balance_iterations); break; case 'i': sscanf(argv[++i], "%i", &lp_par->max_presolve_iter); break; case 'f': strncpy(env->par.param_file, argv[++i], MAX_FILE_NAME_LENGTH); break; case 'j': sscanf(argv[++i], "%i", &lp_par->generate_cgl_cuts); break; case 'z': sscanf(argv[++i], "%lf", &tm_par->diving_threshold); break; }; } /*Sanity checks*/ if (cp_par->block_size >cp_par->max_number_of_cuts){ printf("io: Cut pool block size is too big -- adjusting\n"); cp_par->block_size = cp_par->max_number_of_cuts; } if (cp_par->min_to_delete > cp_par->max_number_of_cuts - cp_par->cuts_to_check){ printf("io: Cut pool min to delete is too big -- adjusting\n"); cp_par->min_to_delete = cp_par->max_number_of_cuts - cp_par->cuts_to_check; } /*if (tm_par->price_in_root && tm_par->colgen_strat[0] != (FATHOM__DO_NOT_GENERATE_COLS__SEND | BEFORE_BRANCH__DO_NOT_GENERATE_COLS)){ printf("io: pricing in root is asked for but colums are to be\n"); printf(" generated in the 1st phase -- adjusting colgen_strat[0]\n"); tm_par->colgen_strat[0] = (FATHOM__DO_NOT_GENERATE_COLS__SEND | BEFORE_BRANCH__DO_NOT_GENERATE_COLS); }*/ if (f) fclose(f); return(FUNCTION_TERMINATED_NORMALLY); }
cell parse(char** s) { // Skip whitespace while (isspace(**s)) (*s)++; if (!**s) return NIL; switch (**s) { case '"': { *(*s)++; cell str = read_string(s); return cons(str, parse(s)); } case ')': (*s)++; return NIL; case '(': { (*s)++; cell first = parse(s); return cons(first, parse(s)); } case '\'': { (*s)++; cell rest = parse(s); // ' -> () if (!rest) return NIL; // '.a -> () // ' -> () if (!IS_PAIR(rest)) return NIL; // 'a -> (quote a) if (!IS_PAIR(car(rest))) return cons(LIST2(sym("quote"), car(rest)), cdr(rest)); // '(a b c) -> (quote a b c) return cons(cons(sym("quote"), rest), cdr(rest)); } case '.': { (*s)++; cell rest = parse(s); if (!rest) return NIL; if (TYPE(rest) != PAIR) return NIL; return car(rest); } default: { char* i = *s; while (*i && !isspace(*i) && *i != '(' && *i != ')') i++; size_t token_len = i - *s; char* token = strncpy(malloc(token_len + 1), *s, token_len); token[token_len] = '\0'; *s = i; cell c; // Try to turn the token into a number char* endptr; long val = strtol(token, &endptr, 0); if (endptr != token) c = make_int(val); else c = sym(token); free(token); return cons(c, parse(s)); } } }
int cb_load_conf (const char *fname, const int check_nodef, const int prefix_dir) { char *s; char *e; const char *name; const char *val; void *var; FILE *fp; char *nores; struct noreserve *noresptr; int i; int j; int ret; int saveret; int line; char buff[COB_SMALL_BUFF]; /* initialize the config table */ if (check_nodef) { for (i = 0; config_table[i].name; i++) { config_table[i].val = NULL; } } if (prefix_dir) { snprintf (buff, COB_SMALL_MAX, "%s/%s", cob_config_dir, fname); name = buff; } else { name = fname; } /* open the config file */ fp = fopen (name, "r"); if (fp == NULL) { perror (name); return -1; } /* read the config file */ ret = 0; line = 0; while (fgets (buff, COB_SMALL_BUFF, fp)) { line++; /* skip comments */ if (buff[0] == '#') { continue; } /* skip blank lines */ for (s = buff; *s; s++) { if (isgraph (*s)) { break; } } if (!*s) { continue; } /* get the tag */ s = strpbrk (buff, " \t:="); if (!s) { fprintf (stderr, "%s:%d: invalid line\n", fname, line); ret = -1; continue; } *s = 0; /* find the entry */ for (i = 0; config_table[i].name; i++) { if (strcmp (buff, config_table[i].name) == 0) { break; } } if (!config_table[i].name) { fprintf (stderr, "%s:%d: unknown tag '%s'\n", fname, line, buff); ret = -1; continue; } /* get the value */ for (s++; *s && strchr (" \t:=", *s); s++) { ; } e = s + strlen (s) - 1; for (; e >= s && strchr (" \t\r\n", *e); e--) { ; } e[1] = 0; config_table[i].val = s; /* set the value */ name = config_table[i].name; var = config_table[i].var; val = config_table[i].val; switch (config_table[i].type) { case ANY: if (strcmp (name, "assign-clause") == 0) { if (strcmp (val, "cobol2002") == 0) { unsupported_value (fname, line, val); ret = -1; } else if (strcmp (val, "mf") == 0) { cb_assign_clause = CB_ASSIGN_MF; } else if (strcmp (val, "ibm") == 0) { cb_assign_clause = CB_ASSIGN_IBM; } else if (strcmp (val, "jph1") == 0) { cb_assign_clause = CB_ASSIGN_JPH1; } else { invalid_value (fname, line, name); ret = -1; } } else if (strcmp (name, "binary-size") == 0) { if (strcmp (val, "2-4-8") == 0) { cb_binary_size = CB_BINARY_SIZE_2_4_8; } else if (strcmp (val, "1-2-4-8") == 0) { cb_binary_size = CB_BINARY_SIZE_1_2_4_8; } else if (strcmp (val, "1--8") == 0) { cb_binary_size = CB_BINARY_SIZE_1__8; } else { invalid_value (fname, line, name); ret = -1; } } else if (strcmp (name, "binary-byteorder") == 0) { if (strcmp (val, "native") == 0) { cb_binary_byteorder = CB_BYTEORDER_NATIVE; } else if (strcmp (val, "big-endian") == 0) { cb_binary_byteorder = CB_BYTEORDER_BIG_ENDIAN; } else { invalid_value (fname, line, name); ret = -1; } } else if (strcmp (name, "abort-on-io-exception") == 0) { if (strcmp (val, "any") == 0) { cb_abort_on_io_exception = CB_ABORT_ON_IO_ANY; } else if (strcmp (val, "fatal") == 0) { cb_abort_on_io_exception = CB_ABORT_ON_IO_FATAL; } else if (strcmp (val, "never") == 0) { cb_abort_on_io_exception = CB_ABORT_ON_IO_NEVER; } else { invalid_value (fname, line, name); ret = -1; } } else if (strcmp (name, "default-organization") == 0) { if (strcmp (val, "record-sequential") == 0) { cb_default_organization = CB_ORG_RECORD_SEQUENTIAL; } else if (strcmp (val, "line-sequential") == 0) { cb_default_organization = CB_ORG_LINE_SEQUENTIAL; } else { invalid_value (fname, line, name); ret = -1; } } break; case INT: for (j = 0; val[j]; j++) { if (!isdigit (val[j])) { invalid_value (fname, line, name); ret = -1; break; } } *((int *)var) = atoi (val); break; case STRING: val = read_string (val); if (strcmp (name, "include") == 0) { /* include another conf file */ saveret = ret; if (cb_load_conf (val, 0, 1) != 0) { return -1; } ret = saveret; } else if (strcmp (name, "not-reserved") == 0) { nores = read_string (val); noresptr = cobc_malloc (sizeof (struct noreserve)); noresptr->noresword = cobc_malloc (strlen (nores) + 1); strcpy (noresptr->noresword, nores); noresptr->next = norestab; norestab = noresptr; } else { *((const char **)var) = val; } break; case CHAR: if (1 != strnlen (val, 2)) { invalid_value (fname, line, name); ret = -1; } else { *((char *)var) = *val; } break; case BOOLEAN: if (strcmp (val, "yes") == 0) { *((int *)var) = 1; } else if (strcmp (val, "no") == 0) { *((int *)var) = 0; } else { invalid_value (fname, line, name); ret = -1; } break; case SUPPORT: if (strcmp (val, "ok") == 0) { *((enum cb_support *)var) = CB_OK; } else if (strcmp (val, "warning") == 0) { *((enum cb_support *)var) = CB_WARNING; } else if (strcmp (val, "archaic") == 0) { *((enum cb_support *)var) = CB_ARCHAIC; } else if (strcmp (val, "obsolete") == 0) { *((enum cb_support *)var) = CB_OBSOLETE; } else if (strcmp (val, "skip") == 0) { *((enum cb_support *)var) = CB_SKIP; } else if (strcmp (val, "ignore") == 0) { *((enum cb_support *)var) = CB_IGNORE; } else if (strcmp (val, "error") == 0) { *((enum cb_support *)var) = CB_ERROR; } else if (strcmp (val, "unconformable") == 0) { *((enum cb_support *)var) = CB_UNCONFORMABLE; } else { invalid_value (fname, line, name); ret = -1; } break; default: fprintf (stderr, _("%s:%d: invalid type for '%s'\n"), fname, line, name); ret = -1; break; } } fclose (fp); /* if assign_external is not setted in config file */ for (i = 0; config_table[i].name; i++) { if (config_table[i].val == NULL && strcmp (config_table[i].name, "assign_external") == 0) { config_table[i].val = (char *)"no"; *((int *)config_table[i].var) = 0; } } /* checks for no definition */ if (check_nodef) { for (i = 2; config_table[i].name; i++) { if (config_table[i].val == NULL) { fprintf (stderr, "%s: no definition of '%s'\n", fname, config_table[i].name); ret = -1; } } } return ret; }
static enum proto_parse_status skinny_sbuf_parse(struct parser *parser, struct proto_info *parent, unsigned way, uint8_t const *packet, size_t cap_len, size_t wire_len, struct timeval const *now, size_t tot_cap_len, uint8_t const *tot_packet) { struct skinny_parser *skinny_parser = DOWNCAST(parser, parser, skinny_parser); # define SKINNY_HDR_SIZE 8 # define SKINNY_MIN_MSG_SIZE 12 if (wire_len < SKINNY_MIN_MSG_SIZE) { streambuf_set_restart(&skinny_parser->sbuf, way, packet, true); // wait for more return PROTO_OK; } if (cap_len < SKINNY_MIN_MSG_SIZE) return PROTO_TOO_SHORT; struct cursor curs; cursor_ctor(&curs, packet, cap_len); uint32_t msg_len = cursor_read_u32le(&curs); enum skinny_header_version header_ver = cursor_read_u32le(&curs); enum skinny_msgid msg_id = cursor_read_u32le(&curs); SLOG(LOG_DEBUG, "New SKINNY msg of size %"PRIu32", msgid=0x%"PRIx32, msg_len, msg_id); if (header_ver != SKINNY_BASIC && header_ver != SKINNY_CM7_TYPE_A && header_ver != SKINNY_CM7_TYPE_B && header_ver != SKINNY_CM7_TYPE_C) return PROTO_PARSE_ERR; if (msg_len < 4 || msg_len > SKINNY_MAX_HDR_SIZE /* guestimated */) return PROTO_PARSE_ERR; if (wire_len < msg_len + SKINNY_HDR_SIZE) return PROTO_TOO_SHORT; // wait for the message to be complete // Ok we have what looks like a skinny message in there struct skinny_proto_info info; skinny_proto_info_ctor(&info, parser, parent, SKINNY_HDR_SIZE, msg_len, msg_id, header_ver); switch (msg_id) { case SKINNY_STATION_KEY_PAD_BUTTON: if (curs.cap_len < 12) return PROTO_TOO_SHORT; info.set_values |= SKINNY_NEW_KEY_PAD | SKINNY_LINE_INSTANCE | SKINNY_CALL_ID; info.new_key_pad = cursor_read_u32le(&curs); info.line_instance = cursor_read_u32le(&curs); info.call_id = cursor_read_u32le(&curs); break; case SKINNY_MGR_CALL_STATE: if (curs.cap_len < 12) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CALL_STATE | SKINNY_LINE_INSTANCE | SKINNY_CALL_ID; info.call_state = cursor_read_u32le(&curs); info.line_instance = cursor_read_u32le(&curs); info.call_id = cursor_read_u32le(&curs); SLOG(LOG_DEBUG, "New call state: %s", skinny_call_state_2_str(info.call_state)); break; case SKINNY_MGR_CLOSE_RECV_CHANNEL: case SKINNY_MGR_STOP_MEDIA_TRANSMIT: if (curs.cap_len < 8) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CONFERENCE_ID | SKINNY_PASS_THRU_ID; info.conf_id = cursor_read_u32le(&curs); info.pass_thru_id = cursor_read_u32le(&curs); break; case SKINNY_MGR_START_MEDIA_TRANSMIT: if (curs.cap_len < 8) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CONFERENCE_ID | SKINNY_PASS_THRU_ID; info.conf_id = cursor_read_u32le(&curs); info.pass_thru_id = cursor_read_u32le(&curs); enum proto_parse_status status = read_channel(skinny_parser, FROM_MGR, &info, &curs, now); if (PROTO_OK != status) return status; break; case SKINNY_STATION_OPEN_RECV_CHANNEL_ACK: if (curs.cap_len < 4) return PROTO_TOO_SHORT; uint32_t open_status = cursor_read_u32le(&curs); if (open_status == 0 /* Ok */) { enum proto_parse_status status = read_channel(skinny_parser, FROM_STATION, &info, &curs, now); if (PROTO_OK != status) return status; info.set_values |= SKINNY_PASS_THRU_ID; if (curs.cap_len < 4) return PROTO_TOO_SHORT; info.pass_thru_id = cursor_read_u32le(&curs); } break; case SKINNY_MGR_OPEN_RECV_CHANNEL: if (curs.cap_len < 8) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CONFERENCE_ID | SKINNY_PASS_THRU_ID; info.conf_id = cursor_read_u32le(&curs); info.pass_thru_id = cursor_read_u32le(&curs); break; case SKINNY_MGR_DIALED_NUMBER: # define DIALED_NUMBER_SIZE 24 if (curs.cap_len < DIALED_NUMBER_SIZE+8) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CALLED_PARTY | SKINNY_LINE_INSTANCE | SKINNY_CALL_ID; // 24 chars, terminated with 0 (if fits) snprintf(info.called_party, sizeof(info.called_party), "%.*s", (int)DIALED_NUMBER_SIZE, curs.head); cursor_drop(&curs, DIALED_NUMBER_SIZE); info.line_instance = cursor_read_u32le(&curs); info.call_id = cursor_read_u32le(&curs); break; case SKINNY_MGR_CALL_INFO: if (curs.cap_len < 8 + 4 + 5*4) return PROTO_TOO_SHORT; info.set_values |= SKINNY_CALLING_PARTY | SKINNY_CALLED_PARTY | SKINNY_LINE_INSTANCE | SKINNY_CALL_ID; info.line_instance = cursor_read_u32le(&curs); info.call_id = cursor_read_u32le(&curs); cursor_drop(&curs, 4 + 5*4); // drop Call Type and 5 unknown fields // From now on, informations are nul terminated strings if (PROTO_OK != (status = read_string(info.calling_party, sizeof(info.calling_party), &curs))) return status; // Calling party if (header_ver == SKINNY_CM7_TYPE_A || header_ver == SKINNY_CM7_TYPE_B || header_ver == SKINNY_CM7_TYPE_C) { cursor_read_string(&curs, NULL, 24); // Drop calling party voice mailbox } if (PROTO_OK != (status = read_string(info.called_party, sizeof(info.called_party), &curs))) return status; // Called party // discard the rest of informations break; default: break; } (void)proto_parse(NULL, &info.info, way, NULL, 0, 0, now, tot_cap_len, tot_packet); streambuf_set_restart(&skinny_parser->sbuf, way, packet + SKINNY_HDR_SIZE + msg_len, false); // go to next msg return PROTO_OK; }
void load_ns_dbase(void) { dbFILE *f; int ver, i, j, c; NickAlias *na, **nalast, *naprev; NickCore *nc, **nclast, *ncprev; int failed = 0; uint16 tmp16; uint32 tmp32; char *s, *pass; if (!(f = open_db(s_NickServ, NickDBName, NICK_VERSION))) return; ver = get_file_version(f); if (ver <= 11) { // close_db(f); // load_old_ns_dbase(); printf("old database gtfo !\n"); return; } /* First we load nick cores */ for (i = 0; i < 1024 && !failed; i++) { nclast = &nclists[i]; ncprev = NULL; while ((c = getc_db(f)) == 1) { if (c != 1) printf("Invalid format in %s", NickDBName); nc = scalloc(1, sizeof(NickCore)); *nclast = nc; nclast = &nc->next; nc->prev = ncprev; ncprev = nc; slist_init(&nc->aliases); SAFE(read_string(&nc->display, f)); printf("%s", nc->display); if (ver < 14) { SAFE(read_string(&pass, f)); if (pass) { memset(nc->pass, 0, PASSMAX); memcpy(nc->pass, pass, strlen(pass)); } else memset(nc->pass, 0, PASSMAX); } else SAFE(read_buffer(nc->pass, f)); // printf(" %s", nc->pass); SAFE(read_string(&nc->email, f)); // printf(" %s", nc->email); SAFE(read_string(&nc->greet, f)); // printf(" %s", nc->greet); SAFE(read_int32(&nc->icq, f)); // printf(" %d", nc->icq); SAFE(read_string(&nc->url, f)); // printf(" %s\n", nc->url); SAFE(read_int32(&nc->flags, f)); if (!NSAllowKillImmed) nc->flags &= ~NI_KILL_IMMED; SAFE(read_int16(&nc->language, f)); /* Add services opers and admins to the appropriate list, but only if the database version is more than 10. */ /* if (nc->flags & NI_SERVICES_ADMIN) slist_add(&servadmins, nc); if (nc->flags & NI_SERVICES_OPER) slist_add(&servopers, nc); */ // OSEF des axx Sop et Sadmin ! SAFE(read_int16(&nc->accesscount, f)); if (nc->accesscount) { char **access; access = scalloc(sizeof(char *) * nc->accesscount, 1); nc->access = access; for (j = 0; j < nc->accesscount; j++, access++) SAFE(read_string(access, f)); } SAFE(read_int16(&tmp16, f)); nc->memos.memocount = (int16) tmp16; SAFE(read_int16(&tmp16, f)); nc->memos.memomax = (int16) tmp16; if (nc->memos.memocount) { Memo *memos; memos = scalloc(sizeof(Memo) * nc->memos.memocount, 1); nc->memos.memos = memos; for (j = 0; j < nc->memos.memocount; j++, memos++) { SAFE(read_int32(&memos->number, f)); SAFE(read_int16(&memos->flags, f)); SAFE(read_int32(&tmp32, f)); memos->time = tmp32; SAFE(read_buffer(memos->sender, f)); SAFE(read_string(&memos->text, f)); memos->moduleData = NULL; } } SAFE(read_int16(&nc->channelcount, f)); SAFE(read_int16(&tmp16, f)); nc->channelmax = CSMaxReg; if (ver < 13) { /* Used to be dead authentication system */ SAFE(read_int16(&tmp16, f)); SAFE(read_int32(&tmp32, f)); SAFE(read_int16(&tmp16, f)); SAFE(read_string(&s, f)); } } /* while (getc_db(f) != 0) */ *nclast = NULL; } /* for (i) */ for (i = 0; i < 1024 && !failed; i++) { nalast = &nalists[i]; naprev = NULL; while ((c = getc_db(f)) == 1) { if (c != 1) printf("Invalid format in %s", NickDBName); na = scalloc(1, sizeof(NickAlias)); SAFE(read_string(&na->nick, f)); SAFE(read_string(&na->last_usermask, f)); SAFE(read_string(&na->last_realname, f)); SAFE(read_string(&na->last_quit, f)); SAFE(read_int32(&tmp32, f)); na->time_registered = tmp32; SAFE(read_int32(&tmp32, f)); na->last_seen = tmp32; SAFE(read_int16(&na->status, f)); na->status &= ~NS_TEMPORARY; SAFE(read_string(&s, f)); na->nc = findcore(s); free(s); slist_add(&na->nc->aliases, na); if (!(na->status & NS_VERBOTEN)) { if (!na->last_usermask) na->last_usermask = sstrdup(""); if (!na->last_realname) na->last_realname = sstrdup(""); } na->nc->flags &= ~NI_SERVICES_ROOT; *nalast = na; nalast = &na->next; na->prev = naprev; naprev = na; } /* while (getc_db(f) != 0) */ *nalast = NULL; } /* for (i) */ // close_db(f); // nevermind wasting memory for (i = 0; i < 1024; i++) { NickAlias *next; for (na = nalists[i]; na; na = next) { next = na->next; /* We check for coreless nicks (although it should never happen) */ if (!na->nc) { printf("%s: while loading database: %s has no core! We delete it (here just ignore it !).", s_NickServ, na->nick); // delnick(na); continue; } /* Add the Services root flag if needed. */ /* for (j = 0; j < RootNumber; j++) if (!stricmp(ServicesRoots[j], na->nick)) na->nc->flags |= NI_SERVICES_ROOT; */ // OSEF de savoir si Paul Pierre ou Jacques est Services Root ! } } }
memcache_item* file_reader::read_item(void) { // parse next line unsigned int s_dumpflags = 0; unsigned int s_time = 0; unsigned int s_exptime = 0; unsigned int s_nbytes = 0; unsigned int s_nsuffix = 0; unsigned int s_flags = 0; unsigned int s_clsid = 0; unsigned int s_nkey = 0; // scan int values if (fscanf(m_file, "%u, %u, %u, %u, %u, %u, %u, %u, ", &s_dumpflags, &s_time, &s_exptime, &s_nbytes, &s_nsuffix, &s_flags, &s_clsid, &s_nkey) < 8) { if (is_eof()) return NULL; fprintf(stderr, "%s:%u: error parsing item values.\n", m_filename, m_line); return NULL; } // read key unsigned int key_actlen = 0; char *key = read_string(s_nkey, s_nkey + 1, &key_actlen); if (key_actlen != s_nkey) { fprintf(stderr, "%s:%u: warning: key column is %u bytes, expected %u bytes.\n", m_filename, m_line, key_actlen, s_nkey); } key[s_nkey] = '\0'; // read data int c = fgetc(m_file); if (c != ',') { fprintf(stderr, "%s:%u: error parsing csv file, got '%c' instead of delmiter.\n", m_filename, m_line, c); free(key); return NULL; } fgetc(m_file); unsigned int data_actlen = 0; char *data = read_string(s_nbytes - 2, s_nbytes, &data_actlen); if (data_actlen != s_nbytes - 2) { fprintf(stderr, "%s:%u: warning: data column is %u bytes, expected %u bytes.\n", m_filename, m_line, data_actlen, s_nbytes); free(key); free(data); return NULL; } data[s_nbytes - 2] = '\r'; data[s_nbytes - 1] = '\n'; // handle end of line c = fgetc(m_file); if (c == '\r') { c = fgetc(m_file); } if (c != '\n') { fprintf(stderr, "%s:%u: warning: end of line expected but not found.\n", m_filename, m_line); } m_line++; // return item memcache_item *item = new memcache_item(s_dumpflags, s_time, s_exptime, s_flags, s_nsuffix, s_clsid); item->set_key(key, s_nkey); item->set_data(data, s_nbytes); return item; }
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth) { if (depth >= 100) { err = true; return; } if (in == end) { err = true; return; } switch (*in) { // ---------------------------------------------- // integer case 'i': { ++in; // 'i' std::string val = read_until(in, end, 'e', err); if (err) return; TORRENT_ASSERT(*in == 'e'); ++in; // 'e' ret = entry(entry::int_t); ret.integer() = boost::lexical_cast<entry::integer_type>(val); } break; // ---------------------------------------------- // list case 'l': { ret = entry(entry::list_t); ++in; // 'l' while (*in != 'e') { ret.list().push_back(entry()); entry& e = ret.list().back(); bdecode_recursive(in, end, e, err, depth + 1); if (err) return; if (in == end) { err = true; return; } } TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // dictionary case 'd': { ret = entry(entry::dictionary_t); ++in; // 'd' while (*in != 'e') { entry key; bdecode_recursive(in, end, key, err, depth + 1); if (err) return; entry& e = ret[key.string()]; bdecode_recursive(in, end, e, err, depth + 1); if (err) return; if (in == end) { err = true; return; } } TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // string default: if (isdigit((unsigned char)*in)) { std::string len_s = read_until(in, end, ':', err); if (err) return; TORRENT_ASSERT(*in == ':'); ++in; // ':' int len = std::atoi(len_s.c_str()); ret = entry(entry::string_t); read_string(in, end, len, ret.string(), err); if (err) return; } else { err = true; return; } } }
ssize_t trace_report(int fd, struct pevent **ppevent, bool __repipe) { char buf[BUFSIZ]; char test[] = { 23, 8, 68 }; char *version; int show_version = 0; int show_funcs = 0; int show_printk = 0; ssize_t size = -1; int file_bigendian; int host_bigendian; int file_long_size; int file_page_size; struct pevent *pevent; int err; *ppevent = NULL; repipe = __repipe; input_fd = fd; if (do_read(buf, 3) < 0) return -1; if (memcmp(buf, test, 3) != 0) { pr_debug("no trace data in the file"); return -1; } if (do_read(buf, 7) < 0) return -1; if (memcmp(buf, "tracing", 7) != 0) { pr_debug("not a trace file (missing 'tracing' tag)"); return -1; } version = read_string(); if (version == NULL) return -1; if (show_version) printf("version = %s\n", version); free(version); if (do_read(buf, 1) < 0) return -1; file_bigendian = buf[0]; host_bigendian = bigendian(); pevent = read_trace_init(file_bigendian, host_bigendian); if (pevent == NULL) { pr_debug("read_trace_init failed"); goto out; } if (do_read(buf, 1) < 0) goto out; file_long_size = buf[0]; file_page_size = read4(pevent); if (!file_page_size) goto out; pevent_set_long_size(pevent, file_long_size); pevent_set_page_size(pevent, file_page_size); err = read_header_files(pevent); if (err) goto out; err = read_ftrace_files(pevent); if (err) goto out; err = read_event_files(pevent); if (err) goto out; err = read_proc_kallsyms(pevent); if (err) goto out; err = read_ftrace_printk(pevent); if (err) goto out; size = trace_data_size; repipe = false; if (show_funcs) { pevent_print_funcs(pevent); } else if (show_printk) { pevent_print_printk(pevent); } *ppevent = pevent; pevent = NULL; out: if (pevent) pevent_free(pevent); return size; }
int main(int argc, char **argv) { int max_tries = 5; int try; char username[32]; int optidx = 0; int ask = 1; struct sigaction sa; setprogname(argv[0]); #ifdef KRB5 { krb5_error_code ret; ret = krb5_init_context(&context); if (ret) errx (1, "krb5_init_context failed: %d", ret); } #endif openlog("login", LOG_ODELAY | LOG_PID, LOG_AUTH); if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx)) usage (1); argc -= optidx; argv += optidx; if(help_flag) usage(0); if (version_flag) { print_version (NULL); return 0; } if (geteuid() != 0) errx(1, "only root may use login, use su"); /* Default tty settings. */ stty_default(); if(p_flag) copy_env(); else { /* this set of variables is always preserved by BSD login */ if(getenv("TERM")) add_env("TERM", getenv("TERM")); if(getenv("TZ")) add_env("TZ", getenv("TZ")); } if(*argv){ if(strchr(*argv, '=') == NULL && strcmp(*argv, "-") != 0){ strlcpy (username, *argv, sizeof(username)); ask = 0; } } #if defined(DCE) && defined(AIX) esetenv("AUTHSTATE", "DCE", 1); #endif /* XXX should we care about environment on the command line? */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGALRM, &sa, NULL); alarm(login_timeout); for(try = 0; try < max_tries; try++){ struct passwd *pwd; char password[128]; int ret; char ttname[32]; char *tty, *ttyn; char prompt[128]; #ifdef OTP char otp_str[256]; #endif if(ask){ f_flag = 0; #if 0 r_flag = 0; #endif ret = read_string("login: "******""); } else #endif { #ifdef OTP if(auth_level && strcmp(auth_level, "otp") == 0 && otp_challenge(&otp_ctx, username, otp_str, sizeof(otp_str)) == 0) snprintf (prompt, sizeof(prompt), "%s's %s Password: "******"Password: "******"Login incorrect.\n"); ask = 1; continue; } if(f_flag == 0 && check_password(pwd, password)){ fprintf(stderr, "Login incorrect.\n"); ask = 1; continue; } ttyn = ttyname(STDIN_FILENO); if(ttyn == NULL){ snprintf(ttname, sizeof(ttname), "%s??", _PATH_TTY); ttyn = ttname; } if (strncmp (ttyn, _PATH_DEV, strlen(_PATH_DEV)) == 0) tty = ttyn + strlen(_PATH_DEV); else tty = ttyn; if (login_access (pwd, remote_host ? remote_host : tty) == 0) { fprintf(stderr, "Permission denied\n"); if (remote_host) syslog(LOG_NOTICE, "%s LOGIN REFUSED FROM %s", pwd->pw_name, remote_host); else syslog(LOG_NOTICE, "%s LOGIN REFUSED ON %s", pwd->pw_name, tty); exit (1); } else { if (remote_host) syslog(LOG_NOTICE, "%s LOGIN ACCEPTED FROM %s ppid=%d", pwd->pw_name, remote_host, (int) getppid()); else syslog(LOG_NOTICE, "%s LOGIN ACCEPTED ON %s ppid=%d", pwd->pw_name, tty, (int) getppid()); } alarm(0); do_login(pwd, tty, ttyn); } exit(1); }
/** * Call by the exeption to handle the syscall * \private */ void syscall_handler(registers_t * regs) { int32_t res = 0; int32_t syscall = regs->v_reg[0]; // code of the syscall switch (syscall) { case FOURCHETTE: res = create_proc(get_arg((char **) regs->a_reg[2], 0), regs->a_reg[0], regs->a_reg[1], (char **) regs->a_reg[2]); if (res < 0) *p_error = res; break; case PRINT: res = print_string((char *) regs->a_reg[0]); return; /* We save the good return value in the pcb */ case READ: res = read_string((char *) regs->a_reg[0], regs->a_reg[1]); return; /* We save the good return value in the pcb */ case FPRINT: if (regs->a_reg[0] == CONSOLE) kprint((char *) regs->a_reg[1]); else kmaltaprint8((char *) regs->a_reg[1]); break; case SLEEP: res = go_to_sleep(regs->a_reg[0]); break; case BLOCK: res = kblock(regs->a_reg[0], BLOCKED); break; case UNBLOCK: kwakeup(regs->a_reg[0]); break; case WAIT: res = waitfor(regs->a_reg[0], (int32_t *) regs->a_reg[1]); break; case SEND: res = send_msg(pcb_get_pid(get_current_pcb()), (msg_arg *) regs->a_reg[0]); break; case RECV: res = recv_msg(pcb_get_pid(get_current_pcb()), (msg_arg *) regs->a_reg[0]); if (res == NOTFOUND) go_to_sleep(((msg_arg *) regs->a_reg[0])->timeout); break; case PERROR: kperror((char *) regs->a_reg[0]); break; case GERROR: res = kgerror(); break; case SERROR: kserror(regs->a_reg[0]); break; case GETPINFO: res = get_pinfo(regs->a_reg[0], (pcbinfo *) regs->a_reg[1]); break; case GETPID: res = pcb_get_pid(get_current_pcb()); break; case GETALLPID: res = get_all_pid((int *) regs->a_reg[0]); break; case CHGPPRI: res = chg_ppri(regs->a_reg[0], regs->a_reg[1]); break; case KILL: res = kkill(regs->a_reg[0]); break; case EXIT: kexit(regs->a_reg[0]); break; default: kprintln("ERROR: Unknown syscall"); break; } // saves the return code regs->v_reg[0] = res; return; }
/***************************************************************************** * Function: var_clusterFileSystems * ****************************************************************************/ unsigned char * var_clusterFileSystems(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { /* variables we may use later */ static long long_ret; static u_long ulong_ret; static unsigned char string[SPRINT_MAX_LEN]; char file_path[MAX_PATH_SIZE]; uint32_t num; char *dir_list; if (header_generic(vp,name,length,exact,var_len,write_method) == MATCH_FAILED ) return NULL; /* * this is where we do the value assignments for the mib results. */ switch(vp->magic) { case SYSVERSION: sprintf(file_path, "%s%s", LUSTRE_PATH,"version"); if( SUCCESS != read_string(file_path, (char *)string,sizeof(string))) return NULL; *var_len = strlen((char *)string); return (unsigned char *) string; case SYSKERNELVERSION: sprintf(file_path, "%s%s", LUSTRE_PATH,"kernel_version"); if( SUCCESS != read_string(file_path, (char *)string,sizeof(string))) return NULL; *var_len = strlen((char *)string); return (unsigned char *) string; case SYSHEALTHCHECK: sprintf(file_path, "%s%s", LUSTRE_PATH,FILENAME_SYSHEALTHCHECK); if( SUCCESS != read_string(file_path, (char *)string,sizeof(string))) return NULL; *var_len = strlen((char*)string); return (unsigned char *) string; case SYSSTATUS: *write_method = write_sysStatus; long_ret = (long) get_sysstatus(); if (long_ret != ERROR) return (unsigned char *) &long_ret; return NULL; case OSDNUMBER: if( 0 == (dir_list = get_file_list(OSD_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",OSD_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case OSCNUMBER: if( 0 == (dir_list = get_file_list(OSC_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",OSC_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case MDDNUMBER: if( 0 == (dir_list = get_file_list(MDS_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",MDS_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case MDCNUMBER: if( 0 == (dir_list = get_file_list(MDC_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",MDC_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case CLIMOUNTNUMBER: if( 0 == (dir_list = get_file_list(CLIENT_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",CLIENT_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case LOVNUMBER: if( 0 == (dir_list = get_file_list(LOV_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",LOV_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; case LDLMNUMBER: if( 0 == (dir_list = get_file_list(LDLM_PATH, DIR_TYPE, &num))) return NULL; DEBUGMSGTL(("lsnmpd","num(%s)=%d\n",LDLM_PATH,num)); ulong_ret = num; free(dir_list); return (unsigned char *) &ulong_ret; default: ERROR_MSG(""); } return NULL; }
int main(int argc, char** argv) { if (argc != 2) { printf("Usage: %s HPROF_FILE\n", argv[0]); exit(1); } FILE* hprof_fp = fopen(argv[1], "r"); die(hprof_fp == NULL, "File error"); hprof_header* header; char version[19]; u4 ident_size; int count = fread(version, sizeof(version), 1, hprof_fp); die(count != 1, "Unable to read hprof header"); count = fread(&ident_size, sizeof(u4), 1, hprof_fp); die(count != 1, "Unable to read hprof header"); int success = fseek(hprof_fp, sizeof(u8), SEEK_CUR); die(success != 0, "Could not seek forward in the file"); printf("Header: version=%s identsize=%ju\n", version, (uintmax_t) be32_to_native(ident_size)); // For now just reuse it hprof_record_header* record_header = calloc(1, sizeof(hprof_record_header)); hprof_heap_summary* heap_summary = calloc(1, sizeof(hprof_heap_summary)); // The string table is a skip list that should give us // O(n log n) insertion and O(log n) lookup, This is not as // good as a malloc'd array, but does not suffer from the // out of order issues that the string id's present us with skiplist_t *string_table = malloc(sizeof(skiplist_t)); skiplist_init(string_table); skiplist_set_cmp_fn(string_table, stringtable_cmp); skiplist_set_search_fn(string_table, stringtable_search); skiplist_set_destroy_fn(string_table, __destroy); skiplist_t *class_table = malloc(sizeof(skiplist_t)); skiplist_init(class_table); skiplist_set_cmp_fn(class_table, classtable_cmp); skiplist_set_search_fn(class_table, classtable_search); skiplist_set_destroy_fn(class_table, __destroy); while(1) { if (feof(hprof_fp)) { break; } //read_record_header(record_header, hprof_fp); funpack(hprof_fp, "bd>d>", &record_header->tag, &record_header->profiling_ms, &record_header->remaining_bytes); //printf("Tag=%ju\n", (uintmax_t) record_header->tag); switch(record_header->tag) { case UTF8: //printf("UTF8\n"); ; hprof_utf8 *utf8 = malloc(sizeof(hprof_utf8)); funpack(hprof_fp, "q>", &utf8->id); //fread(&utf8->id, sizeof(id), 1, hprof_fp); long bytes_remain = record_header->remaining_bytes - sizeof(id); // Awesome, hprof strings are utf8, this is good ! the only established // C type is char and its a byte wide :D utf8->num_chars = bytes_remain / sizeof(char); utf8->hprof_offset = ftell(hprof_fp); skiplist_insert(string_table, utf8); fseek(hprof_fp, bytes_remain, SEEK_CUR); break; case LOAD_CLASS: //printf("LOAD_CLASS\n"); ; hprof_load_class *class = malloc(sizeof(hprof_load_class)); fread(&class->serial_number, sizeof(u4), 1, hprof_fp); class->serial_number = be32_to_native(class->serial_number); fseek(hprof_fp, sizeof(id) + sizeof(u4), SEEK_CUR); fread(&class->name_id, sizeof(id), 1, hprof_fp); class->name_id = be64_to_native(class->name_id); skiplist_insert(class_table, class); //fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case UNLOAD_CLASS: //printf("UNLOAD_CLASS\n"); fseek(hprof_fp, record_header->remaining_bytes, SEEK_CUR); break; case FRAME: //printf("FRAME\n"); // This is bad !!! If it is slow think about doing two complete passes to // make all the I/O as sequential as possible // This implementation is going to jump all over the hprof file ; long curr_pos = ftell(hprof_fp); id ids[4]; fread(&ids, sizeof(id), 4, hprof_fp); u4 class_serial_num; fread(&class_serial_num, sizeof(u4), 1, hprof_fp); class_serial_num = be32_to_native(class_serial_num); hprof_load_class *clazz = (hprof_load_class*) skiplist_search(class_table, &class_serial_num); i4 line_num; fread(&line_num, sizeof(i4), 1, hprof_fp); line_num = be32_to_native(line_num); char *method_name = read_string(be64_to_native(ids[1]), string_table, hprof_fp); char *method_sig = read_string(be64_to_native(ids[2]), string_table, hprof_fp); char *source_file = read_string(be64_to_native(ids[3]), string_table, hprof_fp); char *class_name = "<UNKNOWN_CLASS>"; if(clazz != NULL) { class_name = read_string(clazz->name_id, string_table, hprof_fp); } // SOMETIMES NULL //printf("%s\n", read_string(ids[3], string_table, hprof_fp)); class_name = (class_name == NULL) ? "<UNKNOWN_CLASS>" : class_name; method_name = (method_name == NULL) ? "<UNKNOWN_METHOD>" : method_name; method_sig = (method_sig == NULL) ? "<UNKNOWN_METHOD_SIG>" : method_sig; source_file = (source_file == NULL) ? "<UNKNOWN_SOURCE>" : source_file; switch(line_num) { case -1: printf("Class %s\n \tMethod=%s\n\tSource=%s @ <UNKNOWN>\n", class_name, method_name, source_file); break; case -2: printf("Class %s\n \tMethod=%s\n\tSource=%s @ <COMPILED_METHOD>\n", class_name, method_name, source_file); break; case -3: printf("Class %s\n \tMethod=%s\n\tSource=%s @ <NATIVE_METHOD>\n", class_name, method_name, source_file); break; default: printf("Class %s\n \tMethod=%s\n\tSource=%s @ %ji\n", class_name, method_name, source_file, (intmax_t) line_num); break; } break; case TRACE: //printf("TRACE\n"); ; hprof_stacktrace* stacktrace = calloc(1, sizeof(hprof_stacktrace)); fread(&stacktrace->serial_number, sizeof(u4), 1, hprof_fp); fread(&stacktrace->thread_number, sizeof(u4), 1, hprof_fp); fread(&stacktrace->number_frames, sizeof(u4), 1, hprof_fp); printf("StackTrace serial_num=%ju " "thread_num=%ju num_frames=%ju\n", (uintmax_t) be64_to_native(stacktrace->serial_number), (uintmax_t) be64_to_native(stacktrace->thread_number), (uintmax_t) be64_to_native(stacktrace->number_frames)); for (int i=0; i < be32_to_native(stacktrace->number_frames); i++) { id frame_id; fread(&frame_id, sizeof(id), 1, hprof_fp); printf("FrameID=%ju\n", (uintmax_t) be64_to_native(frame_id)); } free(stacktrace); break; case ALLOC_SITES: //printf("ALLOC_SITES\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case HEAP_SUMMARY: //printf("HEAP SUMMARY\n"); fread(&heap_summary->live_bytes, sizeof(u4), 1, hprof_fp); fread(&heap_summary->live_instances, sizeof(u4), 1, hprof_fp); fread(&heap_summary->allocated_bytes, sizeof(u8), 1, hprof_fp); fread(&heap_summary->allocated_instances, sizeof(u8), 1, hprof_fp); printf("Heap summary:\n\tReachable bytes=%ju\n\t" "Reachable instances=%ju\n\t" "Allocated bytes=%ju\n\t" "Allocated instances=%ju\n", (uintmax_t) be32_to_native(heap_summary->live_bytes), (uintmax_t) be32_to_native(heap_summary->live_instances), (uintmax_t) be64_to_native(heap_summary->allocated_bytes), (uintmax_t) be64_to_native(heap_summary->allocated_instances)); break; case START_THREAD: //printf("START_THREAD\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case END_THREAD: //printf("END_THREAD\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case HEAP_DUMP: //printf("HEAP_DUMP\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case CPU_SAMPLES: //printf("CPU_SAMPLES\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case CONTROL_SETTINGS: //printf("CONTROL_SETTINGS\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case HEAP_DUMP_SEGMENT: //printf("HEAP_DUMP_SEGMENT\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); break; case HEAP_DUMP_END: //printf("HEAP_DUMP_END\n"); fseek(hprof_fp, be32_to_native(record_header->remaining_bytes), SEEK_CUR); exit(1); break; default: printf("BANG\n"); exit(1); break; } //printf("%lu\n", ftell(hprof_fp)); } skiplist_destroy(string_table); free(string_table); skiplist_destroy(class_table); free(class_table); fclose(hprof_fp); return 0; }
/***************************************************************************** * Function: var_lnetInformation * ****************************************************************************/ unsigned char * var_lnetInformation(struct variable *vp, oid *name, size_t *length, int exact, size_t *var_len, WriteMethod **write_method) { /* variables we may use later */ static unsigned char string[SPRINT_MAX_LEN]; static unsigned int i[7]; static unsigned long long ull[4]; static unsigned long next_update; static counter64 c64; static unsigned int c32; struct timeval current_tv; unsigned long current; char file_path[MAX_PATH_SIZE]; /* Update at most every LNET_STATS_INTERVAL milliseconds */ gettimeofday(¤t_tv, NULL); current = current_tv.tv_sec * 1000000 + current_tv.tv_usec; if (current >= next_update) { sprintf(file_path, "%s%s", LNET_PATH, "stats"); if (read_string(file_path, (char *) string, sizeof(string)) != SUCCESS) return NULL; sscanf((char *) string, "%u %u %u %u %u %u %u %llu %llu %llu %llu", &i[0], &i[1], &i[2], &i[3], &i[4], &i[5], &i[6], &ull[0], &ull[1], &ull[2], &ull[3]); next_update = current + (LNET_CHECK_INTERVAL * 1000); } if (header_generic(vp, name, length, exact, var_len, write_method) == MATCH_FAILED) return NULL; switch (vp->magic) { case LNETMSGSALLOC: *var_len = sizeof(c32); c32 = i[0]; return (unsigned char *) &c32; case LNETMSGSMAX: *var_len = sizeof(c32); c32 = i[1]; return (unsigned char *) &c32; case LNETERRORS: *var_len = sizeof(c32); c32 = i[2]; return (unsigned char *) &c32; case LNETSENDCOUNT: *var_len = sizeof(c32); c32 = i[3]; return (unsigned char *) &c32; case LNETRECVCOUNT: *var_len = sizeof(c32); c32 = i[4]; return (unsigned char *) &c32; case LNETROUTECOUNT: *var_len = sizeof(c32); c32 = i[5]; return (unsigned char *) &c32; case LNETDROPCOUNT: *var_len = sizeof(c32); c32 = i[6]; return (unsigned char *) &c32; case LNETSENDBYTES: convert_ull(&c64, ull[0], var_len); return (unsigned char *) &c64; case LNETRECVBYTES: convert_ull(&c64, ull[1], var_len); return (unsigned char *) &c64; case LNETROUTEBYTES: convert_ull(&c64, ull[2], var_len); return (unsigned char *) &c64; case LNETDROPBYTES: convert_ull(&c64, ull[3], var_len); return (unsigned char *) &c64; default: return NULL; } }
bool lsb_decode_heka_message(lsb_heka_message *m, const char *buf, size_t len, lsb_logger logger) { if (!m || !buf || len == 0) { if (logger) { logger(__func__, 4, LSB_ERR_UTIL_NULL); } return false; } const char *cp = buf; // current position const char *lp = buf; // last position const char *ep = buf + len; // end position int wiretype = 0; int tag = 0; long long val = 0; bool timestamp = false; lsb_clear_heka_message(m); do { cp = lsb_pb_read_key(cp, &tag, &wiretype); switch (tag) { case LSB_PB_UUID: cp = read_string(wiretype, cp, ep, &m->uuid); if (m->uuid.len != LSB_UUID_SIZE) cp = NULL; break; case LSB_PB_TIMESTAMP: cp = process_varint(wiretype, cp, ep, &m->timestamp); if (cp) timestamp = true; break; case LSB_PB_TYPE: cp = read_string(wiretype, cp, ep, &m->type); break; case LSB_PB_LOGGER: cp = read_string(wiretype, cp, ep, &m->logger); break; case LSB_PB_SEVERITY: cp = process_varint(wiretype, cp, ep, &val); if (cp) m->severity = (int)val; break; case LSB_PB_PAYLOAD: cp = read_string(wiretype, cp, ep, &m->payload); break; case LSB_PB_ENV_VERSION: cp = read_string(wiretype, cp, ep, &m->env_version); break; case LSB_PB_PID: cp = process_varint(wiretype, cp, ep, &val); if (cp) m->pid = (int)val; break; case LSB_PB_HOSTNAME: cp = read_string(wiretype, cp, ep, &m->hostname); break; case LSB_PB_FIELDS: if (wiretype != 2) { cp = NULL; break; } if (m->fields_len == m->fields_size) { int step = 8; m->fields_size += step; lsb_heka_field *tmp = realloc(m->fields, m->fields_size * sizeof(lsb_heka_field)); if (!tmp) { if (logger) logger(__func__, 0, "fields reallocation failed"); return false; } m->fields = tmp; memset(&m->fields[m->fields_len], 0, step * sizeof(lsb_heka_field)); } cp = process_fields(&m->fields[m->fields_len], cp, ep); ++m->fields_len; break; default: cp = NULL; break; } if (cp) lp = cp; } while (cp && cp < ep); if (!cp) { if (logger) { logger(__func__, 4, "tag:%d wiretype:%d position:%d", tag, wiretype, lp - buf); } return false; } if (!m->uuid.s) { if (logger) logger(__func__, 4, "missing " LSB_UUID); return false; } if (!timestamp) { if (logger) logger(__func__, 4, "missing " LSB_TIMESTAMP); return false; } m->raw.s = buf; m->raw.len = len; return true; }
static void read_sref(FILE *fob, mxArray **data, double dbu_to_uu) { mxArray *pstruct; mxArray *pprop = NULL; mxArray *pa; double *pd; tList xylist; uint16_t rtype, rlen; int nprop = 0; int mtotal = 0; int k, m, nle; element_t sref; const char *fields[] = {"internal", "xy", "prop"}; xy_block vertex; /* initialize element */ init_element(&sref, GDS_SREF); /* output data structure */ pstruct = mxCreateStructMatrix(1,1, 3, fields); /* create a list for the XY data record(s) */ if ( create_list(&xylist) == -1 ) mexErrMsgTxt("gds_read_element (sref) : could not create list for XY records."); /* read element properties */ while (1) { if ( read_record_hdr(fob, &rtype, &rlen) ) mexErrMsgTxt("gds_read_element (sref) : could not read record header."); if (rtype == ENDEL) break; switch (rtype) { case XY: m = rlen / (2*sizeof(int32_t)); vertex.mxy = m; vertex.xy = read_xy2(fob, m, dbu_to_uu); list_insert_object(xylist, &vertex, sizeof(xy_block), AFTER); mtotal += m; break; case SNAME: if ( read_string(fob, sref.sname, rlen) ) mexErrMsgTxt("gds_read_element (sref) : could not read structure name."); break; case STRANS: if ( read_word(fob, &sref.strans.flags) ) mexErrMsgTxt("gds_read_element (sref) : could not read strans data."); sref.has |= HAS_STRANS; break; case MAG: if ( read_real8(fob, &sref.strans.mag) ) mexErrMsgTxt("gds_read_element (sref) : could not read magnification."); sref.has |= HAS_MAG; break; case ANGLE: if ( read_real8(fob, &sref.strans.angle) ) mexErrMsgTxt("gds_read_element (sref) : could not read angle."); sref.has |= HAS_ANGLE; break; case ELFLAGS: sref.elflags = read_elflags(fob); sref.has |= HAS_ELFLAGS; break; case PLEX: sref.plex = read_plex(fob); sref.has |= HAS_PLEX; break; case PROPATTR: pprop = resize_property_structure(pprop, nprop+1); mxSetFieldByNumber(pprop, nprop, 0, read_propattr(fob)); break; case PROPVALUE: mxSetFieldByNumber(pprop, nprop, 1, read_propvalue(fob,rlen)); nprop += 1; break; default: mexPrintf("Unknown record id: 0x%x\n", rtype); mexErrMsgTxt("SREF : found unknown element property."); } } /* catenate XY records */ nle = list_entries(xylist); if ( !nle ) mexErrMsgTxt("gds_read_element (sref) : element has no XY record."); pa = mxCreateDoubleMatrix(mtotal,2, mxREAL); pd = mxGetData(pa); list_head(xylist); for (k=0; k<nle; k++) { get_current_object(xylist, &vertex, sizeof(xy_block)); memcpy(pd, vertex.xy, 2*vertex.mxy*sizeof(double)); pd += 2*vertex.mxy; mxFree(vertex.xy); } mxSetFieldByNumber(pstruct, 0, 1, pa); erase_list_entries(xylist); delete_list(&xylist); /* set prop field */ if ( nprop ) { mxSetFieldByNumber(pstruct, 0, 2, pprop); } else { mxSetFieldByNumber(pstruct, 0, 2, empty_matrix()); } /* store structure with element data */ mxSetFieldByNumber(pstruct, 0, 0, copy_element_to_array(&sref)); /* return data */ *data = pstruct; }
// static bool BitmapFontLoader::load(const char * const filepath, BitmapFont &font) { uint32_t largest_id = 0; std::vector<BmfCharBlock> character_blocks; BmfCommonBlock common_block; std::ifstream file(filepath, std::ifstream::in | std::ifstream::binary); if (!file.is_open()) { log::error("BitmapFontLoader: Count not open file %", filepath); return false; } try { if (! (read_uint8(file) == 'B' && read_uint8(file) == 'M' && read_uint8(file) == 'F')) { throw ParseError("Invalid file header."); } uint8_t version = read_uint8(file); if (version != BmfVersion) { throw ParseError("Wrong version. Expected " + to_string(BmfVersion) + ", found " + to_string(static_cast<unsigned int>(version))); } while (file.peek() != std::istream::traits_type::eof()) { uint8_t block_type = read_uint8(file); uint32_t block_size = read_uint32(file); switch (block_type) { case BmfInfoBlock::TYPE: { BmfInfoBlock block; block.font_size = read_int16(file); block.bit_field = read_uint8(file); block.char_set = read_uint8(file); block.stretch_h = read_uint16(file); block.anti_aliasing = read_uint8(file); block.padding_up = read_uint8(file); block.padding_right = read_uint8(file); block.padding_down = read_uint8(file); block.padding_left = read_uint8(file); block.spacing_horizontal = read_uint8(file); block.spacing_vertical = read_uint8(file); block.outline = read_uint8(file); read_string(file); } break; case BmfCommonBlock::TYPE: common_block.line_height = read_uint16(file); common_block.base = read_uint16(file); common_block.scale_w = read_uint16(file); common_block.scale_h = read_uint16(file); common_block.pages = read_uint16(file); common_block.bit_field = read_uint8(file); common_block.alpha_channel = read_uint8(file); common_block.red_channel = read_uint8(file); common_block.green_channel = read_uint8(file); common_block.blue_channel = read_uint8(file); break; case BmfPageBlock::TYPE: read_string(file); break; case BmfCharBlock::TYPE: { int number_of_characters = block_size / 20; log::debug("BitmapFontLoader: number of characters in font file: %", number_of_characters); for (int i=0; i<number_of_characters; i++) { BmfCharBlock block; block.id = read_uint32(file); block.x = read_uint16(file); block.y = read_uint16(file); block.width = read_uint16(file); block.height = read_uint16(file); block.offset_x = read_int16(file); block.offset_y = read_int16(file); block.advance_x = read_uint16(file); block.page = read_uint8(file); block.channel = read_uint8(file); //log::debug("BitmapFontLoader: char id: % (%)", block.id, (char)block.id); character_blocks.push_back(block); if (block.id > largest_id) largest_id = block.id; } } break; case BmfKerningPairBlock::TYPE: { int number_of_kerning_pairs = block_size / 10; for (int i=0; i<number_of_kerning_pairs; i++) { BmfKerningPairBlock block; block.first = read_uint32(file); block.second = read_uint32(file); block.amount = read_int16(file); } } break; default: throw ParseError("Invalid block type " + to_string(static_cast<unsigned int>(block_type))); } } } catch (EndOfFile &eof) { log::error("BitmapFontLoader: Encountered end of file unexpectedly."); log::debug("File position: %", file.tellg()); file.close(); return false; } catch (ParseError &err) { log::error("BitmapFontLoader: Failed to parse font definition. Position: %\n Reason: %", file.tellg(), err.what()); file.close(); return false; } file.close(); font.m_base = common_block.base; font.m_line_height = common_block.line_height; font.reserve(largest_id+1); for (BmfCharBlock &cblock : character_blocks) { BitmapFontCharacter c; c.id = cblock.id; c.x = cblock.x; c.y = cblock.y; c.width = cblock.width; c.height = cblock.height; c.offset_x = cblock.offset_x; c.offset_y = cblock.offset_y; c.advance_x = cblock.advance_x; font.add_character(c); } return true; }
static void read_aref(FILE *fob, mxArray **data, double dbu_to_uu) { mxArray *pstruct; mxArray *pprop = NULL; uint16_t rtype, rlen; int nprop = 0; element_t aref; const char *fields[] = {"internal", "xy", "prop"}; /* initialize element */ init_element(&aref, GDS_AREF); /* output data structure */ pstruct = mxCreateStructMatrix(1,1, 3, fields); /* read element properties */ while (1) { if ( read_record_hdr(fob, &rtype, &rlen) ) mexErrMsgTxt("gds_read_element (aref) : could not read record header."); if (rtype == ENDEL) break; switch (rtype) { case XY: mxSetFieldByNumber(pstruct, 0, 1, read_xy(fob, rlen, dbu_to_uu)); break; case SNAME: if ( read_string(fob, aref.sname, rlen) ) mexErrMsgTxt("gds_read_element (sref) : could not read structure name."); break; case COLROW: read_colrow(fob, &aref.nrow, &aref.ncol); break; case STRANS: if ( read_word(fob, &aref.strans.flags) ) mexErrMsgTxt("gds_read_element (aref) : could not read strans data."); aref.has |= HAS_STRANS; break; case MAG: if ( read_real8(fob, &aref.strans.mag) ) mexErrMsgTxt("gds_read_element (aref) : could not read magnification."); aref.has |= HAS_MAG; break; case ANGLE: if ( read_real8(fob, &aref.strans.angle) ) mexErrMsgTxt("gds_read_element (aref) : could not read angle."); aref.has |= HAS_ANGLE; break; case ELFLAGS: aref.elflags = read_elflags(fob); aref.has |= HAS_ELFLAGS; break; case PLEX: aref.plex = read_plex(fob); aref.has |= HAS_PLEX; break; case PROPATTR: pprop = resize_property_structure(pprop, nprop+1); mxSetFieldByNumber(pprop, nprop, 0, read_propattr(fob)); break; case PROPVALUE: mxSetFieldByNumber(pprop, nprop, 1, read_propvalue(fob,rlen)); nprop += 1; break; default: mexPrintf("Unknown record id: 0x%x\n", rtype); mexErrMsgTxt("AREF : found unknown element property."); } } /* set prop field */ if ( nprop ) { mxSetFieldByNumber(pstruct, 0, 2, pprop); } else { mxSetFieldByNumber(pstruct, 0, 2, empty_matrix()); } /* store structure with element data */ mxSetFieldByNumber(pstruct, 0, 0, copy_element_to_array(&aref)); /* return data */ *data = pstruct; }
/* * Read next token and return its type tk * - set lex->token to tk * - set lex->tk_pos, etc. * - if token is TK_STRING, TK_NUM_RATIONAL, TK_NUM_FLOAT, TK_BV_CONSTANT, TK_SYMBOL, TK_ERROR, * the token value is stored in lex->buffer (as a string). */ yices_token_t next_yices_token(lexer_t *lex) { yices_token_t tk; reader_t *rd; string_buffer_t *buffer; int c; rd = &lex->reader; c = reader_current_char(rd); buffer = lex->buffer; string_buffer_reset(buffer); // skip spaces and comments for (;;) { while (isspace(c)) c = reader_next_char(rd); if (c != ';') break; do { // read to end-of-line or eof c = reader_next_char(rd); } while (c != '\n' && c != EOF); } // record token position (start of token) lex->tk_pos = rd->pos; lex->tk_line = rd->line; lex->tk_column = rd->column; switch (c) { case '(': tk = TK_LP; goto next_then_return; case ')': tk = TK_RP; goto next_then_return; case EOF: tk = TK_EOS; goto done; case ':': c = reader_next_char(rd); if (c == ':') { tk = TK_COLON_COLON; goto next_then_return; } else { // store ':' in the buffer since that may be used for reporting errors string_buffer_append_char(buffer, ':'); string_buffer_close(buffer); tk = TK_ERROR; goto done; } case '"': tk = read_string(lex); goto done; case '+': case '-': string_buffer_append_char(buffer, c); c = reader_next_char(rd); if (isdigit(c)) { string_buffer_append_char(buffer, c); reader_next_char(rd); tk = read_number(lex); } else { tk = read_symbol(lex); } goto done; case '0': string_buffer_append_char(buffer, c); c = reader_next_char(rd); if (c == 'b') { tk = read_bv_constant(lex); } else if (c == 'x') { tk = read_hex_constant(lex); } else { tk = read_number(lex); } goto done; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': string_buffer_append_char(buffer, c); reader_next_char(rd); tk = read_number(lex); goto done; default: // symbol or keyword string_buffer_append_char(buffer, c); reader_next_char(rd); tk = read_symbol(lex); goto done; } /* * read next character and exit */ next_then_return: reader_next_char(rd); done: lex->token = tk; return tk; }
static void read_text(FILE *fob, mxArray **data, double dbu_to_uu) { mxArray *pstruct; mxArray *pprop = NULL; uint16_t rtype, rlen; int nprop = 0; char tstr[TXTLEN+4]; element_t text; const char *fields[] = {"internal", "xy", "prop", "text"}; /* initialize element */ init_element(&text, GDS_TEXT); /* output data structure */ pstruct = mxCreateStructMatrix(1,1, 4, fields); /* read element properties */ while (1) { if ( read_record_hdr(fob, &rtype, &rlen) ) mexErrMsgTxt("gds_read_element (text) : could not read record header."); if (rtype == ENDEL) break; switch (rtype) { case STRING: if ( read_string(fob, tstr, rlen) ) mexErrMsgTxt("gds_read_element (text) : could not read string."); struct_set_string(pstruct, 3, tstr); break; case TEXTTYPE: text.dtype = read_type(fob); break; case XY: mxSetFieldByNumber(pstruct, 0, 1, read_xy(fob, rlen, dbu_to_uu)); break; case LAYER: text.layer = read_layer(fob); break; case PATHTYPE: text.ptype = read_type(fob); text.has |= HAS_PTYPE; break; case WIDTH: text.width = dbu_to_uu * read_width(fob); text.has |= HAS_WIDTH; break; case PRESENTATION: if ( read_word(fob, &text.present) ) mexErrMsgTxt("gds_read_element (text) : could not read presentation data."); text.has |= HAS_PRESTN; break; case STRANS: if ( read_word(fob, &text.strans.flags) ) mexErrMsgTxt("gds_read_element (text) : could not read strans data."); text.has |= HAS_STRANS; break; case MAG: if ( read_real8(fob, &text.strans.mag) ) mexErrMsgTxt("gds_read_element (text) : could not read magnification."); text.has |= HAS_MAG; break; case ANGLE: if ( read_real8(fob, &text.strans.angle) ) mexErrMsgTxt("gds_read_element (text) : could not read angle."); text.has |= HAS_ANGLE; break; case ELFLAGS: text.elflags = read_elflags(fob); text.has |= HAS_ELFLAGS; break; case PLEX: text.plex = read_plex(fob); text.has |= HAS_PLEX; break; case PROPATTR: pprop = resize_property_structure(pprop, nprop+1); mxSetFieldByNumber(pprop, nprop, 0, read_propattr(fob)); break; case PROPVALUE: mxSetFieldByNumber(pprop, nprop, 1, read_propvalue(fob,rlen)); nprop += 1; break; default: mexPrintf("Unknown record id: 0x%x\n", rtype); mexErrMsgTxt("TEXT : found unknown element property."); } } /* set prop field */ if ( nprop ) { mxSetFieldByNumber(pstruct, 0, 2, pprop); } else { mxSetFieldByNumber(pstruct, 0, 2, empty_matrix()); } /* store structure with element data */ mxSetFieldByNumber(pstruct, 0, 0, copy_element_to_array(&text)); /* return data */ *data = pstruct; }
static void on_stack_change(jsonsl_t parser, jsonsl_action_t action, struct jsonsl_state_st * state, const jsonsl_char_t * at) { /* printf("%c%c", action, state->type); if (state->type == JSONSL_T_SPECIAL) { printf("%c", state->special_flags); } printf("%d", state->pos_begin); if (action == JSONSL_ACTION_POP) { printf("-%d", state->pos_cur); } printf("\n"); */ struct bson_state * bstate = (struct bson_state *) parser->data; if (action == JSONSL_ACTION_PUSH) { if (state->type == JSONSL_T_OBJECT || state->type == JSONSL_T_LIST) { if (bstate->cur_entry > -1) { bstate->cur_entry++; bstate->entry[bstate->cur_entry].key = (bstring) state->data; } else { bstate->cur_entry = 0; bstate->entry[bstate->cur_entry].key = NULL; } bstate->entry[bstate->cur_entry].bson = bson_new(); bstate->entry[bstate->cur_entry].array_index = 0; } } else if (action == JSONSL_ACTION_POP) { if (state->type == JSONSL_T_HKEY) { state->data = read_string(bstate->text + state->pos_begin, state->pos_cur - state->pos_begin); } else if (state->type == JSONSL_T_OBJECT || state->type == JSONSL_T_LIST) { if (bstate->cur_entry > 0) { struct bson_entry * entry = &(bstate->entry[bstate->cur_entry]); struct bson_entry * parent = &(bstate->entry[bstate->cur_entry - 1]); if (state->type == JSONSL_T_OBJECT) { bson_append_document(parent->bson, bdata(entry->key), blength(entry->key), entry->bson); } else { bson_append_array(parent->bson, bdata(entry->key), blength(entry->key), entry->bson); } } bstate->cur_entry--; } else { bstring key = (bstring) state->data; if (key == NULL) { key = bformat("%d", bstate->entry[bstate->cur_entry].array_index); bstate->entry[bstate->cur_entry].array_index++; } if (state->type == JSONSL_T_SPECIAL) { if (state->special_flags & JSONSL_SPECIALf_BOOLEAN) { bson_append_bool(bstate->entry[bstate->cur_entry].bson, bdata(key), blength(key), state->special_flags & JSONSL_SPECIALf_TRUE); } else if (state->special_flags & JSONSL_SPECIALf_NULL) { bson_append_null(bstate->entry[bstate->cur_entry].bson, bdata(key), blength(key)); } else if (state->special_flags & JSONSL_SPECIALf_NUMERIC) { size_t length = state->pos_cur - state->pos_begin; char num[length + 1]; * (num + length) = '\0'; memcpy(num, bstate->text + state->pos_begin, length); if (state->special_flags & JSONSL_SPECIALf_NUMNOINT) { bson_append_double(bstate->entry[bstate->cur_entry].bson, bdata(key), blength(key), atof(num)); } else { bson_append_int64(bstate->entry[bstate->cur_entry].bson, bdata(key), blength(key), atoi(num)); } } } else { bstring value = read_string(bstate->text + state->pos_begin, state->pos_cur - state->pos_begin); bson_append_utf8(bstate->entry[bstate->cur_entry].bson, bdata(key), blength(key), bdata(value), blength(value)); } } } }
StackFrame * Parser::parse_backtrace_frame(Mode mode) { size_t id = read_uint(); StackFrameState *frame = lookup(frames, id); if (!frame) { frame = new StackFrameState; int c = read_byte(); while (c != trace::BACKTRACE_END && c != -1) { switch (c) { case trace::BACKTRACE_MODULE: frame->module = read_string(); break; case trace::BACKTRACE_FUNCTION: frame->function = read_string(); break; case trace::BACKTRACE_FILENAME: frame->filename = read_string(); break; case trace::BACKTRACE_LINENUMBER: frame->linenumber = read_uint(); break; case trace::BACKTRACE_OFFSET: frame->offset = read_uint(); break; default: std::cerr << "error: unknown backtrace detail " << c << "\n"; exit(1); } c = read_byte(); } frame->fileOffset = file->currentOffset(); frames[id] = frame; } else if (file->currentOffset() < frame->fileOffset) { int c = read_byte(); while (c != trace::BACKTRACE_END && c != -1) { switch (c) { case trace::BACKTRACE_MODULE: scan_string(); break; case trace::BACKTRACE_FUNCTION: scan_string(); break; case trace::BACKTRACE_FILENAME: scan_string(); break; case trace::BACKTRACE_LINENUMBER: scan_uint(); break; case trace::BACKTRACE_OFFSET: scan_uint(); break; default: std::cerr << "error: unknown backtrace detail " << c << "\n"; exit(1); } c = read_byte(); } } return frame; }