void historyCommand(){ char strin[1000]; char *ptr; long ret; int choice; int i; int k = strncmp(input, "!-", 2); printf("\n%s\n", input); if(k!=0){ strncpy(strin, &input[1],3); //Ignores the first character of input and copies // the next 3 chars ret = strtol(strin,&ptr,10); choice = ret; choice--; if(histLoop == 0 && choice > 0 && choice <= historyCount){ strcpy(input,history[choice]); tokenise(); } else if(histLoop == 1 && choice > 0 && choice < 21){ strcpy(input,history[choice]); tokenise(); } else{ printf("%s : event not found here 4",input); } } else{ strncpy(strin, &input[2],3); //Ignores the first character of input and copies // the next 3 chars ret = strtol(strin,&ptr,10); choice = ret; if(histLoop == 0 && choice > 0 && choice <= historyCount){ i = historyCount - choice; i--; if(i > 0){ strcpy(input,history[i]); tokenise(); } } else if(histLoop == 1 && choice > 0 && choice < 20){ i = 20 - choice; i--; if(i>0){ strcpy(input,history[i]); tokenise(); } } } }
void data_test() { char *orig, *copy, *num_str; char **tokens; int num; /* safe_strdup () Test */ fprintf(stdout, "TEST: safe_strdup () \t\t... \t"); orig = "Original"; copy = safe_strdup(orig); (strcmp(orig, copy) == 0) ? fprintf(stdout, "OK\n") : fprintf(stdout, "ERROR\n"); /* safe_atoi () Test */ fprintf(stdout, "TEST: safe_atoi () \t\t... \t"); num_str = "1234"; num = safe_atoi(num_str); (num == 1234) ? fprintf(stdout, "OK\n") : fprintf(stdout, "ERROR\n"); fprintf(stdout, "TEST: tokenise () \t\t... \t"); tokens = (char**)safe_malloc(5 * sizeof(char*)); tokenise("One,Two,Three,Four,Five", tokens, 5); (strcmp(tokens[0], "One") == 0) ? fprintf(stdout, "OK\n") : fprintf(stdout, "ERROR\n"); free(tokens); free(copy); }
QVariant WorkbookParserPrivate::parse() { QString expression; QModelIndex index; // TODO possibly a range of data has changed. if (pWorkbook) { index = pWorkbook->currentWorksheetView()->currentIndex(); expression = pWorkbook->currentWorksheetView()->model()->data(index).toString(); } else if (pWorksheet) { index = pWorksheet->currentIndex(); expression = pWorksheet->model()->data(index).toString(); } clearErrors(); // formulae must start with an = sign but it has no relevance later. if (expression.startsWith("=")) { QStringList tokenList = splitExpression(expression.mid(1)); tokenise(tokenList); } return QVariant(QVariant::Double); }
void z_tokenise(const char *text, int length, zword parse_dest, zword dictionarytable, BOOL write_unrecognized) { zword separatortable; zword numparsedloc; int numseparators; int maxwords, parsed_words; if(parse_dest > dynamic_size || parse_dest < 64) { n_show_error(E_OUTPUT, "parse table in invalid location", parse_dest); return; } numseparators = LOBYTE(dictionarytable); separatortable = dictionarytable + 1; dictionarytable += numseparators + 1; maxwords = LOBYTE(parse_dest); numparsedloc = parse_dest + 1; parse_dest+=2; if(maxwords == 0) n_show_warn(E_OUTPUT, "small parse size", maxwords); parsed_words = tokenise(dictionarytable, text, length, &parse_dest, maxwords, separatortable, numseparators, write_unrecognized); LOBYTEwrite(numparsedloc, parsed_words); }
shell_result shell_invoke(const char* cmd_line) { uint8_t token_count = uint8_tokens(cmd_line); if (token_count == 0 || strlen(cmd_line) == 0) { return RESULT_SUCCESS; } char cmd_copy[strlen(cmd_line) + 1]; strncpy(cmd_copy, cmd_line, strlen(cmd_line) + 1); char* tokens[token_count]; tokenise(cmd_copy, tokens, token_count); shell_command command = new_shell_command(tokens, token_count); shell_result result = current_shell_state.active_handler->handler(&command); if (result >= SHELL_RESULT_FAIL) { handle_failure(result, command.command); } else { if (result == SHELL_RESULT_EXIT_MODAL) { current_shell_state = (shell_state) { .active_handler = &default_handler, .modal = false }; } if (result == SHELL_RESULT_ENTER_MODAL) { current_shell_state = (shell_state) { .active_handler = lookup_handler(command.command), .modal = true }; } } return result; }
void EventComp::addEvents(std::string key, std::string eventMsg) { std::cout << "Adding " << key << "event message : " << eventMsg << " : to object " << this->getId() << std::endl; //Parametise by ; Parameters msgStr = tokenise(eventMsg,';'); std::vector<Parameters> msgs; for (int x=0; x< msgStr.size(); ++x) { Parameters params = tokenise(msgStr[x],' '); msgs.push_back(params); std::cout << ">> " << key << " : " << msgStr[x] << std::endl; // int dump; std::cin >> dump; } eventMap_.insert(std::pair<std::string,std::vector<Parameters> >(key,msgs)); }
const char *ScriptTokeniser::fillToken () { if (!tokenise()) { return 0; } add('\0'); return m_token; }
int main() { char *test = "select foo" ; tokenise(test); return 0; }
void scanner(char *ipRange) { char *wee[10]; char *begin[10]; char *end[10]; tokenise(ipRange, wee, "-"); int octaB, octaE, octbB, octbE, octcB, octcE; tokenise(wee[0], begin, "."); tokenise(wee[1], end, "."); octaB = atoi(begin[0]); // YYY.XXX.XXX.XXX octaE = atoi(end[0]); octbB = atoi(begin[1]); octbE = atoi(end[1]); octcB = atoi(begin[2]); octcE = atoi(end[2]); int loop1; for (loop1=octaB; loop1<=octaE; loop1++) { int loop2; for (loop2=octbB; loop2<=octbE; loop2++) { int loop3; for (loop3=octcB; loop3<=octcE; loop3++) { int loop4; for (loop4=0; loop4<=255; loop4++) { char* host; asprintf(&host, "%i.%i.%i.%i", loop1, loop2,loop3, loop4); //printf("\n\rScanning: %s", host); if (scanHost(host) == 0 && checkHost(host) == 0) // This will run scanHost THEN checkHost right? { syslog(LOG_DEBUG, "Oh a sheep!"); //printf("\n\r - %s is vulnerable", host); infectHost(host); } } } } } }
void quote() { //state = LITERAL; while(1) { tokenise( buffer, word ); if( word == NULL || !literul_handler( word ) ) { return; } } }
/** * Skip any whitespace then look for a token, throwing an exception if no valid token * is found. * * Advance the string iterator past the parsed token on success. On failure the string iterator is * in an undefined location. */ const Token& Tokeniser::nextToken() { if ( tokens.size()>tokp ) return tokens[tokp++]; // Don't extend stream of tokens further than the end of stream; if ( tokp>0 && tokens[tokp-1].type==T_EOS ) return tokens[tokp-1]; tokens.push_back(Token()); Token& tok = tokens[tokp++]; if (tokenise(inp, inEnd, tok)) return tok; throw TokenException("Found illegal character"); }
void parentheses() { //if (state == RUN) // state = R_DUMMY; //else // state = C_DUMMY; while(1) { tokenise( buffer, word ); if( word == NULL || !r_dummy_handler( word ) ) { return; } } }
ConfigReader::ConfigReader(String filename) { ifstream inputFile(filename.c_str()); if (inputFile.is_open()) { string line; string input; while (inputFile >> line) { input += line; } tokenise(input); config(); }
void find_cmd(char* cmdbuf,CMDENTRY cmds[]) { int i; char* cp; cp = non_ws(cmdbuf); /* locate first non-whitespace character */ cblk.nargs = tokenise(cmdbuf,cmd,arg,qual,all); cblk.arg = arg; cblk.qualifier = qual; cblk.qual_int = atoi(qual); cblk.all = all; cblk.cmd = cmd; cblk.function = NULL; cblk.unknown_cmd = FALSE; for ( i=0 ; !STREMP(cmds[i].cmd); i++ ) { if (strlen(cmds[i].abbrev) == 1 && /* look for special command */ cmds[i].abbrev[0] < 'A' && *cp == cmds[i].abbrev[0]) { cblk.function = cmds[i].function; cblk.all = cp+1; return; } else if (strncmp(cmd,cmds[i].cmd,MAXBUFSZ) == 0 || strncmp(cmd,cmds[i].abbrev,MAXBUFSZ) == 0) { cblk.function = cmds[i].function; strncpy(cblk.cmd,cmds[i].cmd,MAXBUFSZ); cblk.cmd[MAXBUFSZ-1] = '\0'; /* does # args match that required? */ if (cmds[i].nargs != 0 && cmds[i].nargs != cblk.nargs) { cblk.nargs = -1; } return; } } /* empty sentinal command should invoke unknown command handler */ if (!STREMP(cblk.cmd)) { cblk.function = cmds[i].function; cblk.unknown_cmd = TRUE; } return; }
static int parse(char *s, char *fields[], int nfields) { int c, argc; char *start, *end; argc = 0; c = *s; while(c){ s = tokenise(s, &start, &end); c = *s++; if(*start == 0) break; if(argc >= nfields-1) return -1; *end = 0; fields[argc++] = start; } fields[argc] = 0; return argc; }
// getAddrRange(): Gets the phones 3G range + 2 // eg, 100.100.100.0-100.100.102.255 char *getAddrRange() { struct ifaddrs *ifaddr, *ifa; int family, s; char host[NI_MAXHOST]; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs"); exit(EXIT_FAILURE); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { family = ifa->ifa_addr->sa_family; if (family == AF_INET) { if (family == AF_INET || family == AF_INET6) { s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) { printf("getnameinfo() failed: %s\n", gai_strerror(s)); return "0.0.0.0-0.0.0.0"; } if (strcmp(ifa->ifa_name, "pdp_ip0") == 0) { syslog(LOG_DEBUG, ifa->ifa_name); syslog(LOG_DEBUG, host); char *wee[20]; tokenise(host, wee, "."); char *range; int octc = atoi(wee[2]); asprintf(&range, "%s.%s.%i.0-%s.%s.%i.255", wee[0], wee[1], octc, wee[0], wee[1], octc+2); return range; } } } } freeifaddrs(ifaddr); return "0.0.0.0-0.0.0.0"; }
int parse(char *file) { token *tokens[MAX_TOKEN_NUM]; ast *syntax_tree; int token_count = tokenise(file, tokens); if (tokens == NULL) { fprintf(stderr, "Couldn't read file: %s\n", file); return -1; } show_tokens(tokens, token_count); build_ast(tokens, syntax_tree); if (syntax_tree == NULL) { fprintf(stderr, "Couldn't parse file: %s\n", file); return -1; } pretty_print_ast(syntax_tree); return 0; }
//------------------------------------------------------------------------------ int begin_doskey(wchar_t* chars, unsigned max_chars) { // Find the alias for which to retrieve text for. wchar_t alias[64]; { int i, n; int found_word = 0; const wchar_t* read = chars; for (i = 0, n = min(sizeof_array(alias) - 1, max_chars); i < n && *read; ++i) { if (!!iswspace(*read) == found_word) { if (!found_word) found_word = 1; else break; } alias[i] = *read++; } alias[i] = '\0'; } // Find the alias' text. { int bytes; wchar_t* exe; wchar_t exe_path[MAX_PATH]; GetModuleFileNameW(NULL, exe_path, sizeof_array(exe_path)); exe = wcsrchr(exe_path, L'\\'); exe = (exe != NULL) ? (exe + 1) : exe_path; // Check it exists. if (!GetConsoleAliasW(alias, exe_path, 1, exe)) return 0; // It does. Allocate space and fetch it. bytes = max_chars * sizeof(wchar_t); g_state.alias_text = malloc(bytes * 2); GetConsoleAliasW(alias, g_state.alias_text, bytes, exe); // Copy the input and tokenise it. Lots of pointer aliasing here... g_state.input = g_state.alias_text + max_chars; memcpy(g_state.input, chars, bytes); g_state.token_count = tokenise(g_state.input, g_state.tokens, sizeof_array(g_state.tokens)); g_state.alias_next = g_state.alias_text; } // Expand all '$?' codes except those that expand into arguments. { wchar_t* read = g_state.alias_text; wchar_t* write = read; while (*read) { if (read[0] != '$') { *write++ = *read++; continue; } ++read; switch (*read) { case '$': *write++ = '$'; break; case 'g': case 'G': *write++ = '>'; break; case 'l': case 'L': *write++ = '<'; break; case 'b': case 'B': *write++ = '|'; break; case 't': case 'T': *write++ = '\1'; break; default: *write++ = '$'; *write++ = *read; } ++read; } *write = '\0'; } return continue_doskey(chars, max_chars); }
QList<Token> TextModelLavaan::parse(QTextBlock &block) { BlockStatus *status = blockStatus(block); status->clearError(); QList<Token> tokens = tokenise(block); if (status->isError()) { qDebug() << "error : " << status->message << "\n"; return tokens; } if (tokens.length() == 0 || tokens.at(0).type == Comment) return tokens; Token &first = tokens[0]; if (first.type != Variable) { status->setError("Expected a variable", first.pos, first.text.length()); return tokens; } else if (tokens.length() == 1) { status->setError("Expected an operator", first.pos + first.text.length(), -1); return tokens; } if (tokens.length() >= 2) { Token &second = tokens[1]; if (second.type == Comment) { status->setError("Expected an operator", first.pos + first.text.length(), -1); return tokens; } else if (second.type == Operator) { if (second.text != "~~" && second.text != "~" && second.text != "=~" && second.text != "==" && second.text != ">" && second.text != "<" && second.text != ":=") { status->setError("Unrecognised operator", second.pos, second.text.length()); return tokens; } else if (tokens.length() == 2) { status->setError("Expected an expression", second.pos + second.text.length(), -1); return tokens; } } else { status->setError("Expected an operator", second.pos, second.text.length()); return tokens; } } int i = 2; checkExpression(tokens, i, status); if (status->isError()) return tokens; while (i < tokens.length()) { Token token = tokens.at(i); if (token.type == Comment) break; if (token.type != Plus) { status->setError("Expected a plus", token.pos, token.text.length()); return tokens; } i++; if (i >= tokens.length()) { status->setError("Expected an expression", token.pos + token.text.length(), -1); return tokens; } checkExpression(tokens, i, status); if (status->isError()) return tokens; } return tokens; }
void getInput(){ /*char input[1000];*/ while(1){ printf(pointer); if(fgets(input, MAX, stdin) == NULL){ exit(0); } int t = strncmp(input, "!", 1); int k = strncmp(input, "!-", 2); if( t != 0){ saveHistory(); saveHistoryFile(); } if(t == 0){/* if(input[3] == '\0' || input[2] == '\0' || input[4] == '\0'){ if((isdigit(input[1]) && input[2] == '\0') || (isdigit(input[1]) && isdigit(input[2]) )){ printf("hehEHE111"); historyCommand(); } }*/ if(input[3] == '\0'){ if(isdigit(input[1])){ historyCommand(); } else{ printf("%s : event not found here 1",input); } } else if(input[4] == '\0' && k !=0){ if(isdigit(input[1]) && isdigit(input[2])){ historyCommand(); } else{ printf("%s : event not found here 2",input); } } else if(k==0){ if(input[4]=='\0' && isdigit(input[2])){ historyCommand(); } else if((input[5]=='\0') && isdigit(input[2]) && isdigit(input[3])){ historyCommand(); } else{ printf("%s : event not found here 3",input); } } else{ printf("%s : event not found",input); } } else tokenise(); } }
ast_t *pf(const char *data, ast_t *(*func)(parse_state_t*)) { token_list_t *tl = tokenise(data); parse_state_t *ps = parse_state_new(tl); return func(ps); }
int main() { /* DIRECTORY AND MEMORY OBJECTS */ /* I know the array is unnecessary, but at 2am my brain isnt entirely working very well to optimise shit so i just did whatever worked */ struct Entry directory[MAX_SPACE]; // array of directory entries Entry* head = NULL; // head of linked list int entries = 0; // keeps track of number of entries int blkCount; // number of blocks needed int tokCount; // keeps track of file data int arrCount; // keeps track of index /* INPUT OBJECTS */ char file[30]; // for input string int i = 0, itemCount = 0; // number of items currently in list out of MAX_SIZE char *input[MAX_LINES]; // maximum number of instructions to be processed char *copy[MAX_LINES]; // to copy the input line (otherwise menu gets messed up) char line[1024]; // fgets buffer char *tok[MAX_NUM_TOKENS]; // maximum number of tokens for each line of instructions int len; // length for each tokenised line int exe; // its definitely used somewhere in this code trust me // input file do { printf("\nEnter input file name (with .csv): "); scanf("%s", &file); } while (access(file, F_OK) != 0); FILE* stream = fopen(file, "r"); // add items from buffer into input and increment itemCount for each item while (fgets(line, 1024, stream)) { input[i] = strdup(line); copy[i] = strdup(line); i++; itemCount++; char* tmp = strdup(line); free(tmp); } printf("File loaded!"); do { printf("\n\nType index of line to execute: \n"); for (int j = 1; j < itemCount; j++) printf("%d: %s", j, input[j]); printf("%d: view directory\n%d: view system\n%d: exit\n>> ", itemCount, itemCount + 1, itemCount + 2); scanf("%d", &exe); if (exe == itemCount) printDir(head); else if (exe == itemCount + 1) printSys(); else if (exe < itemCount) { if (strcmp(input[exe], "NULL\n") == 0) continue; strcpy(copy[exe], input[exe]); // duplicate string len = tokenise(copy[exe], tok); // tokenise string // ADDING if (strcmp(tok[0], "add") == 0) { blkCount = ((len - 1) / 3) + ((len - 1) % 3); // determine number of blocks needed int blkArray[blkCount]; // array of available blocks // check if there is enough space if (checkSpace(blkCount, blkArray) == 0) { tokCount = 1; // start from the second elent in tok[] for (int i = 0; i < blkCount; i++) { arrCount = 0; // counter for index inside block array // while not all the tokens are loaded while (tokCount != len && arrCount < 3) { // loading into file system!!! yay // printf("Putting %d in %d\n", atoi(tok[tokCount]), (blkArray[i] * 4) + arrCount); fileSystem[(blkArray[i] * 4) + arrCount] = atoi(tok[tokCount]); tokCount++; arrCount++; } // if all data is loaded if (tokCount == len) printf(""); else { // linking!!!! woooo // printf("Linking %d to %d\n", blkArray[i] + 3, blkArray[i + 1]); fileSystem[(blkArray[i] * 4) + 3] = blkArray[i + 1]; // links to the next block } } // updating directory Entry entry = { atoi(tok[1]), blkArray[0], blkArray[blkCount - 1], NULL }; directory[entries] = entry; // if the entry is the first entry, head = that entry if (entries == 0) head = &directory[entries]; // link prev entry to current entry if ((entries - 1) >= 0) directory[entries - 1].next = &directory[entries]; entries++; printf("\nEntry %d loaded!\n", exe); strcpy(input[exe], "NULL\n"); } else printf("There isn't enough space in memory.\n"); } // READING else if (strcmp(tok[0], "read") == 0) { // run time is like more than O(n) sorry Entry* curr = head; while (curr != NULL) { if (atoi(tok[1]) - curr->file < 0) curr = curr->next; else { int block = curr->start; while (1) // while true la ok everything also while true { for (arrCount = 0; arrCount < 3; arrCount++) { if (fileSystem[(block * 4) + arrCount] == atoi(tok[1])) { printf("\nFile: %d is located at block %d, index %d.\n", atoi(tok[1]), block, (block * 4) + arrCount); break; } } if (block == curr->end) break; block = fileSystem[(block * 4) + 3]; // move on to the next block } } break; } } // DELETING else if (strcmp(tok[0], "delete") == 0) { // run time is also O(n) sorry Entry* curr = head; Entry* prev = NULL; while (curr != NULL) { if (curr->file != atoi(tok[1])) { prev = curr; curr = curr->next; } else { int block = curr->start; while (1) { // deleting for (arrCount = 0; arrCount < 3; arrCount++) fileSystem[(block * 4) + arrCount] = 0; // if all data is deleted if (block == curr->end) break; else block = fileSystem[(block * 4) + 3]; // move on to the next block } // updating directory if (entries == 1) // if entry is the only entry in directory head = NULL; else if (entries > 1) prev->next = curr->next; // link the entry behind to the entry ahead entries--; printf("\nEntry %d deleted!\n", curr->file); break; } } } } } while (exe != itemCount + 2); printf("\nBye!\n"); }
/* * processLine() * * Take a string, tokenise it, validate it and pass it on for calculation. This * is the glue function of ralcalc really. */ int processLine(const char *line, int quiet, displayMode dm, char siPrefix, int precision) { tokenItem tokenList; int rc; FILE *rcptr; double result; double lastResult = 0.0; int hasError = 0; char resultStr[100]; char formatStr[20]; if(!line) return errBadInput; if(rcpath){ rcptr = fopen(rcpath, "rb"); if(rcptr){ rc = fread(&lastResult, sizeof(double), 1, rcptr); if(rc != 1){ fprintf(stderr, "Warning: Previous value file corrupt, ignoring.\n"); lastResult = 0.0; } fclose(rcptr); } } /* First element always defined and not dynamic for less hassle */ tokenList.next = NULL; tokenList.type = tkEndToken; rc = tokenise(&tokenList, line, lastResult, quiet); if(rc != errNoError) hasError = 1; rc = validate(&tokenList, line, quiet); if(rc != errNoError) hasError = 1; rc = assignPrecedence(&tokenList); if(rc != errNoError) hasError = 1; if(!hasError && tokenList.next){ result = process(&(tokenList.next)); switch(dm){ case dmSI: doubleToString(result, resultStr, 100, siPrefix, precision); break; case dmExponent: if(precision == -1){ snprintf(resultStr, 100, "%lg", result); }else{ snprintf(formatStr, 20, "%%.%dlg", precision); snprintf(resultStr, 100, formatStr, result); } break; case dmRaw: if(precision == -1){ snprintf(resultStr, 100, "%f", result); }else{ snprintf(formatStr, 20, "%%.%df", precision); snprintf(resultStr, 100, formatStr, result); } break; } if(!quiet){ printf("%s = %s\n", line, resultStr); }else{ printf("%s\n", resultStr); } if(rcpath){ rcptr = fopen(rcpath, "wb"); if(rcptr){ rc = fwrite(&result, sizeof(double), 1, rcptr); if(rc != 1){ fprintf(stderr, "Error writing last value file.\n"); } fclose(rcptr); } } } if(tokenList.next) freeList(tokenList.next); return hasError; }
int main(int argc, char *argv[]) { int c; /* used to parse arguments */ char *cur_entry; /* Entry we are benchmarking */ char *distrib = NULL; /* distribution to use. */ char *mirror_list = D_MIRROR; /* mirror list file */ char *config_file = D_CONFIG; /* configuration file */ char *proxy = NULL; /* Proxy server to use */ char *infile = NULL; /* optional infile */ char *outfile = D_OUT; /* outfile name */ char *topfile = NULL; char *area = strdup(D_AREA); /* Area to test */ char *grab_file = D_FILE; /* File to grab */ char *update_url = D_UPDATE_URL; /* URL to use for updating */ char *country_list = NULL; /* List of countries to b/m */ char *section_list = NULL; /* List of section to include */ FILE *infile_p, *outfile_p; /* input/output file pointers */ FILE *config_p; /* config file pointer */ FILE *mirror_p; /* mirror list pointer */ FILE *topfile_p; int timeout = 15; /* time to benchmark each server */ /* int toplist = 0; *//* Whether to write toplist. *//* UNUSED */ int argsCount = 0; /* persistent counter for args */ char *args[100]; /* persistent args array */ /* char str[100] = ""; *//* We don't need to put optarg in str */ char str[4] = "-? "; /* short option string */ /* int i; *//* UNUSED */ char *end; struct stat buf; /* Number of servers to test. If negative, test them all. */ int test_number = -1; /* Server information structures. */ server_t current; server_t *best = NULL; /* Parse options... */ while((c = getopt(argc, argv, "y:a:c:d:e:f:i:m:o:p:s:t:u:w:n:vh")) != -1) { if (optarg) { /* not set with -h */ str[1] = c; /* args[argsCount] = (char*)malloc(strlen(str)); *//* BAD: it should be malloc(strlen(str)+1) */ /* strcat(str, optarg); *//* BAD: optarg may be too long */ args[argsCount] = malloc(strlen(str)+strlen(optarg)+1); memset(args[argsCount],0,strlen(str)+strlen(optarg)+1); strncpy(args[argsCount],str,strlen(str)); strncat(args[argsCount],optarg,strlen(optarg)); argsCount++; } switch(c) { /* Sections to include into apt-source */ case 'y': section_list = optarg; break; /* Area to benchmark */ case 'a': free(area); /* allocated by strdup */ area = optarg; break; /* Distribution we'll write into apt-sources. */ case 'd': distrib = optarg; break; /* Configuration file to use */ case 'c': /* printf("Option: %c\n",c); printf("Option arg: %s\n", optarg); */ /* config_file = (char *)malloc(25); strcpy(config_file, optarg); */ config_file = optarg; printf("Using configuration file: %s\n", config_file); break; /* Number of servers to benchmark */ case 'e': test_number = strtol(optarg, &end, 10); if (!*optarg || end!=optarg+strlen(optarg)) { fprintf(stderr, "Error parsing number" " of servers to be" " benchmarked\n"); exit(1); } break; /* File, relative to Debian base, to grab from server. */ case 'f': grab_file = optarg; break; /* User-specified list of servers to benchmark. */ case 'i': infile = optarg; break; /* The list of mirrors */ case 'm': mirror_list = optarg; break; /* The output file we use */ case 'o': outfile = optarg; break; /* Proxy server we should use */ case 'p': proxy = optarg; break; /* List of countries to benchmark */ case 's': country_list = optarg; break; /* Time for which to benchmark each server. */ case 't': timeout = strtol(optarg, &end, 10); if (!*optarg || end!=optarg+strlen(optarg)) { fprintf(stderr, "Error parsing server" " benchmark time" " interval\n"); exit(1); } break; /* The URL we should update ourselves from */ case 'u': update_url = optarg; break; /* Should we write a list of the "top" servers? */ case 'w': /* toplist = 1; *//* UNUSED */ topfile = optarg; break; /* Number of servers to write in "top" server list */ case 'n': bestnumber = strtol(optarg, &end, 10); if (!*optarg || end!=optarg+strlen(optarg)) { fprintf(stderr, "Error parsing number" " of best servers to" " write\n"); exit(1); } break; case 'v': version(); break; /* Help!! */ case 'h': default: usage(); /* display help */ break; } } argc -= optind; argv += optind; /* Simple check for stupidity */ if ((test_number >= 0) && (bestnumber > test_number)) bestnumber = test_number; best = malloc(sizeof(server_t) * (bestnumber + 1)); if (best == NULL) { perror("malloc"); exit(1); } /* Zero the "best" structure (just after malloc for readability) */ memset(best, 0, sizeof(server_t) * (bestnumber + 1)); /* We require an area and distribution argument if we are not updating */ if ((argc == 0) && (distrib == NULL)) usage(); /* Check for silly combination of country and area arguments */ /* if ((area != NULL) && (country_list != NULL)) usage(); */ /* Setup default area argument */ /* if ((area == NULL) && (country_list == NULL)) area = d_area; */ /* Setup default file argument if none given */ /* if (grab_file == NULL) grab_file = d_file; */ if (strcmp(area, D_AREA) && (country_list != NULL)) usage(); /* * if the use does not specify the mirror list file verify if * there is the file and if not download it from main debian * mirror */ if (strcmp(mirror_list, D_MIRROR) == 0) { if (stat(mirror_list, &buf)!= 0) { mirror_p = select_mirror(mirror_list, -1); if (update(mirror_p, update_url, proxy) != 0) { fprintf(stderr, "Failed to download mirror list. Exiting.\n"); exit(1); } } } /* Open mirror file. We pass argc so it can tell if we're updating or not */ mirror_p = select_mirror(mirror_list, argc); if (mirror_p == NULL) { perror("fopen"); fprintf(stderr, "Error opening mirror file. Exiting.\n"); exit(1); } /* the only possible argument now is "update", for updating the mirrors list */ if (argc == 1) { if (strcmp(argv[0], "update") != 0) usage(); /* If necessary, set update_url to default */ /* if (update_url == NULL) update_url = d_update_url; */ if (update(mirror_p, update_url, proxy) != 0) { fprintf(stderr, "Update failed. Exiting.\n"); exit(1); } printf("Update complete. Exiting.\n"); exit(0); } /* argc should be 0. If not, there's something wrong. */ if (argc != 0) usage(); /* We open the infile. Either a temporary file, or a user-specified one. */ infile_p = select_infile(infile); if (infile_p == NULL) { perror("tmpfile"); fprintf(stderr, "Failed to open infile. Exiting.\n"); exit(1); } /* Set up default if user hasn't specified an outfile */ /* if (outfile == NULL) outfile = d_out; */ /* Open the output file... */ outfile_p = select_outfile(outfile); if (outfile_p == NULL) { perror("fopen"); fprintf(stderr, "Error opening output file. Exiting.\n"); exit(1); } /* Open the topfile */ if (topfile) { topfile_p = select_outfile(topfile); if (topfile_p == NULL) { perror("fopen"); fprintf(stderr, "Error opening topfile. Exiting.\n"); exit(1); } } /* Open config file */ config_p = select_config(config_file); if (config_p == NULL) { perror("fopen"); fprintf(stderr, "Error opening config file. Exiting.\n"); exit(1); } /* Fill temporary file with useful stuff if it's not user-specified. */ if (infile == NULL) { /* if (area != NULL) { if (build_area_file(config_p, infile_p, mirror_p, area) != 0) { fprintf(stderr, "Error building area file. Exiting.\n"); exit(1); } } else { */ if (country_list) { if (build_country_file(config_p, infile_p, mirror_p, country_list) != 0) { fprintf(stderr, "Error building country file. Exiting.\n"); exit(1); } } else { if (build_area_file(config_p, infile_p, mirror_p, area) != 0) { fprintf(stderr, "Error building area file. Exiting.\n"); exit(1); } } } /* Make sure we're at the beginning... */ rewind(infile_p); /* This is the main loop. It'll exit when we've exhausted the URL list or test_number is 0 */ while (((cur_entry = next_entry(infile_p)) != NULL) && test_number != 0) { if (ferror(infile_p) != 0) { fprintf(stderr, "Error while reading input file\n"); exit(1); } /* Turn entry into a pretty structure */ tokenise(¤t, cur_entry); /* Do the benchmark */ if (benchmark(¤t, proxy, timeout, grab_file) != 0) { fprintf(stderr, "Error while performing benchmark. Exiting.\n"); exit(1); } decide_best(¤t, best); free(cur_entry); if (test_number > 0) --test_number; } /* write the results */ printf("Writing new sources.list file: %s \n", outfile); /* * sc */ /* if (write_list(outfile_p, best, distrib) != 0) { */ if (write_list(outfile_p, best, distrib, section_list, args, argsCount) != 0) { fprintf(stderr, "Error writing output file. Exiting."); exit(1); } /* close the file */ fclose(outfile_p); /* We write out the top servers to a file if asked. Note there's no point in freeing the "best" structures. */ if (topfile) { printf("writing topfile: %s\n", topfile); if (write_top(infile_p, topfile_p, best) != 0) { fprintf(stderr, "Error writing top servers list. Exiting."); exit(1); } /* close the file */ fclose(topfile_p); } /* We're all done */ /* free(best); */ /* See above: 'there's no point in freeing the "best" structures' */ /* Bis repetita placent */ exit(0); }
// tokenise the input file (or stdin if filename is empty), outputing the appropriate Python code void process(const std::string &filename, const Options &opt, const std::set<std::string> &restrict_vars) { std::ifstream file_stream; if (!filename.empty()) { file_stream.open(filename.c_str()); if (!file_stream) { std::cerr << exec_name << ": cannot open " << filename << '\n'; exit(1); } } std::istream &infile = (filename.empty() ? std::cin : file_stream); std::string line; std::vector<Token> tokens; // map from demangled (original) variable name to mangled name for variables on lhs of an assignment statement; // not used for --assign or --test Varmap assigned_vars; // set of "seen" variable names (e.g. "a", "a.b", "a.b["); only used for --assign Varset variable_hierarchy; // variables that appear in expressions (other than as arguments to function calls); only used for --test // (key = mangled id, value = demangled id) Varmap test_vars; // with the input to --test is raw python code (vs just being a list of boolean expressions, one per line) bool test_is_raw_python = false; std::string pending_line; int pending_line_num = 0; for (int line_num = 1;std::getline(infile, line);++line_num) { size_t len = line.length(); if (len != 0 && line[len - 1] == '\\') { if (pending_line.empty()) { pending_line_num = line_num; } pending_line += line.substr(0, len - 1); pending_line += ' '; continue; } int actual_line_num = line_num; if (!pending_line.empty()) { line = pending_line + line; pending_line.clear(); actual_line_num = pending_line_num; } tokens.resize(0); tokenise(line, filename, line_num, opt, tokens, test_is_raw_python); // debug_tokens(tokens); if (opt.assign) { process_assign(tokens, line, filename, actual_line_num, variable_hierarchy); } else if (opt.test) { process_test(tokens, line, filename, actual_line_num, &test_is_raw_python, test_vars); } else { process_command(tokens, assigned_vars, opt, restrict_vars); } } if (opt.command) { print_assigned_variables(assigned_vars); } if (opt.test && !test_is_raw_python) { validate_test_variables(test_vars); } }
void historyCommand(){ char strin[1000]; char *ptr; long ret; int choice; int i; int k = strncmp(input, "!-", 2); char tempArray[1000]; int len; printf("\n%s\n", input); if(k!=0){ strncpy(strin, &input[1],3); //Ignores the first character of input and copies // the next 3 chars ret = strtol(strin,&ptr,10); choice = ret; choice--; if(choice > 0 && choice < 10){ strncpy(tempArray,&input[2],MAX-3); } else if(choice >= 10){ strncpy(tempArray,&input[3],MAX-4); } else{ printf("Invalid History number entered"); return; } if(histLoop == 0 && choice >= 0 && choice <= historyCount){ strcpy(input,history[choice]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } else if(histLoop == 1 && choice > 0 && choice < 21){ strcpy(input,history[choice]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } else{ printf("%s : event not found here 4",input); } } else{ strncpy(strin, &input[2],3); //Ignores the first character of input and copies // the next 3 chars ret = strtol(strin,&ptr,10); choice = ret; printf("REACH HEHRE 1:%i",choice); if(choice > 0 && choice < 10){ strncpy(tempArray,&input[4],MAX-3); } else if(choice >= 10 && choice <20){ strncpy(tempArray,&input[5],MAX-4); } else{ printf("Invalid History number entered"); return; } if(histLoop == 0 && choice > 0 && choice <= historyCount){ i = historyCount - choice; i--; printf("REACH HEHRE 3:%i",choice); if(i > 0){ strcpy(input,history[i]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } } /*else if(histLoop == 0 && choice >-20){ choice = choice * -1; i = historyCount - choice; i--; printf("TA IS:%i", choice); if(i > 0){ strcpy(input,history[i]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } }*/ else if(histLoop == 1 && choice > 0 && choice < 20){ i = 20 - choice; i--; printf("REACH HEHRE 4:%i",choice); if(i>0){ strcpy(input,history[i]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } } /*else if (histLoop == 1 && choice >-20){ printf("REACH HEHRE 2:%i",choice); choice = choice * -1; i = 20 - choice; i--; printf("TA IS:%i", choice); if(i > 0){ strcpy(input,history[i]); len = strlen(input); strcpy(&input[len],tempArray); tokenise(); } }*/ } }
int main(int argc, char *argv[]) { /* SET UP TABLES ETC */ mktoktbl(); /* END: SET UP TABLES ETC */ /* PARSE ARGUMENTS */ int ninbas=0; char **inbas=NULL; int ninobj=0; char **inobj=NULL; enum {NONE, OBJ, TAPE} outtype=NONE; char *outfile=NULL; bool emu=false; int arg; int state=0; for(arg=1;arg<argc;arg++) { char *varg=argv[arg]; if(strcmp(varg, "-")==0) varg="/dev/stdin"; if(*varg=='-') { if(strcmp(varg, "-V")==0) { printf(VERSION_MSG); return(EXIT_SUCCESS); } else if(strcmp(varg, "--emu")==0) { emu=true; } else if(strcmp(varg, "--no-emu")==0) { emu=false; } else if(strcmp(varg, "--debug")==0) { debug=true; } else if(strcmp(varg, "--no-debug")==0) { debug=false; } else if(strcmp(varg, "-b")==0) state=1; else if(strcmp(varg, "-l")==0) state=7; else if(strcmp(varg, "-t")==0) state=2; else if(strcmp(varg, "-W")==0) state=3; else if(strcmp(varg, "-W-")==0) state=4; else if(strcmp(varg, "-O")==0) state=5; else if(strcmp(varg, "-O-")==0) state=6; else { fprintf(stderr, "bast: No such option %s\n", varg); return(EXIT_FAILURE); } } else { bool flag=false; switch(state) { case 0: case 1: if(addinbas(&ninbas, &inbas, varg)) { fprintf(stderr, "bast: Internal error: Failed to add %s to inbas list\n", varg); return(EXIT_FAILURE); } state=0; break; case 7: if(addinbas(&ninobj, &inobj, varg)) { fprintf(stderr, "bast: Internal error: Failed to add %s to inobj list\n", varg); return(EXIT_FAILURE); } state=0; break; case 2: outtype=TAPE; outfile=strdup(varg); state=0; break; case 3: flag=true; // fallthrough case 4: if(strcmp("all", varg)==0) { Wobjlen=flag; state=0; } else if(strcmp("object-length", varg)==0) { Wobjlen=flag; state=0; } else if(strcmp("object-checksum", varg)==0) { Wobjsum=flag; state=0; } else if(strcmp("se-basic", varg)==0) { Wsebasic=flag; state=0; } else if(strcmp("embedded-newline", varg)==0) { Wembeddednewline=flag; state=0; } break; case 5: flag=true; // fallthrough case 6: if(strcmp("cut-numbers", varg)==0) { Ocutnumbers=flag; state=0; } break; default: fprintf(stderr, "bast: Internal error: Bad state %u in args\n", state); return(EXIT_FAILURE); break; } } } /* END: PARSE ARGUMENTS */ if(!(ninbas||ninobj)) { fprintf(stderr, "bast: No input files specified\n"); return(EXIT_FAILURE); } if((outtype==NONE)||!outfile) { fprintf(stderr, "bast: No output file specified\n"); return(EXIT_FAILURE); } int nsegs=0; segment * data=NULL; /* READ BASIC FILES */ if(ninbas&&!inbas) { fprintf(stderr, "bast: Internal error: ninbas!=0 and inbas is NULL\n"); return(EXIT_FAILURE); } int fbas; for(fbas=0;fbas<ninbas;fbas++) { int fline=0; int dfl=0; FILE *fp=fopen(inbas[fbas], "r"); if(!fp) { fprintf(stderr, "bast: Failed to open input file %s\n", inbas[fbas]); return(EXIT_FAILURE); } segment *curr=addsegment(&nsegs, &data); if(!curr) { fprintf(stderr, "bast: Internal error: failed to add segment for file %s\n", inbas[fbas]); return(EXIT_FAILURE); } curr->name=(char *)malloc(10); sprintf(curr->name, "bas%u", fbas); curr->type=BASIC; curr->data.bas.nlines=0; curr->data.bas.basic=NULL; curr->data.bas.line=0; curr->data.bas.lline=NULL; curr->data.bas.renum=0; curr->data.bas.block=NULL; while(!feof(fp)) { char *line=fgetl(fp); if(line) { fline+=dfl+1; dfl=0; if(*line) { while(line[strlen(line)-1]=='\\') // line splicing { char *second=fgetl(fp); if(!second) continue; dfl++; if(!*second) { free(second); continue; } line[strlen(line)-1]=0; char *splice=(char *)realloc(line, strlen(line)+strlen(second)+2); if(!splice) { free(second); continue; } line=splice; strcat(splice, second); free(second); } if(Wembeddednewline && strchr(line, '\x0D')) // 0x0D is newline in ZX BASIC { fprintf(stderr, "bast: Warning: embedded newline (\\0D) in ZX Basic line\n\t"LOC"\n", LOCARG); } if(addbasline(&curr->data.bas.nlines, &curr->data.bas.basic, line)) { fprintf(stderr, "bast: Internal error: Failed to store line as text\n\t"LOC"\n", LOCARG); return(EXIT_FAILURE); } curr->data.bas.basic[curr->data.bas.nlines-1].sline=fline; if(*line=='#') { char *cmd=strtok(line, " "); if(cmd) { if(strcmp(cmd, "#pragma")==0) { char *prgm=strtok(NULL, " "); if(prgm) { if(strcmp(prgm, "name")==0) { char *basname=strtok(NULL, ""); if(basname) { if(curr->name) free(curr->name); curr->name=strdup(basname); } } else if(strcmp(prgm, "line")==0) { char *pline=strtok(NULL, ""); if(pline) { unsigned int val; if(sscanf(pline, "%u", &val)==1) { curr->data.bas.line=val; } else { curr->data.bas.line=-1; curr->data.bas.lline=strdup(pline); } } else { fprintf(stderr, "bast: Warning: #pragma line missing argument\n\t"LOC"\n", LOCARG); } } else if(strcmp(prgm, "renum")==0) { curr->data.bas.renum=1; curr->data.bas.rnstart=0; curr->data.bas.rnoffset=0; curr->data.bas.rnend=0; char *arg=strtok(NULL, " "); while(arg) { unsigned int val=0; if(*arg) sscanf(arg+1, "%u", &val); switch(*arg) { case '=': curr->data.bas.rnstart=val; break; case '+': curr->data.bas.rnoffset=val; break; case '-': curr->data.bas.rnend=val; break; default: fprintf(stderr, "bast: Warning: #pragma renum bad argument %s\n\t"LOC"\n", arg, LOCARG); break; } arg=strtok(NULL, " "); } } else { fprintf(stderr, "bast: Warning: #pragma %s not recognised (ignoring)\n\t"LOC"\n", prgm, LOCARG); } } else { fprintf(stderr, "bast: #pragma without identifier\n\t"LOC"\n", LOCARG); return(EXIT_FAILURE); } } else if(strcmp(cmd, "##")==0) { // comment, ignore } else { fprintf(stderr, "bast: Unrecognised directive %s\n\t"LOC"\n", cmd, LOCARG); return(EXIT_FAILURE); } } } } free(line); } } fprintf(stderr, "bast: BASIC segment '%s', read %u physical lines\n", curr->name, curr->data.bas.nlines); } /* END: READ BASIC FILES */ /* READ OBJECT FILES */ int fobj; for(fobj=0;fobj<ninobj;fobj++) { FILE *fp=fopen(inobj[fobj], "r"); if(!fp) { fprintf(stderr, "bast: Failed to open input file %s\n", inobj[fobj]); return(EXIT_FAILURE); } segment *curr=addsegment(&nsegs, &data); if(!curr) { fprintf(stderr, "bast: Internal error: failed to add segment for file %s\n", inobj[fobj]); return(EXIT_FAILURE); } curr->name=(char *)malloc(10); sprintf(curr->name, "bin%u", fobj); curr->type=BINARY; err=false; bin_load(inobj[fobj], fp, &curr->data.bin, &curr->name); if(err) { fprintf(stderr, "bast: Failed to load BINARY segment from file %s\n", inobj[fobj]); return(EXIT_FAILURE); } } /* END: READ OBJECT FILES */ /* TODO: fork the assembler for each #[r]asm/#endasm block */ /* TOKENISE BASIC SEGMENTS */ if(ninbas) { int i; for(i=0;i<nsegs;i++) { if(data[i].type==BASIC) { data[i].data.bas.blines=0; fprintf(stderr, "bast: Tokenising BASIC segment %s\n", data[i].name); int j; for(j=0;j<data[i].data.bas.nlines;j++) { err=false; if(debug) fprintf(stderr, "bast: tokenising line %s\n", data[i].data.bas.basic[j].text); tokenise(&data[i].data.bas.basic[j], inbas, i, data[i].data.bas.renum); if(data[i].data.bas.basic[j].ntok) data[i].data.bas.blines++; if(err) return(EXIT_FAILURE); } fprintf(stderr, "bast: Tokenised BASIC segment %s (%u logical lines)\n", data[i].name, data[i].data.bas.blines); } } } /* END: TOKENISE BASIC SEGMENTS */ /* LINKER & LABELS */ // PASS 1: Find labels, renumber labelled BASIC sources, load in !links as attached bin_segs int nlabels=0; label * labels=NULL; int i; for(i=0;i<nsegs;i++) { fprintf(stderr, "bast: Linker (Pass 1): %s\n", data[i].name); switch(data[i].type) { case BASIC:; int num=0,dnum=0; if(data[i].data.bas.renum==1) { dnum=data[i].data.bas.rnoffset?data[i].data.bas.rnoffset:10; int end=data[i].data.bas.rnend?data[i].data.bas.rnend:9999; while(data[i].data.bas.blines*dnum>end) { dnum--; if((dnum==7)||(dnum==9)) dnum--; } if(!dnum) { fprintf(stderr, "bast: Renumber: Couldn't fit %s into available lines\n", data[i].name); return(EXIT_FAILURE); } num=data[i].data.bas.rnstart?data[i].data.bas.rnstart:dnum; fprintf(stderr, "bast: Renumber: BASIC segment %s, start %u, spacing %u, end <=%u\n", data[i].name, num, dnum, end); } int dl; init_char(&data[i].data.bas.block, &dl, (int *)&data[i].data.bas.blen); int last=0; int j; for(j=0;j<data[i].data.bas.nlines;j++) { if(data[i].data.bas.basic[j].ntok) { if(num) { if(data[i].data.bas.renum!=1) { fprintf(stderr, "bast: Linker (Pass 1): Internal error (num!=0 but renum!=1), %s\n", data[i].name); return(EXIT_FAILURE); } data[i].data.bas.basic[j].number=num; num+=dnum; } else { if(data[i].data.bas.renum) { fprintf(stderr, "bast: Linker (Pass 1): Internal error (num==0 but renum!=0), %s\n", data[i].name); return(EXIT_FAILURE); } while(last<nlabels) { labels[last].sline=j; labels[last++].line=data[i].data.bas.basic[j].number; } } int k; for(k=0;k<data[i].data.bas.basic[j].ntok;k++) { if(data[i].data.bas.basic[j].tok[k].tok==TOKEN_RLINK) { if(data[i].data.bas.basic[j].tok[k].data) { FILE *fp=fopen(data[i].data.bas.basic[j].tok[k].data, "rb"); if(fp) { data[i].data.bas.basic[j].tok[k].data2=(char *)malloc(sizeof(bin_seg)); err=false; bin_load(data[i].data.bas.basic[j].tok[k].data, fp, (bin_seg *)data[i].data.bas.basic[j].tok[k].data2, NULL); if(err) { fprintf(stderr, "bast: Linker: failed to attach BINARY segment\n\t%s:%u\n", data[i].name, j); return(EXIT_FAILURE); } } else { fprintf(stderr, "bast: Linker: failed to open rlinked file %s\n\t%s:%u\n", data[i].data.bas.basic[j].tok[k].data, data[i].name, j); return(EXIT_FAILURE); } } else { fprintf(stderr, "bast: Linker: Internal error: TOKEN_RLINK without filename\n\t%s:%u", data[i].name, j); return(EXIT_FAILURE); } } } } else if(*data[i].data.bas.basic[j].text=='.') { if(isvalidlabel(data[i].data.bas.basic[j].text+1)) { label lbl; lbl.text=strdup(data[i].data.bas.basic[j].text+1); lbl.seg=i; lbl.line=num; lbl.sline=j; addlabel(&nlabels, &labels, lbl); } } } buildbas(&data[i].data.bas, false); if(data[i].data.bas.blen==-1) { fprintf(stderr, "bast: Failed to link BASIC segment %s\n", data[i].name); return(EXIT_FAILURE); } if(data[i].data.bas.renum) data[i].data.bas.renum=2; break; case BINARY: // TODO: export symbol table (we don't have symbols in object files yet) // Nothing else on pass 1 break; default: fprintf(stderr, "bast: Linker: Internal error: Bad segment-type %u\n", data[i].type); return(EXIT_FAILURE); break; } } // PASS 2: Replace labels with the linenumbers/addresses to which they point for(i=0;i<nsegs;i++) { fprintf(stderr, "bast: Linker (Pass 2): %s\n", data[i].name); switch(data[i].type) { case BASIC: if(data[i].data.bas.line<0) { if(!data[i].data.bas.lline) { fprintf(stderr, "bast: Linker: Internal error: line<0 but lline=NULL, %s\n", data[i].name); return(EXIT_FAILURE); } int l; for(l=0;l<nlabels;l++) { // TODO limit label scope to this file & the files it has #imported if((data[labels[l].seg].type==BASIC) && (strcmp(data[i].data.bas.lline, labels[l].text)==0)) { data[i].data.bas.line=labels[l].line; break; } } if(l==nlabels) { fprintf(stderr, "bast: Linker: Undefined label %s\n\t%s:#pragma line\n", data[i].data.bas.lline, data[i].name); return(EXIT_FAILURE); } } int j; for(j=0;j<data[i].data.bas.nlines;j++) { int k; for(k=0;k<data[i].data.bas.basic[j].ntok;k++) { if(data[i].data.bas.basic[j].tok[k].tok==TOKEN_LABEL) { int l; for(l=0;l<nlabels;l++) { // TODO limit label scope to this file & the files it has #imported if((data[labels[l].seg].type==BASIC) && (strcmp(data[i].data.bas.basic[j].tok[k].data, labels[l].text)==0)) { if(debug) fprintf(stderr, "bast: Linker: expanded %%%s", data[i].data.bas.basic[j].tok[k].data); if(data[i].data.bas.basic[j].tok[k].index) { if(debug) fprintf(stderr, "%s%02x", data[i].data.bas.basic[j].tok[k].index>0?"+":"-", abs(data[i].data.bas.basic[j].tok[k].index)); } data[i].data.bas.basic[j].tok[k].tok=TOKEN_ZXFLOAT; if(Ocutnumbers) { data[i].data.bas.basic[j].tok[k].data=strdup("."); if(debug) fprintf(stderr, " to %u (cut)\n", labels[l].line+data[i].data.bas.basic[j].tok[k].index); } else { data[i].data.bas.basic[j].tok[k].data=(char *)malloc(6); sprintf(data[i].data.bas.basic[j].tok[k].data, "%05u", labels[l].line+data[i].data.bas.basic[j].tok[k].index); if(debug) fprintf(stderr, " to %s\n", data[i].data.bas.basic[j].tok[k].data); } data[i].data.bas.basic[j].tok[k].data2=(char *)malloc(6); zxfloat(data[i].data.bas.basic[j].tok[k].data2, labels[l].line+data[i].data.bas.basic[j].tok[k].index); break; } } if(l==nlabels) { fprintf(stderr, "bast: Linker: Undefined label %s\n\t"LOC"\n", data[i].data.bas.basic[j].tok[k].data, data[i].name, j); return(EXIT_FAILURE); } } else if(data[i].data.bas.basic[j].tok[k].tok==TOKEN_PTRLBL) { int l; for(l=0;l<nlabels;l++) { // TODO limit label scope to this file & the files it has #imported if((data[labels[l].seg].type==BASIC) && (strcmp(data[i].data.bas.basic[j].tok[k].data, labels[l].text)==0)) { if(debug) fprintf(stderr, "bast: Linker: expanded @%s", data[i].data.bas.basic[j].tok[k].data); if(data[i].data.bas.basic[j].tok[k].index) { if(debug) fprintf(stderr, "%s%02x", data[i].data.bas.basic[j].tok[k].index>0?"+":"-", abs(data[i].data.bas.basic[j].tok[k].index)); } data[i].data.bas.basic[j].tok[k].tok=TOKEN_ZXFLOAT; if(Ocutnumbers) { data[i].data.bas.basic[j].tok[k].data=strdup("."); if(debug) fprintf(stderr, " to %u (cut)\n", (unsigned int)data[labels[l].seg].data.bas.basic[labels[l].sline].offset+data[i].data.bas.basic[j].tok[k].index); } else { data[i].data.bas.basic[j].tok[k].data=(char *)malloc(6); sprintf(data[i].data.bas.basic[j].tok[k].data, "%05u", (unsigned int)data[labels[l].seg].data.bas.basic[labels[l].sline].offset+data[i].data.bas.basic[j].tok[k].index); if(debug) fprintf(stderr, " to %s\n", data[i].data.bas.basic[j].tok[k].data); } data[i].data.bas.basic[j].tok[k].data2=(char *)malloc(6); zxfloat(data[i].data.bas.basic[j].tok[k].data2, data[labels[l].seg].data.bas.basic[labels[l].sline].offset+data[i].data.bas.basic[j].tok[k].index); break; } } if(l==nlabels) { fprintf(stderr, "bast: Linker: Undefined label %s\n\t"LOC"\n", data[i].data.bas.basic[j].tok[k].data, data[i].name, j); return(EXIT_FAILURE); } } } } break; case BINARY: if(data[i].data.bin.nbytes) { int j; for(j=0;j<data[i].data.bin.nbytes;j++) { switch(data[i].data.bin.bytes[j].type) { case BYTE: // do nothing break; // TODO LBL, LBM (labelpointer parsing) default: fprintf(stderr, "bast: Linker: Bad byte-type %u\n\t%s+0x%04X\n", data[i].data.bin.bytes[j].type, data[i].name, j); return(EXIT_FAILURE); break; } } } break; default: fprintf(stderr, "bast: Linker: Internal error: Bad segment-type %u\n", data[i].type); return(EXIT_FAILURE); break; } } fprintf(stderr, "bast: Linker passed all segments\n"); /* END: LINKER & LABELS */ /* CREATE OUTPUT */ switch(outtype) { case TAPE: fprintf(stderr, "bast: Creating TAPE output\n"); if(nsegs) { FILE *fout=fopen(outfile, "wb"); if(!fout) { fprintf(stderr, "bast: Could not open output file %s for writing!\n", outfile); return(EXIT_FAILURE); } int i; for(i=0;i<nsegs;i++) { // write header fputc(0x13, fout); fputc(0x00, fout); unsigned char cksum=0; fputc(0x00, fout); // HEADER int j; char name[10]; switch(data[i].type) { case BASIC: fputc(0, fout); // PROGRAM memset(name, ' ', 10); memcpy(name, data[i].name, min(10, strlen(data[i].name))); for(j=0;j<10;j++) { fputc(name[j], fout); cksum^=name[j]; } buildbas(&data[i].data.bas, true); if(data[i].data.bas.blen==-1) { fprintf(stderr, "bast: Failed to link BASIC segment %s\n", data[i].name); return(EXIT_FAILURE); } fputc(data[i].data.bas.blen, fout); cksum^=data[i].data.bas.blen&0xFF; fputc(data[i].data.bas.blen>>8, fout); cksum^=data[i].data.bas.blen>>8; if(data[i].data.bas.line) // Parameter 1 = autostart line { fputc(data[i].data.bas.line, fout); cksum^=data[i].data.bas.line&0xFF; fputc(data[i].data.bas.line>>8, fout); cksum^=data[i].data.bas.line>>8; } else // Parameter 1 = 0xFFFF { fputc(0xFF, fout); fputc(0xFF, fout); } // Parameter 2 = data[i].data.bas.blen fputc(data[i].data.bas.blen, fout); cksum^=data[i].data.bas.blen&0xFF; fputc(data[i].data.bas.blen>>8, fout); cksum^=data[i].data.bas.blen>>8; fputc(cksum, fout); // write data block fputc((data[i].data.bas.blen+2), fout); fputc((data[i].data.bas.blen+2)>>8, fout); fputc(0xFF, fout); // DATA cksum=0xFF; for(j=0;j<data[i].data.bas.blen;j++) { fputc(data[i].data.bas.block[j], fout); cksum^=data[i].data.bas.block[j]; } fputc(cksum, fout); free(data[i].data.bas.block); break; case BINARY: fputc(3, fout); // CODE cksum^=3; memset(name, ' ', 10); memcpy(name, data[i].name, min(10, strlen(data[i].name))); for(j=0;j<10;j++) { fputc(name[j], fout); cksum^=name[j]; } fputc(data[i].data.bin.nbytes, fout); cksum^=data[i].data.bin.nbytes&0xFF; fputc(data[i].data.bin.nbytes>>8, fout); cksum^=data[i].data.bin.nbytes>>8; // Parameter 1 = address fputc(data[i].data.bin.org, fout); cksum^=data[i].data.bin.org&0xFF; fputc(data[i].data.bin.org>>8, fout); cksum^=data[i].data.bin.org>>8; // Parameter 2 = 0x8000 fputc(0x00, fout); fputc(0x80, fout); cksum^=0x80; fputc(cksum, fout); // write data block fputc((data[i].data.bin.nbytes+2), fout); fputc((data[i].data.bin.nbytes+2)>>8, fout); fputc(0xFF, fout); // DATA cksum=0xFF; for(j=0;j<data[i].data.bin.nbytes;j++) { fputc(data[i].data.bin.bytes[j].byte, fout); cksum^=data[i].data.bin.bytes[j].byte; } fputc(cksum, fout); free(data[i].data.bin.bytes); break; default: fprintf(stderr, "bast: Internal error: Don't know how to make TAPE output of segment type %u\n", data[i].type); return(EXIT_FAILURE); break; } fprintf(stderr, "bast: Wrote segment %s\n", data[i].name); } fclose(fout); }
void argument_parser::parse(std::string const & input) { string_vector tokens = tokenise(input, " "); parse(tokens); }
main(int argc, char *argv[]) { int sd, n, nr, nw, len, tk = 0, i, j = 0; char buf[MAX_BLOCK_SIZE]; char host[60]; char path[MAX_BLOCK_SIZE]; char files[MAX_BLOCK_SIZE]; char tmp[MAX_BLOCK_SIZE]; char filename[MAX_BLOCK_SIZE]; char *tokens[MAX_TOKENS]; struct sockaddr_in ser_addr; struct hostent *hp; /* Get the server host name. */ if (argc == 1) /* Assume server is running on the local host. */ gethostname(host, sizeof (host)); else if (argc == 2) /* Use the given host name. */ strcpy(host, argv[1]); else { printf("Usage: %s [ <server_host_name> [ <server_port> ] ] \n", argv[0]); exit(1); } /* Get the host address and build a server socket address. */ bzero((char *) & ser_addr, sizeof (ser_addr)); ser_addr.sin_family = AF_INET; ser_addr.sin_port = htons(SERV_TCP_PORT); if ((hp = gethostbyname(host)) == NULL) { printf("host %s not found\n", host); exit(1); } ser_addr.sin_addr.s_addr = *(u_long *) hp->h_addr; /* Create TCP socket and connect socket to server address. */ sd = socket(PF_INET, SOCK_STREAM, 0); if (connect(sd, (struct sockaddr *) & ser_addr, sizeof (ser_addr)) < 0) { perror("client connect"); exit(1); } while (++i) { printf("myftp[%d]: ", i); fgets(buf, sizeof (buf), stdin); nr = strlen(buf); if (buf[nr - 1] == '\n') { buf[nr - 1] = '\0'; --nr; } memset(tmp, 0x0, MAX_BLOCK_SIZE); memcpy(tmp, buf, MAX_BLOCK_SIZE); /* Tokenize user input. */ tk = tokenise(tmp, tokens); if (strcmp(buf, "quit") == 0) { printf("client disconnect.\n"); exit(0); } if (strcmp(buf, "pwd") == 0) { bzero(buf, sizeof (buf)); bzero(path, sizeof (path)); /* Set the opcode. */ buf[0] = PWD_1; nw = writen(sd, buf, 1); /* Read the return opcode. */ nr = readn(sd, &buf[0], sizeof (buf)); if (buf[0] == PWD_1) { nr = readn(sd, &buf[1], sizeof (buf)); bcopy(&buf[1], &len, 2); len = (int) ntohs(len); /* Read status code. */ char status; nr = readn(sd, &buf[3], sizeof (buf)); if (buf[3] == PWD_STATUS_OKAY) { nr = readn(sd, path, sizeof (buf)); printf("\t%s\n", path); } else printf("\tpwd returned with status PWD_STATUS_ERROR.\n"); } } else if (strncmp(buf, "cd ", 3) == 0) { if (tk == 2) { bzero(buf, sizeof (buf)); buf[0] = CD_1; nw = writen(sd, buf, 1); nw = strlen(tokens[1]); len = htons(nw); bcopy(&len, &buf[1], 2); writen(sd, &buf[1], 2); writen(sd, tokens[1], nw); readn(sd, &buf[0], sizeof (buf)); if (buf[0] == CD_1) { readn(sd, &buf[1], sizeof (buf)); if (buf[1] == CD_STATUS_OKAY) printf("\tnavigated directory successfully.\n"); else printf("\tcd returned with status CD_STATUS_ERROR. check path: %s \n", tokens[1]); } } else printf("\tmalformed command. correct syntax is: cd <path>\n"); } else if (strncmp(buf, "dir", 3) == 0) { bzero(buf, sizeof (buf)); bzero(files, sizeof (files)); buf[0] = DIR_1; nw = writen(sd, buf, 1); nr = readn(sd, &buf[0], sizeof (buf)); if (buf[0] == DIR_1) { nr = readn(sd, &buf[1], sizeof (buf)); bcopy(&buf[1], &len, 2); len = (int) ntohs(len); char status; nr = readn(sd, &buf[3], sizeof (buf)); if (buf[3] == DIR_STATUS_OKAY) { nr = readn(sd, files, sizeof (buf)); printf("%s\n\n", files); } else printf("\tdir returned with status DIR_STATUS_ERROR.\n"); } } else if (strncmp(buf, "get", 3) == 0) { if (tk == 2) { int fsize, fd, cr = 0; char chunk[MAX_BLOCK_SIZE]; bzero(buf, sizeof (buf)); buf[0] = GET_1; nw = writen(sd, buf, 1); nw = strlen(tokens[1]); len = htons(nw); bcopy(&len, &buf[1], 2); writen(sd, &buf[1], 2); writen(sd, tokens[1], nw); readn(sd, &buf[0], sizeof (buf)); if (buf[0] == GET_1) { readn(sd, &buf[1], sizeof (buf)); if (buf[1] == GET_STATUS_READ_ERROR) printf("\tget returned with status GET_STATUS_READ_ERROR. check file %s.\n", tokens[1]); else if (buf[1] == GET_STATUS_PERM_ERROR) printf("\tget returned with status GET_STATUS_PERM_ERROR. check permissions.\n"); else if (buf[1] == GET_STATUS_OTHER_ERROR) printf("\tget returned with status GET_STATUS_OTHER_ERROR.\n"); if (buf[1] == GET_STATUS_READY) { bzero(buf, sizeof (buf)); /* write opcode */ buf[0] = GET_2; writen(sd, &buf[0], 1); /* write filename length */ bcopy(&len, &buf[1], 2); writen(sd, &buf[1], 2); /* write filename */ writen(sd, tokens[1], nw); /* clear the buffer for next message */ bzero(buf, sizeof (buf)); /* read opcode */ readn(sd, &buf[0], sizeof (buf)); if (buf[0] == GET_2) { /* read status */ readn(sd, &buf[1], sizeof (buf)); if (buf[1] == GET_STATUS_READY) { /* read length */ readn(sd, &buf[2], sizeof (buf)); bcopy(&buf[2], &fsize, 4); len = ntohl(fsize); /* create a new file */ if ((fd = open(tokens[1], O_WRONLY | O_CREAT | O_TRUNC, 0666)) != -1) { /* allocate and initialize chunk memory */ char chunk[MAX_BLOCK_SIZE]; lseek(fd, 0, SEEK_SET); /* read the first block */ nr = readn(sd, chunk, MAX_BLOCK_SIZE); /* if file size is below max block size */ if (len < MAX_BLOCK_SIZE) /* write the used portion of the chunk to file */ nw = write(fd, chunk, len); else { /* otherwise, write the maximum block size */ nw = write(fd, chunk, MAX_BLOCK_SIZE); /* add the chunks written to file to counter */ cr += nw; /* keep reading chunks until the entire file has been read */ while (cr < len) { /* reinitialize the chunk memory to be safe */ memset(chunk, '\0', MAX_BLOCK_SIZE); /* move the file offset to the start of the next block */ lseek(fd, cr, SEEK_SET); /* read the next block */ nr = readn(sd, chunk, MAX_BLOCK_SIZE); /* write the block to file */ if ((len - cr) < MAX_BLOCK_SIZE) nw = write(fd, chunk, (len - cr)); else nw = write(fd, chunk, MAX_BLOCK_SIZE); /* aggregate the chunks written to file */ cr += nw; } } printf("\tfile saved.\n"); } else printf("\terror creating new file.\n"); } else printf("\terror getting file.\n"); } } } } else printf("\tmalformed command. correct syntax is: get <filename>\n"); } else if (strncmp(buf, "put", 3) == 0) { if (tk == 2) { int fsize, fd, cw = 0, nw; char *newf; char chunk[MAX_BLOCK_SIZE]; memset(buf, '\0', MAX_BLOCK_SIZE); if ((fd = open(tokens[1], O_RDONLY, 0766)) == -1) { printf("\tfile does not exist in local path.\n"); } else { /* write opcode */ buf[0] = PUT_1; nw = writen(sd, buf, 1); /* write filename length */ nw = strlen(tokens[1]); len = htons(nw); bcopy(&len, &buf[1], 2); writen(sd, &buf[1], 2); /* write filename */ writen(sd, tokens[1], nw); /* clear buffer for the server response */ memset(buf, '\0', MAX_BLOCK_SIZE); /* read the return opcode */ readn(sd, &buf[0], sizeof (buf)); /* read status */ readn(sd, &buf[1], sizeof (buf)); if (buf[1] == PUT_STATUS_READY) { /* write opcode */ buf[0] = PUT_2; nw = writen(sd, buf, 1); /* write length */ fsize = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); len = htonl(fsize); bcopy(&len, &buf[1], 4); nw = writen(sd, &buf[1], 4); /** * this next part writes the file stream. */ /* set aside a block of memory to buffer chunks */ char chunk[MAX_BLOCK_SIZE]; /* initialize chunk memory */ memset(chunk, '\0', MAX_BLOCK_SIZE); /* set zero offset */ lseek(fd, 0, SEEK_SET); /* read the file into the first block and write it to socket */ nr = read(fd, chunk, MAX_BLOCK_SIZE); nw = writen(sd, chunk, MAX_BLOCK_SIZE); /* add bytes written to the total bytes written */ cw += nw; /* keep reading chunks until file entire file has been read */ while (cw < fsize) { /* reinitialize chunk */ memset(chunk, '\0', MAX_BLOCK_SIZE); /* move the offset to start of next chunk */ lseek(fd, cw, SEEK_SET); /* read in the next chunk */ if ((fsize - cw) > MAX_BLOCK_SIZE) { nr = read(fd, chunk, MAX_BLOCK_SIZE); } else { nr = read(fd, chunk, (fsize - cw)); } /* write the current chunk to socket */ writen(sd, chunk, MAX_BLOCK_SIZE); /* aggregate bytes written */ cw += nr; } printf("\tokay to write file.\n"); } else printf("\tfile already exists in server path.\n"); } } } else if (strcmp(buf, "lpwd") == 0) { bzero(buf, MAX_BLOCK_SIZE); getcwd(buf, MAX_BLOCK_SIZE); printf("\t%s\n", buf); } else if (strncmp(buf, "lcd", 3) == 0) { if (tk == 2) { if (chdir(tokens[1]) != 0) { printf("\tinvalid directory specified.\n"); } } else { printf("\tmalformed command. correct syntax is: lcd <path>\n"); } } else if (strncmp(buf, "ldir", 4) == 0) { DIR *dp; // directory pointer struct dirent *dirp; // directory structure int fc = 0; // file count memset(buf, '\0', MAX_BLOCK_SIZE); memset(tmp, '\0', MAX_BLOCK_SIZE); memset(files, '\0', MAX_BLOCK_SIZE); /* return the directory pointer of the current path */ if ((dp = opendir(".")) == NULL) return; /* built a string with the name of each file, one per line */ while ((dirp = readdir(dp)) != NULL) { fc++; strcpy(tmp, dirp->d_name); if (tmp[0] != '.') { if (fc != 1) strcat(files, "\n\t"); else strcat(files, "\t"); strcat(files, dirp->d_name); } } /* output the string containing file names */ printf("%s\n\n", files); } } }