int ipcs_main(int argc UNUSED_PARAM, char **argv) { int id = 0; unsigned flags = 0; unsigned opt; char *opt_i; #define flag_print (1<<0) #define flag_msg (1<<1) #define flag_sem (1<<2) #define flag_shm (1<<3) opt = getopt32(argv, "i:aqsmtcplu", &opt_i); if (opt & 0x1) { // -i id = xatoi(opt_i); flags |= flag_print; } if (opt & 0x2) flags |= flag_msg | flag_sem | flag_shm; // -a if (opt & 0x4) flags |= flag_msg; // -q if (opt & 0x8) flags |= flag_sem; // -s if (opt & 0x10) flags |= flag_shm; // -m if (opt & 0x20) format = TIME; // -t if (opt & 0x40) format = CREATOR; // -c if (opt & 0x80) format = PID; // -p if (opt & 0x100) format = LIMITS; // -l if (opt & 0x200) format = STATUS; // -u if (flags & flag_print) { if (flags & flag_shm) { print_shm(id); fflush_stdout_and_exit(EXIT_SUCCESS); } if (flags & flag_sem) { print_sem(id); fflush_stdout_and_exit(EXIT_SUCCESS); } if (flags & flag_msg) { print_msg(id); fflush_stdout_and_exit(EXIT_SUCCESS); } bb_show_usage(); } if (!(flags & (flag_shm | flag_msg | flag_sem))) flags |= flag_msg | flag_shm | flag_sem; bb_putchar('\n'); if (flags & flag_shm) { do_shm(); bb_putchar('\n'); } if (flags & flag_sem) { do_sem(); bb_putchar('\n'); } if (flags & flag_msg) { do_msg(); bb_putchar('\n'); } fflush_stdout_and_exit(EXIT_SUCCESS); }
/* This functions gets a user input from terminal and display the memory data for the correspendign SA */ void display_brt_sa ( void) { uint8_t subaddr; while (1) { dp_display_text("Sub Address #(1 to 31 ): "); rx_char_ptr = rx_char; read_user_input(rx_char_ptr); xatoi ( &rx_char_ptr, &subaddr); dp_display_text("\r\nInput recived : "); dp_display_value(subaddr,HEX); if ((subaddr > 0 ) && (subaddr < 32)) { display_brt_data(CORE1553BRT_0 ,subaddr); break; } else { dp_display_text("\r\n\Invaid input !!!!! Enter the Sub Address # ( 1 to 31)to display Data: "); } } }
void args_parse(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (!strncmp(argv[i], "--no-spawn", 10)) { config.spawn = 0; } else if (!strncmp(argv[i], "--checkout=", 11)) { checkout = argv[i] + 11; } else if (!strncmp(argv[i], "--icon-size=", 12)) { xatoi(&config.icon_size, argv[i] + 12, XATOI_NONNEG, "config.icon_size"); } else if (!strncmp(argv[i], "--die-when-loaded", 17)) { die_when_loaded = 1; } else if (!strncmp(argv[i], "--at-pointer", 12)) { config.at_pointer = 1; } else if (!strncmp(argv[i], "--hide-on-startup", 17)) { config.hide_on_startup = 1; } else if (!strncmp(argv[i], "--simple", 8)) { simple = 1; } else if (!strncmp(argv[i], "--csv-file=", 11)) { csv_file = argv[i] + 11; } else if (!strncmp(argv[i], "--csv-cmd=", 10)) { csv_cmd = argv[i] + 10; } } }
int main(int argc , char *argv[]) { long double num = 0; long double sum = 0; if(argc > 1) { num = xatoi(argv[1]); for(long double i = 2;i<=num;i++) { if(prime(i)) { sum += i; } } printf("Total sum = %Lf" , sum); } else { printf("please enter the argument"); } return 0; }
int chpst_main(int argc ATTRIBUTE_UNUSED, char **argv) { INIT_G(); if (applet_name[3] == 'd') envdir(argc, argv); if (applet_name[1] == 'o') softlimit(argc, argv); if (applet_name[0] == 's') setuidgid(argc, argv); if (applet_name[0] == 'e') envuidgid(argc, argv); // otherwise we are chpst { char *m,*d,*o,*p,*f,*c,*r,*t,*n; getopt32(argv, "+u:U:e:m:d:o:p:f:c:r:t:/:n:vP012", &set_user,&env_user,&env_dir, &m,&d,&o,&p,&f,&c,&r,&t,&root,&n); // if (option_mask32 & 0x1) // -u // if (option_mask32 & 0x2) // -U // if (option_mask32 & 0x4) // -e if (option_mask32 & 0x8) limits = limitl = limita = limitd = xatoul(m); // -m if (option_mask32 & 0x10) limitd = xatoul(d); // -d if (option_mask32 & 0x20) limito = xatoul(o); // -o if (option_mask32 & 0x40) limitp = xatoul(p); // -p if (option_mask32 & 0x80) limitf = xatoul(f); // -f if (option_mask32 & 0x100) limitc = xatoul(c); // -c if (option_mask32 & 0x200) limitr = xatoul(r); // -r if (option_mask32 & 0x400) limitt = xatoul(t); // -t // if (option_mask32 & 0x800) // -/ if (option_mask32 & 0x1000) nicelvl = xatoi(n); // -n // The below consts should match #defines at top! //if (option_mask32 & 0x2000) OPT_verbose = 1; // -v //if (option_mask32 & 0x4000) OPT_pgrp = 1; // -P //if (option_mask32 & 0x8000) OPT_nostdin = 1; // -0 //if (option_mask32 & 0x10000) OPT_nostdout = 1; // -1 //if (option_mask32 & 0x20000) OPT_nostderr = 1; // -2 } argv += optind; if (!argv || !*argv) bb_show_usage(); if (OPT_pgrp) setsid(); if (env_dir) edir(env_dir); if (root) { xchdir(root); xchroot("."); } slimit(); if (nicelvl) { errno = 0; if (nice(nicelvl) == -1) bb_perror_msg_and_die("nice"); } if (env_user) euidgid(env_user); if (set_user) suidgid(set_user); if (OPT_nostdin) close(0); if (OPT_nostdout) close(1); if (OPT_nostderr) close(2); BB_EXECVP(argv[0], argv); bb_perror_msg_and_die("exec %s", argv[0]); }
int ipcs_main(int argc UNUSED_PARAM, char **argv) { int format = 0; unsigned opt; char *opt_i; opt = getopt32(argv, "i:aqsmtcplu", &opt_i); #define flag_msg (1<<2) #define flag_sem (1<<3) #define flag_shm (1<<4) if (opt & (1<<5)) format = TIME; // -t if (opt & (1<<6)) format = CREATOR; // -c if (opt & (1<<7)) format = PID; // -p if (opt & (1<<8)) format = LIMITS; // -l if (opt & (1<<9)) format = STATUS; // -u if (opt & (1<<0)) { // -i int id; id = xatoi(opt_i); if (opt & flag_shm) { print_shm(id); fflush_stdout_and_exit(EXIT_SUCCESS); } if (opt & flag_sem) { print_sem(id); fflush_stdout_and_exit(EXIT_SUCCESS); } if (opt & flag_msg) { print_msg(id); fflush_stdout_and_exit(EXIT_SUCCESS); } bb_show_usage(); } if ((opt & (1<<1)) // -a || !(opt & (flag_msg | flag_sem | flag_shm)) // none of -q,-s,-m == all ) { opt |= flag_msg | flag_sem | flag_shm; } bb_putchar('\n'); if (opt & flag_msg) { do_msg(format); bb_putchar('\n'); } if (opt & flag_shm) { do_shm(format); bb_putchar('\n'); } if (opt & flag_sem) { do_sem(format); bb_putchar('\n'); } fflush_stdout_and_exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { int d; int s = xatoi(&d, argv[i]); printf("%s -> errno=%d_(%s) status=%d int=%d\n", argv[i], errno, strerror(errno), s, d); } exit(EXIT_SUCCESS); }
uint8_t get_data_input ( void) { uint8_t data_in; rx_char_ptr = rx_char; read_user_input(rx_char_ptr); xatoi ( &rx_char_ptr, &data_in); dp_display_value(data_in,HEX); return data_in; //display_brt_data(CORE1553BRT_0 ,subaddr); }
int strToRegNum(char* token) { int regNum = -1; char * sentToken = malloc(sizeof(char*)); strcpy(sentToken, token); int regType = token[0]; switch (regType) { case 'r': case 'R': regNum = xatoi(token); break; case 'f': case 'F': regNum = num_of_int_registers + xatoi(token); break; default: //error(E_CMD_REG_INV, ACTION_PRINTMSG); break; } return regNum; }
double get_width(char* buffer, double denominator) { long int num; char* strnpointer; // strip leading zeroes from 08 and 09, which for some reason xatoi cannot properly parse if (strcmp(buffer, "08") == 0) { strnpointer = "8"; } else if (strcmp(buffer, "09") == 0) { strnpointer = "9"; } else { strnpointer = buffer; } xatoi(&strnpointer, &num); /* to do double division, you must cast at least one operand to a double otherwise integer division happens */ /* ex: long double div = 100 * (1/2.0); */ return 124.0 * ((double) num / denominator); }
int main(int argc, char **argv) { int i; struct sbuf s; if (argc < 2) usage(); for (i = 1; i < argc; i++) { if (argv[i][0] != '-') icon_name = argv[i]; if (!strncmp(argv[i], "--icon-size=", 12)) xatoi(&icon_size, argv[i] + 12, XATOI_NONNEG, "config.icon_size"); if (!strncmp(argv[i], "--theme=", 8)) theme = argv[i] + 8; if (!strncmp(argv[i], "--help", 6)) usage(); } if (!icon_name) { fprintf(stderr, "fatal: no icon-name specified\n"); exit(1); } sbuf_init(&s); icon_find_init(); if (theme) icon_find_add_theme(theme); else icon_find_add_theme("default"); icon_find_add_theme("hicolor"); sbuf_cpy(&s, icon_name); icon_find(&s, icon_size); if (s.len) printf("%s\n", s.buf); else fprintf(stderr, "warning: could not find icon '%s'\n", icon_name); return 0; }
int dial(char *host, char *port) { struct sockaddr_in sin; struct hostent *serv; int s, p; p = xatoi(port); if (p == -1) return -1; s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) { perror("socket"); return -1; } serv = gethostbyname(host); if (serv == NULL) { perror("gethostbyname"); return -1; } memset(&sin, '\0', sizeof(sin)); sin.sin_family = AF_INET; memcpy((char *)&sin.sin_addr.s_addr, (char *)serv->h_addr, serv->h_length); sin.sin_port = htons(p); if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) { perror("connect"); return -1; } return s; }
/* This function will get teh Input from Terminal and check for valid input for the SA */ uint8_t validate_brt_sa_input ( void) { uint8_t subaddr; dp_display_text("Sub Address #(1 to 31 ): "); rx_char_ptr = rx_char; read_user_input(rx_char_ptr); xatoi ( &rx_char_ptr, &subaddr); dp_display_value(subaddr,HEX); if ((subaddr > 0 ) && (subaddr < 32)) { return subaddr; //display_brt_data(CORE1553BRT_0 ,subaddr); } else { dp_display_text("\r\n\Invaid input !!!!! Enter the Sub Address # ( 1 to 31)to display Data: "); return 0; } }
int main(int argc, char *argv[]) { int interval = 5; int count; int always = 1; int opt; int projects = 0; int zones = 0; /* project reporting is the default if no option is specified */ rcid_type_t stat_type = RCIDT_PROJECT; (void) setlocale(LC_ALL, ""); (void) textdomain(TEXT_DOMAIN); (void) setpname("rcapstat"); global = unformatted = 0; while ((opt = getopt(argc, argv, "gpuzT:")) != (int)EOF) { switch (opt) { case 'g': global = 1; break; case 'p': projects = 1; stat_type = RCIDT_PROJECT; break; case 'u': unformatted = 1; break; case 'z': stat_type = RCIDT_ZONE; zones = 1; break; case 'T': if (optarg) { if (*optarg == 'u') timestamp_fmt = UDATE; else if (*optarg == 'd') timestamp_fmt = DDATE; else usage(); } else { usage(); } break; default: usage(); } } if (argc > optind) if ((interval = xatoi(argv[optind++])) <= 0) die(gettext("invalid interval specified\n")); if (argc > optind) { if ((count = xatoi(argv[optind++])) <= 0) die(gettext("invalid count specified\n")); always = 0; } if (argc > optind || (projects > 0 && zones > 0)) usage(); while (always || count-- > 0) { if (read_stats(stat_type) != E_SUCCESS) return (E_ERROR); if (timestamp_fmt != NODATE) print_timestamp(timestamp_fmt); if (!unformatted) { print_stats(stat_type); (void) fflush(stdout); if (count || always) (void) sleep(interval); } else { struct stat st; print_unformatted_stats(); (void) fflush(stdout); while (stat(STAT_FILE_DEFAULT, &st) == 0 && st.st_mtime == stat_mod) (void) usleep((useconds_t)(0.2 * MICROSEC)); } } return (E_SUCCESS); }
int importXmlItemFileForAlarm( const char * filename, struct xmlItemAlarm_t * xmlItemAlarmList, int * xmlItemListAlarmTotal ) { int subscript; int subscriptCount; int attrSubscript; xmlChar * longStr; xmlNodePtr node; xmlNodePtr content; xmlNodePtr sonNode; xmlNodePtr grandsonNode; *xmlItemListAlarmTotal = 0; xmlKeepBlanksDefault(0); // create the doc and root node xmlDocPtr doc = xmlReadFile( filename, "UTF-8", XML_PARSE_RECOVER ); if ( doc == NULL ) { // printf("Error: xml Data file \"%s\" import failed.\n", filename); return 0; } xmlNodePtr root_node = xmlDocGetRootElement( doc ); if ( root_node == NULL ) { // printf("Error: failed to get the root of xml doc.\n"); return 0; } if ( xmlStrcmp( root_node->name, BAD_CAST "xmlItemListAlarm") != 0 ) { // printf("Error: name of root node of xml doc not matched.\n"); return 0; } if ( xmlHasProp( root_node, BAD_CAST "xmlItemListAlarmTotal") ) { longStr = xmlGetProp( root_node, BAD_CAST "xmlItemListAlarmTotal" ); *xmlItemListAlarmTotal = xatoi( (char *) longStr ); if ( *xmlItemListAlarmTotal > MAX_ITEMLIST_SAVE ) *xmlItemListAlarmTotal = MAX_ITEMLIST_SAVE; // printf("itemListTotal: %d\n", *itemListTotal ); } else { // printf("Error: failed to get the itemListTotal.\n"); return 0; } node = root_node->xmlChildrenNode; for (subscriptCount=1; subscriptCount <= *xmlItemListAlarmTotal; subscriptCount++) { // printf("subscriptCount: %d\n", subscriptCount); if ( node == NULL ) { // printf("Error: not enough item node.\n"); *xmlItemListAlarmTotal = 0; return 0; } subscript = subscriptCount; xmlItemAlarmList[subscript].message = NULL; sonNode = node->xmlChildrenNode; while( sonNode != NULL ) { // longStr = xmlNodeGetContent( sonNode ); // printf("name: %s\ncontent: %s\n", (char *) sonNode->name, (char *) longStr); if ( xmlStrcmp( sonNode->name, BAD_CAST "message" ) == 0) { longStr = xmlNodeGetContent( sonNode ); xmlItemAlarmList[subscript].message = malloc( strlen(longStr) +1 ); strcpy( xmlItemAlarmList[subscript].message, (char *) longStr ); } else { // printf("Error: unknown sonNode of xml doc item, %s", (char *) sonNode->name ); *xmlItemListAlarmTotal = 0; return 0; } sonNode = sonNode->next; } node = node->next; } printf("import success.\n"); // printf("xmlItemListTotal: %d\n", *xmlItemListTotal); xmlFreeDoc(doc); xmlCleanupParser(); return 1; }
int patch_main(int argc UNUSED_PARAM, char **argv) { int opts; int reverse, state = 0; char *oldname = NULL, *newname = NULL; char *opt_p, *opt_i; long oldlen = oldlen; /* for compiler */ long newlen = newlen; /* for compiler */ INIT_TT(); opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i); argv += optind; reverse = opts & FLAG_REVERSE; TT.prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative! TT.filein = TT.fileout = -1; if (opts & FLAG_INPUT) { xmove_fd(xopen_stdin(opt_i), STDIN_FILENO); } else { if (argv[0] && argv[1]) { xmove_fd(xopen_stdin(argv[1]), STDIN_FILENO); } } if (argv[0]) { oldname = xstrdup(argv[0]); newname = xstrdup(argv[0]); } // Loop through the lines in the patch for(;;) { char *patchline; patchline = xmalloc_fgetline(stdin); if (!patchline) break; // Other versions of patch accept damaged patches, // so we need to also. if (!*patchline) { free(patchline); patchline = xstrdup(" "); } // Are we assembling a hunk? if (state >= 2) { if (*patchline==' ' || *patchline=='+' || *patchline=='-') { dlist_add(&TT.current_hunk, patchline); if (*patchline != '+') oldlen--; if (*patchline != '-') newlen--; // Context line? if (*patchline==' ' && state==2) TT.context++; else state=3; // If we've consumed all expected hunk lines, apply the hunk. if (!oldlen && !newlen) state = apply_one_hunk(); continue; } fail_hunk(); state = 0; continue; } // Open a new file? if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) { char *s, **name = reverse ? &newname : &oldname; int i; if (*patchline == '+') { name = reverse ? &oldname : &newname; state = 1; } finish_oldfile(); if (!argv[0]) { free(*name); // Trim date from end of filename (if any). We don't care. for (s = patchline+4; *s && *s!='\t'; s++) if (*s=='\\' && s[1]) s++; i = atoi(s); if (i>1900 && i<=1970) *name = xstrdup("/dev/null"); else { *s = 0; *name = xstrdup(patchline+4); } } // We defer actually opening the file because svn produces broken // patches that don't signal they want to create a new file the // way the patch man page says, so you have to read the first hunk // and _guess_. // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@ // but a missing ,value means the value is 1. } else if (state == 1 && !strncmp("@@ -", patchline, 4)) { int i; char *s = patchline+4; // Read oldline[,oldlen] +newline[,newlen] TT.oldlen = oldlen = TT.newlen = newlen = 1; TT.oldline = strtol(s, &s, 10); if (*s == ',') TT.oldlen = oldlen = strtol(s+1, &s, 10); TT.newline = strtol(s+2, &s, 10); if (*s == ',') TT.newlen = newlen = strtol(s+1, &s, 10); if (oldlen < 1 && newlen < 1) bb_error_msg_and_die("Really? %s", patchline); TT.context = 0; state = 2; // If this is the first hunk, open the file. if (TT.filein == -1) { int oldsum, newsum, empty = 0; char *name; oldsum = TT.oldline + oldlen; newsum = TT.newline + newlen; name = reverse ? oldname : newname; // We're deleting oldname if new file is /dev/null (before -p) // or if new hunk is empty (zero context) after patching if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum)) { name = reverse ? newname : oldname; empty++; } // handle -p path truncation. for (i=0, s = name; *s;) { if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break; if (*s++ != '/') continue; while (*s == '/') s++; i++; name = s; } if (empty) { // File is empty after the patches have been applied state = 0; if (option_mask32 & FLAG_RMEMPTY) { // If flag -E or --remove-empty-files is set printf("removing %s\n", name); xunlink(name); } else { printf("patching file %s\n", name); xclose(xopen(name, O_WRONLY | O_TRUNC)); } // If we've got a file to open, do so. } else if (!(option_mask32 & FLAG_PATHLEN) || i <= TT.prefix) { struct stat statbuf; // If the old file was null, we're creating a new one. if (!strcmp(oldname, "/dev/null") || !oldsum) { printf("creating %s\n", name); s = strrchr(name, '/'); if (s) { *s = 0; bb_make_directory(name, -1, FILEUTILS_RECUR); *s = '/'; } TT.filein = xopen(name, O_CREAT|O_EXCL|O_RDWR); } else { printf("patching file %s\n", name); TT.filein = xopen(name, O_RDONLY); } TT.tempname = xasprintf("%sXXXXXX", name); TT.fileout = xmkstemp(TT.tempname); // Set permissions of output file fstat(TT.filein, &statbuf); fchmod(TT.fileout, statbuf.st_mode); TT.linenum = 0; TT.hunknum = 0; } } TT.hunknum++; continue; } // If we didn't continue above, discard this line. free(patchline); } finish_oldfile(); if (ENABLE_FEATURE_CLEAN_UP) { free(oldname); free(newname); } return TT.exitval; }
int patoi(char* str) { long num; xatoi(&str, &num); return (int)num; }
static void TaskMonitor(void *pvParameters) // Monitor for Serial Interface { (void) pvParameters; uint8_t *ptr; int32_t p1; // create the buffer on the heap (so they can be moved later). if(LineBuffer == NULL) // if there is no Line buffer allocated (pointer is NULL), then allocate buffer. if( !(LineBuffer = (uint8_t *) pvPortMalloc( sizeof(uint8_t) * LINE_SIZE ))) xSerialPrint_P(PSTR("pvPortMalloc for *LineBuffer fail..!\r\n")); while(1) { xSerialPutChar(&xSerialPort, '>'); ptr = LineBuffer; get_line(ptr, (uint8_t)(sizeof(uint8_t)* LINE_SIZE)); //sizeof (Line); switch (*ptr++) { case 'h' : // help xSerialPrint_P( PSTR("rt - reset maximum & minimum temperatures\r\n") ); xSerialPrint_P( PSTR("t - show the time\r\n") ); xSerialPrint_P( PSTR("t - set the time\r\nt [<year yy> <month mm> <date dd> <day: Sun=0> <hour hh> <minute mm> <second ss>]\r\n") ); break; #ifdef portRTC_DEFINED case 't' : /* t [<year yy> <month mm> <date dd> <day: Sun=0> <hour hh> <minute mm> <second ss>] */ if (xatoi(&ptr, &p1)) { SetTimeDate.tm_year = (uint8_t)p1 + 100; // convert to (Gregorian - 1900) xatoi(&ptr, &p1); SetTimeDate.tm_mon = (uint8_t)p1; xatoi(&ptr, &p1); SetTimeDate.tm_mday = (uint8_t)p1; xatoi(&ptr, &p1); SetTimeDate.tm_wday = (uint8_t)p1; xatoi(&ptr, &p1); SetTimeDate.tm_hour = (uint8_t)p1; xatoi(&ptr, &p1); SetTimeDate.tm_min = (uint8_t)p1; if (!xatoi(&ptr, &p1)) break; SetTimeDate.tm_sec = (uint8_t)p1; xSerialPrintf_P(PSTR("Set: %u/%u/%u %2u:%02u:%02u\r\n"), SetTimeDate.tm_year, SetTimeDate.tm_mon, SetTimeDate.tm_mday, SetTimeDate.tm_hour, SetTimeDate.tm_min, SetTimeDate.tm_sec); if (setDateTimeDS1307( &SetTimeDate ) == pdTRUE) xSerialPrint_P( PSTR("Setting successful\r\n") ); } else { if (getDateTimeDS1307( &xCurrentTempTime.DateTime) == pdTRUE) xSerialPrintf_P(PSTR("Current: %u/%u/%u %2u:%02u:%02u\r\n"), xCurrentTempTime.DateTime.tm_year + 1900, xCurrentTempTime.DateTime.tm_mon, xCurrentTempTime.DateTime.tm_mday, xCurrentTempTime.DateTime.tm_hour, xCurrentTempTime.DateTime.tm_min, xCurrentTempTime.DateTime.tm_sec); } break; #endif case 'r' : // reset switch (*ptr++) { case 't' : // temperature xMaximumTempTime = xCurrentTempTime; xMinimumTempTime = xCurrentTempTime; // Now we commit the time and temperature to the EEPROM, forever... eeprom_update_block(&xMaximumTempTime, &xMaximumEverTempTime, sizeof(xRTCTempArray)); eeprom_update_block(&xMinimumTempTime, &xMinimumEverTempTime, sizeof(xRTCTempArray)); break; default : break; } break; default : break; } // xSerialPrintf_P(PSTR("\r\nSerial Monitor: Stack HighWater @ %u"), uxTaskGetStackHighWaterMark(NULL)); // xSerialPrintf_P(PSTR("\r\nFree Heap Size: %u\r\n"), xPortGetMinimumEverFreeHeapSize() ); // needs heap_1, heap_2 or heap_4 for this function to succeed. } }
int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); const char *program_usage_string = _( "& [-v -i -n INCREMENT] -e|--event EVENT DIR..." ); char *event_name = NULL; int interactive = 0; /* must be _int_, OPT_BOOL expects that! */ int nice_incr = 0; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_STRING('e', "event" , &event_name, "EVENT", _("Run EVENT on DIR")), OPT_BOOL('i', "interactive" , &interactive, _("Communicate directly to the user")), OPT_INTEGER('n', "nice" , &nice_incr, _("Increment the nice value by INCREMENT")), OPT_END() }; parse_opts(argc, argv, program_options, program_usage_string); argv += optind; if (!*argv || !event_name) show_usage_and_die(program_usage_string, program_options); load_abrt_conf(); const char *const opt_env_nice = getenv("ABRT_EVENT_NICE"); if (opt_env_nice != NULL && opt_env_nice[0] != '\0') { log_debug("Using ABRT_EVENT_NICE=%s to increment the nice value", opt_env_nice); nice_incr = xatoi(opt_env_nice); } if (nice_incr != 0) { log_debug("Incrementing the nice value by %d", nice_incr); const int ret = nice(nice_incr); if (ret == -1) perror_msg_and_die("Failed to increment the nice value"); } bool post_create = (strcmp(event_name, "post-create") == 0); char *dump_dir_name = NULL; while (*argv) { dump_dir_name = xstrdup(*argv++); int i = strlen(dump_dir_name); while (--i >= 0) if (dump_dir_name[i] != '/') break; dump_dir_name[++i] = '\0'; struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ DD_OPEN_READONLY); if (!dd) return 1; uid = dd_load_text_ext(dd, FILENAME_UID, DD_FAIL_QUIETLY_ENOENT); dd_close(dd); struct run_event_state *run_state = new_run_event_state(); if (!interactive) make_run_event_state_forwarding(run_state); run_state->logging_callback = do_log; if (post_create) run_state->post_run_callback = is_crash_a_dup; int r = run_event_on_dir_name(run_state, dump_dir_name, event_name); const bool no_action_for_event = (r == 0 && run_state->children_count == 0); free_run_event_state(run_state); /* Needed only if is_crash_a_dup() was called, but harmless * even if it wasn't: */ dup_uuid_fini(); dup_corebt_fini(); if (no_action_for_event) error_msg_and_die("No actions are found for event '%s'", event_name); //TODO: consider this case: // new dump is created, post-create detects that it is a dup, // but then load_crash_info(dup_name) *FAILS*. // In this case, we later delete damaged dup_name (right?) // but new dump never gets its FILENAME_COUNT set! /* Is crash a dup? (In this case, is_crash_a_dup() should have * aborted "post-create" event processing as soon as it saw uuid * and determined that there is another crash with same uuid. * In this case it sets crash_dump_dup_name) */ if (crash_dump_dup_name) error_msg_and_die("DUP_OF_DIR: %s", crash_dump_dup_name); /* Was there error on one of processing steps in run_event? */ if (r != 0) return r; /* yes */ free(dump_dir_name); dump_dir_name = NULL; } /* exit 0 means, that there is no duplicate of dump-dir */ return 0; }
int patch_main(int argc UNUSED_PARAM, char **argv) { struct stat saved_stat; char *patch_line; FILE *patch_file; int patch_level; int ret = 0; char plus = '+'; unsigned opt; enum { OPT_R = (1 << 2), OPT_N = (1 << 3), /*OPT_f = (1 << 4), ignored */ /*OPT_E = (1 << 5), ignored, this is the default */ /*OPT_g = (1 << 6), ignored */ OPT_dry_run = (1 << 7) * ENABLE_LONG_OPTS, }; xfunc_error_retval = 2; { const char *p = "-1"; const char *i = "-"; /* compat */ #if ENABLE_LONG_OPTS static const char patch_longopts[] ALIGN1 = "strip\0" Required_argument "p" "input\0" Required_argument "i" "reverse\0" No_argument "R" "forward\0" No_argument "N" /* "Assume user knows what [s]he is doing, do not ask any questions": */ "force\0" No_argument "f" /*ignored*/ # if ENABLE_DESKTOP "remove-empty-files\0" No_argument "E" /*ignored*/ /* "Controls actions when a file is under RCS or SCCS control, * and does not exist or is read-only and matches the default version, * or when a file is under ClearCase control and does not exist..." * IOW: rather obscure option. * But Gentoo's portage does use -g0 */ "get\0" Required_argument "g" /*ignored*/ # endif "dry-run\0" No_argument "\xfd" # if ENABLE_DESKTOP "backup-if-mismatch\0" No_argument "\xfe" /*ignored*/ "no-backup-if-mismatch\0" No_argument "\xff" /*ignored*/ # endif ; applet_long_options = patch_longopts; #endif /* -f,-E,-g are ignored */ opt = getopt32(argv, "p:i:RN""fEg:", &p, &i, NULL); if (opt & OPT_R) plus = '-'; patch_level = xatoi(p); /* can be negative! */ patch_file = xfopen_stdin(i); } patch_line = xmalloc_fgetline(patch_file); while (patch_line) { FILE *src_stream; FILE *dst_stream; //char *old_filename; char *new_filename; char *backup_filename = NULL; unsigned src_cur_line = 1; unsigned dst_cur_line = 0; unsigned dst_beg_line; unsigned bad_hunk_count = 0; unsigned hunk_count = 0; smallint copy_trailing_lines_flag = 0; /* Skip everything upto the "---" marker * No need to parse the lines "Only in <dir>", and "diff <args>" */ do { /* Extract the filename ugsed before the patch was generated */ new_filename = extract_filename(patch_line, patch_level, "--- "); // was old_filename above patch_line = xmalloc_fgetline(patch_file); if (!patch_line) goto quit; } while (!new_filename); free(new_filename); // "source" filename is irrelevant new_filename = extract_filename(patch_line, patch_level, "+++ "); if (!new_filename) { bb_error_msg_and_die("invalid patch"); } /* Get access rights from the file to be patched */ if (stat(new_filename, &saved_stat) != 0) { char *slash = strrchr(new_filename, '/'); if (slash) { /* Create leading directories */ *slash = '\0'; bb_make_directory(new_filename, -1, FILEUTILS_RECUR); *slash = '/'; } src_stream = NULL; saved_stat.st_mode = 0644; } else if (!(opt & OPT_dry_run)) { backup_filename = xasprintf("%s.orig", new_filename); xrename(new_filename, backup_filename); src_stream = xfopen_for_read(backup_filename); } else src_stream = xfopen_for_read(new_filename); if (opt & OPT_dry_run) { dst_stream = xfopen_for_write("/dev/null"); } else { dst_stream = xfopen_for_write(new_filename); fchmod(fileno(dst_stream), saved_stat.st_mode); } printf("patching file %s\n", new_filename); /* Handle all hunks for this file */ patch_line = xmalloc_fgets(patch_file); while (patch_line) { unsigned count; unsigned src_beg_line; unsigned hunk_offset_start; unsigned src_last_line = 1; unsigned dst_last_line = 1; if ((sscanf(patch_line, "@@ -%u,%u +%u,%u", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3) && (sscanf(patch_line, "@@ -%u +%u,%u", &src_beg_line, &dst_beg_line, &dst_last_line) < 2) ) { /* No more hunks for this file */ break; } if (plus != '+') { /* reverse patch */ unsigned tmp = src_last_line; src_last_line = dst_last_line; dst_last_line = tmp; tmp = src_beg_line; src_beg_line = dst_beg_line; dst_beg_line = tmp; } hunk_count++; if (src_beg_line && dst_beg_line) { /* Copy unmodified lines upto start of hunk */ /* src_beg_line will be 0 if it's a new file */ count = src_beg_line - src_cur_line; if (copy_lines(src_stream, dst_stream, count)) { bb_error_msg_and_die("bad src file"); } src_cur_line += count; dst_cur_line += count; copy_trailing_lines_flag = 1; } src_last_line += hunk_offset_start = src_cur_line; dst_last_line += dst_cur_line; while (1) { free(patch_line); patch_line = xmalloc_fgets(patch_file); if (patch_line == NULL) break; /* EOF */ if (!*patch_line) { /* whitespace-damaged patch with "" lines */ free(patch_line); patch_line = xstrdup(" "); } if ((*patch_line != '-') && (*patch_line != '+') && (*patch_line != ' ') ) { break; /* End of hunk */ } if (*patch_line != plus) { /* '-' or ' ' */ char *src_line = NULL; if (src_cur_line == src_last_line) break; if (src_stream) { src_line = xmalloc_fgets(src_stream); if (src_line) { int diff = strcmp(src_line, patch_line + 1); src_cur_line++; free(src_line); if (diff) src_line = NULL; } } /* Do not patch an already patched hunk with -N */ if (src_line == 0 && (opt & OPT_N)) { continue; } if (!src_line) { bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start); bad_hunk_count++; break; } if (*patch_line != ' ') { /* '-' */ continue; } } if (dst_cur_line == dst_last_line) break; fputs(patch_line + 1, dst_stream); dst_cur_line++; } /* end of while loop handling one hunk */ } /* end of while loop handling one file */ /* Cleanup last patched file */ if (copy_trailing_lines_flag) { copy_lines(src_stream, dst_stream, (unsigned)(-1)); } if (src_stream) { fclose(src_stream); } fclose(dst_stream); if (bad_hunk_count) { ret = 1; bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count); } else { /* It worked, we can remove the backup */ if (backup_filename) { unlink(backup_filename); } if (!(opt & OPT_dry_run) && ((dst_cur_line == 0) || (dst_beg_line == 0)) ) { /* The new patched file is empty, remove it */ xunlink(new_filename); // /* old_filename and new_filename may be the same file */ // unlink(old_filename); } } free(backup_filename); //free(old_filename); free(new_filename); } /* end of "while there are patch lines" */ quit: /* 0 = SUCCESS * 1 = Some hunks failed * 2 = More serious problems (exited earlier) */ return ret; }
int rtcwake_main(int argc UNUSED_PARAM, char **argv) { time_t rtc_time; unsigned opt; const char *rtcname = NULL; const char *suspend; const char *opt_seconds; const char *opt_time; time_t sys_time; time_t alarm_time = 0; unsigned seconds = 0; int utc = -1; int fd; #if ENABLE_LONG_OPTS static const char rtcwake_longopts[] ALIGN1 = "auto\0" No_argument "a" "local\0" No_argument "l" "utc\0" No_argument "u" "device\0" Required_argument "d" "mode\0" Required_argument "m" "seconds\0" Required_argument "s" "time\0" Required_argument "t" ; applet_long_options = rtcwake_longopts; #endif opt = getopt32(argv, "alud:m:s:t:", &rtcname, &suspend, &opt_seconds, &opt_time); /* this is the default if (opt & RTCWAKE_OPT_AUTO) utc = -1; */ if (opt & (RTCWAKE_OPT_UTC | RTCWAKE_OPT_LOCAL)) utc = opt & RTCWAKE_OPT_UTC; if (!(opt & RTCWAKE_OPT_SUSPEND_MODE)) suspend = DEFAULT_MODE; if (opt & RTCWAKE_OPT_SECONDS) /* alarm time, seconds-to-sleep (relative) */ seconds = xatoi(opt_seconds); if (opt & RTCWAKE_OPT_TIME) /* alarm time, time_t (absolute, seconds since 1/1 1970 UTC) */ alarm_time = xatol(opt_time); if (!alarm_time && !seconds) bb_error_msg_and_die("must provide wake time"); if (utc == -1) utc = rtc_adjtime_is_utc(); /* the rtcname is relative to /dev */ xchdir("/dev"); /* this RTC must exist and (if we'll sleep) be wakeup-enabled */ fd = rtc_xopen(&rtcname, O_RDONLY); if (strcmp(suspend, "on") && !may_wakeup(rtcname)) bb_error_msg_and_die("%s not enabled for wakeup events", rtcname); /* relative or absolute alarm time, normalized to time_t */ sys_time = time(NULL); { struct tm tm_time; rtc_read_tm(&tm_time, fd); rtc_time = rtc_tm2time(&tm_time, utc); } if (alarm_time) { if (alarm_time < sys_time) bb_error_msg_and_die("time doesn't go backward to %s", ctime(&alarm_time)); alarm_time += sys_time - rtc_time; } else alarm_time = rtc_time + seconds + 1; setup_alarm(fd, &alarm_time, rtc_time); sync(); printf("wakeup from \"%s\" at %s", suspend, ctime(&alarm_time)); fflush_all(); usleep(10 * 1000); if (strcmp(suspend, "on")) xopen_xwrite_close(SYS_POWER_PATH, suspend); else { /* "fake" suspend ... we'll do the delay ourselves */ unsigned long data; do { ssize_t ret = safe_read(fd, &data, sizeof(data)); if (ret < 0) { bb_perror_msg("rtc read"); break; } } while (!(data & RTC_AF)); } xioctl(fd, RTC_AIE_OFF, 0); if (ENABLE_FEATURE_CLEAN_UP) close(fd); return EXIT_SUCCESS; }
void modify_mem_data (uint16_t addr,uint8_t ByteCount){ uint16_t mem_addr,mem_data; uint8_t recv_char=0; uint8_t size, index = 0; uint16_t input_data; uint8_t i=0; uint8_t m=0; uint8_t key; /* Clear the buffer before getting any new data */ for(index = 0; index < 10; index++) { rx_char[index] = '0'; } index = 0; mem_addr = addr; dp_display_text("Enter New data(0x10fe,1234, 0b1010110)\r\n"); for ( i=0; i <= ByteCount ;i++) { dp_display_text("\r\n"); dp_display_value(i,DEC); dp_display_text("\t"); dp_display_value(mem_addr,HEX); dp_display_text(":"); mem_data= HW_get_16bit_reg(mem_addr); dp_display_value(mem_data,HEX); dp_display_text("->"); key = get_key_selection(); if ( key == CHAR_ESC){ // ESC key == exit from writing return; }else if ( key == CHAR_LINE_FEED) // Return key, move to next address { mem_addr = mem_addr + 1; } else { rx_char[0] = key; // put the previosly rxvd character to buffer; index = 1; while(recv_char != CHAR_LINE_FEED) //'\n' { size = UART_get_rx(&g_stdio_uart, &recv_char,1); if(size > 0) { rx_char[index] = recv_char; UART_send (&g_stdio_uart, (uint8_t *)&recv_char,sizeof(recv_char)); index++; size = 0; // clear the rcvd flag } } rx_char_ptr = rx_char; xatoi ( &rx_char_ptr, &input_data); HW_set_16bit_reg(mem_addr,input_data); mem_addr = mem_addr + 1; recv_char = '-'; // DUMMY VALUE TO CHANGE THE DETECTION OF NEW LINE CHAR } } }
void ShortCutData(int nType, HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop) { g_stringsize=string_size; g_stacktop=stacktop; g_variables=variables; { HRESULT hRes; IShellLink* m_psl; IPersistFile* m_ppf; popstring(szBuf); if (nType > SHELLLINKTYPE_GETWORKINGDIR) popstring(szBuf2); hRes=CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*) &m_psl); if (hRes == S_OK) { hRes=m_psl->QueryInterface(IID_IPersistFile, (LPVOID*) &m_ppf); if (hRes == S_OK) { #ifdef UNICODE hRes=m_ppf->Load(szBuf, STGM_READWRITE); #else WCHAR wszPath[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, szBuf, -1, wszPath, MAX_PATH); hRes=m_ppf->Load(wszPath, STGM_READWRITE); #endif if (hRes == S_OK) { if (nType <= SHELLLINKTYPE_GETWORKINGDIR) { //Get switch(nType) { case SHELLLINKTYPE_GETARGS: { hRes=m_psl->GetArguments(szBuf, MAX_PATH); if (hRes != S_OK) szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETDESC: { hRes=m_psl->GetDescription(szBuf, MAX_PATH); if (hRes != S_OK) szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETHOTKEY: { hRes=m_psl->GetHotkey(&wHotkey); if (hRes == S_OK) wsprintf(szBuf, TEXT("%d"), wHotkey); else szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETICONLOC: { hRes=m_psl->GetIconLocation(szBuf, MAX_PATH, &nBuf); if (hRes != S_OK) szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETICONINDEX: { hRes=m_psl->GetIconLocation(szBuf, MAX_PATH, &nBuf); if (hRes == S_OK) wsprintf(szBuf, TEXT("%d"), nBuf); else szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETPATH: { WIN32_FIND_DATA fd; hRes=m_psl->GetPath(szBuf, MAX_PATH, &fd, SLGP_UNCPRIORITY); if (hRes != S_OK) szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETSHOWMODE: { hRes=m_psl->GetShowCmd(&nBuf); if (hRes == S_OK) wsprintf(szBuf, TEXT("%d"), nBuf); else szBuf[0]=TEXT('\0'); }; break; case SHELLLINKTYPE_GETWORKINGDIR: { hRes=m_psl->GetWorkingDirectory(szBuf, MAX_PATH); if (hRes != S_OK) szBuf[0]=TEXT('\0'); }; break; } } else { //Set switch(nType) { case SHELLLINKTYPE_SETARGS: { hRes=m_psl->SetArguments(szBuf2); }; break; case SHELLLINKTYPE_SETDESC: { hRes=m_psl->SetDescription(szBuf2); }; break; case SHELLLINKTYPE_SETHOTKEY: { wHotkey=(unsigned short)xatoi(szBuf2); hRes=m_psl->SetHotkey(wHotkey); }; break; case SHELLLINKTYPE_SETICONLOC: { hRes=m_psl->GetIconLocation(szBuf, MAX_PATH, &nBuf); if (hRes == S_OK) hRes=m_psl->SetIconLocation(szBuf2, nBuf); }; break; case SHELLLINKTYPE_SETICONINDEX: { int nBuf2; nBuf=xatoi(szBuf2); hRes=m_psl->GetIconLocation(szBuf, MAX_PATH, &nBuf2); if (hRes == S_OK) hRes=m_psl->SetIconLocation(szBuf, nBuf); }; break; case SHELLLINKTYPE_SETPATH: { hRes=m_psl->SetPath(szBuf2); }; break; case SHELLLINKTYPE_SETSHOWMODE: { nBuf=xatoi(szBuf2); hRes=m_psl->SetShowCmd(nBuf); }; break; case SHELLLINKTYPE_SETWORKINGDIR: { hRes=m_psl->SetWorkingDirectory(szBuf2); }; break; } if (hRes == S_OK) hRes=m_ppf->Save(NULL, FALSE); #ifdef SHELLLINK_DEBUG else MessageBox(hwndParent, "ERROR: Save()", "ShellLink", MB_OK); #endif } } #ifdef SHELLLINK_DEBUG else MessageBox(hwndParent, "ERROR: Load()", "ShellLink", MB_OK); #endif } #ifdef SHELLLINK_DEBUG else MessageBox(hwndParent, "CShellLink::Initialise, Failed in call to QueryInterface for IPersistFile, HRESULT was %x\n", "ShellLink", MB_OK); #endif // Cleanup: if (m_ppf) m_ppf->Release(); if (m_psl) m_psl->Release(); } #ifdef SHELLLINK_DEBUG else MessageBox(hwndParent, "ERROR: CoCreateInstance()", "ShellLink", MB_OK); #endif if (hRes == S_OK) { if (nType <= SHELLLINKTYPE_GETWORKINGDIR) pushstring(szBuf); else pushstring(TEXT("0")); } else { if (nType <= SHELLLINKTYPE_GETWORKINGDIR) pushstring(TEXT("")); else pushstring(TEXT("-1")); } } }
int patch_main(int argc UNUSED_PARAM, char **argv) { struct stat saved_stat; char *patch_line; FILE *patch_file; int patch_level; int ret = 0; char plus = '+'; xfunc_error_retval = 2; { const char *p = "-1"; const char *i = "-"; /* compat */ if (getopt32(argv, "p:i:R", &p, &i) & 4) plus = '-'; patch_level = xatoi(p); /* can be negative! */ patch_file = xfopen_stdin(i); } patch_line = xmalloc_fgetline(patch_file); while (patch_line) { FILE *src_stream; FILE *dst_stream; //char *old_filename; char *new_filename; char *backup_filename; unsigned src_cur_line = 1; unsigned dst_cur_line = 0; unsigned dst_beg_line; unsigned bad_hunk_count = 0; unsigned hunk_count = 0; smallint copy_trailing_lines_flag = 0; /* Skip everything upto the "---" marker * No need to parse the lines "Only in <dir>", and "diff <args>" */ do { /* Extract the filename used before the patch was generated */ new_filename = extract_filename(patch_line, patch_level, "--- "); // was old_filename above patch_line = xmalloc_fgetline(patch_file); if (!patch_line) goto quit; } while (!new_filename); free(new_filename); // "source" filename is irrelevant new_filename = extract_filename(patch_line, patch_level, "+++ "); if (!new_filename) { bb_error_msg_and_die("invalid patch"); } /* Get access rights from the file to be patched */ if (stat(new_filename, &saved_stat) != 0) { char *slash = strrchr(new_filename, '/'); if (slash) { /* Create leading directories */ *slash = '\0'; bb_make_directory(new_filename, -1, FILEUTILS_RECUR); *slash = '/'; } backup_filename = NULL; src_stream = NULL; saved_stat.st_mode = 0644; } else { backup_filename = xasprintf("%s.orig", new_filename); xrename(new_filename, backup_filename); src_stream = xfopen_for_read(backup_filename); } dst_stream = xfopen_for_write(new_filename); fchmod(fileno(dst_stream), saved_stat.st_mode); printf("patching file %s\n", new_filename); /* Handle all hunks for this file */ patch_line = xmalloc_fgets(patch_file); while (patch_line) { unsigned count; unsigned src_beg_line; unsigned hunk_offset_start; unsigned src_last_line = 1; unsigned dst_last_line = 1; if ((sscanf(patch_line, "@@ -%d,%d +%d,%d", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3) && (sscanf(patch_line, "@@ -%d +%d,%d", &src_beg_line, &dst_beg_line, &dst_last_line) < 2) ) { /* No more hunks for this file */ break; } if (plus != '+') { /* reverse patch */ unsigned tmp = src_last_line; src_last_line = dst_last_line; dst_last_line = tmp; tmp = src_beg_line; src_beg_line = dst_beg_line; dst_beg_line = tmp; } hunk_count++; if (src_beg_line && dst_beg_line) { /* Copy unmodified lines upto start of hunk */ /* src_beg_line will be 0 if it's a new file */ count = src_beg_line - src_cur_line; if (copy_lines(src_stream, dst_stream, count)) { bb_error_msg_and_die("bad src file"); } src_cur_line += count; dst_cur_line += count; copy_trailing_lines_flag = 1; } src_last_line += hunk_offset_start = src_cur_line; dst_last_line += dst_cur_line; while (1) { free(patch_line); patch_line = xmalloc_fgets(patch_file); if (patch_line == NULL) break; /* EOF */ if ((*patch_line != '-') && (*patch_line != '+') && (*patch_line != ' ') ) { break; /* End of hunk */ } if (*patch_line != plus) { /* '-' or ' ' */ char *src_line = NULL; if (src_cur_line == src_last_line) break; if (src_stream) { src_line = xmalloc_fgets(src_stream); if (src_line) { int diff = strcmp(src_line, patch_line + 1); src_cur_line++; free(src_line); if (diff) src_line = NULL; } } if (!src_line) { bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start); bad_hunk_count++; break; } if (*patch_line != ' ') { /* '-' */ continue; } } if (dst_cur_line == dst_last_line) break; fputs(patch_line + 1, dst_stream); dst_cur_line++; } /* end of while loop handling one hunk */ } /* end of while loop handling one file */ /* Cleanup last patched file */ if (copy_trailing_lines_flag) { copy_lines(src_stream, dst_stream, (unsigned)(-1)); } if (src_stream) { fclose(src_stream); } fclose(dst_stream); if (bad_hunk_count) { ret = 1; bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count); } else { /* It worked, we can remove the backup */ if (backup_filename) { unlink(backup_filename); } if ((dst_cur_line == 0) || (dst_beg_line == 0)) { /* The new patched file is empty, remove it */ xunlink(new_filename); // /* old_filename and new_filename may be the same file */ // unlink(old_filename); } } free(backup_filename); //free(old_filename); free(new_filename); } /* end of "while there are patch lines" */ quit: /* 0 = SUCCESS * 1 = Some hunks failed * 2 = More serious problems (exited earlier) */ return ret; }
/* Command interpreter for VBIT, The leading SO and trailing carriage return are already removed The X command returns 2 Other good commands return 0 and bad commands return 1. Also after a P command if selecting a single page fails, the page is created and 8 is the return code */ static int vbit_command(char *Line) { static uint8_t firstLine=true; static uint16_t SRAMAddress; // The address pointer into the FIFO serial ram unsigned char rwmode; unsigned char returncode=0; int pagecount; uint8_t directorySteps; int8_t sign; // 1=plus -1=minus char ch; unsigned char valid; long n; unsigned char i; char str[80]; char *ptr; char *dest; str[0]='O'; str[1]='K'; str[2]='\0'; // char data[80]; // This stuff is to do with locating pages in the display list (Directory command) // (also shared with ee/ea command for uploading pages) NODEPTR np; DISPLAYNODE node; PAGEINDEXRECORD ixRec; uint16_t charcount; uint8_t res; DWORD fileptr; // Used to save the file pointer to the body of the ttx file PAGE page; // ee/ea specific variable static DWORD StartOfPage; DWORD EndOfPage; // Records the start and end of the new page PAGEINDEXRECORD pageindex; uint16_t ix; char packet[45]; static uint8_t row; // Teletext row counter for JA/JZ/JW command // tba // Read, Update or not switch (Line[2]) { case 'R' : rwmode=CMD_MODE_READ; break; case 'U' : rwmode=CMD_MODE_WRITE;break; default: rwmode=CMD_MODE_NONE; } /* Is there actually any data */ if (*Line==0) returncode=1; else switch (Line[1]) { case 'b': // Dump the current page dumpPage(); break; case 'C': // Create magazine lists // TODO: Kill video // TODO: C<pages to pre-allocate> // this would speed up the process immensely // It only needs to be approximate as FatFS will extend the file as needed. cli(); pagecount=300; for (i=1;i<=1;i++) // TODO: Do we need more lists? Probably can find a way around it. SDCreateLists(i,pagecount); sei(); break; case 'D': // Directory - D[<F|L>][<+|->][<n>] // Where F=first, L=Last, +=next, -=prev, n=number of pages to step (default 1) //xprintf(PSTR("D Command needs to be written")); // It would probably be a good idea to save the seek pointer // do the reading required // and then reset it. This would save memory. // If the ee command is active, don't allow D to mess the page variable. if (firstLine) { returncode=1; // ee command is busy. break; } directorySteps=0; sign=1; for (i=2;Line[i];i++) { ch=Line[i]; // xprintf(PSTR("Processing Line[%d]=%c\n\r"),i,Line[i]); switch (ch) { case 'F' : ; // Set the first item DirectoryFirst(); break; case 'L' : ; // Set the last item DirectoryLast(); break; case '+' : ; // Next item directorySteps=1; sign=1; // xprintf(PSTR("D+ not implemented")); break; case '-' : ; // Previous item directorySteps=1; sign=-1; // xprintf(PSTR("D- not implemented")); break; default: // Number of steps (TODO: Extend to a generic decimal) if (ch>='0' && ch <='9') { directorySteps=ch; } Line[i]=0;// Force this to be the last option break; // Break because this must be the last option } // Find the page if (LocatePage(directorySteps*sign)==NULLPTR) { // Probably want to set an error value as we failed to iterate // But I don't think that we return anything different. // We rely on TED scheduler to remember the count returned by the P command and NOT overrun } // TODO: Work out what to do with the rest of the parameters np=GetNodePtr(¤tPage); // TODO: Handle sub pages GetNode(&node,np); // Instead treat the page like a single page f_lseek(&listFIL,(node.pageindex)*sizeof(PAGEINDEXRECORD)); // Seek the page index f_read(&listFIL,&ixRec,sizeof(PAGEINDEXRECORD),&charcount); // and read it // Now seek the actual page that we are referencing res=f_open(&PageF,"pages.all",FA_READ); // Now look for the relevant page f_lseek(&PageF,ixRec.seekptr); // Seek the actual page // Now we have the page, we need to seek through it to get // the data while (PageF.fptr<(ixRec.seekptr+ixRec.pagesize)) { fileptr=PageF.fptr; // Save the file pointer in case we found "OL" f_gets(str,sizeof(str),&PageF); if (str[0]=='O' && str[1]=='L') { f_lseek (&PageF, fileptr); // Step back to the OL line break; } if (ParseLine(&page, str)) { xprintf(PSTR("[insert]file error handler needed:%s\n"),str); // At this point we are stuffed. f_close(&PageF); returncode=1; break; // what else should we do if we get here? } } // bb mpp qq cc tttt ssss n xxxxxxx // Leading zeros rely on PRINTF_LIB_FLOAT in makefile!!! sprintf_P(str,PSTR("%02X %03X %02d %02X %04X 0000 %1d 00000000"), 3, // seconds (hex) 0x100+(currentPage/2), // mpp page.subpage, // ss page.control, // S page.time, // Cycle time (secs) (currentPage>>8)+1); // Mag f_close(&PageF); } // str[0]=0; // might return the directory paramaters here break; case 'E' : // EO, ES, EN, EP, EL, EM - examine switch (Line[2]) { case 'M': // EM - Return Miscellaneous flags { // These are BFLSU. The code below is not correct n = ini_getl("service", "serialmode", 0, inifile); if (n) xputs(PSTR("20")); else xputs(PSTR("00")); break; } break; default: returncode=1; case 'O': // EO - Output dataline actions set by QO // 18 characters on a line, but odd ignores last action n = ini_gets("service", "outputodd", "111Q2233P445566778", str, sizearray(str), inifile); n = ini_gets("service", "outputeven", "111Q2233P445566778", str, sizearray(str), inifile); xprintf(PSTR("%s"),str); break; } break; // E commands case 'e' : // ea or ee : Upload page(s). // These pages add the lines at the end of the page file, and patch the index. // Warning. "page" is shared with the directory command // directory calls are blocked until you do ee. switch (Line[2]) { case 'a' : // Add a page, line at a time. passBackspace=true; if (firstLine) { firstLine=false; ClearPage(&page); // Clear out our Page object res=f_open(&PageF,"pages.all",FA_READ| FA_WRITE); // Ready to write // TODO: check the value of res //xprintf(PSTR("Size of pages.all=%ul\n\r"),PageF.fsize); /* Move to end of pages.all to append data */ res=f_lseek(&PageF, PageF.fsize); //xprintf(PSTR("lseek res=%d\n\r"),res); StartOfPage=PageF.fptr; // We need the Start Of Page for the index } // uh fellows, Although we get \r => Ctrl-P, we need to map it to 0x8d which is the file format. for (ptr=&Line[4];*ptr;ptr++) if (*ptr==0x10) *ptr=0x8d; f_puts(&Line[4],&PageF); // The rest of the line is the file contents f_putc('\n',&PageF); // Add the LF that the interpreter strips out xprintf(PSTR("Now writing:%s\n\r"),&Line[4]); // Don't unencode the line, pages.all should follow MRG \r => ctrl-P substitutions // Probably can ignore Viewdata escapes. // Write the rest of the line to pages.all // Parse the line so we have all the page details so we know where to put it in the array/node if (ParseLine(&page, &Line[4])) { xprintf(PSTR("Your page sucks. Unable to parse this nonsense\n\r")); returncode=1; // failed // TODO: implement the break // break; } break; // a case 'e' : // We finished. End the update passBackspace=false; EndOfPage=PageF.fptr; f_close(&PageF); // We are done with pages.all // We need to refresh the transmission file object so close and re-open it f_close(&pagefileFIL); res=f_open(&pagefileFIL,"pages.all",FA_READ); // Only need to open this once! // Or are we all done? We need to write the page to Pmpp.TTI so that we can rebuild the index later pageindex.seekptr=StartOfPage; pageindex.pagesize=(uint16_t)(EndOfPage-StartOfPage); // Warning! 16 bit file size limits to about 50 subpages. xprintf(PSTR("seek %ld size %d \n\r"),pageindex.seekptr,pageindex.pagesize); // 1: Append pages.idx with the file start/end (append pageindex) f_close(&listFIL); // TODO: Perhaps we should check that this is actually opened first? res=f_open(&listFIL,"pages.idx",FA_READ| FA_WRITE); // Ready to write // TODO: check the value of res ix=listFIL.fsize; // This is the address in the file res=f_lseek(&listFIL, ix); // Locate the end of the file // Now append the page index f_write(&listFIL,&(pageindex.seekptr),4,&charcount); // 4 byte seek pointer f_write(&listFIL,&(pageindex.pagesize),2,&charcount); // 2 byte file size // Now restore the file to the previous opened readonly state f_close(&listFIL); res=f_open(&listFIL,"pages.idx",FA_READ); // 2: Add the page to the page array. (Or we could rebuild just by doing a restart) ix=ix/sizeof(pageindex); xprintf(PSTR("New page mag=%d page=%02X --> added at ix=%d\n\r"),page.mag,page.page,ix); LinkPage(page.mag, page.page, page.subcode, ix); // TODO: // 3: Add the page to the node list. (ditto) // TODO: firstLine=true; // and reset ready for the next file break; // e default: str[0]=0; returncode=1; } break; // e commands case 'G': /* G - Packet 8/30 format 1 [p830f1]*/ if (rwmode==CMD_MODE_NONE) { str[0]=0; returncode=1; break; } /* C, L N, T, D */ switch (Line[3]) { case 'C' : /* Code. 1=format 1 */ //xputs(PSTR("GUC command not implemented. Why would we need it\n")); // It should always default to 0 /** Where is the initial page done? The code below is wrong */ //SetInitialPage(pkt830,str1,str2); // nb. Hard coded to 100 break; case 'D' : /* up to 20 characters label*/ if (rwmode==CMD_MODE_READ) { n = ini_gets("p830f1", "label", "VBITFax ", str, sizearray(str), inifile); xprintf(PSTR("%s"),str); } if (rwmode==CMD_MODE_WRITE) { n = ini_puts("p830f1", "label", &Line[4], inifile); SetStatusLabel(pkt830,&Line[4]); } break; case 'L' : /* Link */ xputs(PSTR("GUL command\n")); /* Alrighty. The MAG is already in the MRAG. All we actually need is ppssss where pp=hex page number and ssss=hex subcode */ n = ini_gets("p830f1", "initialpage", "003F7F", str, MAXSTR, inifile); break; case 'N' : /* Net IC */ if (rwmode==CMD_MODE_READ) { n = ini_gets("p830f1", "nic", "fa6f", str, sizearray(str), inifile); xprintf(PSTR("%s"),str); } if (rwmode==CMD_MODE_WRITE) { n = ini_puts("p830f1", "nic", &Line[4], inifile); SetNIC1(pkt830,&Line[4]); } break; case 'T' : /* Time */ xputs(PSTR("GUT command\n")); i2c_init(); break; default: str[0]=0; returncode=1; } break; case 'H': // H or HO. Set header if (Line[3]=='\0' || Line[5]=='\0') // Don't get confused by checksums { strcpy_P(str,PSTR(" ")); strncat(str,g_Header,32); // Just readback the header. TODO. Get the correct length str[40]=0; } else { strncpy(g_Header,&Line[9],32); // accept new header //g_Header[32]=0; // Make sure it is capped n = ini_puts("service", "header", g_Header, inifile); // Save this value back to the INI file. } break; case 'I': // III or I2 // I20xnnmm if (Line[2]=='2') // SAA7113 I2C. value. 0xnnmm where nn=address mm=value to write { strcpy_P(str,PSTR("Setting SAA7113 I2C register\n")); ptr=&Line[3]; xatoi(&ptr,&n); xprintf(PSTR("Blah=%04X\n"),n); i2c_SetRegister((n>>8)&0xff,n&0xff); xprintf(PSTR("Done\n")); } break; case 'J' : // J<h>,DATA - Send a packet to SRAM address // Probably want a whole family of J commands. // JA<h> - Set the address pointer to SRAM page <h> where <h> is 0..d // JW<data> - Write a complete 45 byte packet to the current address and increment // JR<data> - Read back the next block of data and increment the pointer. // [JT<h> - Retransmit page <h> immediately. (can't work. You must Tx the parent page) ] // JT<mpp> - Transmit page <mpp> immediately. (probably need to set a flag in the magazine stream // to insert the page in the next transmission slot switch (Line[2]) { case 'A': // eg. JA,0 - Set to the start of //xprintf(PSTR("JA set SRAM address (page level)\n")); Line[2]='0';Line[3]='x'; ptr=&Line[2]; xatoi(&ptr,&n); //xprintf(PSTR("JA page=%X SRAMPAGECOUNT=%X SRAMPAGEBASE=%X\n"),n,SRAMPAGECOUNT,SRAMPAGEBASE); if (n>=SRAMPAGECOUNT) // Make sure the page is in range returncode=1; else { n=SRAMPAGEBASE+n*SRAMPAGESIZE; // This is the actual address //xprintf(PSTR("JA address=%04X\n"),n); SRAMAddress=n; //row=1; } // We should now fill the packet with some instructions on how to use it! // Set the SRAM page address 0..e. There are 14 pages // Coarse address setting // For the lulz, JZ gives random access down to byte level break; case 'Z': // Jay-Z, geddit?, JZ<hex addr 16 bit> Line[2]='0';Line[3]='x'; ptr=&Line[2]; xatoi(&ptr,&n); //xprintf(PSTR("JZ set SRAM address (byte level)\n")); //xprintf(PSTR("JZ page=%04X\n"),n); // Set the SRAM page address at byte level. Needs an actual 16 bit address // where only 15 bits are used. // For finer control than the JA command. // For the lulz and ability to plonk stuff using random access. SRAMAddress=n; break; case 'W': // JW,<row>,data - Write a packet to the SRAM page buffer //xprintf(PSTR("JW Write SRAM data\n")); ptr=&Line[3]; while (*ptr>=' ' && !isdigit(*ptr)) ptr++; // Seek the row value row=atoi(ptr); if (!row) // Row address must be greater than 0 { returncode=1; break; } while (isdigit(*ptr) || *ptr==',') ptr++; // Seek the comma after row // If the fifo is transmitting, we must wait here for (i=0;FIFOBusy;i++); // Can this break if the video source has stopped? We may want to timeout on this! // xprintf(PSTR("JW addr=%d\n"),row); // Write a single packet // Not sure how we are going to map control codes but probably the same as OL // Write the packet that we are going to decode into @SRAMAddress // TODO: Check the row number to see we don't have a buffer overrun // Load and decode the packet // Replace this with a section that reads a line of data from USB // For the first attempt, I'll just copy the rest of the command line // I think it is null terminated? Hmm or \r // JW,<rest of command line> PORTC.OUT&=~VBIT_SEL; // Set the mux to MPU so that we are in control for (i=0;i<45;i++)packet[i]=0; WritePrefix(packet, 5, row); // This prefix gets replaced later packet[3]=row; // The row gets encoded just before writing to FIFO //row++; // MRG line format is bit 8 set if it is a control code < ' ' for (int i=5;i<45 && *ptr && *ptr!='\r';i++) { packet[i]=*ptr++ & 0x7f; } // ** find the address of the row ** n=SRAMAddress+(row-1)*PACKETSIZE; SetSerialRamAddress(SPIRAM_WRITE, n); //xprintf(PSTR("JW write address=%04X\n"),n); //SRAMAddress+=PACKETSIZE; WriteSerialRam(packet,45); DeselectSerialRam(); break; case 'R': xprintf(PSTR("JR Read back SRAM data\n")); // Read back a single packet (translated back into OL format) break; case 'T': xprintf(PSTR("JT Transmit mpp\n")); // Set a flag to transmit the selected page ASAP. break; default: returncode=1; } break; case 'L': // L<nn>,<line data> // We don't use L in vbit. Because it would require RAM buffering or more file writing, // instead we use the e command which writes the file directly. xprintf(PSTR("L command not implemented. Use 'e'\n")); str[0]=0; returncode=1; break; case 'M': // MD - Delete all the pages selected by the last P command. xprintf(PSTR("Delete...\n")); // Iterate down all the pages // Traverse down subpages and release nodes // Go into the pages index and null out the entries in pages.idx break; case 'O': /* O - Opt out. Example: O1c*/ /* Two digit hex number. Only 6 bits are used so the valid range is 0..3f */ ptr=&Line[0]; Line[0]='0';Line[1]='x'; xatoi(&ptr,&n); OptRelays=n & 0x3f; break; case 'P': // P<mppss>. An invalid character will set null. P without parameters will return the current value ptr=&Line[2]; if (!*ptr) { sprintf_P(str,PSTR("%s\n\r"),pageFilter); break; } dest=pageFilter; for (i=0;i<5;i++) { ch=*ptr++; if (ch=='*') valid=1; else { switch (i) { case 0 : // M valid=(ch>'0' && ch<'9' );break; case 1 :; // PP case 2 : valid=((ch>='0' && ch<='9') || (ch>='A' && ch<='F'));break; case 3 :; // SS case 4 : valid=(ch>='0' && ch<='9');break; } } if (valid) *dest++ = ch; else { dest[0]=0; break; } } *dest=0; // terminate the string // TODO: Find out how many pages are in this page range pagecount=FindPageCount(); if (pagecount<0) { pagecount=1; returncode=8; // TODO: At this point we must create the page, as we are about to receive the contents. xprintf(PSTR("Page has been created. Please send some data to fill the page\n\r")); } sprintf_P(str,PSTR("%04d"),pagecount); // Where nnn is the number of pages in this filter. 099 is a filler ack and checksum // str[0]=0; break; case 'Q' : // QO, QM if (Line[2]=='M') // QMnn { ptr=&Line[3]; xatoi(&ptr,&n); xprintf(PSTR("QM command, n=%d\n"),n); n = ini_putl("service", "serialmode", n, inifile); // And at this point put it into the vbi configuration // vbi_mode_serial=0 or CTRL_C11_MAGAZINESERIAL_bm /** TBA. This setting needs to be in the VBI section if (n) vbi_mode_serial=0; else vbi_mode_serial=CTRL_C11_MAGAZINESERIAL_bm; */ break; } // QO sets both odd and even lines // QD only sets the odd. if (Line[2]=='O' || Line[2]=='D') // QO[18 characters <P|Q|1..8|F>]. QD is the odd line and has 18 lines { int i; char ch; ptr=&Line[3]; xputc('0'); // Validate it. for (i=0;i<18;i++) { ch=*ptr++; switch (ch) { case '1':;case'2':;case'3':;case'4':;case'5':;case'6':;case'7':;case'8':;case'I':; case'F':; case'P':; case'Q':; case'Z':; break; default: returncode=1; } g_OutputActions[0][i]=ch; // odd field if (Line[2]=='O') g_OutputActions[1][i]=ch; // even field (QO only) } *ptr=0; if (returncode) break; n = ini_puts("service", "outputodd", &Line[3], inifile); if (Line[2]=='O') n = ini_puts("service", "outputeven", &Line[3], inifile); // QO only break; } returncode=1; break; // We could probably use the S command to encapsulate Newfor. We aren't going to be setting the page status much. case 'S' : ; // Newfor. This should be a Newfor command. Hmm, but how to escape SO and SI? // Work out how to escape data. The parity and reserved characters will break the CI break; case 'T': // T <hhmmss> (this syntax was superceded by GUT and GUt) // testIni(); // test3(); // test2(); // UTC is the time of day in seconds Line[8]=0; ptr=&(Line[2]); UTC=0; // Maybe save this. We need to revert if it fails. for (i=2;i<8;i++) { // First multiply according to which digit switch (i) { case 3:; case 5:; case 7: UTC*=10;break; case 4:; case 6: UTC*=6;break; // (already *10!) } ch=*(ptr++)-'0'; UTC+=ch; } // xprintf(PSTR("UTC=%d\n\r"),UTC); // This upsets the protocol! /** UTC=Line[7]-'0'; // s units UTC=UTC+(Line[6]-'0')*10; // s tens UTC=UTC+(Line[5]-'0')*60; // m units UTC=UTC+(Line[4]-'0')*60*10; // m tens UTC=UTC+(Line[3]-'0')*60*60; // h units UTC=UTC+(Line[2]-'0')*60*60*10; // h tens */ // strcpy_P(str,PSTR("OK\n")); str[0]=0; break; case 'U': // TEST Init830F1(); break; case 'V': // Communication settings. 2 hex chars (bit=(on/off) 7=Viewdata/Text 1=CRLF/CR 0=Echo/Silent // VBIT seems a bit fussy. When using TED Scheduler it is best to sat V00 pagecount=sscanf(&(Line[2]),"%2X",&i); // xprintf(PSTR("sscanf returns %d. Parameter is %X0\n\r"),pagecount,i); if (pagecount>0) { echoMode=i; // Yes, it was OK // TODO: Save the result in the INI } else returncode=1; // No, it failed break; case 'W': // TEST Ad-tec opt outs // W14 - Send a mode 14 opt out // We want to be able to test various ATP950 modes. // read the parameter ptr=&Line[2]; xatoi(&ptr,&n); OptOutMode=n; xprintf(PSTR("W=%04X\n"),OptOutMode); // Which command? Set the appropriate opt out mode switch (OptOutMode) { case 14: xprintf(PSTR("Mode 14 shenanigans\n"),n); // Or just flag that we want an opt-out packet OptOutMode=14; OptOutType=OPTOUT_START; // Assemble a mode 14 packet break; default: OptOutMode=0; returncode=1; } // Assemble the packet and break; case 'X': /* X - Exit */ return 2; case 'Y': /* Y - Version. Y2 should return a date string */ strcpy_P(str,PSTR("VBIT620 Version 0.04")); break; case '?' :; // Status TODO xprintf(PSTR("STATUS %02X\n\r"),statusI2C); // Want to know if the chips check out and the file system is OK // Video Input: xprintf(PSTR("Video input: "));report(statusI2C & 0x01); // chip responds, generating field interrupts // Digital Encoder xprintf(PSTR("Digital encoder: "));report(statusI2C & 0x02); // chip responds // FIFO statusFIFO=test2(); xprintf(PSTR("FIFO R/W verified: "));report(statusFIFO); // we can read and write to it // File system xprintf(PSTR("File system: "));report(statusDisk); // There is a card, it is formatted, it has onair/pages.all break; default: xputs(PSTR("Unknown command\n")); returncode=1; }
static bool process_config_parameter(const parm_desc *arg, char *val, priority_t precedence) /* returns true if ok, false if error */ { bool ok = true; if (arg->addr.v == NULL) return ok; switch (arg->type) { case CP_BOOLEAN: { *arg->addr.b = str_to_bool(val); if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> %s\n", arg->name, *arg->addr.b ? "Yes" : "No"); break; } case CP_INTEGER: { remove_comment(val); if (!xatoi(arg->addr.i, val)) return false; if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> %d\n", arg->name, *arg->addr.i); break; } case CP_DOUBLE: { remove_comment(val); if (!xatof(arg->addr.d, val)) return false; if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> %f\n", arg->name, *arg->addr.d); break; } case CP_CHAR: { *arg->addr.c = *val; if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> '%c'\n", arg->name, *arg->addr.c); break; } case CP_STRING: { *arg->addr.s = xstrdup(val); if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> '%s'\n", arg->name, *arg->addr.s); break; } case CP_DIRECTORY: { char *dir = tildeexpand(val, true); if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> '%s'\n", arg->name, dir); if (setup_wordlists(dir, precedence) != 0) exit(EX_ERROR); xfree(dir); break; } case CP_FUNCTION: { ok = (*arg->addr.f)((unsigned char *)val); if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> '%s'\n", arg->name, val); break; } case CP_WORDLIST: { char c = *val; switch (c) { case 'c': wl_mode = WL_M_COMBINED; break; case 's': wl_mode = WL_M_SEPARATE; break; default: fprintf(stderr, "Unknown wordlist type - '%s'.\n", val); exit(EX_ERROR); } if (DEBUG_CONFIG(2)) fprintf(dbgout, "%s -> '%s'\n", arg->name, val); break; } default: { ok = false; break; } } return ok; }
int importRuleFile( const char * filename, struct itemnode_t * itemList, int * itemListTotal, struct xmlDesc_t * xmlDesc ){ int subscript; int subscriptCount; int attrSubscript; int targetSubscript; int targetAttrSubscript; int targetCount; xmlChar * longStr; xmlNodePtr node; xmlNodePtr content; xmlNodePtr sonNode; xmlNodePtr grandsonNode; int format=1; int type; int total; struct xmlDescID_t xmlDescID; int found; xmlDescID.data[XML_ITEM_NOG][0] = 0; xmlDescID.data[XML_ITEM_REGION][0] = 0; xmlDescID.data[XML_ITEM_TITLE][0] = 0; xmlDescID.data[XML_ITEM_TIME][0] = 0; xmlDescID.data[XML_ITEM_CONTENT][0] = 0; xmlDesc[XML_ITEM_REGION].title = NULL; xmlDesc[XML_ITEM_REGION].attrTotal = 0; xmlDesc[XML_ITEM_TITLE].title = NULL; xmlDesc[XML_ITEM_TITLE].attrTotal = 0; xmlDesc[XML_ITEM_TIME].title = NULL; xmlDesc[XML_ITEM_TIME].attrTotal = 0; xmlDesc[XML_ITEM_CONTENT].title = NULL; xmlDesc[XML_ITEM_CONTENT].attrTotal = 0; xmlKeepBlanksDefault(0); // create the doc and root node xmlDocPtr doc = xmlReadFile( filename, "UTF-8", XML_PARSE_RECOVER ); if ( doc == NULL ){ printf("Error: xml Data file \"%s\" import failed.\n", filename); return 0; } xmlNodePtr root_node = xmlDocGetRootElement( doc ); if ( root_node == NULL ){ printf("Error: failed to get the root of xml doc.\n"); return 0; } if ( xmlStrcmp( root_node->name, BAD_CAST "xmlItemDesc") != 0 ){ printf("Error: name of root node of xml rulefile not matched.\n"); return 0; } if ( xmlHasProp( root_node, BAD_CAST "flag") ){ longStr = xmlGetProp( root_node, BAD_CAST "flag" ); if ( xmlStrcmp( longStr, BAD_CAST "id" ) == 0 ) format= XML_DESC_FORMAT_ID; else if ( xmlStrcmp( longStr, BAD_CAST "standard" ) == 0 ) format= XML_DESC_FORMAT_STANDARD; else{ printf("Error: unknown flag value.\n"); return 0; } } node = root_node->xmlChildrenNode; while( node != NULL ){ // printf("subscriptCount: %d\n", subscriptCount); if ( node == NULL ){ printf("Error: not enough item node.\n"); // *itemListTotal = 0; return 0; } type = XML_ITEM_NOG; if ( xmlStrcmp( node->name, BAD_CAST "region") == 0) type = XML_ITEM_REGION; else if ( xmlStrcmp( node->name, BAD_CAST "title") == 0) type = XML_ITEM_TITLE; else if ( xmlStrcmp( node->name, BAD_CAST "time") == 0) type = XML_ITEM_TIME; else if ( xmlStrcmp( node->name, BAD_CAST "content") == 0) type = XML_ITEM_CONTENT; if ( type == XML_ITEM_NOG ){ node = node->next; continue; } total = 0; sonNode = node->xmlChildrenNode; while( sonNode != NULL ){ if ( format == XML_DESC_FORMAT_ID){ if ( xmlStrcmp( sonNode->name, BAD_CAST "subscript" ) == 0){ longStr = xmlNodeGetContent( sonNode ); total++; xmlDescID.data[type][total] = xatoi( (char *) longStr ); }else{ printf("Error: unknown sonNode of xml item desc, %s", (char *) sonNode->name ); return 0; } }else if ( format == XML_DESC_FORMAT_STANDARD ){ if ( xmlStrcmp( sonNode->name, BAD_CAST "title" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlDesc[type].title = longStr; }else if ( xmlStrcmp( sonNode->name, BAD_CAST "attr" ) == 0){ if ( xmlHasProp( sonNode, BAD_CAST "attrTotal") ){ longStr = xmlGetProp( sonNode, BAD_CAST "attrTotal" ); xmlDesc[type].attrTotal = xatoi( (char *) longStr ); for (subscript=1; subscript<= xmlDesc[type].attrTotal; subscript++){ xmlDesc[type].attrTitle[subscript] = NULL; xmlDesc[type].attrValue[subscript] = NULL; } grandsonNode = sonNode->xmlChildrenNode; while ( grandsonNode != NULL ){ if ( !xmlHasProp( grandsonNode, BAD_CAST "attrSubscript" )){ printf("Error: failed to get the attrSubscript.\n"); return 0; } longStr = xmlGetProp( grandsonNode, BAD_CAST "attrSubscript" ); attrSubscript = xatoi( (char *) longStr ); if ( xmlStrcmp( grandsonNode->name, BAD_CAST "attrTitle" ) == 0 ){ longStr = xmlNodeGetContent( grandsonNode ); xmlDesc[type].attrTitle[attrSubscript] = malloc( strlen(longStr) +1 ); strcpy( xmlDesc[type].attrTitle[attrSubscript], (char *) longStr ); }if ( xmlStrcmp( grandsonNode->name, BAD_CAST "attrValue" ) == 0 ){ longStr = xmlNodeGetContent( grandsonNode ); xmlDesc[type].attrValue[attrSubscript] = malloc( strlen(longStr) +1 ); strcpy( xmlDesc[type].attrValue[attrSubscript], (char *) longStr ); } grandsonNode = grandsonNode->next; } }else{ printf("Error: failed to get attrTotal.\n"); return 0; } }else{ printf("Error: unknown sonNode of xml item desc, %s", (char *) sonNode->name ); return 0; } } sonNode = sonNode->next; } if ( format == XML_DESC_FORMAT_ID ) xmlDescID.data[type][0] = total; node = node->next; } if ( format == XML_DESC_FORMAT_ID ){ xmlDescPrint( &xmlDescID ); for (subscriptCount=1; subscriptCount<=4; subscriptCount++){ if (subscriptCount == 1) subscript = XML_ITEM_REGION; else if (subscriptCount == 2 ) subscript = XML_ITEM_TITLE; else if (subscriptCount == 3 ) subscript = XML_ITEM_TIME; else if (subscriptCount == 4 ) subscript = XML_ITEM_CONTENT; printf("-"); if ( xmlDescID.data[subscript][0] <= 0 ) continue; printf("+\n"); for ( targetCount=1; targetCount<=xmlDescID.data[subscript][0]; targetCount++ ){ targetSubscript = xmlDescID.data[subscript][targetCount]; // printf("234\n"); if (targetCount == 1){ longStr = itemList[targetSubscript].title; // printf("%s\n", (char *) longStr); xmlDesc[subscript].title = malloc( strlen(longStr) +1 ); strcpy( xmlDesc[subscript].title, (char *) longStr ); // printf("%s\n", xmlDesc[subscript].title); for ( attrSubscript=0; attrSubscript<itemList[targetSubscript].attrTotal; attrSubscript++ ){ longStr = itemList[targetSubscript].attrTitle[attrSubscript]; xmlDesc[subscript].attrTitle[attrSubscript] = malloc( strlen(longStr) +1 ); strcpy( xmlDesc[subscript].attrTitle[attrSubscript], (char *) longStr ); printf("Title: %s\n", (char *) longStr); longStr = itemList[targetSubscript].attrValue[attrSubscript]; xmlDesc[subscript].attrValue[attrSubscript] = malloc( strlen(longStr) +1 ); strcpy( xmlDesc[subscript].attrValue[attrSubscript], (char *) longStr ); printf("Value: %s\n", (char *) longStr); } xmlDesc[subscript].attrTotal = itemList[targetSubscript].attrTotal; printf("attrTotal: %d\n", xmlDesc[subscript].attrTotal); for ( attrSubscript=0; attrSubscript<itemList[targetSubscript].attrTotal; attrSubscript++ ){ printf("%s\n%s\n", xmlDesc[subscript].attrTitle[attrSubscript],xmlDesc[subscript].attrValue[attrSubscript]); } printf("=====\n"); }else{ longStr = itemList[targetSubscript].title; if ( xmlDesc[subscript].title != NULL && xmlStrcmp( longStr, BAD_CAST xmlDesc[subscript].title ) != 0){ free( xmlDesc[subscript].title ); xmlDesc[subscript].title = NULL; } for ( attrSubscript=0; attrSubscript<xmlDesc[subscript].attrTotal; attrSubscript++ ){ printf("%s\n%s\n", xmlDesc[subscript].attrTitle[attrSubscript],xmlDesc[subscript].attrValue[attrSubscript]); } printf("=====\n"); attrSubscript = 0; while( attrSubscript<xmlDesc[subscript].attrTotal ){ found = -1; printf(" %s\n%s\n",xmlDesc[subscript].attrTitle[attrSubscript],xmlDesc[subscript].attrValue[attrSubscript]); for ( targetAttrSubscript=0; targetAttrSubscript<itemList[targetSubscript].attrTotal; targetAttrSubscript++) if ( strcmp( xmlDesc[subscript].attrTitle[attrSubscript], itemList[targetSubscript].attrTitle[targetAttrSubscript]) == 0 ){ if ( xmlDesc[subscript].attrValue[attrSubscript] == NULL && itemList[targetSubscript].attrValue[targetAttrSubscript] == NULL){ found = targetAttrSubscript; break; }else if ( xmlDesc[subscript].attrValue[attrSubscript] != NULL && itemList[targetSubscript].attrValue[targetAttrSubscript] != NULL && strcmp( xmlDesc[subscript].attrValue[attrSubscript], itemList[targetSubscript].attrValue[targetAttrSubscript]) == 0 ){ found = targetAttrSubscript; break; } } if ( found == -1 ){ free( xmlDesc[subscript].attrTitle[attrSubscript] ); xmlDesc[subscript].attrTitle[attrSubscript] = xmlDesc[subscript].attrTitle[ xmlDesc[subscript].attrTotal-1 ]; if ( xmlDesc[subscript].attrValue[attrSubscript] != NULL ){ free( xmlDesc[subscript].attrValue[attrSubscript] ); xmlDesc[subscript].attrValue[attrSubscript] = xmlDesc[subscript].attrValue[ xmlDesc[subscript].attrTotal-1 ]; } xmlDesc[subscript].attrTotal--; }else attrSubscript++; } printf("-===-\n"); for ( attrSubscript=0; attrSubscript<xmlDesc[subscript].attrTotal; attrSubscript++ ){ printf("%s\n%s\n", xmlDesc[subscript].attrTitle[attrSubscript],xmlDesc[subscript].attrValue[attrSubscript]); } printf("=====\n"); } } printf("subscript: %d\n", subscript); printDescNode( xmlDesc, subscript ); // printf("%s\n", xmlDesc[XML_ITEM_TITLE].title); } } printf("import success.\n"); xmlFreeDoc(doc); xmlCleanupParser(); exportRuleFile( filename, xmlDesc ); return 1; }
int slattach_main(int argc ATTRIBUTE_UNUSED, char **argv) { /* Line discipline code table */ static const char proto_names[] ALIGN1 = "slip\0" /* 0 */ "cslip\0" /* 1 */ "slip6\0" /* 2 */ "cslip6\0" /* 3 */ "adaptive\0" /* 8 */ ; int i, encap, opt; struct termios state; const char *proto = "cslip"; const char *extcmd; /* Command to execute after hangup */ const char *baud_str; int baud_code = -1; /* Line baud rate (system code) */ enum { OPT_p_proto = 1 << 0, OPT_s_baud = 1 << 1, OPT_c_extcmd = 1 << 2, OPT_e_quit = 1 << 3, OPT_h_watch = 1 << 4, OPT_m_nonraw = 1 << 5, OPT_L_local = 1 << 6, OPT_F_noflow = 1 << 7 }; INIT_G(); /* Parse command line options */ opt = getopt32(argv, "p:s:c:ehmLF", &proto, &baud_str, &extcmd); /*argc -= optind;*/ argv += optind; if (!*argv) bb_show_usage(); encap = index_in_strings(proto_names, proto); if (encap < 0) invarg(proto, "protocol"); if (encap > 3) encap = 8; /* We want to know if the baud rate is valid before we start touching the ttys */ if (opt & OPT_s_baud) { baud_code = tty_value_to_baud(xatoi(baud_str)); if (baud_code < 0) invarg(baud_str, "baud rate"); } /* Trap signals in order to restore tty states upon exit */ if (!(opt & OPT_e_quit)) { bb_signals(0 + (1 << SIGHUP) + (1 << SIGINT) + (1 << SIGQUIT) + (1 << SIGTERM) , sig_handler); } /* Open tty */ handle = open(*argv, O_RDWR | O_NDELAY); if (handle < 0) { char *buf = concat_path_file("/dev", *argv); handle = xopen(buf, O_RDWR | O_NDELAY); /* maybe if (ENABLE_FEATURE_CLEAN_UP) ?? */ free(buf); } /* Save current tty state */ save_state(); /* Configure tty */ memcpy(&state, &saved_state, sizeof(state)); if (!(opt & OPT_m_nonraw)) { /* raw not suppressed */ memset(&state.c_cc, 0, sizeof(state.c_cc)); state.c_cc[VMIN] = 1; state.c_iflag = IGNBRK | IGNPAR; state.c_oflag = 0; state.c_lflag = 0; state.c_cflag = CS8 | HUPCL | CREAD | ((opt & OPT_L_local) ? CLOCAL : 0) | ((opt & OPT_F_noflow) ? 0 : CRTSCTS); } if (opt & OPT_s_baud) { cfsetispeed(&state, baud_code); cfsetospeed(&state, baud_code); } set_state(&state, encap); /* Exit now if option -e was passed */ if (opt & OPT_e_quit) return 0; /* If we're not requested to watch, just keep descriptor open * until we are killed */ if (!(opt & OPT_h_watch)) while (1) sleep(24*60*60); /* Watch line for hangup */ while (1) { if (ioctl(handle, TIOCMGET, &i) < 0 || !(i & TIOCM_CAR)) goto no_carrier; sleep(15); } no_carrier: /* Execute command on hangup */ if (opt & OPT_c_extcmd) system(extcmd); /* Restore states and exit */ restore_state_and_exit(EXIT_SUCCESS); }
int importXmlItemFile( const char * filename, struct xmlItem_t * xmlItemList, int * xmlItemListTotal ){ int subscript; int subscriptCount; int attrSubscript; xmlChar * longStr; xmlNodePtr node; xmlNodePtr content; xmlNodePtr sonNode; xmlNodePtr grandsonNode; int strType; char title; char attrTitle[100]; char attrValue[100]; int attrTotal; int parent; int tail; *xmlItemListTotal = 0; xmlKeepBlanksDefault(0); // create the doc and root node xmlDocPtr doc = xmlReadFile( filename, "UTF-8", XML_PARSE_RECOVER ); if ( doc == NULL ){ printf("Error: xml Data file \"%s\" import failed.\n", filename); exportXmlItemFile( filename, xmlItemList, xmlItemListTotal ); return 0; } xmlNodePtr root_node = xmlDocGetRootElement( doc ); if ( root_node == NULL ){ printf("Error: failed to get the root of xml doc.\n"); return 0; } if ( xmlStrcmp( root_node->name, BAD_CAST "xmlItemList") != 0 ){ printf("Error: name of root node of xml doc not matched.\n"); return 0; } if ( xmlHasProp( root_node, BAD_CAST "xmlItemListTotal") ){ longStr = xmlGetProp( root_node, BAD_CAST "xmlItemListTotal" ); *xmlItemListTotal = xatoi( (char *) longStr ); if ( *xmlItemListTotal > MAX_ITEMLIST_SAVE ) *xmlItemListTotal = MAX_ITEMLIST_SAVE; // printf("itemListTotal: %d\n", *itemListTotal ); }else{ printf("Error: failed to get the itemListTotal.\n"); return 0; } node = root_node->xmlChildrenNode; for (subscriptCount=1; subscriptCount <= *xmlItemListTotal; subscriptCount++){ // printf("subscriptCount: %d\n", subscriptCount); if ( node == NULL ){ printf("Error: not enough item node.\n"); *xmlItemListTotal = 0; return 0; } subscript = subscriptCount; // if ( xmlHasProp( node, BAD_CAST "subscript") ){ // longStr = xmlGetProp( node, BAD_CAST "subscript" ); // subscript = xatoi( (char *) longStr ); // }else{ // printf("Error: failed to get the subscript of item.\n"); // return 0; // } // printf("subscript: %d\n", subscript); xmlItemList[subscript].text[FRSS_ITEM_TITLE] = NULL; xmlItemList[subscript].text[FRSS_ITEM_TIME] = NULL; xmlItemList[subscript].text[FRSS_ITEM_CONTENT] = NULL; xmlItemList[subscript].richText[FRSS_ITEM_CONTENT] = NULL; xmlItemList[subscript].text[FRSS_ITEM_GUID] = NULL; sonNode = node->xmlChildrenNode; while( sonNode != NULL ){ // longStr = xmlNodeGetContent( sonNode ); // printf("name: %s\ncontent: %s\n", (char *) sonNode->name, (char *) longStr); if ( xmlStrcmp( sonNode->name, BAD_CAST "title" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlItemList[subscript].text[FRSS_ITEM_TITLE] = malloc( strlen(longStr) +1 ); strcpy( xmlItemList[subscript].text[FRSS_ITEM_TITLE], (char *) longStr ); }else if ( xmlStrcmp( sonNode->name, BAD_CAST "time" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlItemList[subscript].text[FRSS_ITEM_TIME] = malloc( strlen(longStr) +1 ); strcpy( xmlItemList[subscript].text[FRSS_ITEM_TIME], (char *) longStr ); }else if ( xmlStrcmp( sonNode->name, BAD_CAST "content" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlItemList[subscript].text[FRSS_ITEM_CONTENT] = malloc( strlen(longStr) +1 ); strcpy( xmlItemList[subscript].text[FRSS_ITEM_CONTENT], (char *) longStr ); }else if ( xmlStrcmp( sonNode->name, BAD_CAST "content:encoded" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlItemList[subscript].richText[FRSS_ITEM_CONTENT] = malloc( strlen(longStr) +1 ); strcpy( xmlItemList[subscript].richText[FRSS_ITEM_CONTENT], (char *) longStr ); }else if ( xmlStrcmp( sonNode->name, BAD_CAST "guid" ) == 0){ longStr = xmlNodeGetContent( sonNode ); xmlItemList[subscript].text[FRSS_ITEM_GUID] = malloc( strlen(longStr) +1 ); strcpy( xmlItemList[subscript].text[FRSS_ITEM_GUID], (char *) longStr ); }else{ printf("Error: unknown sonNode of xml doc item, %s", (char *) sonNode->name ); *xmlItemListTotal = 0; return 0; } sonNode = sonNode->next; } node = node->next; } printf("import success.\n"); printf("xmlItemListTotal: %d\n", *xmlItemListTotal); xmlFreeDoc(doc); xmlCleanupParser(); return 1; }
static int cmd_mem(int argc, char **argv, void *extobj) { int32_t ercd = E_OK; int32_t opt; long ram_address, length, value; char *ptr; VALID_EXTOBJ(extobj, -1); NTSHELL_IO_GET(extobj); if(argc < 2) { ercd = E_SYS; CMD_DEBUG("command error!\r\n"); CMD_DEBUG("Try '%s -h' for more information\r\n", argv[0]); goto error_exit; } opterr = 0; optind = 1; while ((opt=getopt(argc, argv, "d:f:e:hH?")) != -1) { switch (opt) { case 'h': case '?': case 'H': cmd_mem_help(argv[0], extobj); goto error_exit; break; case 'd': if (!xatoi(&argv[2], &ram_address) || !xatoi(&argv[3], &length)){ ercd = E_SYS; CMD_DEBUG("Parameter error!\r\n"); goto error_exit; } for (ptr = (char*)ram_address; length >= 16 ; ptr += 16, length -= 16) cmds_put_dump(ptr, (uint32_t)ptr, 16, 1, extobj); if (length) cmds_put_dump((uint8_t*)ptr, (uint32_t)ptr, length, 1, extobj); break; case 'f': if (!xatoi(&argv[2], &ram_address) || !xatoi(&argv[3], &length) || !xatoi(&argv[4], &value)){ ercd = E_SYS; CMD_DEBUG("Parameter error!\r\n"); goto error_exit; } while (length--) { *(uint8_t*)ram_address = (uint8_t)value; ram_address++; } break; case 'e': if (!xatoi(&argv[2], &ram_address) || !xatoi(&argv[3], &value)) { ercd = E_SYS; CMD_DEBUG("Parameter error!\r\n"); goto error_exit; } length = argc - 3; while(length--) { *(uint8_t*)ram_address = (uint8_t)value; ram_address++; if(!xatoi(&argv[argc - length], &value)) break; } break; default: CMD_DEBUG("%s: unrecognized option:%c\r\n", argv[0], opt); CMD_DEBUG("Try '%s -h' for more information\r\n",argv[0]); break; } } return E_OK; error_exit: return ercd; }