/** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ int read(char *buf, int n) { int buf_size = 0; int api_size = 0; //read the data from the RingBuffer at first buf_size = _ring_buffer.read(buf, n); if (buf_size == n) { return n; } n = n - buf_size; //read the data from the API at second api_size = read1(buf + buf_size, n); return buf_size + api_size; }
ast_t * match(input_t * in, tag_t tag, char * str) { int start = in->start; int i = 0, len = strlen(str); skip_whitespace(in); while (i < len && str[i] == read1(in)) i++; if (i != len) { in->start = start; return NULL; } return new_ast(tag, NULL, NULL); }
void Fread(CL_FORM *base, int nargs) { switch(nargs) { case 0: COPY(SYMVAL(Slisp, 60), ARG(0)); /* *STANDARD-INPUT* */ case 1: LOAD_SYMBOL(SYMBOL(Slisp, 48), ARG(1)); /* T */ case 2: LOAD_NIL(ARG(2)); case 3: LOAD_NIL(ARG(3)); case 4: break; default: Labort(TOO_MANY_ARGS); } read1(ARG(0)); }
void read_file(void) { static int r; static byte i; static byte b; ozcls(); ozputs0(0,"Reading..."); file_length=0; if(open1(filename,O_RDONLY)<0) { ozputs0(20,"Cannot open! Create new? [Y/n]"); if(ozgetch()=='n') exit(0); return; } do { r=read1(line_buf,LINE_BUF_LEN); if(file_length+r>MAX_FILE_LENGTH) { ozcls(); ozputs0(0,"File too long!"); ozputs0(10,"Truncate? [y/N]"); if(ozgetch()!='y') exit(0); r=MAX_FILE_LENGTH-file_length; } for(i=0;i<r;i++) { b=line_buf[i]; b&=0x7f; if(b<32) b='*'; line_buf[i]=b; } if(r>0) { ozwriteauxmem(file_length,line_buf,r); file_length+=r; } } while(r==LINE_BUF_LEN && file_length<MAX_FILE_LENGTH); /* note: LINE_BUF_LEN does not divide MAX_FILE_LENGTH, and this is important for truncate message to work */ close1(); }
void zMoveRel(int32_t dist, char cmd) { P_MOVECTL mov = &zMoveCtl; if (mov->state != ZIDLE) /* if not in idle state */ return; /* exit now */ mov->cmd = cmd; /* save command */ if (dist != 0) /* if distance non zero */ { if (dist > 0) /* if moving positive */ { mov->dist = dist; /* update distance */ mov->state = (mov->dir == ZNEG) ? ZWAITBKLS : ZSTARTMOVE; /* dir chg ? */ mov->dir = ZPOS; /* set to move positive direction */ } else { mov->dist = -dist; /* make distance a positive number */ mov->state = (mov->dir == ZPOS) ? ZWAITBKLS : ZSTARTMOVE; /* dir chg ? */ mov->dir = ZNEG; /* set move direction to negative */ } if (mov->state == ZWAITBKLS) /* if backlash move needed */ { mov->wait = 1; /* set wait flag */ zLoad(&zMA); /* load move parameters */ mov->ctlreg = ZSTART | ZBACKLASH; /* initialize ctl reg */ if (mov->dir == ZPOS) /* if positive direction */ mov->ctlreg |= ZDIR_POS; /* set direction flag */ LOAD(XLDXDIST, zAxis.backlashSteps); /* load backlash */ LOAD(XLDZCTL, mov->ctlreg); /* start move */ read1(XRDSR); if ((readval.i & S_Z_START) == 0) printf("z start not set\n"); } mov->done = 0; /* clear done flag */ mov->stop = 0; /* clear stop flag */ } }
void remcmd() { P_PARM valptr; int parm; int size; putx1('-'); gethex1(); /* read parameter */ parm = val; switch (parm) { case ZMOVE: zMoveCmd(); break; case ZMOVEREL: zMoveRelCmd(); break; case ZJMOV: zJogCmd(); break; case ZSTOP: zStop(); break; case ZHOME: zHomeCmd(); break; case ZSETLOC: zLocCmd(); break; case ZGOHOME: zGoHomeCmd(); break; case XMOVE: xMoveCmd(); break; case XMOVEREL: xMoveRelCmd(); break; case XJMOV: xJogCmd(); break; case XSTOP: xStop(); break; case XHOME: xHomeCmd(); break; case XSETLOC: xLocCmd(); break; case XGOHOME: xGoHomeCmd(); break; case SPINDLE_START: spindleStart(); break; case SPINDLE_STOP: spindleStop(); break; case CMD_PAUSE: pauseCmd(); break; case CMD_RESUME: resumeCmd(); break; case CMD_STOP: stopCmd(); break; case CMD_CLEAR: clearCmd(); break; case CMD_SETUP: setup(); break; case CMD_SPSETUP: spindleSetup(); break; case CMD_ZSETUP: zSetup(); break; case CMD_ZSYNSETUP: zSynSetup(); break; case CMD_ZTAPERSETUP: zTaperSetup(); break; case CMD_XSETUP: xSetup(); break; case CMD_XSYNSETUP: xSynSetup(); break; case CMD_XTAPERSETUP: xTaperSetup(); break; case READSTAT: break; case READISTATE: { char tmpval = zMoveCtl.state; tmpval |= xMoveCtl.state << 4; SNDHEX1(tmpval); } break; case LOADVAL: /* load a local parameter */ gethex1(); /* read the parameter number */ parm = val; /* save it */ if (parm < MAX_PARM) /* if in range */ { valptr = &remparm[parm]; /* pointer to parameter info */ p = valptr->p; /* destination pointer */ size = valptr->size; /* value size */ int type = getnum1(); /* get the value */ if (type == 1) /* if integer */ { if (size == 4) /* if a long word */ *(int32_t *) p = val; /* save as a long word */ else if (size == 1) /* if a character */ *p = (char) val; /* save the character */ else if (size == 2) /* if a short integer */ *(int16_t *) p = val; /* save the value */ } else if (type == 2) /* if floating value */ { *(float *) p = fVal; /* save as a long word */ } } break; case READVAL: /* read a local parameter */ gethex1(); /* save the parameter number */ parm = val; /* save it */ valptr = &remparm[parm]; /* pointer to parameters */ sndhex1(valptr->p,valptr->size); /* send the response */ break; case LOADXREG: /* load a xilinx register */ gethex1(); /* save the parameter number */ parm = val; /* save it */ gethex1(); /* get the value */ LOAD(parm,val); /* load value to xilinx register */ break; case READXREG: /* read a xilinx register */ gethex1(); /* save the parameter number */ parm = val; /* save it */ // read(parm); /* read the xilinx register */ read1(parm); /* read the xilinx register */ SNDHEX1(readval); /* return the parameter */ break; case SENDMOVE: gethex1(); /* save op code and flag */ parm = val; /* save input value */ char rtn = getnum1(); /* read parameter */ if (rtn != NO_VAL) /* if valid number */ { if (rtn == FLOAT_VAL) /* if floating */ queMoveCmd(parm, fVal); /* que command */ else /* if integer */ queIntCmd(parm, val); /* que command */ } break; case MOVEQUESTATUS: parm = MAX_CMDS - moveQue.count; /* calculate amount empty */ sndhex1((unsigned char *) &parm, sizeof(parm)); /* send it back */ break; case READLOC: { char buf[10]; if (zAxis.stepsInch != 0) { sprintf(buf, "%0.4f ", ((float) zLoc) / zAxis.stepsInch); putstr1(buf); } else putstr1("# "); if (xAxis.stepsInch != 0) { sprintf(buf, "%0.4f ", ((float) xLoc) / xAxis.stepsInch); putstr1(buf); } else putstr1("# "); #if 0 int clocksRev = indexPreScaler * indexPeriod; if (clocksRev != 0) { sprintf(buf, "%0.4f", ((float) FCY / clocksRev) * 60); putstr1(buf); } else #endif putstr1("#"); } break; #if DBGMSG case READDBG: if (dbgcnt > 0) /* if debug messages */ { P_DBGMSG p; --dbgcnt; /* count off a message */ p = &dbgdata[dbgemp]; /* get pointer to data */ dbgemp++; /* update empty pointer */ if (dbgemp >= MAXDBGMSG) /* if past end */ dbgemp = 0; /* point back to beginning */ int16_t count = sizeof(p->str); /* get maximum length */ char *p1 = p->str; /* get poninter to string */ while (--count >= 0) /* while not at end of buffer */ { char ch = *p1++; /* read a character */ if (ch == 0) /* if null */ break; /* exit loop */ putx1(ch); /* output character */ } putx1(' '); /* output a space */ if (p->val < 0) { putx1('-'); p->val = -p->val; } sndhex1((unsigned char *) &p->val,sizeof(p->val)); /* output data */ } break; case CLRDBG: clrDbgBuf(); break; #endif case ENCSTART: encStart(true); break; case ENCSTOP: encStop(); break; } putx1('*'); }
int SpawnFishingMonster(UOXSOCKET s, char* cScript, char* cList, char* cNpcID) { /*This function gets the random monster number from the script and list specified. Npcs->AddRespawnNPC passing the new number*/ P_CHAR pc_currchar = MAKE_CHARREF_LRV(currchar[s],-1); if (pc_currchar->inGuardedArea() && SrvParms->guardsactive) //guarded return -1; char sect[512]; int i=0,item[256]={0}; openscript(cScript); sprintf(sect, "%s %s", cList, cNpcID); if(!(strcmp("fishing.scp",cScript))) { if(!i_scripts[fishing_script]->find(sect)) { closescript(); return -1; } } else { if(!i_scripts[npc_script]->find(sect)) { closescript(); if (n_scripts[custom_npc_script][0]!=0) { openscript(n_scripts[custom_npc_script]); if (!i_scripts[custom_npc_script]->find(sect)) { closescript(); return -1; } } else return -1; } } int loopexit=0; do { read1(); if(script1[0]!='}') { item[i]=str2num(script1); i++; } } while(script1[0]!='}' && (++loopexit < MAXLOOPS) ); closescript(); if(i>0) { i=rand()%(i); if(item[i]!=-1) { Npcs->AddRespawnNPC(s,item[i],0); return item[i]; } } return -1; }
void load_headers(void) { static char hdr[8]; static unsigned i,n; static byte j,c; static struct ozfontheader fheader; bookmarksmod=0; backandforth=0; numbookmarks=last=0; show_bar=1; ozcls(); x=0; if(!strncmp(directory,filename,3)) { x=ozputs(0,x,"[bookmarks]"); filename[0]='b'; filename[1]='m'; if(open1(filename,O_RDONLY)>=0) { if(read1(hdr,8)==8 && !strncmp(hdr,"BookMrkA",8) && read1(&last,4)==4 && read1(&numbookmarks,1)==1 && read1(bookmarks,sizeof bookmarks)==sizeof bookmarks ) { if(numbookmarks) bookmarkptr=numbookmarks-1; read1(&line_height,1); if(line_height<8 || line_height>10) line_height=8; if(line_height!=9) num_lines=80/line_height; else num_lines=9; if(read1(&show_bar,1)<1 || show_bar>1) { show_bar=1; } if(read1(&positionptr,1)<1 || positionptr>MAX_POSITIONS || read1(&numpositions,1)<1 || numpositions>MAX_POSITIONS || read1(positions,sizeof positions)<sizeof positions) { numpositions=positionptr=0; } else backandforth=1; } else { numbookmarks=last=0; show_bar=1; none(); } close1(); } else { none(); } filename[0]='w'; filename[1]='b'; } else { none(); } x=ozputs(x,0,"[header]"); if(open1(filename,O_RDONLY)<0) err("Cannot open!"); if(read1(hdr,8)<8 || strncmp(hdr,"WizBookA",8) || read1(&header_length,2)<2 || read1(&length,4)<4 || read1(&numwords,2)<2 || read1(&dictionary_length,2)<2 || header_length>16384 || header_length<dictionary_length+10) err(error_header); header_length+=10; if(last==0) last=header_length; x=ozputs(x,0,"[dictionary]"); for(i=0;i<dictionary_length;i+=n) { n=dictionary_length-i; if(n>FILEBUF_LEN) n=FILEBUF_LEN; if(read1(filebuf,n)<n) err(error_dict); ozwriteauxmem(i,filebuf,n); } if(read1(&index_length,1)<1 || read1(&indentnum,1)<1) err(error_header); myfont=0xFF; if(indentnum&0x80) myfont=FONT_CUSTOM0; else if(indentnum&0x40) { x=ozputs(x,0,"[font]"); if(read1(&fheader,sizeof fheader)<sizeof fheader) err(error_font); for(i=0;i<sizeof fheader;i++) ozwritecustomfontbyte(0,i,((byte*)&fheader)[i]); for(i=sizeof fheader;i<fheader.length;i++) { if(read1(&c,1)<1) err(error_font); ozwritecustomfontbyte(0,i,c); } myfont=FONT_CUSTOM0; } if(myfont!=0xFF) { ozscancustomfonts(); line_height=ozgetfontheight(myfont); num_lines=80/line_height; } else { num_lines=line_height=9; myfont=FONT_OZ_NORMAL; } indentnum&=0x3f; for(n=i=0;i<numwords;i++) { j=0; while(!(0x80 & (c=ozreadauxbyte(n+j))) && j<MAX_WORD_LENGTH) j++; if(j==MAX_WORD_LENGTH) err(error_dict); ozwriteauxbyte(n+j,c&0x7f); j++; dict_idx[i]=n; dict_lens[i]=j; n+=j; } buffer_offset=header_length; ozputs(x,0,"[file]"); }
/* * mainloop() - * основной цикл работы редактора */ mainloop() { int i,m,first=1; register int j; int clsave,ccsave; int k; /* Хитрости с экономией памяти */ register int *lre1= &lread1; #define lread1 (*lre1) int thiscol, thisrow; char ich[8], *cp; /* Для команд с тремя вариантами аргументов */ int (*lnfun)(),(*spfun)(); int openlines(), openspaces(), closelines(),closespaces(),picklines(), pickspaces(); /* === */ extern int templ[4]; struct viewport *oport; /* * Обработка одного символа или команды * ==================================== */ if (cursorline== 0) oldcline = 1; if (cursorcol == 0) oldccol = 1; #ifndef lint goto funcdone; #endif FOREVER { csrsw = clrsw = 0; read1(); if (errsw) { errsw = 0; clrsw = 1; goto errclear; } /* * Редактирование в строке */ if ((! CTRLCHAR) || lread1 == CCCTRLQUOTE || lread1 == CCBACKSPACE || lread1 == CCDELCH) { /* Отмена в 1 колонке */ if (lread1 == CCBACKSPACE && cursorcol == 0) { lread1 = -1; goto contin; } if (openwrite[curfile] == 0) goto nowriterr; /* Строки у нас нет? Дай! */ if (clineno != (i = curwksp->ulhclno+cursorline)) getlin(i); /* исключение символа */ if (lread1==CCDELCH || (imodesw && lread1==CCBACKSPACE) ) { thiscol = cursorcol + curwksp->ulhccno; thisrow = cursorline; if (lread1 == CCBACKSPACE) thiscol--; if (ncline < thiscol + 2) { if (lread1 == CCBACKSPACE) movecursor(LT); lread1 = -1; goto contin; } for (i=thiscol;i<ncline-2;i++) cline[i] = cline[i+1]; ncline--; thiscol -= curwksp->ulhccno; putup(-(1+thiscol),cursorline); poscursor(thiscol,thisrow); fcline = 1; lread1 = -1; goto contin; } /* Проверка на границу окна */ if (cursorcol > curport->rtext) { if (fcline) { putline(0); movep(defrport); goto contin; } else goto margerr; } fcline = 1; if (j = (lread1 == CCBACKSPACE)) { movecursor(LT); lread1 = ' '; } if ((i = cursorcol + curwksp->ulhccno) >= (lcline - 2)) excline(i+2); if (i >= ncline-1) { for (k=ncline-1; k<=i; k++) cline[k] = ' '; cline[i+1] = NEWLINE; ncline = i+2; } else if (imodesw) { thiscol = cursorcol + curwksp->ulhccno; thisrow = cursorline; if (ncline >= lcline) excline(ncline+1); for (i=ncline;i>thiscol;i--) cline[i] = cline[i-1]; ncline++; thiscol -= curwksp->ulhccno; putup(-(1+thiscol),cursorline); poscursor(thiscol,thisrow); } /* Выставим границу */ if (cursorcol >= curport->rtext) curport->redit = curport->rtext + 1; /* Замена символа */ if(lread1==CCCTRLQUOTE) lread1 = esc0; if (cursorcol == curport->rtext - 10) putcha(COBELL); cline[i] = lread1; putch(lread1,1); /* Если переехали границу */ curport->redit = curport->rtext; if (j) movecursor(LT); lread1 = -1; goto contin; } /* Сдвиг вниз, если последняя строка */ if (lread1 == CCRETURN ) { putline(0); if ( cursorline == curport->btext) movew(defplline); if((i=curwksp->ulhccno) !=0) movep(-i); movecursor(lread1); lread1= -1; goto errclear; } /* * Если команда перемещения */ if (lread1<=BT) { movecursor(lread1); if (lread1 <= VMOTCODE ) { putline(0); if(curspos) goto newnumber; } lread1 = -1; goto contin; } /* Если граница поля */ if (cursorcol > curport->rtext) poscursor(curport->rtext,cursorline); putline(0); if (lread1 == CCQUIT) { if (endit() == 0) goto funcdone; gosw = 0; return; } switch (lread1) { case CCENTER: goto gotarg; case CCLPORT: movep(- deflport); goto funcdone; case CCSETFILE: switchfile(); goto funcdone; case CCCHPORT: chgport(-1); goto funcdone; case CCOPEN: if (openwrite[curfile]==0) goto nowriterr; openlines(curwksp->ulhclno + cursorline,definsert); goto funcdone; case CCMISRCH: search(-1); goto funcdone; case CCCLOSE: if (openwrite[curfile]==0) goto nowriterr; closelines(curwksp->ulhclno + cursorline, defdelete); goto funcdone; case CCPUT: if (openwrite[curfile]==0) goto nowriterr; if (pickbuf->nrows == 0) goto nopickerr; put(pickbuf,curwksp->ulhclno+cursorline, curwksp->ulhccno+cursorcol); goto funcdone; case CCPICK: picklines(curwksp->ulhclno + cursorline, defpick); goto funcdone; case CCINSMODE: imodesw = 1 - imodesw; /* change it */ goto funcdone; case CCGOTO: gtfcn(0); goto funcdone; case CCMIPAGE: movew(- defmipage * (1+curport->btext)); goto funcdone; case CCPLSRCH: search(1); goto funcdone; case CCRPORT: movep(defrport); goto funcdone; case CCPLLINE: movew(defplline); goto funcdone; case CCDELCH: goto notimperr; case CCSAVEFILE: savefile(NULL,curfile); goto funcdone; case CCMILINE: movew(-defmiline); goto funcdone; case CCDOCMD: goto notstrerr; case CCPLPAGE: movew(defplpage * (1+curport->btext)); goto funcdone; case CCMAKEPORT: makeport(deffile); goto funcdone; case CCTABS: settab(curwksp->ulhccno + cursorcol); goto funcdone; /* case CCMOVELEFT: */ /* case CCTAB: */ /* case CCMOVEDOWN: */ /* case CCHOME: */ /* case CCRETURN: */ /* case CCMOVEUP: */ default: goto badkeyerr; } /* Повтор ввода аргумента */ reparg: read1(); if(CTRLCHAR) goto yesarg; else goto noargerr; /* * Дай аргумент! */ gotarg: param(0); yesarg: if (lread1 == CCQUIT ) { if (paraml>0 && (dechars(paramv,paraml),*paramv) == 'a') { gosw = 0; if (*(paramv+1) != 'd') return; cleanup(); inputfile = -1; /* to force a dump */ fatal("ABORTED"); } if (endit() == 0) goto funcdone; gosw = 1; return; } switch (lread1) { case CCENTER: goto funcdone; case CCLPORT: if (paramtype <= 0) goto notstrerr; if (s2i(paramv,&i)) goto notinterr; movep(-i); goto funcdone; case CCSETFILE: if (paramtype <= 0) goto notstrerr; if (paramv == 0) goto noargerr; if ( use0flg || !inputfile) dechars(paramv,paraml); use0flg=1; editfile(paramv,0,0,1,1); goto funcdone; case CCCHPORT: if (paramtype <= 0) goto notstrerr; if (s2i(paramv,&i)) goto notinterr; if (i <= 0) goto notposerr; chgport(i-1); goto funcdone; case CCOPEN: if (openwrite[curfile]==0) goto nowriterr; if (paramtype == 0) { splitline(curwksp->ulhclno + paramr0, paramc0 + curwksp->ulhccno); goto funcdone; } else { lnfun = openlines; spfun = openspaces; goto spdir; }; case CCMISRCH: case CCPLSRCH: if (paramtype <= 0) goto notstrerr; if (paramv == 0) goto noargerr; if (searchkey) free(searchkey); searchkey = paramv; paraml = 0; search(lread1==CCPLSRCH?1:-1); goto funcdone; case CCCLOSE: if (openwrite[curfile]==0) goto nowriterr; if (paramtype == 0) combineline(curwksp->ulhclno + paramr0, paramc0 + curwksp->ulhccno); else { if(paramtype > 0 && paramv && paramv[0]=='>') { msrbuf(deletebuf,paramv+1,0); goto funcdone; } lnfun = closelines; spfun = closespaces; goto spdir; } goto funcdone; case CCPUT: if (paramtype > 0 && paramv && paramv[0]=='$' ) { if (msrbuf(pickbuf,paramv+1,1))goto errclear; goto funcdone; } if (paramtype != 0) goto notstrerr; if (openwrite[curfile]==0) goto nowriterr; if (deletebuf->nrows == 0) goto nodelerr; put(deletebuf,curwksp->ulhclno+cursorline, curwksp->ulhccno+cursorcol); goto funcdone; case CCMOVELEFT: case CCTAB: case CCMOVEDOWN: case CCHOME: case CCMOVEUP: case CCMOVERIGHT: case CCBACKTAB: if (s2i(paramv,&i)) goto notinterr; if (i <= 0) goto notposerr; m = ((lread1<=BT) ? lread1:0); while (--i >= 0) movecursor(m); goto funcdone; case CCRETURN: if(paramtype <=0|| !paramv) goto notimperr; dechars(paramv,paraml); switch (paramv[0]) { case '>': msvtag(paramv+1); goto funcdone; case '$': if(mdeftag(paramv+1)){ lread1= -1; goto reparg; } else goto funcdone; case 'w': if(paramv[1]==' ' && paramv[2]=='+') openwrite[curwksp->wfile]=1; else openwrite[curwksp->wfile]=0; goto funcdone; case 'k': defkey(); goto funcdone; case 'r': rescreen(-1); goto funcdone; /* Восттановить экран */ case 'd': if(paramv[1]==' ') defmac(¶mv[2]); goto funcdone; case 'q': lread1=CCQUIT; if(paramv[1]=='a') { gosw=0; return; } goto contin; default: goto noargerr; } case CCPICK: if (paramtype == 0) goto notimperr; if (paramtype > 0 && paramv && paramv[0]=='>') { msrbuf(pickbuf,paramv+1,0); goto funcdone; } lnfun = picklines; spfun = pickspaces; goto spdir; case CCINSMODE: imodesw = 1 - imodesw; /* Щелкнем!! */ goto funcdone; case CCGOTO: if (paramtype == 0) gtfcn(nlines[curfile]); else if (paramtype > 0) { if(paramv && paramv[0]=='$') { mgotag(paramv+1); goto funcdone; } if (s2i(paramv,&i)) goto notinterr; gtfcn(i-1); } else goto noargerr; goto funcdone; case CCMIPAGE: if (paramtype <= 0) goto notstrerr; if (s2i(paramv,&i)) goto notinterr; movew(- i * (1 + curport->btext)); goto funcdone; case CCRPORT: if (paramtype <= 0) goto notstrerr; if (s2i(paramv,&i)) goto notinterr; movep(i); goto funcdone; case CCPLLINE: if (paramtype < 0) goto notstrerr; else if (paramtype == 0) movew(cursorline); else if (paramtype > 0) { if (s2i(paramv,&i)) goto notinterr; movew(i); } goto funcdone; case CCDELCH: goto notimperr; case CCSAVEFILE: if (paramtype <= 0) goto notstrerr; if (paramv == 0) goto noargerr; dechars(paramv,paraml); savefile(paramv,curfile); goto funcdone; case CCMILINE: if (paramtype < 0) goto notstrerr; else if (paramtype == 0) movew(cursorline - curport->btext); else if (paramtype > 0) { if (s2i(paramv,&i)) goto notinterr; movew(-i); } goto funcdone; case CCDOCMD: if(paramtype<=0) goto notstrerr; dechars(paramv,paraml); if (openwrite[curfile] == 0) goto nowriterr; callexec(); goto funcdone; case CCPLPAGE: if (paramtype <= 0) goto notstrerr; if (s2i(paramv,&i)) goto notinterr; movew(i * (1 + curport->btext)); goto funcdone; case CCMAKEPORT: if (paramtype == 0) removeport(); else if (paramtype < 0) goto notstrerr; else { dechars(paramv,paraml); makeport(paramv); } goto funcdone; case CCTABS: clrtab(curwksp->ulhccno + cursorcol); goto funcdone; default: goto badkeyerr; } spdir: if (paramtype > 0) { if(paramv[0] == '$') { if(mdeftag(paramv+1)) goto spdir; else goto funcdone; } if (s2i(paramv,&i)) goto notinterr; if (i <= 0) goto notposerr; (*lnfun)(curwksp->ulhclno + cursorline, i); } else { if (paramc1 == paramc0) { (*lnfun)(curwksp->ulhclno+paramr0, (paramr1-paramr0)+1); } else (*spfun)(curwksp->ulhclno + paramr0, curwksp->ulhccno + paramc0, (paramc1-paramc0), (paramr1-paramr0) + 1); } goto funcdone; badkeyerr: error(DIAG("Illegal key or unnown macro","Неизвестная клавиша или макро")); goto funcdone; notstrerr: error(DIAG("Argument must be a string.","Аргумент должен быть строкой")); goto funcdone; noargerr: error(DIAG("Invalid argument.","Плохой аргумент")); goto funcdone; notinterr: error(DIAG("Argument must be numerik.","Аргумент должен быть числом")); goto funcdone; notposerr: error(DIAG("Argument must be positive.","Аргумент должен быть положительным")); goto funcdone; nopickerr: error(DIAG("Nothing in the pick buffer.","Буфер вставок пуст")); goto funcdone; nodelerr: error (DIAG("Nothing in the close buffer.","Буфер убранных строк пуст")); goto funcdone; notimperr: error(DIAG("Feature not implemented yet.","Еще не определено.")); goto funcdone; margerr: error("Margin stusk; move cursor to free."); goto funcdone; nowriterr: error(DIAG("You cannot modify this file!","Вы не можете изменить этот файл.")); goto funcdone; funcdone: clrsw = 1; newnumber: lread1 = -1; /* signify char read was used */ errclear: oport = curport; k = cursorline; j = cursorcol; switchport(¶mport); paramport.redit = PARAMRINFO; if (clrsw) { if (!errsw && !first) { poscursor(0,0); info(blanks,PARAMRINFO); } poscursor(PARAMREDIT+2,0); if (oport->wksp->wfile) { info(DIAG("file ","файл "),PARAMRINFO); info(openfnames[oport->wksp->wfile],PARAMRINFO); } info(DIAG(" line "," строка: "),PARAMRINFO); clsave = cursorline; first=0; ccsave = cursorcol; } poscursor(ccsave,clsave); i = oport->wksp->ulhclno + k + 1; /* Рисуем номер строки */ cp = ich + 8; *--cp = '\0'; do (*--cp = '0' + (i % 10)); while (i = i/10); info(cp,PARAMRINFO); *cp = '\0'; while (cp != ich) *--cp = ' '; info(ich,PARAMRINFO); switchport(oport); paramport.redit = PARAMREDIT; poscursor(j,k); if (csrsw) { putch(COCURS,1); poscursor(j,k); dumpcbuf(); sleep(1); putup(k,k); poscursor(j,k); } if (imodesw && clrsw && !errsw) telluser(DIAG(" ***** i n s e r t m o d e *****"," * * * * режим вставки * * * * "),0); contin: ; } #undef lread1 }
static long double getnumcore() { /*if (*str=='!' && false) // defines. { string find; if (defines.find(str+1, find)) { str = find; return getnumcore(); // reiterate on define contents } }*/ if (*str=='(') { str++; long double rval=eval(0); if (*str!=')') error("Mismatched parentheses."); str++; return rval; } if (*str=='$') { if (!isxdigit(str[1])) error("Invalid hex value."); if (tolower(str[2])=='x') return -42;//let str get an invalid value so it'll throw an invalid operator later on return strtoul(str+1, (char**)&str, 16); } if (*str=='%') { if (str[1]!='0' && str[1]!='1') error("Invalid binary value."); return strtoul(str+1, (char**)&str, 2); } if (*str=='\'') { if (!str[1] || str[2]!='\'') error("Invalid character."); unsigned int rval=table[(unsigned char)str[1]]; str+=3; return rval; } if (isdigit(*str)) { return strtod(str, (char**)&str); } if (isalpha(*str) || *str=='_' || *str=='.' || *str=='?') { const char * start=str; while (isalnum(*str) || *str=='_') str++; int len=str-start; while (*str==' ') str++; if (*str=='(') { str++; while (*str==' ') str++; autoarray<long double> params; int numparams=0; if (*str!=')') { while (true) { while (*str==' ') str++; params[numparams++]=eval(0); while (*str==' ') str++; if (*str==',') { str++; continue; } if (*str==')') { str++; break; } error("Malformed function call."); } } long double rval; for (int i=0;i<numuserfunc;i++) { if ((int)strlen(userfunc[i].name)==len && !strncmp(start, userfunc[i].name, len)) { if (userfunc[i].numargs!=numparams) error("Wrong number of parameters to function."); char ** oldfuncargnames=funcargnames; long double * oldfuncargvals=funcargvals; const char * oldstr=str; int oldnumuserfuncargs=numuserfuncargs; funcargnames=userfunc[i].arguments; funcargvals=params; str=userfunc[i].content; numuserfuncargs=numparams; rval=eval(0); funcargnames=oldfuncargnames; funcargvals=oldfuncargvals; str=oldstr; numuserfuncargs=oldnumuserfuncargs; return rval; } } if (*str=='_') str++; #define func(name, numpar, code) \ if (!strncasecmp(start, name, len)) \ { \ if (numparams==numpar) return (code); \ else error("Wrong number of parameters to function."); \ } #define varfunc(name, code) \ if (!strncasecmp(start, name, len)) \ { \ code; \ } func("sqrt", 1, sqrt(params[0])); func("sin", 1, sin(params[0])); func("cos", 1, cos(params[0])); func("tan", 1, tan(params[0])); func("asin", 1, asin(params[0])); func("acos", 1, acos(params[0])); func("atan", 1, atan(params[0])); func("arcsin", 1, asin(params[0])); func("arccos", 1, acos(params[0])); func("arctan", 1, atan(params[0])); func("log", 1, log(params[0])); func("log10", 1, log10(params[0])); func("log2", 1, log(params[0])/log(2.0)); func("read1", 1, read1(params[0])); func("read2", 1, read2(params[0])); func("read3", 1, read3(params[0])); func("read4", 1, read4(params[0])); func("read1", 2, read1s(params[0], params[1])); func("read2", 2, read2s(params[0], params[1])); func("read3", 2, read3s(params[0], params[1])); func("read4", 2, read4s(params[0], params[1])); func("canread1", 1, validaddr(params[0], 1)); func("canread2", 1, validaddr(params[0], 2)); func("canread3", 1, validaddr(params[0], 3)); func("canread4", 1, validaddr(params[0], 4)); func("canread", 2, validaddr(params[0], params[1])); //varfunc("min", { // if (!numparams) error("Wrong number of parameters to function."); // double minval=params[0]; // for (int i=1;i<numparams;i++) // { // if (params[i]<minval) minval=params[i]; // } // return minval; // }); //varfunc("max", { // if (!numparams) error("Wrong number of parameters to function."); // double maxval=params[0]; // for (int i=1;i<numparams;i++) // { // if (params[i]>maxval) maxval=params[i]; // } // return maxval; // }); #undef func #undef varfunc error("Unknown function."); } else { for (int i=0;i<numuserfuncargs;i++) { if (!strncmp(start, funcargnames[i], len)) return funcargvals[i]; } foundlabel=true; int i=labelval(&start); str=start; //if (start!=str) error("Internal error. Send this patch to Alcaro.");//not gonna add sublabel/macrolabel support here if (i==-1) forwardlabel=true; return (int)i&0xFFFFFF; //#define const(name, val) if (!strncasecmp(start, name, len)) return val // const("pi", 3.141592653589793238462); // const("\xCF\x80", 3.141592653589793238462); // const("\xCE\xA0", 3.141592653589793238462);//case insensitive pi, yay // const("e", 2.718281828459045235360); //#undef const // error("Unknown constant."); } } error("Invalid number."); }
TVerdict CTestSyscalls::doTestStepL() { int err; if(TestStepName() == KCreat) { INFO_PRINTF1(_L("Creat():")); err = Creat(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen1) { INFO_PRINTF1(_L("open1():")); err = open1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen2) { INFO_PRINTF1(_L("open2():")); err = open2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen3) { INFO_PRINTF1(_L("open3():")); err = open3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen4) { INFO_PRINTF1(_L("open4():")); err = open4(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen5) { INFO_PRINTF1(_L("open5():")); err = open5(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen6) { INFO_PRINTF1(_L("open6():")); err = open6(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KOpenTruncate1) { INFO_PRINTF1(_L("OpenTruncate1:")); err = OpenTruncate1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KOpenTruncate2) { INFO_PRINTF1(_L("OpenTruncate2:")); err = OpenTruncate2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen7) { INFO_PRINTF1(_L("open7():")); err = open7(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KOpenInAppendMode) { INFO_PRINTF1(_L("OpenInAppendMode():")); err = OpenInAppendMode(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kwrite1) { INFO_PRINTF1(_L("write1():")); err = write1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kwrite2) { INFO_PRINTF1(_L("write2():")); err = write2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kwrite3) { INFO_PRINTF1(_L("write3():")); err = write3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kwrite5) { INFO_PRINTF1(_L("write5():")); err = write5(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kread1) { INFO_PRINTF1(_L("read1():")); err = read1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kread2) { INFO_PRINTF1(_L("read2():")); err = read2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kread3) { INFO_PRINTF1(_L("read3():")); err = read3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kread4) { INFO_PRINTF1(_L("read4():")); err = read4(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KOpendir) { INFO_PRINTF1(_L("Opendir():")); err = Opendir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KClosedir) { INFO_PRINTF1(_L("Closedir():")); err = Closedir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KReaddir) { INFO_PRINTF1(_L("Readdir():")); err = Readdir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KLseek) { INFO_PRINTF1(_L("Lseek():")); err = Lseek(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KLseek1) { INFO_PRINTF1(_L("Lseek1():")); err = Lseek1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KAccess) { INFO_PRINTF1(_L("Access():")); err = Access(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KAccess1) { INFO_PRINTF1(_L("Access1():")); err = Access1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KDup) { INFO_PRINTF1(_L("Dup():")); err = Dup(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KDup2) { INFO_PRINTF1(_L("Dup2():")); err = Dup2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename) { INFO_PRINTF1(_L("Rename():")); err = Rename(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename1) { INFO_PRINTF1(_L("Rename1():")); err = Rename1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChmod) { INFO_PRINTF1(_L("Chmod():")); err = Chmod(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChmod1) { INFO_PRINTF1(_L("Chmod1():")); err = Chmod1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChmod_dir) { INFO_PRINTF1(_L("Chmod_dir():")); err = Chmod_dir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFChmod) { INFO_PRINTF1(_L("FChmod():")); err = FChmod(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFChmod_dir) { INFO_PRINTF1(_L("FChmod_dir():")); err = FChmod_dir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KExit) { INFO_PRINTF1(_L("Exit():")); err = Exit(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KClose) { INFO_PRINTF1(_L("Close():")); err = Close(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMkdir) { INFO_PRINTF1(_L("Mkdir():")); err = Mkdir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMk_dir) { INFO_PRINTF1(_L("Mk_dir():")); err = Mk_dir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRmdir) { INFO_PRINTF1(_L("Rmdir():")); err = Rmdir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRm_dir) { INFO_PRINTF1(_L("Rm_dir():")); err = Rm_dir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRmdir1) { INFO_PRINTF1(_L("Rmdir1():")); err = Rmdir1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRmdir_Chdir) { INFO_PRINTF1(_L("Rmdir_Chdir():")); err = Rmdir_Chdir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFsync) { INFO_PRINTF1(_L("Fsync():")); err = Fsync(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KUtimes) { INFO_PRINTF1(_L("Utimes():")); err = Utimes(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KUtime) { INFO_PRINTF1(_L("Utime():")); err = Utime(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChdir) { INFO_PRINTF1(_L("Chdir():")); err = Chdir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFcntl) { INFO_PRINTF1(_L("Fcntl():")); err = Fcntl(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KIoctl) { INFO_PRINTF1(_L("Ioctl():")); err = Ioctl(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFstat) { INFO_PRINTF1(_L("Fstat():")); err = Fstat(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStat) { INFO_PRINTF1(_L("Stat():")); err = Stat(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStat1) { INFO_PRINTF1(_L("Stat1():")); err = Stat1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStat2) { INFO_PRINTF1(_L("Stat2():")); err = Stat2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStat3) { INFO_PRINTF1(_L("Stat3():")); err = Stat3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KGetpid) { INFO_PRINTF1(_L("Getpid():")); err = Getpid(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KClock) { INFO_PRINTF1(_L("Clock():")); err = Clock(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTime) { INFO_PRINTF1(_L("Time():")); err = Time(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KWaitPid) { INFO_PRINTF1(_L("WaitPid():")); err = WaitPid(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KReadV) { INFO_PRINTF1(_L("ReadV():")); err = ReadV(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KWriteV) { INFO_PRINTF1(_L("WriteV():")); err = WriteV(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KSleep) { INFO_PRINTF1(_L("Sleep():")); err = Sleep(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KSeekDir) { INFO_PRINTF1(_L("SeekDir():")); err = SeekDir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRewindDir) { INFO_PRINTF1(_L("RewindDir():")); err = RewindDir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTelldir) { INFO_PRINTF1(_L("Telldir():")); err = Telldir(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestClock) { INFO_PRINTF1(_L("TestClock():")); err = TestClock(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KCreat2) { INFO_PRINTF1(_L("Creat2():")); err = Creat2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopen8) { INFO_PRINTF1(_L("open8():")); err = open8(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStat) { INFO_PRINTF1(_L("KTestStat():")); err = TestStat(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KLseekttytest1) { INFO_PRINTF1(_L("Lseekttytest1():")); err = Lseekttytest1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KLseekttytest2) { INFO_PRINTF1(_L("Lseekttytest2():")); err = Lseekttytest2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KWaitPidtest) { INFO_PRINTF1(_L("WaitPidtest():")); err = WaitPidtest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KWaittest) { INFO_PRINTF1(_L("Waittest():")); err = Waittest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KOpen_FileDes_Test) { INFO_PRINTF1(_L("Open_FileDes_Test():")); err = Open_FileDes_Test(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kopenuid) { INFO_PRINTF1(_L("openuid():")); err = openuid(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMkdir1) { INFO_PRINTF1(_L("Mkdir1():")); err = Mkdir1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMkdir2) { INFO_PRINTF1(_L("Mkdir2():")); err = Mkdir2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename2) { INFO_PRINTF1(_L("Rename2():")); err = Rename2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Ktestfsync) { INFO_PRINTF1(_L("testfsync():")); err = testfsync(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Ktestrename) { INFO_PRINTF1(_L("testrename():")); err = testrename(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Ktestopenvalidate) { INFO_PRINTF1(_L("testopenvalidate():")); err = testopenvalidate(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Ksync_safe) { INFO_PRINTF1(_L("sync_safe():")); err = sync_safe(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KFstat1) { INFO_PRINTF1(_L("Fstat1():")); err = Fstat1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KUtimes1) { INFO_PRINTF1(_L("Utimes1():")); err = Utimes1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMkdir_test1) { INFO_PRINTF1(_L("Mkdir_test1():")); err = Mkdir_test1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChmod_test) { INFO_PRINTF1(_L("Chmod_test():")); err = Chmod_test(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChdir1) { INFO_PRINTF1(_L("Chdir1():")); err = Chdir1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRmdir2) { INFO_PRINTF1(_L("Rmdir2():")); err = Rmdir2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename_test) { INFO_PRINTF1(_L("Rename_test():")); err = Rename_test(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename3) { INFO_PRINTF1(_L("Rename3():")); err = Rename3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KCreat1) { INFO_PRINTF1(_L("Creat1():")); err = Creat1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KReadV1) { INFO_PRINTF1(_L("ReadV1():")); err = ReadV1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KUtimes2) { INFO_PRINTF1(_L("Utimes2():")); err = Utimes2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStat_test) { INFO_PRINTF1(_L("Stat_test():")); err = Stat_test(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMkdir_test2) { INFO_PRINTF1(_L("Mkdir_test2():")); err = Mkdir_test2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChmod2) { INFO_PRINTF1(_L("Chmod2():")); err = Chmod2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KChdir2) { INFO_PRINTF1(_L("Chdir2():")); err = Chdir2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename4) { INFO_PRINTF1(_L("Rename4():")); err = Rename4(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRename5) { INFO_PRINTF1(_L("Rename5():")); err = Rename5(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KRmdir3) { INFO_PRINTF1(_L("Rmdir3():")); err = Rmdir3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kread5) { INFO_PRINTF1(_L("read5():")); err = read5(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } return TestStepResult(); }
/* Get a command from the client. * If a command is received, returns 1, * otherwise return 0. */ int get_command(struct vtcmd *v) { int i,loc; char ch,bootbuf[40]; sum0 = 0; sum1 = 0; /* Get a valid command from the client */ read0(portfd, &v->hdr1, 1); /* Send down the bootstrap code to ODT if we see an @ sign */ if ((havesentbootcode==0) && (v->hdr1 == '@')) { writeC(ttyfd,&v->hdr1,1); for (i=0,loc=BOOTSTART;i<(sizeof(bootcode)/sizeof(int));i++,loc+=2) { sprintf(bootbuf, "%06o/", loc); writeP(portfd, bootbuf, strlen(bootbuf)); /* wait for current value to print */ while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch==' ') break; } sprintf(bootbuf, "%06o\r", bootcode[i]); writeP(portfd, bootbuf, strlen(bootbuf)); /* and suck up any characters sent from ODT */ while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch=='@') break; } } sprintf(bootbuf, "r6/", loc); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch==' ') break; } sprintf(bootbuf, "%06o\r", BOOTSTACK); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch=='@') break; } sprintf(bootbuf, "r7/", loc); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch==' ') break; } sprintf(bootbuf, "%06o\r", BOOTSTART); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch=='@') break; } sprintf(bootbuf, "rs/", loc); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch==' ') break; } sprintf(bootbuf, "%06o\r", 000340); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch=='@') break; } sprintf(bootbuf, "p"); writeP(portfd, bootbuf, strlen(bootbuf)); while (1) { readP(portfd, &ch, 1); writeC(ttyfd,&ch,1); if (ch=='p') break; } havesentbootcode=1; return(0); } if (v->hdr1 != VT_HDR1) { v->hdr1&= 127; writeC(1,&v->hdr1, 1); return(0); } read1(portfd, &v->hdr2, 1); if (v->hdr2 != VT_HDR2) { v->hdr1&= 127; writeC(1,&v->hdr1, 1); v->hdr2&= 127; writeC(1,&v->hdr2, 1); return(0); } read0(portfd, &v->cmd, 1); read1(portfd, &v->record, 1); read0(portfd, &v->blklo, 1); read1(portfd, &v->blkhi, 1); block = v->blkhi<<8&0xff00 | v->blklo&0xff; if(block>=0xff00) { unsigned char tmp0,tmp1; read0(portfd, &tmp0, 1); read1(portfd, &tmp1, 1); block = tmp1<<16&0xff0000 | tmp0<<8&0xff00 | v->blklo&0xff; } /* All done if a quick read */ if (v->cmd == VTC_QUICK) return(1); /* Retrieve the block if a WRITE cmd */ if (v->cmd == VTC_WRITE) { for (i = 0; i < BLKSIZE; i++) { read0(portfd, &inbuf[i], 1); i++; read1(portfd, &inbuf[i], 1); } } /* Get the checksum */ read0(portfd, &(v->sum0), 1); read1(portfd, &(v->sum1), 1); /* Try again on a bad checksum */ if (sum0 | sum1) { fputc('e',stderr); return(0); } return(1); }
inline char readChar() { char c=0; read1(&c); return c; }
int rapMapMap(int argc, char* argv[]) { std::cerr << "RapMap Mapper\n"; std::string versionString = rapmap::version; TCLAP::CmdLine cmd( "RapMap Mapper", ' ', versionString); cmd.getProgramName() = "rapmap"; TCLAP::ValueArg<std::string> index("i", "index", "The location of the pseudoindex", true, "", "path"); TCLAP::ValueArg<std::string> read1("1", "leftMates", "The location of the left paired-end reads", false, "", "path"); TCLAP::ValueArg<std::string> read2("2", "rightMates", "The location of the right paired-end reads", false, "", "path"); TCLAP::ValueArg<std::string> unmatedReads("r", "unmatedReads", "The location of single-end reads", false, "", "path"); TCLAP::ValueArg<uint32_t> numThreads("t", "numThreads", "Number of threads to use", false, 1, "positive integer"); TCLAP::ValueArg<uint32_t> maxNumHits("m", "maxNumHits", "Reads mapping to more than this many loci are discarded", false, 200, "positive integer"); TCLAP::ValueArg<std::string> outname("o", "output", "The output file (default: stdout)", false, "", "path"); TCLAP::SwitchArg endCollectorSwitch("e", "endCollector", "Use the simpler (and faster) \"end\" collector as opposed to the more sophisticated \"skipping\" collector", false); TCLAP::SwitchArg noout("n", "noOutput", "Don't write out any alignments (for speed testing purposes)", false); cmd.add(index); cmd.add(noout); cmd.add(read1); cmd.add(read2); cmd.add(unmatedReads); cmd.add(outname); cmd.add(numThreads); cmd.add(maxNumHits); cmd.add(endCollectorSwitch); auto consoleSink = std::make_shared<spdlog::sinks::stderr_sink_mt>(); auto consoleLog = spdlog::create("stderrLog", {consoleSink}); try { cmd.parse(argc, argv); bool pairedEnd = (read1.isSet() or read2.isSet()); if (pairedEnd and (read1.isSet() != read2.isSet())) { consoleLog->error("You must set both the -1 and -2 arguments to align " "paired end reads!"); std::exit(1); } if (pairedEnd and unmatedReads.isSet()) { consoleLog->error("You cannot specify both paired-end and unmated " "reads in the input!"); std::exit(1); } if (!pairedEnd and !unmatedReads.isSet()) { consoleLog->error("You must specify input; either both paired-end " "or unmated reads!"); std::exit(1); } std::string indexPrefix(index.getValue()); if (indexPrefix.back() != '/') { indexPrefix += "/"; } if (!rapmap::fs::DirExists(indexPrefix.c_str())) { consoleLog->error("It looks like the index you provided [{}] " "doesn't exist", indexPrefix); std::exit(1); } IndexHeader h; std::ifstream indexStream(indexPrefix + "header.json"); { cereal::JSONInputArchive ar(indexStream); ar(h); } indexStream.close(); if (h.indexType() != IndexType::PSEUDO) { consoleLog->error("The index {} does not appear to be of the " "appropriate type (pseudo)", indexPrefix); std::exit(1); } RapMapIndex rmi; rmi.load(indexPrefix); std::cerr << "\n\n\n\n"; // from: http://stackoverflow.com/questions/366955/obtain-a-stdostream-either-from-stdcout-or-stdofstreamfile // set either a file or cout as the output stream std::streambuf* outBuf; std::ofstream outFile; bool haveOutputFile{false}; if (outname.getValue() == "") { outBuf = std::cout.rdbuf(); } else { outFile.open(outname.getValue()); outBuf = outFile.rdbuf(); haveOutputFile = true; } // Now set the output stream to the buffer, which is // either std::cout, or a file. std::ostream outStream(outBuf); // Must be a power of 2 size_t queueSize{268435456}; spdlog::set_async_mode(queueSize); auto outputSink = std::make_shared<spdlog::sinks::ostream_sink_mt>(outStream); auto outLog = std::make_shared<spdlog::logger>("outLog", outputSink); outLog->set_pattern("%v"); uint32_t nthread = numThreads.getValue(); std::unique_ptr<paired_parser> pairParserPtr{nullptr}; std::unique_ptr<single_parser> singleParserPtr{nullptr}; if (!noout.getValue()) { rapmap::utils::writeSAMHeader(rmi, outLog); } SpinLockT iomutex; { ScopedTimer timer; HitCounters hctrs; consoleLog->info("mapping reads . . . \n\n\n"); if (pairedEnd) { std::vector<std::thread> threads; std::vector<std::string> read1Vec = rapmap::utils::tokenize(read1.getValue(), ','); std::vector<std::string> read2Vec = rapmap::utils::tokenize(read2.getValue(), ','); if (read1Vec.size() != read2Vec.size()) { consoleLog->error("The number of provided files for " "-1 and -2 must be the same!"); std::exit(1); } size_t numFiles = read1Vec.size() + read2Vec.size(); char** pairFileList = new char*[numFiles]; for (size_t i = 0; i < read1Vec.size(); ++i) { pairFileList[2*i] = const_cast<char*>(read1Vec[i].c_str()); pairFileList[2*i+1] = const_cast<char*>(read2Vec[i].c_str()); } size_t maxReadGroup{1000}; // Number of reads in each "job" size_t concurrentFile{2}; // Number of files to read simultaneously pairParserPtr.reset(new paired_parser(4 * nthread, maxReadGroup, concurrentFile, pairFileList, pairFileList+numFiles)); /** Create the threads depending on the collector type **/ if (endCollectorSwitch.getValue()) { EndCollector endCollector(&rmi); for (size_t i = 0; i < nthread; ++i) { threads.emplace_back(processReadsPair<EndCollector, SpinLockT>, pairParserPtr.get(), std::ref(rmi), std::ref(endCollector), &iomutex, outLog, std::ref(hctrs), maxNumHits.getValue(), noout.getValue()); } } else { SkippingCollector skippingCollector(&rmi); for (size_t i = 0; i < nthread; ++i) { threads.emplace_back(processReadsPair<SkippingCollector, SpinLockT>, pairParserPtr.get(), std::ref(rmi), std::ref(skippingCollector), &iomutex, outLog, std::ref(hctrs), maxNumHits.getValue(), noout.getValue()); } } for (auto& t : threads) { t.join(); } delete [] pairFileList; } else { std::vector<std::thread> threads; std::vector<std::string> unmatedReadVec = rapmap::utils::tokenize(unmatedReads.getValue(), ','); size_t maxReadGroup{1000}; // Number of reads in each "job" size_t concurrentFile{1}; stream_manager streams( unmatedReadVec.begin(), unmatedReadVec.end(), concurrentFile); singleParserPtr.reset(new single_parser(4 * nthread, maxReadGroup, concurrentFile, streams)); /** Create the threads depending on the collector type **/ if (endCollectorSwitch.getValue()) { EndCollector endCollector(&rmi); for (size_t i = 0; i < nthread; ++i) { threads.emplace_back(processReadsSingle<EndCollector, SpinLockT>, singleParserPtr.get(), std::ref(rmi), std::ref(endCollector), &iomutex, outLog, std::ref(hctrs), maxNumHits.getValue(), noout.getValue()); } } else { SkippingCollector skippingCollector(&rmi); for (size_t i = 0; i < nthread; ++i) { threads.emplace_back(processReadsSingle<SkippingCollector, SpinLockT>, singleParserPtr.get(), std::ref(rmi), std::ref(skippingCollector), &iomutex, outLog, std::ref(hctrs), maxNumHits.getValue(), noout.getValue()); } } for (auto& t : threads) { t.join(); } } consoleLog->info("Done mapping reads."); consoleLog->info("In total saw {} reads.", hctrs.numReads); consoleLog->info("Final # hits per read = {}", hctrs.totHits / static_cast<float>(hctrs.numReads)); consoleLog->info("Discarded {} reads because they had > {} alignments", hctrs.tooManyHits, maxNumHits.getValue()); consoleLog->info("flushing output"); outLog->flush(); } if (haveOutputFile) { outFile.close(); } return 0; } catch (TCLAP::ArgException& e) { consoleLog->error("Exception [{}] when parsing argument {}", e.error(), e.argId()); return 1; } }
/* * Handle a packet. Returns "false" if we encounter a connection-fatal error. */ static bool handlePacket(JdwpState* state) { JdwpNetState* netState = state->netState; const unsigned char* buf = netState->inputBuffer; JdwpReqHeader hdr; u4 length, id; u1 flags, cmdSet, cmd; u2 error; bool reply; int dataLen; cmd = cmdSet = 0; // shut up gcc /*dumpPacket(netState->inputBuffer);*/ length = read4BE(&buf); id = read4BE(&buf); flags = read1(&buf); if ((flags & kJDWPFlagReply) != 0) { reply = true; error = read2BE(&buf); } else { reply = false; cmdSet = read1(&buf); cmd = read1(&buf); } assert((int) length <= netState->inputCount); dataLen = length - (buf - netState->inputBuffer); if (!reply) { ExpandBuf* pReply = expandBufAlloc(); hdr.length = length; hdr.id = id; hdr.cmdSet = cmdSet; hdr.cmd = cmd; dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply); if (expandBufGetLength(pReply) > 0) { int cc; /* * TODO: we currently assume the write() will complete in one * go, which may not be safe for a network socket. We may need * to mutex this against sendRequest(). */ cc = write(netState->clientSock, expandBufGetBuffer(pReply), expandBufGetLength(pReply)); if (cc != (int) expandBufGetLength(pReply)) { LOGE("Failed sending reply to debugger: %s\n", strerror(errno)); expandBufFree(pReply); return false; } } else { LOGW("No reply created for set=%d cmd=%d\n", cmdSet, cmd); } expandBufFree(pReply); } else { LOGV("reply?!\n"); assert(false); } LOGV("----------\n"); consumeBytes(netState, length); return true; }
void zControl() { P_MOVECTL mov = &zMoveCtl; if (mov->stop) /* if stop */ mov->state = ZDONE; /* clean up in done state */ if (DBGMSG) { if (mov->state != mov->prev) { dbgmsg("z st", mov->state); mov->prev = mov->state; } } switch(mov->state) /* dispatch on state */ { case ZIDLE: /* 0 idle state */ break; case ZWAITBKLS: /* 1 wait for backlash move to complete */ if (mov->done) /* if done */ { mov->done = 0; /* clear done flag */ mov->wait = 0; /* clear wait flag */ mov->state = ZSTARTMOVE; /* advance to start move state */ } break; case ZSTARTMOVE: /* 2 start a z move */ mov->ctlreg = ZSTART; /* initialize control reg */ char ch = mov->cmd & ZMSK; /* get type of move */ if (ch == ZSYN) /* if synchronized move */ { zLoad(&zTA); /* load turn parameters */ mov->ctlreg |= ZSRC_SYN; /* set sync flags */ if (mov->cmd & Z_SYN_START) /* if wait for sync */ mov->ctlreg |= ZWAIT_SYNC; /* set to wait for sync */ } else { if (ch == ZJOG) /* if jog */ zLoad(&zJA); /* load jog parameters */ else if (ch == ZMAX) /* if max */ zLoad(&zMA); /* load move parameters */ else /* else */ zLoad(&zTA); /* load turn parameters */ } if (mov->dir == ZPOS) /* if moving positive */ mov->ctlreg |= ZDIR_POS; /* set direction flag */ LOAD(XLDZDIST, mov->dist); /* set distance to move */ LOAD(XLDZCTL, mov->ctlreg); /* start move */ read1(XRDSR); if ((readval.i & S_Z_START) == 0) printf("z start not set\n"); mov->wait = 1; /* set wait flag */ mov->state = ZWAITMOVE; /* wait for move to complete */ break; case ZWAITMOVE: /* 3 wait for a z move to complete */ if (mov->done) /* if done */ { mov->wait = 0; /* clear wait flag */ mov->state = ZDONE; /* clean up everything */ } break; case ZDONE: /* 4 done state */ default: /* all others */ LOAD(XLDZCTL, 0); /* stop move */ mov->stop = 0; /* clear stop flag */ mov->done = 0; /* clear done flag */ mov->cmd = 0; /* clear command */ read1(XRDZLOC); /* read current location */ mov->loc = readval.i; /* save it */ if (mov->loc != mov->expLoc) /* if not at expected location */ { printf("z move error actual %d expected %d\n", mov->loc, mov->expLoc); if (DBGMSG) dbgmsg("zExp", mov->expLoc); } if (DBGMSG) dbgmsg("zloc", mov->loc); mov->state = ZIDLE; /* set state to idle */ if (DBGMSG) dbgmsg("z st", mov->state); break; } }
int urj_flash_cfi_detect (urj_bus_t *bus, uint32_t adr, urj_flash_cfi_array_t **cfi_array) { unsigned int bw; /* bus width */ unsigned int d; /* data offset */ size_t ba; /* bus width address multiplier */ int ma; /* flash mode address multiplier */ urj_bus_area_t area; if (!cfi_array || !bus) { urj_error_set (URJ_ERROR_INVALID, "cfi_array or bus"); return URJ_STATUS_FAIL; } *cfi_array = calloc (1, sizeof (urj_flash_cfi_array_t)); if (!*cfi_array) { urj_error_set (URJ_ERROR_OUT_OF_MEMORY, "calloc(%zd,%zd) fails", (size_t) 1, sizeof (urj_flash_cfi_array_t)); return URJ_STATUS_FAIL; } (*cfi_array)->bus = bus; (*cfi_array)->address = adr; if (URJ_BUS_AREA (bus, adr, &area) != URJ_STATUS_OK) // retain error state return URJ_STATUS_FAIL; if (URJ_BUS_TYPE (bus) != URJ_BUS_TYPE_PARALLEL) return URJ_STATUS_FAIL; bw = area.width; if (bw != 8 && bw != 16 && bw != 32) { urj_error_set (URJ_ERROR_INVALID, "bus width = %d", bw); return URJ_STATUS_FAIL; } (*cfi_array)->bus_width = ba = bw / 8; (*cfi_array)->cfi_chips = calloc (ba, sizeof (urj_flash_cfi_chip_t *)); if (!(*cfi_array)->cfi_chips) { urj_error_set (URJ_ERROR_OUT_OF_MEMORY, "calloc(%zd,%zd) fails", ba, sizeof (urj_flash_cfi_chip_t *)); return URJ_STATUS_FAIL; } for (d = 0; d < bw; d += 8) { #define A(off) (adr + (off) * ba * ma) #define D(data) ((data) << d) #define gD(data) (((data) >> d) & 0xFF) #define read1(off) gD(URJ_BUS_READ( bus, A(off) )) // @@@@ RFHH check status of URJ_BUS_READ_START #define read2(off) (URJ_BUS_READ_START (bus, A(off)), gD (URJ_BUS_READ_NEXT (bus, A((off) + 1))) | gD (URJ_BUS_READ_END (bus)) << 8) #define write1(off,data) URJ_BUS_WRITE( bus, A(off), D(data) ) urj_flash_cfi_query_structure_t *cfi; uint32_t tmp; int ret = -4; /* CFI not detected (Q) */ uint16_t pri_vendor_tbl_adr; /* detect CFI capable devices - see Table 1 in [1] */ for (ma = 1; ma <= 4; ma *= 2) { write1 (CFI_CMD_QUERY_OFFSET, CFI_CMD_QUERY); if (read1 (CFI_QUERY_ID_OFFSET) == 'Q') { ret = -5; /* CFI not detected (R) */ if (read1 (CFI_QUERY_ID_OFFSET + 1) == 'R') break; } write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); } if (ma > 4) { if (ret == -4) urj_error_set (URJ_ERROR_FLASH, "CFI not detected (Q)"); else urj_error_set (URJ_ERROR_FLASH, "CFI not detected (R)"); return URJ_STATUS_FAIL; } if (read1 (CFI_QUERY_ID_OFFSET + 2) != 'Y') { write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); urj_error_set (URJ_ERROR_FLASH, "CFI not detected (Y)"); return URJ_STATUS_FAIL; } (*cfi_array)->cfi_chips[d / 8] = calloc (1, sizeof (urj_flash_cfi_chip_t)); if (!(*cfi_array)->cfi_chips[d / 8]) { write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); urj_error_set (URJ_ERROR_OUT_OF_MEMORY, "calloc(%zd,%zd) fails", (size_t) 1, sizeof (urj_flash_cfi_chip_t)); return URJ_STATUS_FAIL; } cfi = &(*cfi_array)->cfi_chips[d / 8]->cfi; /* Identification string - see Table 6 in [1] */ cfi->identification_string.pri_id_code = read2 (PRI_VENDOR_ID_OFFSET); cfi->identification_string.pri_vendor_tbl = NULL; cfi->identification_string.alt_id_code = read2 (ALT_VENDOR_ID_OFFSET); cfi->identification_string.alt_vendor_tbl = NULL; /* System interface information - see Table 7 in [1] */ tmp = read1 (VCC_MIN_WEV_OFFSET); cfi->system_interface_info.vcc_min_wev = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; tmp = read1 (VCC_MAX_WEV_OFFSET); cfi->system_interface_info.vcc_max_wev = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; tmp = read1 (VPP_MIN_WEV_OFFSET); cfi->system_interface_info.vpp_min_wev = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; tmp = read1 (VPP_MAX_WEV_OFFSET); cfi->system_interface_info.vpp_max_wev = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; /* TODO: Add out of range checks for timeouts */ tmp = read1 (TYP_SINGLE_WRITE_TIMEOUT_OFFSET); cfi->system_interface_info.typ_single_write_timeout = tmp ? (1 << tmp) : 0; tmp = read1 (TYP_BUFFER_WRITE_TIMEOUT_OFFSET); cfi->system_interface_info.typ_buffer_write_timeout = tmp ? (1 << tmp) : 0; tmp = read1 (TYP_BLOCK_ERASE_TIMEOUT_OFFSET); cfi->system_interface_info.typ_block_erase_timeout = tmp ? (1 << tmp) : 0; tmp = read1 (TYP_CHIP_ERASE_TIMEOUT_OFFSET); cfi->system_interface_info.typ_chip_erase_timeout = tmp ? (1 << tmp) : 0; tmp = read1 (MAX_SINGLE_WRITE_TIMEOUT_OFFSET); cfi->system_interface_info.max_single_write_timeout = (tmp ? (1 << tmp) : 0) * cfi->system_interface_info.typ_single_write_timeout; tmp = read1 (MAX_BUFFER_WRITE_TIMEOUT_OFFSET); cfi->system_interface_info.max_buffer_write_timeout = (tmp ? (1 << tmp) : 0) * cfi->system_interface_info.typ_buffer_write_timeout; tmp = read1 (MAX_BLOCK_ERASE_TIMEOUT_OFFSET); cfi->system_interface_info.max_block_erase_timeout = (tmp ? (1 << tmp) : 0) * cfi->system_interface_info.typ_block_erase_timeout; tmp = read1 (MAX_CHIP_ERASE_TIMEOUT_OFFSET); cfi->system_interface_info.max_chip_erase_timeout = (tmp ? (1 << tmp) : 0) * cfi->system_interface_info.typ_chip_erase_timeout; /* Device geometry - see Table 8 in [1] */ /* TODO: Add out of range check */ cfi->device_geometry.device_size = 1 << read1 (DEVICE_SIZE_OFFSET); cfi->device_geometry.device_interface = read2 (FLASH_DEVICE_INTERFACE_OFFSET); /* TODO: Add out of range check */ cfi->device_geometry.max_bytes_write = 1 << read2 (MAX_BYTES_WRITE_OFFSET); tmp = cfi->device_geometry.number_of_erase_regions = read1 (NUMBER_OF_ERASE_REGIONS_OFFSET); cfi->device_geometry.erase_block_regions = malloc (tmp * sizeof (urj_flash_cfi_erase_block_region_t)); if (!cfi->device_geometry.erase_block_regions) { write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); urj_error_set (URJ_ERROR_OUT_OF_MEMORY, "malloc(%zd) fails", (size_t) tmp * sizeof (urj_flash_cfi_erase_block_region_t)); return URJ_STATUS_FAIL; } { int a; int i; for (i = 0, a = ERASE_BLOCK_REGION_OFFSET; i < tmp; i++, a += 4) { uint32_t y = read2 (a); uint32_t z = read2 (a + 2) << 8; if (z == 0) z = 128; cfi->device_geometry.erase_block_regions[i].erase_block_size = z; cfi->device_geometry.erase_block_regions[i]. number_of_erase_blocks = y + 1; } } pri_vendor_tbl_adr = read2 (PRI_VENDOR_TABLE_ADR_OFFSET); /* AMD CFI Primary Vendor-Specific Extended Query Table - see [3] and [4] */ if (cfi->identification_string.pri_id_code == CFI_VENDOR_AMD_SCS && pri_vendor_tbl_adr != 0) { urj_flash_cfi_amd_pri_extened_query_structure_t *pri_vendor_tbl; uint8_t major_version; uint8_t minor_version; uint8_t num_of_banks; int i; #undef A #define A(off) (adr + (pri_vendor_tbl_adr + (off)) * ba * ma) if (read1 (0) != 'P' || read1 (1) != 'R' || read1 (2) != 'I') { write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); urj_error_set (URJ_ERROR_FLASH, "CFI primary vendor table not detected"); return URJ_STATUS_FAIL; } major_version = read1 (MAJOR_VERSION_OFFSET); minor_version = read1 (MINOR_VERSION_OFFSET); if (major_version > '1' || (major_version == '1' && minor_version >= '3')) num_of_banks = read1 (BANK_ORGANIZATION_OFFSET); else num_of_banks = 0; pri_vendor_tbl = calloc (1, sizeof (urj_flash_cfi_amd_pri_extened_query_structure_t) + num_of_banks * sizeof (uint8_t)); if (!pri_vendor_tbl) { write1 (0, CFI_CMD_READ_ARRAY1); write1 (0, CFI_CMD_READ_ARRAY2); urj_error_set (URJ_ERROR_OUT_OF_MEMORY, "calloc(%zd,%zd) fails", (size_t) 1, sizeof (urj_flash_cfi_amd_pri_extened_query_structure_t) + num_of_banks * sizeof (uint8_t)); return URJ_STATUS_FAIL; } if (major_version > '1' || (major_version == '1' && minor_version >= '0')) { pri_vendor_tbl->major_version = major_version; pri_vendor_tbl->minor_version = minor_version; pri_vendor_tbl->address_sensitive_unlock = read1 (ADDRESS_SENSITIVE_UNLOCK_OFFSET); pri_vendor_tbl->erase_suspend = read1 (ERASE_SUSPEND_OFFSET); pri_vendor_tbl->sector_protect = read1 (SECTOR_PROTECT_OFFSET); pri_vendor_tbl->sector_temporary_unprotect = read1 (SECTOR_TEMPORARY_UNPROTECT_OFFSET); pri_vendor_tbl->sector_protect_scheme = read1 (SECTOR_PROTECT_SCHEME_OFFSET); pri_vendor_tbl->simultaneous_operation = read1 (SIMULTANEOUS_OPERATION_OFFSET); pri_vendor_tbl->burst_mode_type = read1 (BURST_MODE_TYPE_OFFSET); pri_vendor_tbl->page_mode_type = read1 (PAGE_MODE_TYPE_OFFSET); } if (major_version > '1' || (major_version == '1' && minor_version >= '1')) { tmp = read1 (ACC_MIN_OFFSET); pri_vendor_tbl->acc_min = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; tmp = read1 (ACC_MAX_OFFSET); pri_vendor_tbl->acc_max = ((tmp >> 4) & 0xF) * 1000 + (tmp & 0xF) * 100; pri_vendor_tbl->top_bottom_sector_flag = read1 (TOP_BOTTOM_SECTOR_FLAG_OFFSET); } if (major_version > '1' || (major_version == '1' && minor_version >= '2')) pri_vendor_tbl->program_suspend = read1 (PROGRAM_SUSPEND_OFFSET); if (major_version > '1' || (major_version == '1' && minor_version >= '3')) { if (pri_vendor_tbl->simultaneous_operation) pri_vendor_tbl->bank_organization = read1 (BANK_ORGANIZATION_OFFSET); else pri_vendor_tbl->bank_organization = 0; for (i = 0; i < pri_vendor_tbl->bank_organization; i++) pri_vendor_tbl->bank_region_info[i] = read1 (BANK_REGION_INFO_OFFSET + i * sizeof (uint8_t)); } if (major_version > '1' || (major_version == '1' && minor_version >= '4')) { pri_vendor_tbl->unlock_bypass = read1 (UNLOCK_BYPASS_OFFSET); tmp = read1 (SECSI_SECTOR_SIZE_OFFSET); pri_vendor_tbl->secsi_sector_size = tmp ? (1 << tmp) : 0; tmp = read1 (EMBEDDED_HWRST_TIMEOUT_MAX_OFFSET); pri_vendor_tbl->embedded_hwrst_timeout_max = tmp ? (1 << tmp) : 0; tmp = read1 (NON_EMBEDDED_HWRST_TIMEOUT_MAX_OFFSET); pri_vendor_tbl->non_embedded_hwrst_timeout_max = tmp ? (1 << tmp) : 0; tmp = read1 (ERASE_SUSPEND_TIMEOUT_MAX_OFFSET); pri_vendor_tbl->erase_suspend_timeout_max = tmp ? (1 << tmp) : 0; tmp = read1 (PROGRAM_SUSPEND_TIMEOUT_MAX_OFFSET); pri_vendor_tbl->program_suspend_timeout_max = tmp ? (1 << tmp) : 0; } cfi->identification_string.pri_vendor_tbl = (void *) pri_vendor_tbl; #undef A #define A(off) (adr + (off) * ba * ma) /* Reverse the order of erase block region information for top boot devices. */ if ((major_version > '1' || (major_version == '1' && minor_version >= '1')) && pri_vendor_tbl->top_bottom_sector_flag == 0x3) { uint32_t y, z; uint32_t n = cfi->device_geometry.number_of_erase_regions; for (i = 0; i < n / 2; i++) { z = cfi->device_geometry.erase_block_regions[i]. erase_block_size; y = cfi->device_geometry.erase_block_regions[i]. number_of_erase_blocks; cfi->device_geometry.erase_block_regions[i]. erase_block_size = cfi->device_geometry.erase_block_regions[n - i - 1]. erase_block_size; cfi->device_geometry.erase_block_regions[i]. number_of_erase_blocks = cfi->device_geometry.erase_block_regions[n - i - 1]. number_of_erase_blocks; cfi->device_geometry.erase_block_regions[n - i - 1]. erase_block_size = z; cfi->device_geometry.erase_block_regions[n - i - 1]. number_of_erase_blocks = y; } } }
inline unsigned char readUChar() { unsigned char c=0; read1((char*)&c); return c; }
int printinputline() { fgetsp=&fgetsdest; do {DOS_NoBytes=read1(&DOS_ByteRead, fdin); if (DOS_NoBytes == 0) return; *fgetsp=DOS_ByteRead; fgetsp++;} while (DOS_ByteRead != 10); *fgetsp=0; prs("\n\n;-"); prnum(lineno); prc(' '); lineno++; prscomment(&fgetsdest); }
// old readbook function void cBooks::readbook_readonly_old(UOXSOCKET s, P_ITEM pBook, int p) { int x, y, pos, j; unsigned char bookpage[14]="\x66\x01\x02\x40\x01\x02\x03\x00\x01\x00\x01\x00\x01"; unsigned long loopexit=0,loopexit2=0; openscript("misc.scp"); sprintf((char*)temp, "BOOK %i", calcserial(pBook->more1, pBook->more2, pBook->more3, pBook->more4)); if (!i_scripts[misc_script]->find((char*)temp)) { closescript(); return; } x=p; do { loopexit=0; do { read2(); } while ( (strcmp((char*)script1, "PAGE")) && (++loopexit < MAXLOOPS) ); x--; } while ( (x>0) && (++loopexit2 < 6666 )); closescript(); openscript("misc.scp"); sprintf((char*)temp, "PAGE %s", script2); if (!i_scripts[misc_script]->find((char*)temp)) { closescript(); return; } pos=ftell(scpfile); x=-1; y=-2; loopexit=0; do { read1(); x++; y+=strlen((char*)script1)+1; } while ( (strcmp((char*)script1, "}")) && (++loopexit < MAXLOOPS) ); y+=13; fseek(scpfile, pos, SEEK_SET); bookpage[1]=y>>8; bookpage[2]=y%256; LongToCharPtr(pBook->serial, &bookpage[3]); bookpage[9]=p>>8; bookpage[10]=p%256; bookpage[11]=x>>8; bookpage[12]=x%256; Xsend(s, bookpage, 13); for (j=0;j<x;j++) { read1(); Xsend(s, script1, strlen((char*)script1)+1); } closescript(); }
void lclcmd(int ch) { if (ch == 'd') /* dump memory */ { putx(' '); if (gethex()) { unsigned char *p; p = (unsigned char *) (int) val; if (gethex()) { newline(); prtbuf(p,val); } } } #if DBGMSG else if (ch == 'D') /* dump dbg buffer */ { newline(); int empty = dbgemp; for (int i = 0; i < dbgcnt; i++) { P_DBGMSG p = &dbgdata[empty]; float t = (float) p->time / 1000; printf("%8.3f %8s %8x %12d\n", t, p->str, (unsigned int) p->val, (int) p->val); empty++; if (empty >= MAXDBGMSG) empty = 0; while (1) { if (pollBufChar() == 0) break; } } printf("z %d x %d\n", zLoc, xLoc); } else if (ch == 'E') /* clear debug buffer */ { clrDbgBuf(); } #endif #if ENCTEST else if (ch == 'e') { printf(" counts "); fflush(stdout); if (getnum()) { encInit(); encRunCount = val; encStart(true); } else { printf(" stop[y] "); fflush(stdout); ch = getx(); if (ch == 'y') { encStop(); } } } #endif else if (ch == 't') { putx(' '); if (getnum()) { newline(); int i; int j = 0; for (i = 0; i < val; i++) { LOAD(XLDZCTL, j); read1(XRDZCTL); int testVal = j & ((1 << (zCtl_size)) - 1); if (readval.i != testVal) { setSync(); printf("%4d z testVal %8x readVal %8x\n", i, (unsigned int) testVal, (unsigned int) readval.i); clrSync(); } LOAD(XLDXCTL, j); read1(XRDXCTL); testVal = j & ((1 << (xCtl_size)) - 1); if (readval.i != testVal) { setSync(); printf("%4d x testVal %8x readVal %8x\n", i, (unsigned int) testVal, (unsigned int) readval.i); clrSync(); } j += 1; while (pollBufChar() != 0) ; } } } else if (ch == 'q') { gpioInfo(GPIOA); usartInfo(USART1); usartInfo(USART2); usartInfo(USART6); putstr1("start remcmd\n"); } else if (ch == 'r') /* read memory */ { putx(' '); if (gethex()) { printf("%x",*(int16_t *) (int) val); } } else if (ch == 'w') /* write memory */ { putx(' '); if (gethex()) { int16_t *p; p = (int16_t *) (int) val; printf(" %x ",*p); if (gethex()) { *p = val; } } } else if (ch == 'a') /* set command address */ { putx(' '); if (getnum()) addr = val; } else if (ch == 'g') /* read spi data */ { putx(' '); if (getnum()) { addr = val; /* save address */ read1(addr); /* read from device */ printf("\nread addr %x val %8lx %10ld",addr,readval.i,readval.i); } } else if (ch == 'G') /* read spi repeatedly */ { putx(' '); if (getnum()) /* enter address */ { addr = val; /* save address */ putx(' '); if (getnum()) /* enter number of tries */ { newline(); int16_t i = (int16_t) val; while (1) { read1(addr); /* read from device */ if (chRdy()) /* if character available */ { ch = chRead(); break; } if ((i != 0) && (--i <= 0)) break; } printf("spiw0 %d spiw1 %d",spiw0,spiw1); } } } else if (ch == 's') /* send val to address a */ { printf(" addr "); fflush(stdout); if (getnum()) /* read address */ { addr = val; printf(" data "); fflush(stdout); if (getnum()) /* read data */ { printf("\nsending addr %x %10ld val %8lx",addr,val,val); LOAD(addr,val); } } } else if (ch == 'p') /* set print flag */ { putx(' '); if (getnum()) { print = val; } } else if (ch == 'r') /* reset */ { LOAD(XLDZCTL,0); LOAD(XLDXCTL,0); LOAD(XLDTCTL,0); LOAD(XLDDCTL,0); } else if (ch == 'x') /* move x rel */ { putx(' '); if (getnum()) { xMoveRel(val, XMOV); } } else if (ch == 'z') /* move z rel */ { putx(' '); if (getnum()) { zMoveRel(val, XMOV); } } else if (ch == 'u') /* send debug message */ { putx(' '); if (getnum()) { dbgmsg("test",val); } } }
void readreg(char addr,char *str) { read1(addr); /* read from device */ printf("\nread addr %2x val %8lx %10ld %s",addr,readval.i,readval.i,str); }
void loop() { int64_t dts_shift = AV_NOPTS_VALUE; uint32_t buf_size = 10240; char *buf = (char *)malloc(buf_size); while(1) { uint32_t len; int idx = 0; int read_bytes = 0; if((read_bytes = read1(in_fd, &len, 4)) != 4) { if(read_bytes == 0) { _exit(0); } error("Can't read input length: %d", read_bytes); } len = ntohl(len); if(len > buf_size) { buf_size = len; free(buf); buf = (char *)malloc(buf_size); } if((read_bytes = read1(in_fd, buf, len)) != len) error("Can't read %d bytes from input: %d", len, read_bytes); int version = 0; ei_decode_version(buf, &idx, &version); int command_idx = idx; int arity = 0; if(ei_decode_tuple_header(buf, &idx, &arity) == -1) error("must pass tuple"); int t = 0; int size = 0; ei_get_type(buf, &idx, &t, &size); if(t != ERL_ATOM_EXT) error("first element must be atom"); char command[MAXATOMLEN+1]; ei_decode_atom(buf, &idx, command); arity--; if(!strcmp(command, "ping")) { pong(); continue; } if(!strcmp(command, "exit")) { return; } if(!strcmp(command, "init_input")) { if(arity != 3) error("Must provide 3 arguments to init_input command"); char content[1024]; char codec[1024]; if(ei_decode_atom(buf, &idx, content) == -1) error("Must provide content as an atom"); if(ei_decode_atom(buf, &idx, codec) == -1) error("Must provide codec as an atom"); int decoder_config_len = 0; ei_get_type(buf, &idx, &t, &decoder_config_len); if(t != ERL_BINARY_EXT) error("decoder config must be a binary"); uint8_t *decoder_config = av_mallocz(decoder_config_len + FF_INPUT_BUFFER_PADDING_SIZE); long bin_len = 0; ei_decode_binary(buf, &idx, decoder_config, &bin_len); Track *t = NULL; if(!strcmp(content, "video")) { t = &input_video; } else if(!strcmp(content, "audio")) { t = &input_audio; } else { error("Unknown media content: '%s'", content); } if(t->codec) error("Double initialization of media '%s'", content); t->codec = avcodec_find_decoder_by_name(codec); t->ctx = avcodec_alloc_context3(t->codec); if(!t->codec || !t->ctx) error("Unknown %s decoder '%s'", content, codec); t->ctx->time_base = (AVRational){1, 90}; t->ctx->extradata_size = decoder_config_len; t->ctx->extradata = decoder_config; if(avcodec_open2(t->ctx, t->codec, NULL) < 0) error("failed to allocate %s decoder", content); reply_atom("ready"); continue; } if(!strcmp(command, "init_output")) { if(arity != 4) error("Must provide 4 arguments to init_output command"); char content[1024]; char codec[1024]; if(ei_decode_atom(buf, &idx, content) == -1) error("Must provide content as an atom"); if(ei_decode_atom(buf, &idx, codec) == -1) error("Must provide codec as an atom"); long track_id = -1; if(ei_decode_long(buf, &idx, &track_id) == -1) error("track_id must be integer"); if(track_id < 1 || track_id > MAX_OUTPUT_TRACKS+1) error("track_id must be from 1 to %d", MAX_OUTPUT_TRACKS+1); track_id--; Track *t = NULL; if(!strcmp(content, "audio")) { t = &output_audio[out_audio_count++]; } else if(!strcmp(content, "video")) { t = &output_video[out_video_count++]; } else { error("invalid_content '%s'", content); } t->track_id = track_id; t->codec = avcodec_find_encoder_by_name(codec); t->ctx = avcodec_alloc_context3(t->codec); if(!t->codec || !t->ctx) error("Unknown encoder '%s'", codec); AVCodecContext* ctx = t->ctx; AVDictionary *opts = NULL; int options_count = 0; if(ei_decode_list_header(buf, &idx, &options_count) < 0) error("options must be a proplist"); while(options_count > 0) { int arity1 = 0; int t,s; ei_get_type(buf, &idx, &t, &s); if(t == ERL_NIL_EXT) { ei_skip_term(buf, &idx); break; } if(ei_decode_tuple_header(buf, &idx, &arity1) < 0) error("options must be a proper proplist"); if(arity1 != 2) error("tuples in options proplist must be arity 2"); char key[MAXATOMLEN]; if(ei_decode_atom(buf, &idx, key) == 0) { if(!strcmp(key, "width")) { long w = 0; if(ei_decode_long(buf, &idx, &w) < 0) error("width must be integer"); ctx->width = w; continue; } if(!strcmp(key, "height")) { long h = 0; if(ei_decode_long(buf, &idx, &h) < 0) error("height must be integer"); ctx->height = h; continue; } if(!strcmp(key, "bitrate")) { long b = 0; if(ei_decode_long(buf, &idx, &b) < 0) error("bitrate must be integer"); ctx->bit_rate = b; continue; } if(!strcmp(key, "sample_rate")) { long sr = 0; if(ei_decode_long(buf, &idx, &sr) < 0) error("sample_rate must be integer"); ctx->sample_rate = sr; continue; } if(!strcmp(key, "channels")) { long ch = 0; if(ei_decode_long(buf, &idx, &ch) < 0) error("channels must be integer"); ctx->channels = ch; continue; } fprintf(stderr, "Unknown key: '%s'\r\n", key); ei_skip_term(buf, &idx); continue; } else if(ei_decode_string(buf, &idx, key) == 0) { char value[MAXATOMLEN]; if(ei_decode_string(buf, &idx, value) < 0) error("key-value must be strings"); av_dict_set(&opts, key, value, 0); } else { error("Invalid options proplist"); } } if(!strcmp(content, "video")) { ctx->pix_fmt = AV_PIX_FMT_YUV420P; } if(!strcmp(content, "audio")) { ctx->sample_fmt = AV_SAMPLE_FMT_S16; ctx->profile = FF_PROFILE_AAC_MAIN; } ctx->flags |= CODEC_FLAG_GLOBAL_HEADER; ctx->time_base = (AVRational){1,90}; if(avcodec_open2(ctx, t->codec, &opts) < 0) error("failed to allocate video encoder"); AVPacket config; config.dts = config.pts = 0; config.flags = CODEC_FLAG_GLOBAL_HEADER; config.data = ctx->extradata; config.size = ctx->extradata_size; reply_avframe(&config, t->codec); continue; } if(!strcmp(command, "video_frame")) { idx = command_idx; struct video_frame *fr = read_video_frame(buf, &idx); AVPacket packet; av_new_packet(&packet, fr->body.size); memcpy(packet.data, fr->body.data, fr->body.size); packet.size = fr->body.size; packet.dts = fr->dts*90; packet.pts = fr->pts*90; packet.stream_index = fr->track_id; // if(packet_size != pkt_size) error("internal error in reading frame body"); if(fr->content == frame_content_audio) { if(!input_audio.ctx) error("input audio uninitialized"); AVFrame *decoded_frame = avcodec_alloc_frame(); int got_output = 0; int ret = avcodec_decode_audio4(input_audio.ctx, decoded_frame, &got_output, &packet); if(got_output) { reply_atom("ok"); } else { error("Got: %d, %d\r\n", ret, got_output); } free(fr); continue; } if(fr->content == frame_content_video) { if(!input_video.ctx) error("input video uninitialized"); AVFrame *decoded_frame = avcodec_alloc_frame(); int could_decode = 0; int ret = avcodec_decode_video2(input_video.ctx, decoded_frame, &could_decode, &packet); if(ret < 0) { error("failed to decode video"); } if(could_decode) { decoded_frame->pts = av_frame_get_best_effort_timestamp(decoded_frame); int sent_config = 0; AVPacket pkt; av_init_packet(&pkt); pkt.data = NULL; pkt.size = 0; int could_encode = 0; if(out_video_count <= 0) error("trying to transcode uninitialized video"); if(avcodec_encode_video2(output_video[0].ctx, &pkt, decoded_frame, &could_encode) != 0) error("Failed to encode h264"); if(could_encode) { if(dts_shift == AV_NOPTS_VALUE) { dts_shift = -pkt.dts; } pkt.dts += dts_shift; reply_avframe(&pkt, output_video[0].codec); } else if(!sent_config) { reply_atom("ok"); } free(fr); continue; } else { reply_atom("ok"); free(fr); continue; } } error("Unknown content"); } // AVCodecContext // AVPacket // AVFrame char *s = (char *)malloc(1024); ei_s_print_term(&s, buf, &command_idx); error("Unknown command: %s", s); } }