static void cap_parser_text_cb (void *user_data, const XML_Char *s, int len) { ParserData *data; ParserState state; gchar *tmp; data = (ParserData *) user_data; /* text is not null terminated. */ tmp = g_strndup (s, len); state = cap_parser_peek_state (data); switch (state) { case PARSER_STATE_MEMORY_TYPE: data->memory_type = g_strdup (tmp); break; case PARSER_STATE_MEMORY_FREE: data->memory_free = parse_long (tmp, &data->memory_has_free); break; case PARSER_STATE_MEMORY_USED: data->memory_used = parse_long (tmp, &data->memory_has_used); break; default: break; } g_free (tmp); }
/*************************************************************************** * cmp_fn_index ***************************************************************************/ bool cmp_fn_index(long bit, const char *arg, const struct flag_type *table, struct buf_type *buf) { int iter; if (buf != NULL) { char flag[MAX_STRING_LENGTH]; int col = 0; add_buf(buf, "\n\r "); for (iter = 0; table[iter].name != NULL; iter++) { sprintf(flag, "%-19.18s", table[iter].name); add_buf(buf, flag); if (++col % 3 == 0) add_buf(buf, "\n\r "); } if (col % 3 != 0) add_buf(buf, "\n\r"); } else { while (isspace((int)*arg) || arg[0] == '=') arg++; if (is_number(arg)) { return IS_SET(bit, parse_long(arg)) > 0; } else { for (iter = 0; table[iter].name != NULL; iter++) if (!str_prefix(arg, table[iter].name)) return bit == table[iter].bit; } } return false; }
/* Returns 0 on success and nonzero on failure. */ int http_parse_status_line(const char *line, struct http_response *response) { const char *p, *q; http_response_init(response); /* Version. */ p = parse_http_version(line, &response->version); if (p == line) return -1; while (*p == ' ') p++; /* Status code. */ errno = 0; response->code = parse_long(p, (char **) &q); if (errno != 0 || q == p) return -1; p = q; /* Reason phrase. */ while (*p == ' ') p++; q = p; while (!is_crlf(q)) q++; /* We expect that the CRLF ends the string. */ if (*skip_crlf(q) != '\0') return -1; response->phrase = mkstr(p, q); return 0; }
/** Get a value as int \param key key \param value value to read \returns value */ static int as_int(const char *key, const char *value) { long ret = 0; if (!parse_long(value, &ret)) die_bad_config(key); return ret; }
static int parse_args(int argc, char* argv[]) { int i; int j; build_options(); for(i = 1; i < argc; i++) { const char* arg = argv[i]; // Stop at the first non-option argument if(arg[0] != '-') break; // Stop after the first "-" or "--" if(arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0')) { i++; break; } j = (arg[1] != '-') ? parse_short(argc-i, argv+i) : parse_long(argv+i); if(j < 0) usage(1, 0); else i += j; } return i; }
void config_reader::parse_debug_line(row<long>& dbg_line, ch_string& str_ln){ #ifdef FULL_DEBUG bj_ostream& os = bj_out; MARK_USED(os); const char* pt_in = str_ln.c_str(); dbg_line.clear(); long num_ln = 0; if(isalnum(*pt_in)){ skip_whitespace(pt_in, num_ln); while(isdigit(*pt_in) || isspace(*pt_in)){ if(isspace(*pt_in)){ pt_in++; continue; } //os << pt_in << "$\n"; long val = parse_long(pt_in, num_ln); //skip_whitespace(pt_in, num_ln); dbg_line.push(val); } } else { skip_line(pt_in, num_ln); } #endif }
int main(int argc, char *argv[]) { if (argc < 2 || argc > 3) { usage(argv[0]); } int uid_arg_idx = 1; bool use_seteuid = false; if (argc == 3) { if (strcmp("-e", argv[1]) == 0) { uid_arg_idx = 2; use_seteuid = true; } else { usage(argv[0]); } } long target_uid = parse_long(argv[uid_arg_idx]); if (target_uid < 0) { err_quit("Target UID should be non-negative"); } print_ids(); printf("\nCalling %s(%ld)\n\n", use_seteuid ? "seteuid" : "setuid", target_uid); if (use_seteuid) { sys_chk(seteuid(target_uid)); } else { sys_chk(setuid(target_uid)); } print_ids(); return EXIT_SUCCESS; }
int parse_int(const char *value, int default_value) { long long_value = parse_long(value, default_value); if ((long)(int)long_value != long_value) return default_value; return (int)long_value; }
static int parse_int(char *str) { long val = parse_long(str); if (val <= INT_MAX && val >= INT_MIN) { return (int)val; } else { return -1; } }
static int parse_line( const char *linebuf, int *year, int *month, int *day, double *delta ) { char s[0x100]; // for substrings long tmp; substr(s, linebuf, 1, 4); // year if (!parse_long(s, &tmp)) { fprintf(stderr, "cannot parse year: \"%s\"\n", s); return 0; } *year = (int) tmp; substr(s, linebuf, 6, 3); // month name abbr if (!parse_month(s, &tmp)) { fprintf(stderr, "cannot parse month: \"%s\"\n", s); return 0; } *month = (int) tmp; substr(s, linebuf, 10, 2); // day if (!parse_long(s, &tmp)) { fprintf(stderr, "cannot parse day: \"%s\"\n", s); return 0; } *day = (int) tmp; substr(s, linebuf, 36, 13); // tai-utc delta if (!parse_double(s, delta)) { fprintf(stderr, "cannot parse delta: %s\n", s); return 0; } return 1; // 1 2 3 4 5 6 7 8 //12345678901234567890123456789012345678901234567890123456789012345678901234567890 // 1234567890123 // 2012 JUL 1 =JD 2456109.5 TAI-UTC= 35.0 S + (MJD - 41317.) X 0.0 S }
static int uri_parse_authority(const char *authority, struct uri *uri) { const char *portsep; const char *host_start, *host_end; char *tail; /* We do not support "user:pass@" userinfo. The proxy has no use for it. */ if (strchr(authority, '@') != NULL) return -1; /* Find the beginning and end of the host. */ host_start = authority; if (*host_start == '[') { /* IPv6 address in brackets. */ host_start++; host_end = strchr(host_start, ']'); if (host_end == NULL) return -1; portsep = host_end + 1; if (!(*portsep == ':' || *portsep == '\0')) return -1; } else { portsep = strrchr(authority, ':'); if (portsep == NULL) portsep = strchr(authority, '\0'); host_end = portsep; } /* Get the port number. */ if (*portsep == ':' && *(portsep + 1) != '\0') { long n; errno = 0; n = parse_long(portsep + 1, &tail); if (errno || *tail || (tail == (portsep + 1)) || !IN_RANGE(n, 1, 65535)) return -1; uri->port = n; } else { uri->port = -1; } /* Get the host. */ uri->host = mkstr(host_start, host_end); if (percent_decode(uri->host) < 0) { free(uri->host); uri->host = NULL; return -1; } return 1; }
static int parse_int (SLFUTURE_CONST char **sp, SLFUTURE_CONST char *smax, int *np, long base, unsigned char map[256]) { long n; int status; if (1 == (status = parse_long (sp, smax, &n, base, map))) *np = (int) n; return status; }
int main(int argc, char * argv[]) { long_index = 0; init_args(); parse_long(argc, argv); printf("Correlation method is %d\n",argum.correlation_method); print_args(); return 0; }
bool parse_cg_line(sk_str *source, sk_cg_geometry *buffer) { if (!source || !buffer) { return false; } char delimiter = ' '; SINT_64 coordinates[4] = { 0 }; sk_iterator tokens; if (!sk_str_split(&tokens, source, delimiter)) { return false; } char *token; sk_str str_token; SINT_64 *curr_coordinate = coordinates; int read = 0; while (read < 4 && tokens.has_next(&tokens)) { token = tokens.next(&tokens); if (!token) { continue; } sk_str_init(&str_token, token, 8); if (!parse_long(&str_token, 0, curr_coordinate)) { sk_str_destroy(&str_token); tokens.destroy(&tokens); return false; } sk_str_destroy(&str_token); ++curr_coordinate; ++read; } buffer->type = LINE; buffer->geometry.line.a.x = coordinates[0]; buffer->geometry.line.a.y = coordinates[1]; buffer->geometry.line.b.x = coordinates[2]; buffer->geometry.line.b.y = coordinates[3]; tokens.destroy(&tokens); return true; }
int main(int argc, char **argv) { long started, wait_idle_ms, timeout_ms; int event_base, error_base, timed_out = 0; if (argc > 1) wait_idle_ms = parse_long(argv[1], DEFAULT_WAIT_MS); if (argc > 2) timeout_ms = parse_long(argv[2], DEFAULT_TIMEOUT_MS); started = now(); Display *disp = XOpenDisplay(NULL); OK(disp); OK(XScreenSaverQueryExtension(disp, &event_base, &error_base)); XScreenSaverInfo *info = XScreenSaverAllocInfo(); OK(info); while (1) { if (now() >= started + timeout_ms * NANOS / MILLIS) BREAK(timed_out); OK(XScreenSaverQueryInfo(disp, DefaultRootWindow(disp), info)); if (info->idle >= wait_idle_ms) break; } XFree(info); XCloseDisplay(disp); exit(timed_out ? EXIT_FAILURE : EXIT_SUCCESS); }
static bool parse_uint32_t(uint32_t* value, const char* arg) { long tmp = 0; if (!parse_long(&tmp, arg)) { return false; } if (tmp < 0 || (unsigned long)tmp > UINT32_MAX) { return false; } *value = tmp; return true; }
/** Parse a string of the form "host[:port]" from <b>addrport</b>. If * <b>address</b> is provided, set *<b>address</b> to a copy of the * host portion of the string. If <b>addr</b> is provided, try to * resolve the host portion of the string and store it into * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided, * store the port number into *<b>port_out</b>, or 0 if no port is given. * If <b>port_out</b> is NULL, then there must be no port number in * <b>addrport</b>. * Return 0 on success, -1 on failure. */ int parse_addr_port(int severity, const char *addrport, char **address, uint32_t *addr, uint16_t *port_out) { const char *colon; char *_address = NULL; int _port; int ok = 1; assert(addrport); colon = strchr(addrport, ':'); if (colon) { _address = tor_strndup(addrport, colon-addrport); _port = (int) parse_long(colon+1,10,1,65535,NULL,NULL); if (!_port) { fprintf(stderr, "Port %s out of range\n", colon+1); ok = 0; } if (!port_out) { fprintf(stderr, "Port %s given on %s when not required\n", colon+1, addrport); ok = 0; } } else { _address = strdup(addrport); _port = 0; } if (addr) { /* There's an addr pointer, so we need to resolve the hostname. */ if (lookup_hostname(_address,addr)) { fprintf(stderr, "Couldn't look up %s\n", _address); ok = 0; *addr = 0; } } if (address && ok) { *address = _address; } else { if (address) *address = NULL; free(_address); } if (port_out) *port_out = ok ? ((uint16_t) _port) : 0; return ok ? 0 : -1; }
static int proc_args(int argc, char *argv[]) { unsigned long cnt, idle_time, tolerance; long length; /* check the function to test: if the first characters match, accept it */ if (strncmp(argv[1], "packet", strlen("packet")) == 0) { if( argc != 3 ) { printf("mouse: wrong no of arguments for test of test_packet() \n"); return 1; } if( (cnt = parse_ulong(argv[2], 10)) == ULONG_MAX ) return 1; printf("mouse:: test_packet(%lu)\n", cnt); return test_packet(cnt); } else if (strncmp(argv[1], "async", strlen("async")) == 0) { if( argc != 3 ) { printf("mouse: wrong no of arguments for test_async() \n"); return 1; } if( (idle_time = parse_ulong(argv[2], 10)) == ULONG_MAX ) return 1; printf("mouse:: test_async(%lu)\n", idle_time); return test_async(idle_time); } else if (strncmp(argv[1], "config", strlen("config")) == 0) { if( argc != 2 ) { printf("mouse: wrong no of arguments for test_config() \n"); return 1; } printf("mouse:: test_config()\n"); return test_config(); } else if (strncmp(argv[1], "gesture", strlen("gesture")) == 0) { if( argc != 4 ) { printf("mouse: wrong no of arguments for test_gesture() \n"); return 1; } if( (length = parse_long(argv[2], 10)) == LONG_MAX ) return 1; if( (tolerance = parse_ulong(argv[3], 10)) == ULONG_MAX ) return 1; printf("mouse:: test_gesture(%ld, %lu)\n", length, tolerance); return test_gesture(length, tolerance); } else { printf("mouse: non valid function \"%s\" to test\n", argv[1]); return 1; } }
/* Returns the character pointer after the HTTP version, or s if there was a parse error. */ static const char *parse_http_version(const char *s, enum http_version *version) { const char *PREFIX = "HTTP/"; const char *p, *q; long major, minor; *version = HTTP_UNKNOWN; p = s; if (memcmp(p, PREFIX, strlen(PREFIX)) != 0) return s; p += strlen(PREFIX); /* Major version. */ errno = 0; major = parse_long(p, (char **) &q); if (errno != 0 || q == p) return s; p = q; if (*p != '.') return s; p++; /* Minor version. */ errno = 0; minor = parse_long(p, (char **) &q); if (errno != 0 || q == p) return s; if (major == 1 && minor == 0) *version = HTTP_10; else if (major == 1 && minor == 1) *version = HTTP_11; return q; }
int parse_args(Tokens *ts, Elements *elements) { int ret; while (ts->current != NULL) { if (strcmp(ts->current, "--") == 0) { ret = parse_doubledash(ts, elements); if (!ret) break; } else if (ts->current[0] == '-' && ts->current[1] == '-') { ret = parse_long(ts, elements); } else if (ts->current[0] == '-' && ts->current[1] != '\0') { ret = parse_shorts(ts, elements); } else ret = parse_argcmd(ts, elements); if (ret) return ret; } return 0; }
static bool parse_arg_block_size(const char *arg) { long int arg_block_size = 0; if (getenv("MTBL_MERGE_BLOCK_SIZE") != NULL) { fprintf(stderr, "%s: Error: specify block size via command-line or environment, not both\n", program_name); return false; } if (!parse_long(arg, &arg_block_size)) return false; opt_block_size = arg_block_size; return true; }
int getopt_long(int argc, char *argv[], const char *optstring, const struct option *longopts, int *longindex) { int short_index, long_index; (void)longindex; if (optind == 0) optind = 1; if (argc == 1) return -1; short_index = find_short_index(&argv[optind]); long_index = find_long_index(&argv[optind]); /* We're done here. */ if (short_index == -1 && long_index == -1) return -1; /* Reorder argv so that non-options come last. * Non-POSIXy, but that's what getopt does by default. */ if ((short_index > 0) && ((short_index < long_index) || (long_index == -1))) { shuffle_block(&argv[optind], &argv[optind + short_index], &argv[argc]); short_index = 0; } else if ((long_index > 0) && ((long_index < short_index) || (short_index == -1))) { shuffle_block(&argv[optind], &argv[optind + long_index], &argv[argc]); long_index = 0; } rarch_assert(short_index == 0 || long_index == 0); if (short_index == 0) return parse_short(optstring, &argv[optind]); else if (long_index == 0) return parse_long(longopts, &argv[optind]); else return '?'; }
int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s <daynum>\n", argv[0]); exit(EXIT_FAILURE); } // Arguments long daynum; if (!parse_long(argv[1], &daynum)) { fprintf(stderr, "Not an integer: %s\n", argv[1]); exit(EXIT_FAILURE); } int delta = sun_delta_tai_utc(daynum); printf("On Modified Julian Day %ld the difference TAI-UTC = %d s\n", daynum, delta); exit(EXIT_SUCCESS); }
static int http_header_get_content_length(const struct http_header *header, unsigned long *content_length) { char *content_length_s; char *tail; int code; content_length_s = http_header_get_first(header, "Content-Length"); if (content_length_s == NULL) { *content_length = 0; return 0; } code = 0; errno = 0; *content_length = parse_long(content_length_s, (char **) &tail); if (errno != 0 || *tail != '\0' || tail == content_length_s) code = 400; free(content_length_s); return code; }
/* FIXME: This function does not handle LONG_LONG */ int _pSLang_sscanf (void) { int num; unsigned int num_refs; char *format; char *input_string, *input_string_max; SLFUTURE_CONST char *f, *s; unsigned char map8[256], map10[256], map16[256]; if (SLang_Num_Function_Args < 2) { _pSLang_verror (SL_INVALID_PARM, "Int_Type sscanf (str, format, ...)"); return -1; } num_refs = (unsigned int) SLang_Num_Function_Args; if (-1 == SLreverse_stack (num_refs)) return -1; num_refs -= 2; if (-1 == SLang_pop_slstring (&input_string)) return -1; if (-1 == SLang_pop_slstring (&format)) { SLang_free_slstring (input_string); return -1; } f = format; s = input_string; input_string_max = input_string + strlen (input_string); init_map (map8, 8); init_map (map10, 10); init_map (map16, 16); num = 0; while (num_refs != 0) { SLang_Object_Type obj; SLang_Ref_Type *ref; SLFUTURE_CONST char *smax; unsigned char *map; int base; int no_assign; int is_short; int is_long; int status; char chf; unsigned int width; int has_width; chf = *f++; if (chf == 0) { /* Hmmm.... what is the most useful thing to do?? */ #if 1 break; #else _pSLang_verror (SL_INVALID_PARM, "sscanf: format not big enough for output list"); goto return_error; #endif } if (isspace (chf)) { char *s1 = _pSLskip_whitespace (s); if (s1 == s) break; s = s1; continue; } if ((chf != '%') || ((chf = *f++) == '%')) { if (*s != chf) break; s++; continue; } no_assign = 0; is_short = 0; is_long = 0; width = 0; smax = input_string_max; /* Look for the flag character */ if (chf == '*') { no_assign = 1; chf = *f++; } /* Width */ has_width = isdigit (chf); if (has_width) { f--; (void) parse_uint (&f, f + strlen(f), &width, 10, map10); chf = *f++; } /* Now the type modifier */ switch (chf) { case 'h': is_short = 1; chf = *f++; break; case 'L': /* not implemented */ case 'l': is_long = 1; chf = *f++; break; } status = -1; if ((chf != 'c') && (chf != '[')) { s = _pSLskip_whitespace (s); if (*s == 0) break; } if (has_width) { if (width > (unsigned int) (input_string_max - s)) width = (unsigned int) (input_string_max - s); smax = s + width; } /* Now the format descriptor */ map = map10; base = 10; try_again: /* used by i, x, and o, conversions */ switch (chf) { case 0: _pSLang_verror (SL_INVALID_PARM, "sscanf: Unexpected end of format"); goto return_error; case 'D': is_long = 1; case 'd': if (is_short) { obj.o_data_type = SLANG_SHORT_TYPE; status = parse_short (&s, smax, &obj.v.short_val, base, map); } else if (is_long) { obj.o_data_type = SLANG_LONG_TYPE; status = parse_long (&s, smax, &obj.v.long_val, base, map); } else { obj.o_data_type = SLANG_INT_TYPE; status = parse_int (&s, smax, &obj.v.int_val, base, map); } break; case 'U': is_long = 1; case 'u': if (is_short) { obj.o_data_type = SLANG_USHORT_TYPE; status = parse_ushort (&s, smax, &obj.v.ushort_val, base, map); } else if (is_long) { obj.o_data_type = SLANG_ULONG_TYPE; status = parse_ulong (&s, smax, &obj.v.ulong_val, base, map); } else { obj.o_data_type = SLANG_INT_TYPE; status = parse_uint (&s, smax, &obj.v.uint_val, base, map); } break; case 'I': is_long = 1; case 'i': if ((s + 1 >= smax) || (*s != 0)) chf = 'd'; else if (((s[1] == 'x') || (s[1] == 'X')) && (s + 2 < smax)) { s += 2; chf = 'x'; } else chf = 'o'; goto try_again; case 'O': is_long = 1; case 'o': map = map8; base = 8; chf = 'd'; goto try_again; case 'X': is_long = 1; case 'x': base = 16; map = map16; chf = 'd'; goto try_again; case 'E': case 'F': is_long = 1; case 'e': case 'f': case 'g': #if SLANG_HAS_FLOAT if (is_long) { obj.o_data_type = SLANG_DOUBLE_TYPE; status = parse_double (&s, smax, &obj.v.double_val); } else { obj.o_data_type = SLANG_FLOAT_TYPE; status = parse_float (&s, smax, &obj.v.float_val); } #else _pSLang_verror (SL_NOT_IMPLEMENTED, "This version of the S-Lang does not support floating point"); status = -1; #endif break; case 's': obj.o_data_type = SLANG_STRING_TYPE; status = parse_string (&s, smax, &obj.v.s_val); break; case 'c': if (has_width == 0) { obj.o_data_type = SLANG_UCHAR_TYPE; obj.v.uchar_val = *s++; status = 1; break; } obj.o_data_type = SLANG_STRING_TYPE; status = parse_bstring (&s, smax, &obj.v.s_val); break; case '[': obj.o_data_type = SLANG_STRING_TYPE; status = parse_range (&s, smax, &f, &obj.v.s_val); break; case 'n': obj.o_data_type = SLANG_UINT_TYPE; obj.v.uint_val = (unsigned int) (s - input_string); status = 1; break; default: status = -1; _pSLang_verror (SL_NOT_IMPLEMENTED, "format specifier '%c' is not supported", chf); break; } if (status == 0) break; if (status == -1) goto return_error; if (no_assign) { SLang_free_object (&obj); continue; } if (-1 == SLang_pop_ref (&ref)) { SLang_free_object (&obj); goto return_error; } if (-1 == SLang_push (&obj)) { SLang_free_object (&obj); SLang_free_ref (ref); goto return_error; } if (-1 == _pSLang_deref_assign (ref)) { SLang_free_ref (ref); goto return_error; } SLang_free_ref (ref); num++; num_refs--; } if (-1 == SLdo_pop_n (num_refs)) goto return_error; SLang_free_slstring (format); SLang_free_slstring (input_string); return num; return_error: /* NULLS ok */ SLang_free_slstring (format); SLang_free_slstring (input_string); return -1; }
static int parse_ulong (SLFUTURE_CONST char **sp, SLFUTURE_CONST char *smax, unsigned long *np, long base, unsigned char map[256]) { return parse_long (sp, smax, (long *) np, base, map); }
/* FIX! make service return error instead of invoking exit() */ int add_service(char *name, const char *port, int max_connections, new_connection_handler_t new_connection_handler, input_handler_t input_handler, connection_closed_handler_t connection_closed_handler, void *priv) { struct service *c, **p; int so_reuseaddr_option = 1; c = malloc(sizeof(struct service)); c->name = strdup(name); c->port = strdup(port); c->max_connections = 1; /* Only TCP/IP ports can support more than one connection */ c->fd = -1; c->connections = NULL; c->new_connection = new_connection_handler; c->input = input_handler; c->connection_closed = connection_closed_handler; c->priv = priv; c->next = NULL; long portnumber; if (strcmp(c->port, "pipe") == 0) c->type = CONNECTION_STDINOUT; else { char *end; portnumber = strtol(c->port, &end, 0); if (!*end && (parse_long(c->port, &portnumber) == ERROR_OK)) { c->portnumber = portnumber; c->type = CONNECTION_TCP; } else c->type = CONNECTION_PIPE; } if (c->type == CONNECTION_TCP) { c->max_connections = max_connections; c->fd = socket(AF_INET, SOCK_STREAM, 0); if (c->fd == -1) { LOG_ERROR("error creating socket: %s", strerror(errno)); exit(-1); } setsockopt(c->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&so_reuseaddr_option, sizeof(int)); socket_nonblock(c->fd); memset(&c->sin, 0, sizeof(c->sin)); c->sin.sin_family = AF_INET; c->sin.sin_addr.s_addr = INADDR_ANY; c->sin.sin_port = htons(c->portnumber); if (bind(c->fd, (struct sockaddr *)&c->sin, sizeof(c->sin)) == -1) { LOG_ERROR("couldn't bind to socket: %s", strerror(errno)); exit(-1); } #ifndef _WIN32 int segsize = 65536; setsockopt(c->fd, IPPROTO_TCP, TCP_MAXSEG, &segsize, sizeof(int)); #endif int window_size = 128 * 1024; /* These setsockopt()s must happen before the listen() */ setsockopt(c->fd, SOL_SOCKET, SO_SNDBUF, (char *)&window_size, sizeof(window_size)); setsockopt(c->fd, SOL_SOCKET, SO_RCVBUF, (char *)&window_size, sizeof(window_size)); if (listen(c->fd, 1) == -1) { LOG_ERROR("couldn't listen on socket: %s", strerror(errno)); exit(-1); } } else if (c->type == CONNECTION_STDINOUT) { c->fd = fileno(stdin); #ifdef _WIN32 /* for win32 set stdin/stdout to binary mode */ if (_setmode(_fileno(stdout), _O_BINARY) < 0) LOG_WARNING("cannot change stdout mode to binary"); if (_setmode(_fileno(stdin), _O_BINARY) < 0) LOG_WARNING("cannot change stdin mode to binary"); if (_setmode(_fileno(stderr), _O_BINARY) < 0) LOG_WARNING("cannot change stderr mode to binary"); #else socket_nonblock(c->fd); #endif } else if (c->type == CONNECTION_PIPE) { #ifdef _WIN32 /* we currenty do not support named pipes under win32 * so exit openocd for now */ LOG_ERROR("Named pipes currently not supported under this os"); exit(1); #else /* Pipe we're reading from */ c->fd = open(c->port, O_RDONLY | O_NONBLOCK); if (c->fd == -1) { LOG_ERROR("could not open %s", c->port); exit(1); } #endif } /* add to the end of linked list */ for (p = &services; *p; p = &(*p)->next) ; *p = c; return ERROR_OK; }
int main (int argc, char **argv) { #if MPI_MASTER_WORKER int process_id; int n_processes; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &process_id); MPI_Comm_size(MPI_COMM_WORLD, &n_processes); #endif static const unsigned NO_EXTRA_MODEL[] = {}; const unsigned EXTRA_GTR[] = { model_index_GTR }; /* configuration */ pltb_config_t config; /* pltb config */ configure_attr_defaults(&config); config.extra_models = (unsigned*)&NO_EXTRA_MODEL; config.n_extra_models = 0; config.base_freq_kind = EMPIRICAL; /* pltb target */ char *datafile = NULL; /* illegal default => to be set */ /* model space config */ int upper_bound = 203; int lower_bound = 0; /* cli related configuration and variables */ opterr = 0; /* avoid errors generated by getopt */ int error = 0; int opt_index; int c; bool print_config = false; bool print_progress = false; while (1) { static struct option long_options[] = { {"data", required_argument, 0, 'f'}, {"opt-base-freq", no_argument, 0, 'b'}, {"upper-bound", required_argument, 0, 'u'}, {"lower-bound", required_argument, 0, 'l'}, {"npthreads", required_argument, 0, 'n'}, {"npthreads-tree", required_argument, 0, 's'}, {"rseed", required_argument, 0, 'r'}, {"config", no_argument, 0, 'c'}, {"progress", no_argument, 0, 'p'}, {"with-gtr", no_argument, 0, 'g'}, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "cpbgf:u:l:n:s:r:", long_options, &opt_index); if (c == -1) break; switch (c) { case 'b': config.base_freq_kind = OPTIMIZED; break; case 'f': if (access(optarg, R_OK) != -1) { datafile = optarg; } else { ERROR("Illegal dataset file: %s\n", optarg); error = 1; } break; case 'u': upper_bound = parse_int(optarg); if (upper_bound < 1 || upper_bound > 202) { ERROR("Illegal value for upper matrix index bound: %s\n", optarg); error = 1; } break; case 'l': lower_bound = parse_int(optarg); if (lower_bound < 0 || lower_bound > 202) { ERROR("Illegal value for lower matrix index bound: %s\n", optarg); error = 1; } break; case 'n': config.attr_model_eval.numberOfThreads = parse_int(optarg); if (config.attr_model_eval.numberOfThreads < 0) { ERROR("Negative value for number of pthreads: %s\n", optarg); error = 1; } break; case 's': config.attr_tree_search.numberOfThreads = parse_int(optarg); if (config.attr_tree_search.numberOfThreads < 0) { ERROR("Negative value for number of pthreads: %s\n", optarg); error = 1; } break; case 'r': config.attr_model_eval.randomNumberSeed = parse_long(optarg); config.attr_tree_search.randomNumberSeed = parse_long(optarg); break; case 'c': print_config = true; break; case 'p': print_progress = true; break; case 'g': config.n_extra_models = 1; config.extra_models = (unsigned*)&EXTRA_GTR; break; case 0: /* all long options return a value != 0 */ assert(false); break; default: error = 1; break; } } while (optind < argc) { error = 1; ERROR("Not recognized option: %s\n", argv[optind++]); break; } if (!error && !datafile) { ERROR("Missing required file argument\n"); error = 1; } if (!error) { if (lower_bound >= upper_bound) { ERROR("Upper bound greater then the lower bound.\n"); error = 1; } } if(!error) { #if MPI_MASTER_WORKER if (print_config && process_id == 0) { #else if (print_config) { #endif DBG("Configuration\n"); DBG("\tDataset: %s\n", datafile); DBG("\tRandom number seeds: %#lx/%#lx\n", config.attr_model_eval.randomNumberSeed, config.attr_tree_search.randomNumberSeed); DBG("\tBase frequencies: "); switch (config.base_freq_kind) { case EMPIRICAL: DBG("Empirical"); break; case OPTIMIZED: DBG("Optimized"); break; case EQUAL: DBG("Equal - not implemented yet"); break; } DBG("\n"); #if MPI_MASTER_WORKER DBG("\tNumber of processes: %d\n", n_processes); #endif DBG("\tNumber of threads per process: %d\n", config.attr_model_eval.numberOfThreads); DBG("\tNumber of threads for tree search: %d\n", config.attr_tree_search.numberOfThreads); #if MPI_MASTER_WORKER if (n_processes > 1) { DBG("\tImplementation: Parallel\n"); } else { DBG("\tImplementation: Sequential\n"); } #endif } // configure model space model_space_t model_space; init_range_model_space(&model_space, (unsigned)lower_bound, (unsigned)upper_bound); // choose implementation #if MPI_MASTER_WORKER if (n_processes > 1) { // mpi master worker error = run_master_worker(process_id, MPI_COMM_WORLD, datafile, &config, &model_space, print_progress); } else #endif { // sequential error = run_sequential(datafile, &config, &model_space); } if (error) { ERROR("Execution ended with error code %d\n", error); } destroy_model_space(&model_space); } else { error = 1; ERROR("Usage: %s (-f|--data) datafile [-b|--opt-freq] [(-l|--lower-bound) incl_index] [(-u|--upper-bound) excl_index] [(-n|--npthreads) number] [(-s|--npthreads-tree) number] [(-r|--rseed) longvalue] [(-c|--config)] [(-p|--progress)] [(-g|--with-gtr)]\n", argv[0]); } #if MPI_MASTER_WORKER MPI_Finalize(); #endif return error; }
/* * parse - parses the command line. The caller is responsible for error * checking. The return value is any erro that may have ocurred. * ERROR_NONE - No error. * ERROR_UNKNOWN - An unknown parameter was passed. * ERROR_MISSING - A parameter was needed but missing. * ERROR_EXTRA - Too many unswitched paremeters. * Note: ERROR_EXTRA is used internally to signal the subroutines to * increment. These cases do not result in an actual error. */ int configfile::parse(int argc, char *argv[]) { // For simplicity's sake, the configfile object tracks the name of // the program. prog_name = argv[0]; // Now parse each argument. Config items are scanned using simple // rules for command line parameters defined as follows: // A character - The object uses that character // A digit - The object uses the unswitched parameter with that index (starting with 0) // A dash - the object uses the standard long-name format of two // dashes followed by the configuration file name with any // spaces in the name replaced with dashes. // One or more of the following can be appended to the string // A dash - The object uses the character or the long-name // convention as above. // An equal sign - For a single character the next parameter will be // used, for a long name anything after the = will be used. int err; int index = 1; int parm_index = 0; while (index < argc) { if (CHAR_DASH == argv[index][0]) { // The first character is a dash, so the parameter must // be a switch item. if (CHAR_DASH == argv[index][1]) { // Long-name parameter err = parse_long(&(argv[index][2])); if (ERROR_NONE != err) return err; } else { // single character parameter (may be multiple) for (int count = 1; 0 != argv[index][count]; ++count) { // Parse the character. We will fail if the character is unknown. if((index + 1) < argc) { err = parse_char(argv[index][count], argv[index + 1]); } else { err = parse_char(argv[index][count], std::string()); } if (ERROR_UNKNOWN == err) return err; else if (ERROR_EXTRA == err) { // The next parameter was also read, so skip it. index++; break; } } } } else { // Cache the unescaped parameters cmds.push_back(argv[index]); // Parse the indexed parameter, if there is one. if (parm_index <= 9) { err = parse_index(parm_index, argv[index]); if ((ERROR_NONE != err) && (ERROR_EXTRA != err)) return err; } ++parm_index; } ++index; } // Return no error. return ERROR_NONE; }
bool parse_cg_polygon(sk_str *source, sk_cg_geometry *buffer) { if (!source || !buffer) { return false; } bool retval = true; char delimiter = ' '; sk_iterator tokens; if (!sk_str_split(&tokens, source, delimiter)) { retval = false; goto str_split_fail; } if (!sk_list_init(&buffer->geometry.polygon.points, NULL)) { retval = false; goto list_init_fail; } char *token; sk_str str_token; SINT_64 x_coord; SINT_64 y_coord; while (tokens.has_next(&tokens)) { token = tokens.next(&tokens); if (!tokens.has_next(&tokens)) { retval = false; goto parse_point_fail; } sk_str_init(&str_token, token, 8); if (!parse_long(&str_token, 0, &x_coord)) { retval = false; sk_str_destroy(&str_token); goto parse_point_fail; } sk_str_destroy(&str_token); token = tokens.next(&tokens); sk_str_init(&str_token, token, 8); if (!parse_long(&str_token, 0, &y_coord)) { retval = false; sk_str_destroy(&str_token); goto parse_point_fail; } sk_str_destroy(&str_token); sk_cg_point *point = ALLOC(*point, 1); point->x = x_coord; point->y = y_coord; sk_list_append(&buffer->geometry.polygon.points, point); } sk_cg_point *first = sk_list_pop_head(&buffer->geometry.polygon.points); sk_cg_point *last = sk_list_pop_tail(&buffer->geometry.polygon.points); if (!sk_cg_point_equals(first, last)) { retval = false; goto parse_point_fail; } sk_list_prepend(&buffer->geometry.polygon.points, first); buffer->type = POLYGON; parse_point_fail: if (!retval) { sk_iterator it; sk_list_begin(&it, &buffer->geometry.polygon.points); while(it.has_next(&it)) { free(it.next(&it)); } sk_list_destroy(&buffer->geometry.polygon.points); } list_init_fail: tokens.destroy(&tokens); str_split_fail: return retval; }