target,func,cwe_id_cleaned,label 1,"spell_suggest(int count) { char_u *line; pos_T prev_cursor = curwin->w_cursor; char_u wcopy[MAXWLEN + 2]; char_u *p; int i; int c; suginfo_T sug; suggest_T *stp; int mouse_used; int need_cap; int limit; int selected = count; int badlen = 0; int msg_scroll_save = msg_scroll; int wo_spell_save = curwin->w_p_spell; if (!curwin->w_p_spell) { did_set_spelllang(curwin); curwin->w_p_spell = TRUE; } if (*curwin->w_s->b_p_spl == NUL) { emsg(_(e_spell_checking_is_not_possible)); return; } if (VIsual_active) { // Use the Visually selected text as the bad word. But reject // a multi-line selection. if (curwin->w_cursor.lnum != VIsual.lnum) { vim_beep(BO_SPELL); return; } badlen = (int)curwin->w_cursor.col - (int)VIsual.col; if (badlen < 0) badlen = -badlen; else curwin->w_cursor.col = VIsual.col; ++badlen; end_visual_mode(); } // Find the start of the badly spelled word. else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { // No bad word or it starts after the cursor: use the word under the // cursor. curwin->w_cursor = prev_cursor; line = ml_get_curline(); p = line + curwin->w_cursor.col; // Backup to before start of word. while (p > line && spell_iswordp_nmw(p, curwin)) MB_PTR_BACK(line, p); // Forward to start of word. while (*p != NUL && !spell_iswordp_nmw(p, curwin)) MB_PTR_ADV(p); if (!spell_iswordp_nmw(p, curwin)) // No word found. { beep_flush(); return; } curwin->w_cursor.col = (colnr_T)(p - line); } // Get the word and its length. // Figure out if the word should be capitalised. need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); // Make a copy of current line since autocommands may free the line. line = vim_strsave(ml_get_curline()); if (line == NULL) goto skip; // Get the list of suggestions. Limit to 'lines' - 2 or the number in // 'spellsuggest', whatever is smaller. if (sps_limit > (int)Rows - 2) limit = (int)Rows - 2; else limit = sps_limit; spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit, TRUE, need_cap, TRUE); if (sug.su_ga.ga_len == 0) msg(_(""Sorry, no suggestions"")); else if (count > 0) { if (count > sug.su_ga.ga_len) smsg(_(""Sorry, only %ld suggestions""), (long)sug.su_ga.ga_len); } else { #ifdef FEAT_RIGHTLEFT // When 'rightleft' is set the list is drawn right-left. cmdmsg_rl = curwin->w_p_rl; if (cmdmsg_rl) msg_col = Columns - 1; #endif // List the suggestions. msg_start(); msg_row = Rows - 1; // for when 'cmdheight' > 1 lines_left = Rows; // avoid more prompt vim_snprintf((char *)IObuff, IOSIZE, _(""Change \""%.*s\"" to:""), sug.su_badlen, sug.su_badptr); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl && STRNCMP(IObuff, ""Change"", 6) == 0) { // And now the rabbit from the high hat: Avoid showing the // untranslated message rightleft. vim_snprintf((char *)IObuff, IOSIZE, "":ot \""%.*s\"" egnahC"", sug.su_badlen, sug.su_badptr); } #endif msg_puts((char *)IObuff); msg_clr_eos(); msg_putchar('\n'); msg_scroll = TRUE; for (i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); // The suggested word may replace only part of the bad word, add // the not replaced part. vim_strncpy(wcopy, stp->st_word, MAXWLEN); if (sug.su_badlen > stp->st_orglen) vim_strncpy(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen, sug.su_badlen - stp->st_orglen); vim_snprintf((char *)IObuff, IOSIZE, ""%2d"", i + 1); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) rl_mirror(IObuff); #endif msg_puts((char *)IObuff); vim_snprintf((char *)IObuff, IOSIZE, "" \""%s\"""", wcopy); msg_puts((char *)IObuff); // The word may replace more than ""su_badlen"". if (sug.su_badlen < stp->st_orglen) { vim_snprintf((char *)IObuff, IOSIZE, _("" < \""%.*s\""""), stp->st_orglen, sug.su_badptr); msg_puts((char *)IObuff); } if (p_verbose > 0) { // Add the score. if (sps_flags & (SPS_DOUBLE | SPS_BEST)) vim_snprintf((char *)IObuff, IOSIZE, "" (%s%d - %d)"", stp->st_salscore ? ""s "" : """", stp->st_score, stp->st_altscore); else vim_snprintf((char *)IObuff, IOSIZE, "" (%d)"", stp->st_score); #ifdef FEAT_RIGHTLEFT if (cmdmsg_rl) // Mirror the numbers, but keep the leading space. rl_mirror(IObuff + 1); #endif msg_advance(30); msg_puts((char *)IObuff); } msg_putchar('\n'); } #ifdef FEAT_RIGHTLEFT cmdmsg_rl = FALSE; msg_col = 0; #endif // Ask for choice. selected = prompt_for_number(&mouse_used); if (mouse_used) selected -= lines_left; lines_left = Rows; // avoid more prompt // don't delay for 'smd' in normal_cmd() msg_scroll = msg_scroll_save; } if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) { // Save the from and to text for :spellrepall. VIM_CLEAR(repl_from); VIM_CLEAR(repl_to); stp = &SUG(sug.su_ga, selected - 1); if (sug.su_badlen > stp->st_orglen) { // Replacing less than ""su_badlen"", append the remainder to // repl_to. repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, ""%s%.*s"", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { // Replacing su_badlen or more, use the whole word. repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen); repl_to = vim_strsave(stp->st_word); } // Replace the word. p = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1); if (p != NULL) { c = (int)(sug.su_badptr - line); mch_memmove(p, line, c); STRCPY(p + c, stp->st_word); STRCAT(p, sug.su_badptr + stp->st_orglen); // For redo we use a change-word command. ResetRedobuff(); AppendToRedobuff((char_u *)""ciw""); AppendToRedobuffLit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen); AppendCharToRedobuff(ESC); // ""p"" may be freed here ml_replace(curwin->w_cursor.lnum, p, FALSE); curwin->w_cursor.col = c; changed_bytes(curwin->w_cursor.lnum, c); } } else curwin->w_cursor = prev_cursor; spell_find_cleanup(&sug); skip: vim_free(line); curwin->w_p_spell = wo_spell_save; }",CWE-787,16 0,"void QuotaManager::StartEviction() { DCHECK(!temporary_storage_evictor_.get()); temporary_storage_evictor_.reset(new QuotaTemporaryStorageEvictor(this, kEvictionIntervalInMilliSeconds)); temporary_storage_evictor_->Start(); } ",none,24 1,"mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module) { mp_ubyte insData[230]; mp_sint32 smpReloc[MP_MAXINSSAMPS]; mp_ubyte nbu[MP_MAXINSSAMPS]; mp_uint32 fileSize = 0; module->cleanUp(); // this will make code much easier to read TXMHeader* header = &module->header; TXMInstrument* instr = module->instr; TXMSample* smp = module->smp; TXMPattern* phead = module->phead; // we're already out of memory here if (!phead || !instr || !smp) return MP_OUT_OF_MEMORY; fileSize = f.sizeWithBaseOffset(); f.read(&header->sig,1,17); f.read(&header->name,1,20); f.read(&header->whythis1a,1,1); header->whythis1a=0; f.read(&header->tracker,1,20); f.readWords(&header->ver,1); if (header->ver != 0x102 && header->ver != 0x103 && // untested header->ver != 0x104) return MP_LOADER_FAILED; f.readDwords(&header->hdrsize,1); header->hdrsize-=4; mp_uint32 hdrSize = 0x110; if (header->hdrsize > hdrSize) hdrSize = header->hdrsize; mp_ubyte* hdrBuff = new mp_ubyte[hdrSize]; memset(hdrBuff, 0, hdrSize); f.read(hdrBuff, 1, header->hdrsize); header->ordnum = LittleEndian::GET_WORD(hdrBuff); header->restart = LittleEndian::GET_WORD(hdrBuff+2); header->channum = LittleEndian::GET_WORD(hdrBuff+4); header->patnum = LittleEndian::GET_WORD(hdrBuff+6); header->insnum = LittleEndian::GET_WORD(hdrBuff+8); header->freqtab = LittleEndian::GET_WORD(hdrBuff+10); header->tempo = LittleEndian::GET_WORD(hdrBuff+12); header->speed = LittleEndian::GET_WORD(hdrBuff+14); memcpy(header->ord, hdrBuff+16, 256); if(header->ordnum > MP_MAXORDERS) header->ordnum = MP_MAXORDERS; if(header->insnum > MP_MAXINS) return MP_LOADER_FAILED; delete[] hdrBuff; header->mainvol=255; header->flags = XModule::MODULE_XMNOTECLIPPING | XModule::MODULE_XMARPEGGIO | XModule::MODULE_XMPORTANOTEBUFFER | XModule::MODULE_XMVOLCOLUMNVIBRATO; header->uppernotebound = 119; mp_sint32 i,y,sc; for (i=0;i<32;i++) header->pan[i]=0x80; // old version? if (header->ver == 0x102 || header->ver == 0x103) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;yinsnum;y++) { f.readDwords(&instr[y].size,1); f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); mp_uword numSamples = 0; f.readWords(&numSamples,1); if(numSamples > MP_MAXINSSAMPS) return MP_LOADER_FAILED; instr[y].samp = numSamples; if (instr[y].size == 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); memset(insData, 0, 230); if (instr[y].size - 33 > 230) return MP_OUT_OF_MEMORY; f.read(insData, 1, instr[y].size - 33); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;laddVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;scaddSongMessageLine(line); // ignore empty samples #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16; #else s+=instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } for (y=0;ypatnum;y++) { if (header->ver == 0x104 || header->ver == 0x103) { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); f.readWords(&phead[y].rows,1); f.readWords(&phead[y].patdata,1); } else { f.readDwords(&phead[y].len,1); f.read(&phead[y].ptype,1,1); phead[y].rows = (mp_uword)f.readByte()+1; f.readWords(&phead[y].patdata,1); } phead[y].effnum=2; phead[y].channum=(mp_ubyte)header->channum; phead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6]; // out of memory? if (phead[y].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[y].patternData,0,phead[y].rows*header->channum*6); if (phead[y].patdata) { mp_ubyte *buffer = new mp_ubyte[phead[y].patdata]; // out of memory? if (buffer == NULL) { return MP_OUT_OF_MEMORY; } f.read(buffer,1,phead[y].patdata); //printf(""%i\n"", phead[y].patdata); mp_sint32 pc = 0, bc = 0; for (mp_sint32 r=0;rchannum;c++) { mp_ubyte slot[5]; memset(slot,0,5); if ((buffer[pc]&128)) { mp_ubyte pb = buffer[pc]; pc++; if ((pb&1)) { //phead[y].patternData[bc]=buffer[pc]; slot[0]=buffer[pc]; pc++; } if ((pb&2)) { //phead[y].patternData[bc+1]=buffer[pc]; slot[1]=buffer[pc]; pc++; } if ((pb&4)) { //phead[y].patternData[bc+2]=buffer[pc]; slot[2]=buffer[pc]; pc++; } if ((pb&8)) { //phead[y].patternData[bc+3]=buffer[pc]; slot[3]=buffer[pc]; pc++; } if ((pb&16)) { //phead[y].patternData[bc+4]=buffer[pc]; slot[4]=buffer[pc]; pc++; } } else { //memcpy(phead[y].patternData+bc,buffer+pc,5); memcpy(slot,buffer+pc,5); pc+=5; } char gl=0; for (mp_sint32 i=0;i64) bl=64; slot[4]=(bl*261120)>>16;*/ } if ((!slot[3])&&(slot[4])) slot[3]=0x20; if (slot[3]==0xE) { slot[3]=(slot[4]>>4)+0x30; slot[4]=slot[4]&0xf; } if (slot[3]==0x21) { slot[3]=(slot[4]>>4)+0x40; slot[4]=slot[4]&0xf; } if (slot[0]==97) slot[0]=XModule::NOTE_OFF; phead[y].patternData[bc]=slot[0]; phead[y].patternData[bc+1]=slot[1]; XModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]); phead[y].patternData[bc+4]=slot[3]; phead[y].patternData[bc+5]=slot[4]; /*if ((y==3)&&(c==2)) { for (mp_sint32 bl=0;bl<6;bl++) cprintf(""%x "",phead[y].patternData[bc+bl]); cprintf(""\r\n""); getch(); };*/ /*printf(""Note : %i\r\n"",phead[y].patternData[bc]); printf(""Ins : %i\r\n"",phead[y].patternData[bc+1]); printf(""Vol : %i\r\n"",phead[y].patternData[bc+2]); printf(""Eff : %i\r\n"",phead[y].patternData[bc+3]); printf(""Effop: %i\r\n"",phead[y].patternData[bc+4]); getch();*/ bc+=6; } // for c } // for r delete[] buffer; } } if (header->ver == 0x104) { mp_sint32 s = 0; mp_sint32 e = 0; for (y=0;yinsnum;y++) { // fixes MOOH.XM loading problems // seems to store more instruments in the header than in the actual file if (f.posWithBaseOffset() >= fileSize) break; //TXMInstrument* ins = &instr[y]; f.readDwords(&instr[y].size,1); if (instr[y].size < 29) { mp_ubyte buffer[29]; memset(buffer, 0, sizeof(buffer)); f.read(buffer, 1, instr[y].size - 4); memcpy(instr[y].name, buffer, 22); instr[y].type = buffer[22]; instr[y].samp = LittleEndian::GET_WORD(buffer + 23); } else { f.read(&instr[y].name,1,22); f.read(&instr[y].type,1,1); f.readWords(&instr[y].samp,1); } if (instr[y].samp > MP_MAXINSSAMPS) return MP_LOADER_FAILED; //printf(""%i, %i\n"", instr[y].size, instr[y].samp); if (instr[y].size <= 29) { #ifdef MILKYTRACKER s+=16; #endif for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; continue; } f.readDwords(&instr[y].shsize,1); #ifdef VERBOSE printf(""%i/%i: %i, %i, %i, %s\n"",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name); #endif memset(insData, 0, 230); if (instr[y].size - 33 > 230) { //return -7; break; } f.read(insData, 1, instr[y].size - 33); /*printf(""%i\r\n"",instr[y].size); printf(""%s\r\n"",instr[y].name); printf(""%i\r\n"",instr[y].type); printf(""%i\r\n"",instr[y].samp); printf(""%i\r\n"",instr[y].shsize);*/ //getch(); memset(smpReloc, 0, sizeof(smpReloc)); if (instr[y].samp) { mp_ubyte* insDataPtr = insData; //f.read(&nbu,1,96); memcpy(nbu, insDataPtr, MP_MAXINSSAMPS); insDataPtr+=MP_MAXINSSAMPS; TEnvelope venv; TEnvelope penv; memset(&venv,0,sizeof(venv)); memset(&penv,0,sizeof(penv)); mp_sint32 k; for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } for (k = 0; k < XM_ENVELOPENUMPOINTS; k++) { penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr); penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2); insDataPtr+=4; } venv.num = *insDataPtr++; if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS; penv.num = *insDataPtr++; if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS; venv.sustain = *insDataPtr++; venv.loops = *insDataPtr++; venv.loope = *insDataPtr++; penv.sustain = *insDataPtr++; penv.loops = *insDataPtr++; penv.loope = *insDataPtr++; venv.type = *insDataPtr++; penv.type = *insDataPtr++; mp_ubyte vibtype, vibsweep, vibdepth, vibrate; mp_uword volfade; vibtype = *insDataPtr++; vibsweep = *insDataPtr++; vibdepth = *insDataPtr++; vibrate = *insDataPtr++; vibdepth<<=1; //f.readWords(&volfade,1); volfade = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; volfade<<=1; //instr[y].res = LittleEndian::GET_WORD(insDataPtr); insDataPtr+=2; for (mp_sint32 l=0;laddVolumeEnvelope(venv)) return MP_OUT_OF_MEMORY; if (!module->addPanningEnvelope(penv)) return MP_OUT_OF_MEMORY; mp_sint32 g=0, sc; for (sc=0;scaddSongMessageLine(line); #ifndef MILKYTRACKER // ignore empty samples when not being a tracker if (smp[g+s].samplen) { smpReloc[sc] = g; g++; } else smpReloc[sc] = -1; #else smpReloc[sc] = g; g++; #endif } instr[y].samp = g; for (sc = 0; sc < MP_MAXINSSAMPS; sc++) { if (smpReloc[nbu[sc]] == -1) instr[y].snum[sc] = -1; else instr[y].snum[sc] = smpReloc[nbu[sc]]+s; } for (sc=0;sc>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA, adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT), oldSize); if (result != MP_OK) return result; if (adpcm) smp[s].res = 0; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } e++; } else { for (mp_sint32 i = 0; i < 120; i++) instr[y].snum[i] = -1; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } header->smpnum=s; header->volenvnum=e; header->panenvnum=e; } else { mp_sint32 s = 0; for (y=0;yinsnum;y++) { for (sc=0;sc>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; } mp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize); if (result != MP_OK) return result; } s++; if (s>=MP_MAXSAMPLES) return MP_OUT_OF_MEMORY; } #ifdef MILKYTRACKER s+=16 - instr[y].samp; #endif } } // convert modplug stereo samples for (mp_sint32 s = 0; s < header->smpnum; s++) { if (smp[s].type & 32) { // that's what's allowed, stupid modplug tracker smp[s].type &= 3+16; if (smp[s].sample == NULL) continue; if (!(smp[s].type&16)) { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sbyte* sample = (mp_sbyte*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -128) s = -128; if (s > 127) s = 127; sample[i] = (mp_sbyte)s; } } else { smp[s].samplen>>=1; smp[s].loopstart>>=1; smp[s].looplen>>=1; mp_sword* sample = (mp_sword*)smp[s].sample; mp_sint32 samplen = smp[s].samplen; for (mp_sint32 i = 0; i < samplen; i++) { mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1; if (s < -32768) s = -32768; if (s > 32767) s = 32767; sample[i] = (mp_sword)s; } } } // correct loop type 0x03 (undefined) // will become ping pong loop // note that FT2 will refuse to load XM files with such a loop type if ((smp[s].type & 0x3) == 0x3) smp[s].type&=~1; } // correct number of patterns if necessary, otherwise the post processing will remove // the ""invalid"" patterns from the order list bool addPatterns = false; for (i = 0; i < header->ordnum; i++) if (header->ord[i]+1 > header->patnum) { header->patnum = header->ord[i]+1; addPatterns = true; } // if the pattern number has been adjusted, add some empty patterns if (addPatterns) { for (i = 0; i < header->patnum; i++) if (phead[i].patternData == NULL) { phead[i].rows = 64; phead[i].effnum = 2; phead[i].channum = (mp_ubyte)header->channum; phead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6]; // out of memory? if (phead[i].patternData == NULL) { return MP_OUT_OF_MEMORY; } memset(phead[i].patternData,0,phead[i].rows*header->channum*6); } } // check for MODPLUG extensions if (f.posWithBaseOffset() + 8 <= fileSize) { char buffer[4]; f.read(buffer, 1, 4); if (memcmp(buffer, ""text"", 4) == 0) { mp_uint32 len = f.readDword(); module->allocateSongMessage(len+1); memset(module->message, 0, len+1); f.read(module->message, 1, len); } } module->postProcessSamples(); return MP_OK; }",CWE-787,16 1,"pcl_status_read(byte * data, uint max_data, pcl_state_t * pcs) { uint count = min(max_data, pcs->status.write_pos - pcs->status.read_pos); if (count) memcpy(data, pcs->status.buffer + pcs->status.read_pos, count); pcs->status.read_pos += count; if (pcs->status.read_pos == pcs->status.write_pos) { gs_free_object(pcs->memory, pcs->status.buffer, ""status buffer""); pcs->status.write_pos = pcs->status.read_pos = 0; } return count; }",CWE-787,16 0," void DidGetHostUsage(const std::string& host, StorageType type, int64 usage) { host_ = host; type_ = type; usage_ = usage; } ",none,24 1,"LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = ""LZWDecodeCompat""; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, ""LZWDecode: Corrupted LZW table at scanline %d"", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, ""Corrupted LZW table at scanline %d"", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, ""Corrupted LZW table at scanline %d"", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, ""Wrong length of decoded "" ""string: data probably corrupted at scanline %d"", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } assert(occ >= codep->length); op += codep->length; occ -= codep->length; tp = op; do { *--tp = codep->value; } while( (codep = codep->next) != NULL ); } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, ""Not enough data at scanline %d (short %I64d bytes)"", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, ""Not enough data at scanline %d (short %llu bytes)"", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); }",CWE-787,16 1,"auth_request_get_var_expand_table_full(const struct auth_request *auth_request, auth_request_escape_func_t *escape_func, unsigned int *count) { const unsigned int auth_count = N_ELEMENTS(auth_request_var_expand_static_tab); struct var_expand_table *tab, *ret_tab; const char *orig_user, *auth_user; if (escape_func == NULL) escape_func = escape_none; /* keep the extra fields at the beginning. the last static_tab field contains the ending NULL-fields. */ tab = ret_tab = t_malloc((*count + auth_count) * sizeof(*tab)); memset(tab, 0, *count * sizeof(*tab)); tab += *count; *count += auth_count; memcpy(tab, auth_request_var_expand_static_tab, auth_count * sizeof(*tab)); tab[0].value = escape_func(auth_request->user, auth_request); tab[1].value = escape_func(t_strcut(auth_request->user, '@'), auth_request); tab[2].value = strchr(auth_request->user, '@'); if (tab[2].value != NULL) tab[2].value = escape_func(tab[2].value+1, auth_request); tab[3].value = escape_func(auth_request->service, auth_request); /* tab[4] = we have no home dir */ if (auth_request->local_ip.family != 0) tab[5].value = net_ip2addr(&auth_request->local_ip); if (auth_request->remote_ip.family != 0) tab[6].value = net_ip2addr(&auth_request->remote_ip); tab[7].value = dec2str(auth_request->client_pid); if (auth_request->mech_password != NULL) { tab[8].value = escape_func(auth_request->mech_password, auth_request); } if (auth_request->userdb_lookup) { tab[9].value = auth_request->userdb == NULL ? """" : dec2str(auth_request->userdb->userdb->id); } else { tab[9].value = auth_request->passdb == NULL ? """" : dec2str(auth_request->passdb->passdb->id); } tab[10].value = auth_request->mech_name == NULL ? """" : escape_func(auth_request->mech_name, auth_request); tab[11].value = auth_request->secured ? ""secured"" : """"; tab[12].value = dec2str(auth_request->local_port); tab[13].value = dec2str(auth_request->remote_port); tab[14].value = auth_request->valid_client_cert ? ""valid"" : """"; if (auth_request->requested_login_user != NULL) { const char *login_user = auth_request->requested_login_user; tab[15].value = escape_func(login_user, auth_request); tab[16].value = escape_func(t_strcut(login_user, '@'), auth_request); tab[17].value = strchr(login_user, '@'); if (tab[17].value != NULL) { tab[17].value = escape_func(tab[17].value+1, auth_request); } } tab[18].value = auth_request->session_id == NULL ? NULL : escape_func(auth_request->session_id, auth_request); if (auth_request->real_local_ip.family != 0) tab[19].value = net_ip2addr(&auth_request->real_local_ip); if (auth_request->real_remote_ip.family != 0) tab[20].value = net_ip2addr(&auth_request->real_remote_ip); tab[21].value = dec2str(auth_request->real_local_port); tab[22].value = dec2str(auth_request->real_remote_port); tab[23].value = strchr(auth_request->user, '@'); if (tab[23].value != NULL) { tab[23].value = escape_func(t_strcut(tab[23].value+1, '@'), auth_request); } tab[24].value = strrchr(auth_request->user, '@'); if (tab[24].value != NULL) tab[24].value = escape_func(tab[24].value+1, auth_request); tab[25].value = auth_request->master_user == NULL ? NULL : escape_func(auth_request->master_user, auth_request); tab[26].value = auth_request->session_pid == (pid_t)-1 ? NULL : dec2str(auth_request->session_pid); orig_user = auth_request->original_username != NULL ? auth_request->original_username : auth_request->user; tab[27].value = escape_func(orig_user, auth_request); tab[28].value = escape_func(t_strcut(orig_user, '@'), auth_request); tab[29].value = strchr(orig_user, '@'); if (tab[29].value != NULL) tab[29].value = escape_func(tab[29].value+1, auth_request); if (auth_request->master_user != NULL) auth_user = auth_request->master_user; else auth_user = orig_user; tab[30].value = escape_func(auth_user, auth_request); tab[31].value = escape_func(t_strcut(auth_user, '@'), auth_request); tab[32].value = strchr(auth_user, '@'); if (tab[32].value != NULL) tab[32].value = escape_func(tab[32].value+1, auth_request); if (auth_request->local_name != NULL) tab[33].value = escape_func(auth_request->local_name, auth_request); else tab[33].value = """"; return ret_tab; }",CWE-20,3 1,"static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { struct cgroup *cgrp; BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX); cgrp = cgroup_kn_lock_live(of->kn, false); if (!cgrp) return -ENODEV; spin_lock(&release_agent_path_lock); strlcpy(cgrp->root->release_agent_path, strstrip(buf), sizeof(cgrp->root->release_agent_path)); spin_unlock(&release_agent_path_lock); cgroup_kn_unlock(of->kn); return nbytes; }",CWE-269,6 1,"bool IsIdentityConsumingSwitch(const MutableGraphView& graph, const NodeDef& node) { if ((IsIdentity(node) || IsIdentityNSingleInput(node)) && node.input_size() > 0) { TensorId tensor_id = ParseTensorName(node.input(0)); if (IsTensorIdControlling(tensor_id)) { return false; } NodeDef* input_node = graph.GetNode(tensor_id.node()); return IsSwitch(*input_node); } return false; }",CWE-476,12 1,"virNodeDeviceGetMdevTypesCaps(const char *sysfspath, virMediatedDeviceTypePtr **mdev_types, size_t *nmdev_types) { virMediatedDeviceTypePtr *types = NULL; size_t ntypes = 0; size_t i; /* this could be a refresh, so clear out the old data */ for (i = 0; i < *nmdev_types; i++) virMediatedDeviceTypeFree(*mdev_types[i]); VIR_FREE(*mdev_types); *nmdev_types = 0; if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0) return -1; *mdev_types = g_steal_pointer(&types); *nmdev_types = ntypes; return 0; }",CWE-119,0 1,"ex_diffgetput(exarg_T *eap) { linenr_T lnum; int count; linenr_T off = 0; diff_T *dp; diff_T *dprev; diff_T *dfree; int idx_cur; int idx_other; int idx_from; int idx_to; int i; int added; char_u *p; aco_save_T aco; buf_T *buf; int start_skip, end_skip; int new_count; int buf_empty; int found_not_ma = FALSE; // Find the current buffer in the list of diff buffers. idx_cur = diff_buf_idx(curbuf); if (idx_cur == DB_COUNT) { emsg(_(e_current_buffer_is_not_in_diff_mode)); return; } if (*eap->arg == NUL) { // No argument: Find the other buffer in the list of diff buffers. for (idx_other = 0; idx_other < DB_COUNT; ++idx_other) if (curtab->tp_diffbuf[idx_other] != curbuf && curtab->tp_diffbuf[idx_other] != NULL) { if (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[idx_other]->b_p_ma) break; found_not_ma = TRUE; } if (idx_other == DB_COUNT) { if (found_not_ma) emsg(_(e_no_other_buffer_in_diff_mode_is_modifiable)); else emsg(_(e_no_other_buffer_in_diff_mode)); return; } // Check that there isn't a third buffer in the list for (i = idx_other + 1; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != curbuf && curtab->tp_diffbuf[i] != NULL && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma)) { emsg(_(e_more_than_two_buffers_in_diff_mode_dont_know_which_one_to_use)); return; } } else { // Buffer number or pattern given. Ignore trailing white space. p = eap->arg + STRLEN(eap->arg); while (p > eap->arg && VIM_ISWHITE(p[-1])) --p; for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i) ; if (eap->arg + i == p) // digits only i = atol((char *)eap->arg); else { i = buflist_findpat(eap->arg, p, FALSE, TRUE, FALSE); if (i < 0) return; // error message already given } buf = buflist_findnr(i); if (buf == NULL) { semsg(_(e_cant_find_buffer_str), eap->arg); return; } if (buf == curbuf) return; // nothing to do idx_other = diff_buf_idx(buf); if (idx_other == DB_COUNT) { semsg(_(e_buffer_str_is_not_in_diff_mode), eap->arg); return; } } diff_busy = TRUE; // When no range given include the line above or below the cursor. if (eap->addr_count == 0) { // Make it possible that "":diffget"" on the last line gets line below // the cursor line when there is no difference above the cursor. if (eap->cmdidx == CMD_diffget && eap->line1 == curbuf->b_ml.ml_line_count && diff_check(curwin, eap->line1) == 0 && (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0)) ++eap->line2; else if (eap->line1 > 0) --eap->line1; } if (eap->cmdidx == CMD_diffget) { idx_from = idx_other; idx_to = idx_cur; } else { idx_from = idx_cur; idx_to = idx_other; // Need to make the other buffer the current buffer to be able to make // changes in it. // set curwin/curbuf to buf and save a few things aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]); } // May give the warning for a changed buffer here, which can trigger the // FileChangedRO autocommand, which may do nasty things and mess // everything up. if (!curbuf->b_changed) { change_warning(0); if (diff_buf_idx(curbuf) != idx_to) { emsg(_(e_buffer_changed_unexpectedly)); goto theend; } } dprev = NULL; for (dp = curtab->tp_first_diff; dp != NULL; ) { if (dp->df_lnum[idx_cur] > eap->line2 + off) break; // past the range that was specified dfree = NULL; lnum = dp->df_lnum[idx_to]; count = dp->df_count[idx_to]; if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off && u_save(lnum - 1, lnum + count) != FAIL) { // Inside the specified range and saving for undo worked. start_skip = 0; end_skip = 0; if (eap->addr_count > 0) { // A range was specified: check if lines need to be skipped. start_skip = eap->line1 + off - dp->df_lnum[idx_cur]; if (start_skip > 0) { // range starts below start of current diff block if (start_skip > count) { lnum += count; count = 0; } else { count -= start_skip; lnum += start_skip; } } else start_skip = 0; end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1 - (eap->line2 + off); if (end_skip > 0) { // range ends above end of current/from diff block if (idx_cur == idx_from) // :diffput { i = dp->df_count[idx_cur] - start_skip - end_skip; if (count > i) count = i; } else // :diffget { count -= end_skip; end_skip = dp->df_count[idx_from] - start_skip - count; if (end_skip < 0) end_skip = 0; } } else end_skip = 0; } buf_empty = BUFEMPTY(); added = 0; for (i = 0; i < count; ++i) { // remember deleting the last line of the buffer buf_empty = curbuf->b_ml.ml_line_count == 1; ml_delete(lnum); --added; } for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i) { linenr_T nr; nr = dp->df_lnum[idx_from] + start_skip + i; if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) break; p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, FALSE)); if (p != NULL) { ml_append(lnum + i - 1, p, 0, FALSE); vim_free(p); ++added; if (buf_empty && curbuf->b_ml.ml_line_count == 2) { // Added the first line into an empty buffer, need to // delete the dummy empty line. buf_empty = FALSE; ml_delete((linenr_T)2); } } } new_count = dp->df_count[idx_to] + added; dp->df_count[idx_to] = new_count; if (start_skip == 0 && end_skip == 0) { // Check if there are any other buffers and if the diff is // equal in them. for (i = 0; i < DB_COUNT; ++i) if (curtab->tp_diffbuf[i] != NULL && i != idx_from && i != idx_to && !diff_equal_entry(dp, idx_from, i)) break; if (i == DB_COUNT) { // delete the diff entry, the buffers are now equal here dfree = dp; dp = dp->df_next; if (dprev == NULL) curtab->tp_first_diff = dp; else dprev->df_next = dp; } } // Adjust marks. This will change the following entries! if (added != 0) { mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added); if (curwin->w_cursor.lnum >= lnum) { // Adjust the cursor position if it's in/after the changed // lines. if (curwin->w_cursor.lnum >= lnum + count) curwin->w_cursor.lnum += added; else if (added < 0) curwin->w_cursor.lnum = lnum; } } changed_lines(lnum, 0, lnum + count, (long)added); if (dfree != NULL) { // Diff is deleted, update folds in other windows. #ifdef FEAT_FOLDING diff_fold_update(dfree, idx_to); #endif vim_free(dfree); } else // mark_adjust() may have changed the count in a wrong way dp->df_count[idx_to] = new_count; // When changing the current buffer, keep track of line numbers if (idx_cur == idx_to) off += added; } // If before the range or not deleted, go to next diff. if (dfree == NULL) { dprev = dp; dp = dp->df_next; } } // restore curwin/curbuf and a few other things if (eap->cmdidx != CMD_diffget) { // Syncing undo only works for the current buffer, but we change // another buffer. Sync undo if the command was typed. This isn't // 100% right when "":diffput"" is used in a function or mapping. if (KeyTyped) u_sync(FALSE); aucmd_restbuf(&aco); } theend: diff_busy = FALSE; if (diff_need_update) ex_diffupdate(NULL); // Check that the cursor is on a valid character and update its // position. When there were filler lines the topline has become // invalid. check_cursor(); changed_line_abv_curs(); if (diff_need_update) // redraw already done by ex_diffupdate() diff_need_update = FALSE; else { // Also need to redraw the other buffers. diff_redraw(FALSE); apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf); } }",CWE-416,10 1,"jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; JAS_DBGLOG(100, (""jp2_decode(%p, \""%s\"")\n"", in, optstr)); if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf(""error: cannot get box\n""); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf(""error: expecting signature box\n""); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf(""incorrect magic number\n""); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf(""expecting file type box\n""); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf(""got box type %s\n"", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf(""error: no code stream found\n""); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf(""error: cannot decode code stream\n""); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf(""error: missing IHDR box\n""); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf(""warning: number of components mismatch\n""); } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf(""error: no components\n""); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf(""warning: component data type mismatch\n""); } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf(""error: unsupported compression type\n""); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts( dec->image))) { jas_eprintf(""warning: number of components mismatch\n""); } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf(""warning: component data type mismatch\n""); } } } else { jas_eprintf(""warning: superfluous BPCC box\n""); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf(""error: no COLR box\n""); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf(""error: failed to parse ICC profile\n""); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf(""ICC Profile CS %08x\n"", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); assert(dec->image->cmprof_); jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf(""warning: missing PCLR box or superfluous CMAP box\n""); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf(""warning: missing CMAP box or superfluous PCLR box\n""); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf(""error: invalid component number in CMAP box\n""); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf(""error: invalid CMAP LUT index\n""); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, sizeof(uint_fast16_t)))) { jas_eprintf(""error: no memory\n""); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #endif } } } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf(""error: invalid channel number in CDEF box\n""); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf(""error: no components\n""); goto error; } #if 0 jas_eprintf(""no of components is %d\n"", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; }",CWE-125,1 0," virtual void SaveCellularNetwork(const CellularNetwork* network) { DCHECK(network); if (!EnsureCrosLoaded() || !network) return; SetAutoConnect(network->service_path().c_str(), network->auto_connect()); } ",none,24 0," virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) { network_manager_observers_.RemoveObserver(observer); } ",none,24 0,"WifiNetwork::WifiNetwork(const WifiNetwork& network) : WirelessNetwork(network) { encryption_ = network.encryption(); passphrase_ = network.passphrase(); identity_ = network.identity(); cert_path_ = network.cert_path(); } ",none,24 1,"cvtchar(register const char *sp) /* convert a character to a terminfo push */ { unsigned char c = 0; int len; switch (*sp) { case '\\': switch (*++sp) { case '\'': case '$': case '\\': case '%': c = UChar(*sp); len = 2; break; case '\0': c = '\\'; len = 1; break; case '0': case '1': case '2': case '3': len = 1; while (isdigit(UChar(*sp))) { c = UChar(8 * c + (*sp++ - '0')); len++; } break; default: c = UChar(*sp); len = (c != '\0') ? 2 : 1; break; } break; case '^': c = UChar(*++sp); if (c == '?') c = 127; else c &= 0x1f; len = 2; break; default: c = UChar(*sp); len = (c != '\0') ? 1 : 0; } if (isgraph(c) && c != ',' && c != '\'' && c != '\\' && c != ':') { dp = save_string(dp, ""%\'""); dp = save_char(dp, c); dp = save_char(dp, '\''); } else if (c != '\0') { dp = save_string(dp, ""%{""); if (c > 99) dp = save_char(dp, c / 100 + '0'); if (c > 9) dp = save_char(dp, ((int) (c / 10)) % 10 + '0'); dp = save_char(dp, c % 10 + '0'); dp = save_char(dp, '}'); } return len; }",CWE-787,16 1,"static void mkiss_close(struct tty_struct *tty) { struct mkiss *ax; write_lock_irq(&disc_data_lock); ax = tty->disc_data; tty->disc_data = NULL; write_unlock_irq(&disc_data_lock); if (!ax) return; /* * We have now ensured that nobody can start using ap from now on, but * we have to wait for all existing users to finish. */ if (!refcount_dec_and_test(&ax->refcnt)) wait_for_completion(&ax->dead); /* * Halt the transmit queue so that a new transmit cannot scribble * on our buffers */ netif_stop_queue(ax->dev); /* Free all AX25 frame buffers. */ kfree(ax->rbuff); kfree(ax->xbuff); ax->tty = NULL; unregister_netdev(ax->dev); free_netdev(ax->dev); }",CWE-416,10 1,"static void warnf(struct Configurable *config, const char *fmt, ...) { if(!(config->conf & CONF_MUTE)) { va_list ap; int len; char *ptr; char print_buffer[256]; va_start(ap, fmt); va_start(ap, fmt); len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap); va_end(ap); ptr = print_buffer; while(len > 0) { fputs(WARN_PREFIX, config->errors); if(len > (int)WARN_TEXTWIDTH) { int cut = WARN_TEXTWIDTH-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } fwrite(ptr, cut + 1, 1, config->errors); fputs(""\n"", config->errors); ptr += cut+1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } } }",CWE-125,1 0," virtual void RemoveCellularDataPlanObserver( CellularDataPlanObserver* observer) { data_plan_observers_.RemoveObserver(observer); } ",none,24 0,"void QuotaManager::GetGlobalUsage( StorageType type, GlobalUsageCallback* callback) { LazyInitialize(); GetUsageTracker(type)->GetGlobalUsage(callback); } ",none,24 1," void Compute(OpKernelContext* ctx) override { try { const Tensor& input = ctx->input(kInputTensorIndex); const Tensor& input_min_vec = ctx->input(kInputMinVecIndex); float* input_min_vec_data = (float*)const_cast( static_cast(input_min_vec.flat().data())); const Tensor& input_max_vec = ctx->input(kInputMaxVecIndex); float* input_max_vec_data = (float*)const_cast( static_cast(input_max_vec.flat().data())); const Tensor& input_requested_min = ctx->input(this->kRequestMinIndex); const float input_requested_min_float = input_requested_min.flat()(0); const Tensor& input_requested_max = ctx->input(this->kRequestMaxIndex); const float input_requested_max_float = input_requested_max.flat()(0); size_t depth = input_min_vec.NumElements(); OP_REQUIRES( ctx, input.dims() == 4, errors::InvalidArgument(""Current RequantizePerChannel operator"" ""supports 4D tensors only."")); OP_REQUIRES( ctx, input_min_vec.dim_size(0) == depth, errors::InvalidArgument(""input_min has incorrect size, expected "", depth, "" was "", input_min_vec.dim_size(0))); OP_REQUIRES( ctx, input_max_vec.dim_size(0) == depth, errors::InvalidArgument(""input_max has incorrect size, expected "", depth, "" was "", input_max_vec.dim_size(0))); if (out_type_ == DT_QINT8) DCHECK(input_requested_min_float < 0.0f); const float factor = (out_type_ == DT_QINT8) ? 127.0f : 255.0f; const float requested_min_max = std::max(std::abs(input_requested_min_float), std::abs(input_requested_max_float)); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputTensorIndex, input.shape(), &output)); std::vector scales(depth); for (int i = 0; i < depth; ++i) { float min_max_from_vec = std::max(std::abs(input_min_vec_data[i]), std::abs(input_max_vec_data[i])); scales[i] = factor * (min_max_from_vec / requested_min_max / static_cast(1L << 31)); } mkldnn::primitive_attr reorder_attr; reorder_attr.set_output_scales(2, scales); memory::dims dims_mkl_order = TFShapeToMklDnnDimsInNCHW(input.shape(), FORMAT_NHWC); memory::desc input_md = memory::desc(dims_mkl_order, MklDnnType(), memory::format_tag::nhwc); memory::desc output_md = (out_type_ == DT_QINT8) ? memory::desc(dims_mkl_order, MklDnnType(), memory::format_tag::nhwc) : memory::desc(dims_mkl_order, MklDnnType(), memory::format_tag::nhwc); void* input_buf = static_cast(const_cast(input.flat().data())); void* output_buf; if (out_type_ == DT_QINT8) { output_buf = static_cast( const_cast(output->flat().data())); } else { output_buf = static_cast( const_cast(output->flat().data())); } std::unique_ptr input_mem_prim( new memory(input_md, cpu_engine_, input_buf)); std::unique_ptr output_mem_prim( new memory(output_md, cpu_engine_, output_buf)); mkldnn::reorder::primitive_desc reorder_pd = ReorderPd(cpu_engine_, input_mem_prim->get_desc(), cpu_engine_, output_mem_prim->get_desc(), reorder_attr); std::shared_ptr reorder_stream; MklDnnThreadPool eigen_tp(ctx); reorder_stream.reset(CreateStream(&eigen_tp, cpu_engine_)); std::unordered_map reorder_args = { {MKLDNN_ARG_FROM, *input_mem_prim}, {MKLDNN_ARG_TO, *output_mem_prim}}; std::unique_ptr reorder_prim( new mkldnn::reorder(reorder_pd)); reorder_prim->execute(*reorder_stream, reorder_args); Tensor* output_min = nullptr; Tensor* output_max = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMinIndex, {}, &output_min)); OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMaxIndex, {}, &output_max)); output_min->flat()(0) = input_requested_min_float; output_max->flat()(0) = input_requested_max_float; } catch (mkldnn::error& e) { string error_msg = ""Status: "" + std::to_string(e.status) + "", message: "" + std::string(e.message) + "", in file "" + std::string(__FILE__) + "":"" + std::to_string(__LINE__); OP_REQUIRES_OK( ctx, errors::Aborted(""Operation received an exception:"", error_msg)); } }",CWE-20,3 1,"setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * * Other useful resources: * https://github.com/systemd/systemd/blob/HEAD/src/shared/seccomp-util.c * https://github.com/moby/moby/blob/HEAD/profiles/seccomp/default.json * **** END NOTE ON CODE SHARING */ struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog), EPERM}, /* Useless old syscall */ {SCMP_SYS (uselib), EPERM}, /* Don't allow disabling accounting */ {SCMP_SYS (acct), EPERM}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt), EPERM}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl), EPERM}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key), EPERM}, {SCMP_SYS (keyctl), EPERM}, {SCMP_SYS (request_key), EPERM}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages), EPERM}, {SCMP_SYS (mbind), EPERM}, {SCMP_SYS (get_mempolicy), EPERM}, {SCMP_SYS (set_mempolicy), EPERM}, {SCMP_SYS (migrate_pages), EPERM}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare), EPERM}, {SCMP_SYS (setns), EPERM}, {SCMP_SYS (mount), EPERM}, {SCMP_SYS (umount), EPERM}, {SCMP_SYS (umount2), EPERM}, {SCMP_SYS (pivot_root), EPERM}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, /* seccomp can't look into clone3()'s struct clone_args to check whether * the flags are OK, so we have no choice but to block clone3(). * Return ENOSYS so user-space will fall back to clone(). * (GHSA-67h7-w3jq-vh4q; see also https://github.com/moby/moby/commit/9f6b562d) */ {SCMP_SYS (clone3), ENOSYS}, /* New mount manipulation APIs can also change our VFS. There's no * legitimate reason to do these in the sandbox, so block all of them * rather than thinking about which ones might be dangerous. * (GHSA-67h7-w3jq-vh4q) */ {SCMP_SYS (open_tree), ENOSYS}, {SCMP_SYS (move_mount), ENOSYS}, {SCMP_SYS (fsopen), ENOSYS}, {SCMP_SYS (fsconfig), ENOSYS}, {SCMP_SYS (fsmount), ENOSYS}, {SCMP_SYS (fspick), ENOSYS}, {SCMP_SYS (mount_setattr), ENOSYS}, }; struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open), EPERM}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace), EPERM} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed"")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, ""i386"") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, ""x86_64"") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, ""arm"") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, ""aarch64"") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter"")); if (multiarch && extra_arches != NULL) { for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter"")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++) { int scall = syscall_blocklist[i].scall; int errnum = syscall_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; int errnum = syscall_nondevel_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blocklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf"")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; }",CWE-20,3 1,"int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map response_attrs; map::iterator riter; bufferlist metadata_bl; string expires = get_s3_expiration_header(s, lastmod); if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX ""prepend-metadata"")) { dump_header(s, ""Rgwx-Object-Size"", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section(""obj_metadata""); encode_json(""attrs"", attrs, &jf); utime_t ut(lastmod); encode_json(""mtime"", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, ""Rgwx-Embedded-Metadata-Len"", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, ""Rgwx-Mtime"", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldpp_dout(this, 0) << ""ERROR: failed to decode pg ver attr, ignoring"" << dendl; } dump_header(s, ""Rgwx-Obj-PG-Ver"", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldpp_dout(this, 0) << ""ERROR: failed to decode pg ver attr, ignoring"" << dendl; } if (source_zone_short_id != 0) { dump_header(s, ""Rgwx-Source-Zone-Short-Id"", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, ""x-amz-version-id"", version_id); dump_header_if_nonempty(s, ""x-amz-expiration"", expires); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, ""x-rgw-object-type"", ""Appendable""); dump_header(s, ""x-rgw-next-append-position"", s->obj_size); } else { dump_header(s, ""x-rgw-object-type"", ""Normal""); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -ERR_INVALID_REQUEST; } if (strcmp(p->param, ""response-content-type"") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, ""X-Object-Meta-Static-Large-Object"", ""True""); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldpp_dout(this,0) << ""Error caught buffer::error couldn't decode TagSet "" << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, ""x-amz-object-lock-mode"", retention.get_mode()); dump_time_header(s, ""x-amz-object-lock-retain-until-date"", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << ""ERROR: failed to decode RGWObjectRetention"" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, ""x-amz-object-lock-legal-hold"",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << ""ERROR: failed to decode RGWObjectLegalHold"" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = ""binary/octet-stream""; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; }",CWE-79,17 1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_2 dirh; char buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer; long long start; int bytes = 0; int dir_count, size, res; struct dir_ent *ent, *cur_ent = NULL; struct dir *dir; TRACE(""squashfs_opendir: inode start block %d, offset %d\n"", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) MEM_ERROR(); dir->dir_count = 0; dir->cur_entry = NULL; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 0) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; offset = (*i)->offset; size = (*i)->data + bytes; while(bytes < size) { if(swap) { squashfs_dir_header_2 sdirh; res = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh)); if(res) SQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh); } else res = read_directory_data(&dirh, &start, &offset, sizeof(dirh)); if(res == FALSE) goto corrupted; dir_count = dirh.count + 1; TRACE(""squashfs_opendir: Read directory header @ byte position "" ""%d, %d directory entries\n"", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR(""File system corrupted: too many entries in directory\n""); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_2 sdire; res = read_directory_data(&sdire, &start, &offset, sizeof(sdire)); if(res) SQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire); } else res = read_directory_data(dire, &start, &offset, sizeof(*dire)); if(res == FALSE) goto corrupted; bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR(""File system corrupted: filename too long\n""); goto corrupted; } res = read_directory_data(dire->name, &start, &offset, dire->size + 1); if(res == FALSE) goto corrupted; dire->name[dire->size + 1] = '\0'; /* check name for invalid characters (i.e /, ., ..) */ if(check_name(dire->name, dire->size + 1) == FALSE) { ERROR(""File system corrupted: invalid characters in name\n""); goto corrupted; } TRACE(""squashfs_opendir: directory entry %s, inode "" ""%d:%d, type %d\n"", dire->name, dirh.start_block, dire->offset, dire->type); ent = malloc(sizeof(struct dir_ent)); if(ent == NULL) MEM_ERROR(); ent->name = strdup(dire->name); ent->start_block = dirh.start_block; ent->offset = dire->offset; ent->type = dire->type; ent->next = NULL; if(cur_ent == NULL) dir->dirs = ent; else cur_ent->next = ent; cur_ent = ent; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: squashfs_closedir(dir); return NULL; }",CWE-200,4 0," virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) { return false; } ",none,24 0,"Network::Network(const Network& network) { service_path_ = network.service_path(); device_path_ = network.device_path(); ip_address_ = network.ip_address(); type_ = network.type(); state_ = network.state(); error_ = network.error(); } ",none,24 1,"void simplestring_addn(simplestring* target, const char* source, int add_len) { if(target && source) { if(!target->str) { simplestring_init_str(target); } if(target->len + add_len + 1 > target->size) { /* newsize is current length + new length */ int newsize = target->len + add_len + 1; int incr = target->size * 2; /* align to SIMPLESTRING_INCR increments */ newsize = newsize - (newsize % incr) + incr; target->str = (char*)realloc(target->str, newsize); target->size = target->str ? newsize : 0; } if(target->str) { if(add_len) { memcpy(target->str + target->len, source, add_len); } target->len += add_len; target->str[target->len] = 0; /* null terminate */ } } }",CWE-119,0 0,"CellularNetwork::DataLeft CellularNetwork::data_left() const { if (data_plans_.empty()) return DATA_NORMAL; const CellularDataPlan& plan(data_plans_[0]); if (plan.plan_type == CELLULAR_DATA_PLAN_UNLIMITED) { base::TimeDelta remaining = plan.plan_end_time - plan.update_time; if (remaining <= base::TimeDelta::FromSeconds(0)) return DATA_NONE; else if (remaining <= base::TimeDelta::FromSeconds(kCellularDataVeryLowSecs)) return DATA_VERY_LOW; else if (remaining <= base::TimeDelta::FromSeconds(kCellularDataLowSecs)) return DATA_LOW; else return DATA_NORMAL; } else if (plan.plan_type == CELLULAR_DATA_PLAN_METERED_PAID || plan.plan_type == CELLULAR_DATA_PLAN_METERED_BASE) { int64 remaining = plan.plan_data_bytes - plan.data_bytes_used; if (remaining <= 0) return DATA_NONE; else if (remaining <= kCellularDataVeryLowBytes) return DATA_VERY_LOW; else if (remaining <= kCellularDataLowBytes) return DATA_LOW; else return DATA_NORMAL; } return DATA_NORMAL; } ",none,24 1,"struct nft_flow_rule *nft_flow_rule_create(struct net *net, const struct nft_rule *rule) { struct nft_offload_ctx *ctx; struct nft_flow_rule *flow; int num_actions = 0, err; struct nft_expr *expr; expr = nft_expr_first(rule); while (nft_expr_more(rule, expr)) { if (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION) num_actions++; expr = nft_expr_next(expr); } if (num_actions == 0) return ERR_PTR(-EOPNOTSUPP); flow = nft_flow_rule_alloc(num_actions); if (!flow) return ERR_PTR(-ENOMEM); expr = nft_expr_first(rule); ctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL); if (!ctx) { err = -ENOMEM; goto err_out; } ctx->net = net; ctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC; while (nft_expr_more(rule, expr)) { if (!expr->ops->offload) { err = -EOPNOTSUPP; goto err_out; } err = expr->ops->offload(ctx, flow, expr); if (err < 0) goto err_out; expr = nft_expr_next(expr); } nft_flow_rule_transfer_vlan(ctx, flow); flow->proto = ctx->dep.l3num; kfree(ctx); return flow; err_out: kfree(ctx); nft_flow_rule_destroy(flow); return ERR_PTR(err); }",CWE-269,6 1,"static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MaxTextExtent]; CINInfo cin; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; ssize_t i; PixelPacket *q; size_t extent, length; ssize_t count, y; unsigned char magick[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,""\200\052\137\327"",4) != 0))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,""dpx:file.version"",property); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,""dpx:file.filename"",property); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,""dpx:file.create_date"",property); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,""dpx:file.create_time"",property); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,""dpx:image.orientation"",""%d"", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,""dpx:image.label"",property); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,""dpx:origination.x_offset"",""%.20g"", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,""dpx:origination.y_offset"",""%.20g"", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,""dpx:origination.filename"",property); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,""dpx:origination.create_date"",property); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,""dpx:origination.create_time"",property); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,""dpx:origination.device"",property); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,""dpx:origination.model"",property); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,""dpx:origination.serial"",property); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,""dpx:film.id"",""%d"",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,""dpx:film.type"",""%d"",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,""dpx:film.offset"",""%d"", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,""dpx:film.prefix"",""%.20g"",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format, sizeof(cin.film.format)); (void) SetImageProperty(image,""dpx:film.format"",property); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,""dpx:film.frame_position"",""%.20g"", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,""dpx:film.frame_rate"",""%g"", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,""dpx:film.frame_id"",property); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,""dpx:film.slate_info"",property); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); profile=BlobToStringInfo((const void *) NULL,cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,""dpx:user.data"",profile); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,MagickFalse); quantum_type=RGBQuantum; extent=GetQuantumExtent(image,quantum_info,quantum_type); (void) extent; length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } status=SetQuantumPad(image,quantum_info,0); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { const void *stream; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; stream=ReadBlobStream(image,length,pixels,&count); if (count != (ssize_t) length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,(unsigned char *) stream,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); SetImageColorspace(image,LogColorspace); (void) CloseBlob(image); return(GetFirstImageInList(image)); }",CWE-787,16 1,"mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc) { /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */ const mrb_irep *irep = proc->body.irep; const mrb_pool_value *pool = irep->pool; const mrb_sym *syms = irep->syms; mrb_code insn; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; uint32_t a; uint16_t b; uint16_t c; mrb_sym mid; const struct mrb_irep_catch_handler *ch; #ifdef DIRECT_THREADED static const void * const optable[] = { #define OPCODE(x,_) &&L_OP_ ## x, #include ""mruby/ops.h"" #undef OPCODE }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; mrb_gc_arena_restore(mrb, ai); if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb_vm_ci_proc_set(mrb->c->ci, proc); #define regs (mrb->c->ci->stack) INIT_DISPATCH { CASE(OP_NOP, Z) { /* do nothing */ NEXT; } CASE(OP_MOVE, BB) { regs[a] = regs[b]; NEXT; } CASE(OP_LOADL, BB) { switch (pool[b].tt) { /* number */ case IREP_TT_INT32: regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32); break; case IREP_TT_INT64: #if defined(MRB_INT64) regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; #else #if defined(MRB_64BIT) if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) { regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64); break; } #endif goto L_INT_OVERFLOW; #endif case IREP_TT_BIGINT: goto L_INT_OVERFLOW; #ifndef MRB_NO_FLOAT case IREP_TT_FLOAT: regs[a] = mrb_float_value(mrb, pool[b].u.f); break; #endif default: /* should not happen (tt:string) */ regs[a] = mrb_nil_value(); break; } NEXT; } CASE(OP_LOADI, BB) { SET_FIXNUM_VALUE(regs[a], b); NEXT; } CASE(OP_LOADINEG, BB) { SET_FIXNUM_VALUE(regs[a], -b); NEXT; } CASE(OP_LOADI__1,B) goto L_LOADI; CASE(OP_LOADI_0,B) goto L_LOADI; CASE(OP_LOADI_1,B) goto L_LOADI; CASE(OP_LOADI_2,B) goto L_LOADI; CASE(OP_LOADI_3,B) goto L_LOADI; CASE(OP_LOADI_4,B) goto L_LOADI; CASE(OP_LOADI_5,B) goto L_LOADI; CASE(OP_LOADI_6,B) goto L_LOADI; CASE(OP_LOADI_7, B) { L_LOADI: SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0); NEXT; } CASE(OP_LOADI16, BS) { SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b); NEXT; } CASE(OP_LOADI32, BSS) { SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c)); NEXT; } CASE(OP_LOADSYM, BB) { SET_SYM_VALUE(regs[a], syms[b]); NEXT; } CASE(OP_LOADNIL, B) { SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_LOADSELF, B) { regs[a] = regs[0]; NEXT; } CASE(OP_LOADT, B) { SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF, B) { SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGV, BB) { mrb_value val = mrb_gv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETGV, BB) { mrb_gv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETSV, BB) { mrb_value val = mrb_vm_special_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETSV, BB) { mrb_vm_special_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIV, BB) { regs[a] = mrb_iv_get(mrb, regs[0], syms[b]); NEXT; } CASE(OP_SETIV, BB) { mrb_iv_set(mrb, regs[0], syms[b], regs[a]); NEXT; } CASE(OP_GETCV, BB) { mrb_value val; val = mrb_vm_cv_get(mrb, syms[b]); regs[a] = val; NEXT; } CASE(OP_SETCV, BB) { mrb_vm_cv_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETIDX, B) { mrb_value va = regs[a], vb = regs[a+1]; switch (mrb_type(va)) { case MRB_TT_ARRAY: if (!mrb_integer_p(vb)) goto getidx_fallback; regs[a] = mrb_ary_entry(va, mrb_integer(vb)); break; case MRB_TT_HASH: regs[a] = mrb_hash_get(mrb, va, vb); break; case MRB_TT_STRING: switch (mrb_type(vb)) { case MRB_TT_INTEGER: case MRB_TT_STRING: case MRB_TT_RANGE: regs[a] = mrb_str_aref(mrb, va, vb, mrb_undef_value()); break; default: goto getidx_fallback; } break; default: getidx_fallback: mid = MRB_OPSYM(aref); goto L_SEND_SYM; } NEXT; } CASE(OP_SETIDX, B) { c = 2; mid = MRB_OPSYM(aset); SET_NIL_VALUE(regs[a+3]); goto L_SENDB_SYM; } CASE(OP_GETCONST, BB) { regs[a] = mrb_vm_const_get(mrb, syms[b]); NEXT; } CASE(OP_SETCONST, BB) { mrb_vm_const_set(mrb, syms[b], regs[a]); NEXT; } CASE(OP_GETMCNST, BB) { regs[a] = mrb_const_get(mrb, regs[a], syms[b]); NEXT; } CASE(OP_SETMCNST, BB) { mrb_const_set(mrb, regs[a+1], syms[b], regs[a]); NEXT; } CASE(OP_GETUPVAR, BBB) { mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (e && b < MRB_ENV_LEN(e)) { *regs_a = e->stack[b]; } else { *regs_a = mrb_nil_value(); } NEXT; } CASE(OP_SETUPVAR, BBB) { struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP, S) { pc += (int16_t)a; JUMP; } CASE(OP_JMPIF, BS) { if (mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNOT, BS) { if (!mrb_test(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPNIL, BS) { if (mrb_nil_p(regs[a])) { pc += (int16_t)b; JUMP; } NEXT; } CASE(OP_JMPUW, S) { a = (uint32_t)((pc - irep->iseq) + (int16_t)a); CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) { struct RBreak *brk = (struct RBreak*)mrb->exc; mrb_value target = mrb_break_value_get(brk); mrb_assert(mrb_integer_p(target)); a = (uint32_t)mrb_integer(target); mrb_assert(a >= 0 && a < irep->ilen); } CHECKPOINT_MAIN(RBREAK_TAG_JUMP) { ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE); if (ch) { /* avoiding a jump from a catch handler into the same handler */ if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) { THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a)); } } } CHECKPOINT_END(RBREAK_TAG_JUMP); mrb->exc = NULL; /* clear break object */ pc = irep->iseq + a; JUMP; } CASE(OP_EXCEPT, B) { mrb_value exc; if (mrb->exc == NULL) { exc = mrb_nil_value(); } else { switch (mrb->exc->tt) { case MRB_TT_BREAK: case MRB_TT_EXCEPTION: exc = mrb_obj_value(mrb->exc); break; default: mrb_assert(!""bad mrb_type""); exc = mrb_nil_value(); break; } mrb->exc = NULL; } regs[a] = exc; NEXT; } CASE(OP_RESCUE, BB) { mrb_value exc = regs[a]; /* exc on stack */ mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, ""class or module required for rescue clause""); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); NEXT; } CASE(OP_RAISEIF, B) { mrb_value exc = regs[a]; if (mrb_break_p(exc)) { mrb->exc = mrb_obj_ptr(exc); goto L_BREAK; } mrb_exc_set(mrb, exc); if (mrb->exc) { goto L_RAISE; } NEXT; } CASE(OP_SSEND, BBB) { regs[a] = regs[0]; insn = OP_SEND; } goto L_SENDB; CASE(OP_SSENDB, BBB) { regs[a] = regs[0]; } goto L_SENDB; CASE(OP_SEND, BBB) goto L_SENDB; L_SEND_SYM: c = 1; /* push nil after arguments */ SET_NIL_VALUE(regs[a+2]); goto L_SENDB_SYM; CASE(OP_SENDB, BBB) L_SENDB: mid = syms[b]; L_SENDB_SYM: { mrb_callinfo *ci = mrb->c->ci; mrb_method_t m; struct RClass *cls; mrb_value recv, blk; ARGUMENT_NORMALIZE(a, &c, insn); recv = regs[a]; cls = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, c); if (MRB_METHOD_CFUNC_P(m)) { if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); mrb_vm_ci_proc_set(ci, p); recv = p->body.func(mrb, recv); } else { if (MRB_METHOD_NOARG_P(m)) { check_method_noarg(mrb, ci); } recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } ci->stack[0] = recv; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } } JUMP; CASE(OP_CALL, Z) { mrb_callinfo *ci = mrb->c->ci; mrb_value recv = ci->stack[0]; struct RProc *m = mrb_proc_ptr(recv); /* replace callinfo */ ci->u.target_class = MRB_PROC_TARGET_CLASS(m); mrb_vm_ci_proc_set(ci, m); if (MRB_PROC_ENV_P(m)) { ci->mid = MRB_PROC_ENV(m)->mid; } /* prepare stack */ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; /* pop stackpos */ ci = cipop(mrb); pc = ci->pc; ci[1].stack[0] = recv; irep = mrb->c->ci->proc->body.irep; } else { /* setup environment for calling method */ proc = m; irep = m->body.irep; if (!irep) { mrb->c->ci->stack[0] = mrb_nil_value(); a = 0; c = OP_R_NORMAL; goto L_OP_RETURN_BODY; } mrb_int nargs = mrb_ci_bidx(ci)+1; if (nargs < irep->nregs) { mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+nargs, irep->nregs-nargs); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; } pool = irep->pool; syms = irep->syms; JUMP; } CASE(OP_SUPER, BB) { mrb_method_t m; struct RClass *cls; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; const struct RProc *p = ci->proc; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(p); if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */ mid = p->e.env->mid; /* restore old mid */ } if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) { target_class = mrb_vm_ci_target_class(ci); } else if (target_class->tt == MRB_TT_MODULE) { target_class = mrb_vm_ci_target_class(ci); if (target_class->tt != MRB_TT_ICLASS) { goto super_typeerror; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { super_typeerror: ; mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR, ""self has wrong type to call super in this context""); mrb_exc_set(mrb, exc); goto L_RAISE; } ARGUMENT_NORMALIZE(a, &b, OP_SUPER); cls = target_class->super; m = mrb_method_search_vm(mrb, &cls, mid); if (MRB_METHOD_UNDEF_P(m)) { m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1); mid = MRB_SYM(method_missing); } /* push callinfo */ ci = cipush(mrb, a, 0, cls, NULL, mid, b); /* prepare stack */ ci->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; if (MRB_METHOD_PROC_P(m)) { mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m)); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; mrb_assert(!mrb_break_p(v)); if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */ if (ci->cci == CINFO_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->ci->stack[0] = v; ci = cipop(mrb); pc = ci->pc; } else { /* setup environment for calling method */ mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m))); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs); pc = irep->iseq; } JUMP; } CASE(OP_ARGARY, BS) { mrb_int m1 = (b>>11)&0x3f; mrb_int r = (b>>10)&0x1; mrb_int m2 = (b>>5)&0x1f; mrb_int kd = (b>>4)&0x1; mrb_int lv = (b>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; mrb_int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } if (kd) { regs[a+1] = stack[m1+r+m2]; regs[a+2] = stack[m1+r+m2+1]; } else { regs[a+1] = stack[m1+r+m2]; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER, W) { mrb_int m1 = MRB_ASPEC_REQ(a); mrb_int o = MRB_ASPEC_OPT(a); mrb_int r = MRB_ASPEC_REST(a); mrb_int m2 = MRB_ASPEC_POST(a); mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0; /* unused int b = MRB_ASPEC_BLOCK(a); */ mrb_int const len = m1 + o + r + m2; mrb_callinfo *ci = mrb->c->ci; mrb_int argc = ci->n; mrb_value *argv = regs+1; mrb_value * const argv0 = argv; mrb_int const kw_pos = len + kd; /* where kwhash should be */ mrb_int const blk_pos = kw_pos + 1; /* where block should be */ mrb_value blk = regs[mrb_ci_bidx(ci)]; mrb_value kdict = mrb_nil_value(); /* keyword arguments */ if (ci->nk > 0) { mrb_int kidx = mrb_ci_kidx(ci); kdict = regs[kidx]; if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) { kdict = mrb_nil_value(); ci->nk = 0; } } if (!kd && !mrb_nil_p(kdict)) { if (argc < 14) { ci->n++; argc++; /* include kdict in normal arguments */ } else if (argc == 14) { /* pack arguments and kdict */ regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]); argc = ci->n = 15; } else {/* argc == 15 */ /* push kdict to packed arguments */ mrb_ary_push(mrb, regs[1], regs[2]); } ci->nk = 0; } if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) { kdict = mrb_hash_dup(mrb, kdict); } /* arguments is passed with Array */ if (argc == 15) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } /* strict argument check */ if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } /* extract first argument array to arguments */ else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } /* rest arguments */ mrb_value rest = mrb_nil_value(); if (argc < len) { mrb_int mlen = m2; if (argc < m1+m2) { mlen = m1 < argc ? argc - m1 : 0; } /* copy mandatory and optional arguments */ if (argv0 != argv && argv) { value_move(®s[1], argv, argc-mlen); /* m1 + o */ } if (argc < m1) { stack_clear(®s[argc+1], m1-argc); } /* copy post mandatory arguments */ if (mlen) { value_move(®s[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(®s[len-m2+mlen+1], m2-mlen); } /* initialize rest arguments with empty Array */ if (r) { rest = mrb_ary_new_capa(mrb, 0); regs[m1+o+1] = rest; } /* skip initializer of passed arguments */ if (o > 0 && argc > m1+m2) pc += (argc - m1 - m2)*3; } else { mrb_int rnum = 0; if (argv0 != argv) { value_move(®s[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); regs[m1+o+1] = rest; } if (m2 > 0 && argc-m2 > m1) { value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2); } pc += o*3; } /* need to be update blk first to protect blk from GC */ regs[blk_pos] = blk; /* move block */ if (kd) { if (mrb_nil_p(kdict)) kdict = mrb_hash_new_capa(mrb, 0); regs[kw_pos] = kdict; /* set kwhash */ } /* format arguments for generated code */ mrb->c->ci->n = len; /* clear local (but non-argument) variables */ if (irep->nlocals-blk_pos-1 > 0) { stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1); } JUMP; } CASE(OP_KARG, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) { mrb_value str = mrb_format(mrb, ""missing keyword: %v"", k); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } regs[a] = mrb_hash_get(mrb, kdict, k); mrb_hash_delete_key(mrb, kdict, k); NEXT; } CASE(OP_KEY_P, BB) { mrb_value k = mrb_symbol_value(syms[b]); mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; mrb_bool key_p = FALSE; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) { key_p = mrb_hash_key_p(mrb, kdict, k); } regs[a] = mrb_bool_value(key_p); NEXT; } CASE(OP_KEYEND, Z) { mrb_int kidx = mrb_ci_kidx(mrb->c->ci); mrb_value kdict; if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) { mrb_value keys = mrb_hash_keys(mrb, kdict); mrb_value key1 = RARRAY_PTR(keys)[0]; mrb_value str = mrb_format(mrb, ""unknown keyword: %v"", key1); mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str)); goto L_RAISE; } NEXT; } CASE(OP_BREAK, B) { c = OP_R_BREAK; goto L_RETURN; } CASE(OP_RETURN_BLK, B) { c = OP_R_RETURN; goto L_RETURN; } CASE(OP_RETURN, B) c = OP_R_NORMAL; L_RETURN: { mrb_callinfo *ci; ci = mrb->c->ci; if (ci->mid) { mrb_value blk = regs[mrb_ci_bidx(ci)]; if (mrb_proc_p(blk)) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { L_RAISE: ci = mrb->c->ci; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) goto L_FTOP; goto L_CATCH; } while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) { ci = cipop(mrb); if (ci[1].cci == CINFO_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } pc = ci[0].pc; if (ci == mrb->c->cibase) { ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL); if (ch == NULL) { L_FTOP: /* fiber top */ if (mrb->c == mrb->root_c) { mrb->c->ci->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } } L_CATCH: if (ch == NULL) goto L_STOP; if (FALSE) { L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */ ci = mrb->c->ci; } proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target); } else { mrb_int acc; mrb_value v; ci = mrb->c->ci; v = regs[a]; mrb_gc_protect(mrb, v); switch (c) { case OP_R_RETURN: /* Fall through to OP_R_NORMAL otherwise */ if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { const struct RProc *dst; mrb_callinfo *cibase; cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } /* check jump destination */ while (cibase <= ci && ci->proc != dst) { if (ci->cci > CINFO_NONE) { /* jump cross C boundary */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { /* no jump destination */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci = mrb->c->ci; while (cibase <= ci && ci->proc != dst) { CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) { cibase = mrb->c->cibase; dst = top_proc(mrb, proc); } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK); ci = cipop(mrb); pc = ci->pc; } proc = ci->proc; mrb->exc = NULL; /* clear break object */ break; } /* fallthrough */ case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; c = mrb->c; if (!c->prev) { /* toplevel return */ regs[irep->nlocals] = v; goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP); } if (!c->vmexec && c->prev->ci == c->prev->cibase) { mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, ""double resume""); mrb_exc_set(mrb, exc); goto L_RAISE; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) { c = mrb->c; } CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL); /* automatic yield at the end */ c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; mrb->c->status = MRB_FIBER_RUNNING; c->prev = NULL; if (c->vmexec) { mrb_gc_arena_restore(mrb, ai); c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } ci = mrb->c->ci; } CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_RETURN) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v); } CHECKPOINT_END(RBREAK_TAG_RETURN); mrb->exc = NULL; /* clear break object */ break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR, ""break from proc-closure""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK); /* break from fiber block */ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->cci > CINFO_NONE) { ci = cipop(mrb); mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { struct RBreak *brk; L_BREAK: brk = (struct RBreak*)mrb->exc; proc = mrb_break_proc_get(brk); v = mrb_break_value_get(brk); ci = mrb->c->ci; switch (mrb_break_tag_get(brk)) { #define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n); RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS) #undef DISPATCH_CHECKPOINTS default: mrb_assert(!""wrong break tag""); } } while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) { if (ci[-1].cci == CINFO_SKIP) { goto L_BREAK_ERROR; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER); ci = cipop(mrb); pc = ci->pc; } CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) { UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v); } CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET); if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } mrb->exc = NULL; /* clear break object */ break; default: /* cannot happen */ break; } mrb_assert(ci == mrb->c->ci); mrb_assert(mrb->exc == NULL); if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->cci; ci = cipop(mrb); if (acc == CINFO_SKIP || acc == CINFO_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym_name(mrb, ci->mid))); proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci[1].stack[0] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_BLKPUSH, BS) { int m1 = (b>>11)&0x3f; int r = (b>>10)&0x1; int m2 = (b>>5)&0x1f; int kd = (b>>4)&0x1; int lv = (b>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) || MRB_ENV_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2+kd])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2+kd]; NEXT; } L_INT_OVERFLOW: { mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, ""integer overflow""); mrb_exc_set(mrb, exc); } goto L_RAISE; #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH(op_name) \ /* need to check if op is overridden */ \ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { \ OP_MATH_CASE_INTEGER(op_name); \ OP_MATH_CASE_FLOAT(op_name, integer, float); \ OP_MATH_CASE_FLOAT(op_name, float, integer); \ OP_MATH_CASE_FLOAT(op_name, float, float); \ OP_MATH_CASE_STRING_##op_name(); \ default: \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATH_CASE_INTEGER(op_name) \ case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER): \ { \ mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0 #else #define OP_MATH_CASE_FLOAT(op_name, t1, t2) \ case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2): \ { \ mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif #define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW #define OP_MATH_CASE_STRING_add() \ case TYPES2(MRB_TT_STRING, MRB_TT_STRING): \ regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); \ mrb_gc_arena_restore(mrb, ai); \ break #define OP_MATH_CASE_STRING_sub() (void)0 #define OP_MATH_CASE_STRING_mul() (void)0 #define OP_MATH_OP_add + #define OP_MATH_OP_sub - #define OP_MATH_OP_mul * #define OP_MATH_TT_integer MRB_TT_INTEGER #define OP_MATH_TT_float MRB_TT_FLOAT CASE(OP_ADD, B) { OP_MATH(add); } CASE(OP_SUB, B) { OP_MATH(sub); } CASE(OP_MUL, B) { OP_MATH(mul); } CASE(OP_DIV, B) { #ifndef MRB_NO_FLOAT mrb_float x, y, f; #endif /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER): { mrb_int x = mrb_integer(regs[a]); mrb_int y = mrb_integer(regs[a+1]); mrb_int div = mrb_div_int(mrb, x, y); SET_INT_VALUE(mrb, regs[a], div); } NEXT; #ifndef MRB_NO_FLOAT case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT): x = (mrb_float)mrb_integer(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER): x = mrb_float(regs[a]); y = (mrb_float)mrb_integer(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: mid = MRB_OPSYM(div); goto L_SEND_SYM; } #ifndef MRB_NO_FLOAT f = mrb_div_float(x, y); SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } #define OP_MATHI(op_name) \ /* need to check if op is overridden */ \ switch (mrb_type(regs[a])) { \ OP_MATHI_CASE_INTEGER(op_name); \ OP_MATHI_CASE_FLOAT(op_name); \ default: \ SET_INT_VALUE(mrb,regs[a+1], b); \ mid = MRB_OPSYM(op_name); \ goto L_SEND_SYM; \ } \ NEXT; #define OP_MATHI_CASE_INTEGER(op_name) \ case MRB_TT_INTEGER: \ { \ mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z; \ if (mrb_int_##op_name##_overflow(x, y, &z)) \ OP_MATH_OVERFLOW_INT(); \ else \ SET_INT_VALUE(mrb,regs[a], z); \ } \ break #ifdef MRB_NO_FLOAT #define OP_MATHI_CASE_FLOAT(op_name) (void)0 #else #define OP_MATHI_CASE_FLOAT(op_name) \ case MRB_TT_FLOAT: \ { \ mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b; \ SET_FLOAT_VALUE(mrb, regs[a], z); \ } \ break #endif CASE(OP_ADDI, BB) { OP_MATHI(add); } CASE(OP_SUBI, BB) { OP_MATHI(sub); } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_NO_FLOAT #define OP_CMP(op,sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #else #define OP_CMP(op, sym) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\ break;\ default:\ mid = MRB_OPSYM(sym);\ goto L_SEND_SYM;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #endif CASE(OP_EQ, B) { if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==,eq); } NEXT; } CASE(OP_LT, B) { OP_CMP(<,lt); NEXT; } CASE(OP_LE, B) { OP_CMP(<=,le); NEXT; } CASE(OP_GT, B) { OP_CMP(>,gt); NEXT; } CASE(OP_GE, B) { OP_CMP(>=,ge); NEXT; } CASE(OP_ARRAY, BB) { regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARRAY2, BBB) { regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT, B) { mrb_value splat = mrb_ary_splat(mrb, regs[a+1]); if (mrb_nil_p(regs[a])) { regs[a] = splat; } else { mrb_assert(mrb_array_p(regs[a])); mrb_ary_concat(mrb, regs[a], splat); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH, BB) { mrb_assert(mrb_array_p(regs[a])); for (mrb_int i=0; i pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+pre> 2; if (pool[b].tt & IREP_TT_SFLAG) { sym = mrb_intern_static(mrb, pool[b].u.str, len); } else { sym = mrb_intern(mrb, pool[b].u.str, len); } regs[a] = mrb_symbol_value(sym); NEXT; } CASE(OP_STRING, BB) { mrb_int len; mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0); len = pool[b].tt >> 2; if (pool[b].tt & IREP_TT_SFLAG) { regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len); } else { regs[a] = mrb_str_new(mrb, pool[b].u.str, len); } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_STRCAT, B) { mrb_assert(mrb_string_p(regs[a])); mrb_str_concat(mrb, regs[a], regs[a+1]); NEXT; } CASE(OP_HASH, BB) { mrb_value hash = mrb_hash_new_capa(mrb, b); int i; int lim = a+b*2; for (i=a; ireps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_BLOCK, BB) { c = OP_L_BLOCK; goto L_MAKE_LAMBDA; } CASE(OP_METHOD, BB) { c = OP_L_METHOD; goto L_MAKE_LAMBDA; } CASE(OP_RANGE_INC, B) { regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], FALSE); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_RANGE_EXC, B) { regs[a] = mrb_range_new(mrb, regs[a], regs[a+1], TRUE); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS, B) { regs[a] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS, BB) { struct RClass *c = 0, *baseclass; mrb_value base, super; mrb_sym id = syms[b]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE, BB) { struct RClass *cls = 0, *baseclass; mrb_value base; mrb_sym id = syms[b]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); if (!baseclass) baseclass = mrb->object_class; base = mrb_obj_value(baseclass); } cls = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(cls); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC, BB) { mrb_value recv = regs[a]; struct RProc *p; const mrb_irep *nirep = irep->reps[b]; /* prepare closure */ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; /* prepare call stack */ cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0); irep = p->body.irep; pool = irep->pool; syms = irep->syms; mrb_stack_extend(mrb, irep->nregs); stack_clear(regs+1, irep->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_DEF, BB) { struct RClass *target = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; mrb_sym mid = syms[b]; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, target, mid, m); mrb_method_added(mrb, target, mid); mrb_gc_arena_restore(mrb, ai); regs[a] = mrb_symbol_value(mid); NEXT; } CASE(OP_SCLASS, B) { regs[a] = mrb_singleton_class(mrb, regs[a]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; regs[a] = mrb_obj_value(target); NEXT; } CASE(OP_ALIAS, BB) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_alias_method(mrb, target, syms[a], syms[b]); mrb_method_added(mrb, target, syms[a]); NEXT; } CASE(OP_UNDEF, B) { struct RClass *target = check_target_class(mrb); if (!target) goto L_RAISE; mrb_undef_method_id(mrb, target, syms[a]); NEXT; } CASE(OP_DEBUG, Z) { FETCH_BBB(); #ifdef MRB_USE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_NO_STDIO printf(""OP_DEBUG %d %d %d\n"", a, b, c); #else abort(); #endif #endif NEXT; } CASE(OP_ERR, B) { size_t len = pool[a].tt >> 2; mrb_value exc; mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0); exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len); mrb_exc_set(mrb, exc); goto L_RAISE; } CASE(OP_EXT1, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include ""mruby/ops.h"" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT2, Z) { insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include ""mruby/ops.h"" #undef OPCODE } pc--; NEXT; } CASE(OP_EXT3, Z) { uint8_t insn = READ_B(); switch (insn) { #define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY; #include ""mruby/ops.h"" #undef OPCODE } pc--; NEXT; } CASE(OP_STOP, Z) { /* stop VM */ CHECKPOINT_RESTORE(RBREAK_TAG_STOP) { /* do nothing */ } CHECKPOINT_MAIN(RBREAK_TAG_STOP) { UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value()); } CHECKPOINT_END(RBREAK_TAG_STOP); L_STOP: mrb->jmp = prev_jmp; if (mrb->exc) { mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION); return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { mrb_callinfo *ci = mrb->c->ci; while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) { ci = cipop(mrb); } exc_catched = TRUE; pc = ci->pc; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }",CWE-787,16 0,"void QuotaManagerProxy::RegisterClient(QuotaClient* client) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::RegisterClient, client)); return; } if (manager_) manager_->RegisterClient(client); else client->OnQuotaManagerDestroyed(); } ",none,24 1," void Compute(OpKernelContext *ctx) override { const Tensor *indices_t, *values_t, *shape_t, *dense_t; OP_REQUIRES_OK(ctx, ctx->input(""sp_indices"", &indices_t)); OP_REQUIRES_OK(ctx, ctx->input(""sp_values"", &values_t)); OP_REQUIRES_OK(ctx, ctx->input(""sp_shape"", &shape_t)); OP_REQUIRES_OK(ctx, ctx->input(""dense"", &dense_t)); // Validations. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()), errors::InvalidArgument( ""Input sp_indices should be a matrix but received shape: "", indices_t->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values_t->shape()) && TensorShapeUtils::IsVector(shape_t->shape()), errors::InvalidArgument( ""Inputs sp_values and sp_shape should be vectors "" ""but received shapes: "", values_t->shape().DebugString(), "" and "", shape_t->shape().DebugString())); OP_REQUIRES( ctx, values_t->dim_size(0) == indices_t->dim_size(0), errors::InvalidArgument( ""The first dimension of values and indices should match. ("", values_t->dim_size(0), "" vs. "", indices_t->dim_size(0), "")"")); const auto indices_mat = indices_t->matrix(); const auto shape_vec = shape_t->vec(); const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec)); const auto rhs_dims = BCast::FromShape(dense_t->shape()); BCast b(lhs_dims, rhs_dims, false); // false for keeping the same num dims. // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal // to dims in rhs (from right to left). auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) { if (lhs.size() < rhs.size()) return false; for (size_t i = 0; i < rhs.size(); ++i) { if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false; } return true; }; OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(), errors::InvalidArgument( ""SparseDenseBinaryOpShared broadcasts dense to sparse "" ""only; got incompatible shapes: ["", absl::StrJoin(lhs_dims, "",""), ""] vs. ["", absl::StrJoin(rhs_dims, "",""), ""]"")); Tensor *output_values = nullptr; Tensor dense_gathered; const int64_t nnz = indices_t->dim_size(0); OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({nnz}), &output_values)); OP_REQUIRES_OK( ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}), &dense_gathered)); bool op_is_div = false; if (absl::StrContains(ctx->op_kernel().type_string_view(), ""Div"")) { op_is_div = true; } // Pulls relevant entries from the dense side, with reshape and broadcasting // *of the dense side* taken into account. Use a TensorRef to avoid blowing // up memory. // // We can directly use the sparse indices to look up dense side, because // ""b.y_reshape()"" and ""b.y_bcast()"" are guaranteed to have rank ""ndims"". auto dense_gathered_flat = dense_gathered.flat(); const int ndims = lhs_dims.size(); switch (ndims) { #define CASE(NDIM) \ case NDIM: { \ TensorRef> rhs_ref = \ dense_t->shaped(b.y_reshape()) \ .broadcast(BCast::ToIndexArray(b.y_bcast())); \ Eigen::array idx; \ bool indices_valid = true; \ for (int i = 0; i < nnz; ++i) { \ for (int d = 0; d < NDIM; ++d) { \ idx[d] = internal::SubtleMustCopy(indices_mat(i, d)); \ if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) { \ indices_valid = false; \ } \ } \ OP_REQUIRES( \ ctx, indices_valid, \ errors::InvalidArgument(""Provided indices are out-of-bounds w.r.t. "" \ ""dense side with broadcasted shape"")); \ dense_gathered_flat(i) = rhs_ref.coeff(idx); \ if (op_is_div) { \ OP_REQUIRES(ctx, dense_gathered_flat(i) != 0, \ errors::InvalidArgument( \ ""SparseDenseCwiseDiv cannot divide by zero,"" \ ""but input dense tensor contains zero "")); \ } \ } \ break; \ } CASE(1); CASE(2); CASE(3); CASE(4); CASE(5); default: OP_REQUIRES( ctx, false, errors::InvalidArgument(""Only tensors with ranks between 1 and 5 "" ""are currently supported. Tensor rank: "", ndims)); #undef CASE } output_values->flat().device(ctx->eigen_device()) = values_t->flat().binaryExpr(dense_gathered_flat, typename Functor::func()); }",CWE-190,2 1,"static int pkey_GOST_ECcp_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { GOST_KEY_TRANSPORT *gkt = NULL; EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx); struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx); int pkey_nid = EVP_PKEY_base_id(pubk); ASN1_OBJECT *crypt_params_obj = (pkey_nid == NID_id_GostR3410_2001 || pkey_nid == NID_id_GostR3410_2001DH) ? OBJ_nid2obj(NID_id_Gost28147_89_CryptoPro_A_ParamSet) : OBJ_nid2obj(NID_id_tc26_gost_28147_param_Z); const struct gost_cipher_info *param = get_encryption_params(crypt_params_obj); unsigned char ukm[8], shared_key[32], crypted_key[44]; int ret = 0; int key_is_ephemeral = 1; gost_ctx cctx; EVP_PKEY *sec_key = EVP_PKEY_CTX_get0_peerkey(pctx); if (data->shared_ukm_size) { memcpy(ukm, data->shared_ukm, 8); } else { if (RAND_bytes(ukm, 8) <= 0) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_RNG_ERROR); return 0; } } if (!param) goto err; /* Check for private key in the peer_key of context */ if (sec_key) { key_is_ephemeral = 0; if (!gost_get0_priv_key(sec_key)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_NO_PRIVATE_PART_OF_NON_EPHEMERAL_KEYPAIR); goto err; } } else { key_is_ephemeral = 1; if (out) { sec_key = EVP_PKEY_new(); if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new()) || !EVP_PKEY_copy_parameters(sec_key, pubk) || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_ERROR_COMPUTING_SHARED_KEY); goto err; } } } if (out) { int dgst_nid = NID_undef; EVP_PKEY_get_default_digest_nid(pubk, &dgst_nid); if (dgst_nid == NID_id_GostR3411_2012_512) dgst_nid = NID_id_GostR3411_2012_256; if (!VKO_compute_key(shared_key, EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)), EVP_PKEY_get0(sec_key), ukm, 8, dgst_nid)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_ERROR_COMPUTING_SHARED_KEY); goto err; } gost_init(&cctx, param->sblock); keyWrapCryptoPro(&cctx, shared_key, ukm, key, crypted_key); } gkt = GOST_KEY_TRANSPORT_new(); if (!gkt) { goto err; } if (!ASN1_OCTET_STRING_set(gkt->key_agreement_info->eph_iv, ukm, 8)) { goto err; } if (!ASN1_OCTET_STRING_set(gkt->key_info->imit, crypted_key + 40, 4)) { goto err; } if (!ASN1_OCTET_STRING_set (gkt->key_info->encrypted_key, crypted_key + 8, 32)) { goto err; } if (key_is_ephemeral) { if (!X509_PUBKEY_set (&gkt->key_agreement_info->ephem_key, out ? sec_key : pubk)) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY); goto err; } } ASN1_OBJECT_free(gkt->key_agreement_info->cipher); gkt->key_agreement_info->cipher = OBJ_nid2obj(param->nid); if (key_is_ephemeral) EVP_PKEY_free(sec_key); if (!key_is_ephemeral) { /* Set control ""public key from client certificate used"" */ if (EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 3, NULL) <= 0) { GOSTerr(GOST_F_PKEY_GOST_ECCP_ENCRYPT, GOST_R_CTRL_CALL_FAILED); goto err; } } if ((*out_len = i2d_GOST_KEY_TRANSPORT(gkt, out ? &out : NULL)) > 0) ret = 1; OPENSSL_cleanse(shared_key, sizeof(shared_key)); GOST_KEY_TRANSPORT_free(gkt); return ret; err: OPENSSL_cleanse(shared_key, sizeof(shared_key)); if (key_is_ephemeral) EVP_PKEY_free(sec_key); GOST_KEY_TRANSPORT_free(gkt); return -1; }",CWE-787,16 1,"eval7( char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string) // after ""."" operator { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); int len; char_u *s; char_u *name_start = NULL; char_u *start_leader, *end_leader; int ret = OK; char_u *alias; /* * Initialise variable so that clear_tv() can't mistake this for a * string and free a string that isn't there. */ rettv->v_type = VAR_UNKNOWN; /* * Skip '!', '-' and '+' characters. They are handled later. */ start_leader = *arg; if (eval_leader(arg, in_vim9script()) == FAIL) return FAIL; end_leader = *arg; if (**arg == '.' && (!isdigit(*(*arg + 1)) #ifdef FEAT_FLOAT || in_old_script(2) #endif )) { semsg(_(e_invalid_expression_str), *arg); ++*arg; return FAIL; } switch (**arg) { /* * Number constant. */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': ret = eval_number(arg, rettv, evaluate, want_string); // Apply prefixed ""-"" and ""+"" now. Matters especially when // ""->"" follows. if (ret == OK && evaluate && end_leader > start_leader && rettv->v_type != VAR_BLOB) ret = eval7_leader(rettv, TRUE, start_leader, &end_leader); break; /* * String constant: ""string"". */ case '""': ret = eval_string(arg, rettv, evaluate); break; /* * Literal string constant: 'str''ing'. */ case '\'': ret = eval_lit_string(arg, rettv, evaluate); break; /* * List: [expr, expr] */ case '[': ret = eval_list(arg, rettv, evalarg, TRUE); break; /* * Dictionary: #{key: val, key: val} */ case '#': if (in_vim9script()) { ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE; } else if ((*arg)[1] == '{') { ++*arg; ret = eval_dict(arg, rettv, evalarg, TRUE); } else ret = NOTDONE; break; /* * Lambda: {arg, arg -> expr} * Dictionary: {'key': val, 'key': val} */ case '{': if (in_vim9script()) ret = NOTDONE; else ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg); if (ret == NOTDONE) ret = eval_dict(arg, rettv, evalarg, FALSE); break; /* * Option value: &name */ case '&': ret = eval_option(arg, rettv, evaluate); break; /* * Environment variable: $VAR. */ case '$': ret = eval_env_var(arg, rettv, evaluate); break; /* * Register contents: @r. */ case '@': ++*arg; if (evaluate) { if (in_vim9script() && IS_WHITE_OR_NUL(**arg)) semsg(_(e_syntax_error_at_str), *arg); else if (in_vim9script() && !valid_yank_reg(**arg, FALSE)) emsg_invreg(**arg); else { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_reg_contents(**arg, GREG_EXPR_SRC); } } if (**arg != NUL) ++*arg; break; /* * nested expression: (expression). * or lambda: (arg) => expr */ case '(': ret = NOTDONE; if (in_vim9script()) { ret = get_lambda_tv(arg, rettv, TRUE, evalarg); if (ret == OK && evaluate) { ufunc_T *ufunc = rettv->vval.v_partial->pt_func; // Compile it here to get the return type. The return // type is optional, when it's missing use t_unknown. // This is recognized in compile_return(). if (ufunc->uf_ret_type->tt_type == VAR_VOID) ufunc->uf_ret_type = &t_unknown; if (compile_def_function(ufunc, FALSE, COMPILE_TYPE(ufunc), NULL) == FAIL) { clear_tv(rettv); ret = FAIL; } } } if (ret == NOTDONE) { *arg = skipwhite_and_linebreak(*arg + 1, evalarg); ret = eval1(arg, rettv, evalarg); // recursive! *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg == ')') ++*arg; else if (ret == OK) { emsg(_(e_missing_closing_paren)); clear_tv(rettv); ret = FAIL; } } break; default: ret = NOTDONE; break; } if (ret == NOTDONE) { /* * Must be a variable or function name. * Can also be a curly-braces kind of name: {expr}. */ s = *arg; len = get_name_len(arg, &alias, evaluate, TRUE); if (alias != NULL) s = alias; if (len <= 0) ret = FAIL; else { int flags = evalarg == NULL ? 0 : evalarg->eval_flags; if (evaluate && in_vim9script() && len == 1 && *s == '_') { emsg(_(e_cannot_use_underscore_here)); ret = FAIL; } else if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(') { // ""name(..."" recursive! *arg = skipwhite(*arg); ret = eval_func(arg, evalarg, s, len, rettv, flags, NULL); } else if (flags & EVAL_CONSTANT) ret = FAIL; else if (evaluate) { // get the value of ""true"", ""false"" or a variable if (len == 4 && in_vim9script() && STRNCMP(s, ""true"", 4) == 0) { rettv->v_type = VAR_BOOL; rettv->vval.v_number = VVAL_TRUE; ret = OK; } else if (len == 5 && in_vim9script() && STRNCMP(s, ""false"", 5) == 0) { rettv->v_type = VAR_BOOL; rettv->vval.v_number = VVAL_FALSE; ret = OK; } else if (len == 4 && in_vim9script() && STRNCMP(s, ""null"", 4) == 0) { rettv->v_type = VAR_SPECIAL; rettv->vval.v_number = VVAL_NULL; ret = OK; } else { name_start = s; ret = eval_variable(s, len, 0, rettv, NULL, EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT); } } else { // skip the name check_vars(s, len); ret = OK; } } vim_free(alias); } // Handle following '[', '(' and '.' for expr[expr], expr.name, // expr(expr), expr->name(expr) if (ret == OK) ret = handle_subscript(arg, name_start, rettv, evalarg, TRUE); /* * Apply logical NOT and unary '-', from right to left, ignore '+'. */ if (ret == OK && evaluate && end_leader > start_leader) ret = eval7_leader(rettv, FALSE, start_leader, &end_leader); return ret; }",CWE-787,16 1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_3 dirh; char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer; long long start; int bytes = 0; int dir_count, size, res; struct dir_ent *ent, *cur_ent = NULL; struct dir *dir; TRACE(""squashfs_opendir: inode start block %d, offset %d\n"", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) MEM_ERROR(); dir->dir_count = 0; dir->cur_entry = NULL; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; offset = (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { if(swap) { squashfs_dir_header_3 sdirh; res = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh)); if(res) SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh); } else res = read_directory_data(&dirh, &start, &offset, sizeof(dirh)); if(res == FALSE) goto corrupted; dir_count = dirh.count + 1; TRACE(""squashfs_opendir: Read directory header @ byte position "" ""%d, %d directory entries\n"", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR(""File system corrupted: too many entries in directory\n""); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_3 sdire; res = read_directory_data(&sdire, &start, &offset, sizeof(sdire)); if(res) SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire); } else res = read_directory_data(dire, &start, &offset, sizeof(*dire)); if(res == FALSE) goto corrupted; bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR(""File system corrupted: filename too long\n""); goto corrupted; } res = read_directory_data(dire->name, &start, &offset, dire->size + 1); if(res == FALSE) goto corrupted; dire->name[dire->size + 1] = '\0'; /* check name for invalid characters (i.e /, ., ..) */ if(check_name(dire->name, dire->size + 1) == FALSE) { ERROR(""File system corrupted: invalid characters in name\n""); goto corrupted; } TRACE(""squashfs_opendir: directory entry %s, inode "" ""%d:%d, type %d\n"", dire->name, dirh.start_block, dire->offset, dire->type); ent = malloc(sizeof(struct dir_ent)); if(ent == NULL) MEM_ERROR(); ent->name = strdup(dire->name); ent->start_block = dirh.start_block; ent->offset = dire->offset; ent->type = dire->type; ent->next = NULL; if(cur_ent == NULL) dir->dirs = ent; else cur_ent->next = ent; cur_ent = ent; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: squashfs_closedir(dir); return NULL; }",CWE-200,4 1,"static void do_viewlog(HttpRequest req, HttpResponse res) { if (is_readonly(req)) { send_error(req, res, SC_FORBIDDEN, ""You do not have sufficient privileges to access this page""); return; } do_head(res, ""_viewlog"", ""View log"", 100); if ((Run.flags & Run_Log) && ! (Run.flags & Run_UseSyslog)) { FILE *f = fopen(Run.files.log, ""r""); if (f) { size_t n; char buf[512]; StringBuffer_append(res->outputbuffer, ""

""); } else { StringBuffer_append(res->outputbuffer, ""Error opening logfile: %s"", STRERROR); } } else { StringBuffer_append(res->outputbuffer, ""Cannot view logfile:
""); if (! (Run.flags & Run_Log)) StringBuffer_append(res->outputbuffer, ""Monit was started without logging""); else StringBuffer_append(res->outputbuffer, ""Monit uses syslog""); } do_foot(res); }",CWE-79,17 1,"gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor) { const int angle_rounded = (int)floor(angle * 100); if (bgcolor < 0 || bgcolor >= gdMaxColors) { return NULL; } /* impact perf a bit, but not that much. Implementation for palette images can be done at a later point. */ if (src->trueColor == 0) { if (bgcolor >= 0) { bgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]); } gdImagePaletteToTrueColor(src); } /* no interpolation needed here */ switch (angle_rounded) { case 9000: return gdImageRotate90(src, 0); case 18000: return gdImageRotate180(src, 0); case 27000: return gdImageRotate270(src, 0); } if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) { return NULL; } switch (src->interpolation_id) { case GD_NEAREST_NEIGHBOUR: return gdImageRotateNearestNeighbour(src, angle, bgcolor); break; case GD_BILINEAR_FIXED: return gdImageRotateBilinear(src, angle, bgcolor); break; case GD_BICUBIC_FIXED: return gdImageRotateBicubicFixed(src, angle, bgcolor); break; default: return gdImageRotateGeneric(src, angle, bgcolor); } return NULL; }",CWE-119,0 1,"processDataRcvd(ptcpsess_t *const __restrict__ pThis, char **buff, const int buffLen, struct syslogTime *stTime, const time_t ttGenTime, multi_submit_t *pMultiSub, unsigned *const __restrict__ pnMsgs) { DEFiRet; char c = **buff; int octatesToCopy, octatesToDiscard; if(pThis->inputState == eAtStrtFram) { if(pThis->bSuppOctetFram && isdigit((int) c)) { pThis->inputState = eInOctetCnt; pThis->iOctetsRemain = 0; pThis->eFraming = TCP_FRAMING_OCTET_COUNTING; } else if(pThis->bSPFramingFix && c == ' ') { /* Cisco very occasionally sends a SP after a LF, which * thrashes framing if not taken special care of. Here, * we permit space *in front of the next frame* and * ignore it. */ FINALIZE; } else { pThis->inputState = eInMsg; pThis->eFraming = TCP_FRAMING_OCTET_STUFFING; } } if(pThis->inputState == eInOctetCnt) { if(isdigit(c)) { pThis->iOctetsRemain = pThis->iOctetsRemain * 10 + c - '0'; } else { /* done with the octet count, so this must be the SP terminator */ DBGPRINTF(""TCP Message with octet-counter, size %d.\n"", pThis->iOctetsRemain); if(c != ' ') { errmsg.LogError(0, NO_ERRCODE, ""Framing Error in received TCP message: "" ""delimiter is not SP but has ASCII value %d."", c); } if(pThis->iOctetsRemain < 1) { /* TODO: handle the case where the octet count is 0! */ DBGPRINTF(""Framing Error: invalid octet count\n""); errmsg.LogError(0, NO_ERRCODE, ""Framing Error in received TCP message: "" ""invalid octet count %d."", pThis->iOctetsRemain); } else if(pThis->iOctetsRemain > iMaxLine) { /* while we can not do anything against it, we can at least log an indication * that something went wrong) -- rgerhards, 2008-03-14 */ DBGPRINTF(""truncating message with %d octets - max msg size is %d\n"", pThis->iOctetsRemain, iMaxLine); errmsg.LogError(0, NO_ERRCODE, ""received oversize message: size is %d bytes, "" ""max msg size is %d, truncating..."", pThis->iOctetsRemain, iMaxLine); } pThis->inputState = eInMsg; } } else { assert(pThis->inputState == eInMsg); if (pThis->eFraming == TCP_FRAMING_OCTET_STUFFING) { if(pThis->iMsg >= iMaxLine) { /* emergency, we now need to flush, no matter if we are at end of message or not... */ int i = 1; char currBuffChar; while(i < buffLen && ((currBuffChar = (*buff)[i]) != '\n' && (pThis->pLstn->pSrv->iAddtlFrameDelim == TCPSRV_NO_ADDTL_DELIMITER || currBuffChar != pThis->pLstn->pSrv->iAddtlFrameDelim))) { i++; } LogError(0, NO_ERRCODE, ""error: message received is at least %d byte larger than max msg"" "" size; message will be split starting at: \""%.*s\""\n"", i, (i < 32) ? i : 32, *buff); doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); /* we might think if it is better to ignore the rest of the * message than to treat it as a new one. Maybe this is a good * candidate for a configuration parameter... * rgerhards, 2006-12-04 */ } if ((c == '\n') || ((pThis->pLstn->pSrv->iAddtlFrameDelim != TCPSRV_NO_ADDTL_DELIMITER) && (c == pThis->pLstn->pSrv->iAddtlFrameDelim)) ) { /* record delimiter? */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } else { /* IMPORTANT: here we copy the actual frame content to the message - for BOTH framing modes! * If we have a message that is larger than the max msg size, we truncate it. This is the best * we can do in light of what the engine supports. -- rgerhards, 2008-03-14 */ if(pThis->iMsg < iMaxLine) { *(pThis->pMsg + pThis->iMsg++) = c; } } } else { assert(pThis->eFraming == TCP_FRAMING_OCTET_COUNTING); octatesToCopy = pThis->iOctetsRemain; octatesToDiscard = 0; if (buffLen < octatesToCopy) { octatesToCopy = buffLen; } if (octatesToCopy + pThis->iMsg > iMaxLine) { octatesToDiscard = octatesToCopy - (iMaxLine - pThis->iMsg); octatesToCopy = iMaxLine - pThis->iMsg; } memcpy(pThis->pMsg + pThis->iMsg, *buff, octatesToCopy); pThis->iMsg += octatesToCopy; pThis->iOctetsRemain -= (octatesToCopy + octatesToDiscard); *buff += (octatesToCopy + octatesToDiscard - 1); if (pThis->iOctetsRemain == 0) { /* we have end of frame! */ doSubmitMsg(pThis, stTime, ttGenTime, pMultiSub); ++(*pnMsgs); pThis->inputState = eAtStrtFram; } } } finalize_it: RETiRet; }",CWE-190,2 1,"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), "" Enter ReadOneMNGImage()""); image=mng_info->image; if (LocaleCompare(image_info->magick,""MNG"") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,""\212MNG\r\n\032\n"",8) != 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,""MNG"") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,""errr"",MagickPathExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Reading MNG chunk type %c%c%c%c, length: %.20g"", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,""CorruptImage""); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, ""InsufficientImageDataInFile""); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""JNGCompressNotSupported"",""`%s'"",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""DeltaPNGNotSupported"",""`%s'"",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skip to IEND.""); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""CorruptImage""); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG width: %.20g"",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG height: %.20g"",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,""WidthOrHeightExceedsLimit""); } (void) FormatLocaleString(page_geometry,MagickPathExtent, ""%.20gx%.20g+0+0"",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" repeat=%d, final_delay=%.20g, iterations=%.20g"", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""DEFI chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if (length < 2) { if (chunk) chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""CorruptImage""); } object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""Nonzero object_id in MNG-LC datastream"",""`%s'"", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""object id too large"",""`%s'"",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, ""DEFI cannot redefine a frozen MNG object"",""`%s'"", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" x_off[%d]: %.20g, y_off[%d]: %.20g"", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""FRAM chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_mode=%d"",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_delay=%.20g"",(double) frame_delay); } if (change_timeout) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_timeout=%.20g"",(double) frame_timeout); } if (change_clipping) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g"", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" subframe_width=%.20g, subframe_height=%.20g"",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" LOOP level %.20g has %.20g iterations "", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" ENDL: LOOP level %.20g has %.20g remaining iters"", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""CLON is not implemented yet"",""`%s'"", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, ""MAGN is not implemented yet for nonzero objects"", ""`%s'"",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, ""Unknown MAGN method in MNG datastream"",""`%s'"", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""PAST is not implemented yet"",""`%s'"", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""SHOW is not implemented yet"",""`%s'"", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""pHYg is not implemented."",""`%s'"",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""BASI is not implemented yet"",""`%s'"", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 13) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 15) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 17) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing %c%c%c%c chunk"",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skipping invisible object""); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Inserted transparent background layer, W=%.20g, H=%.20g"", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Seeking back to beginning of %c%c%c%c chunk"",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""exit ReadJNGImage() with error""); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing MNG MAGN chunk""); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocate magnified image""); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the rows to %.20g"", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Delete original image""); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the columns to %.20g"", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished MAGN processing""); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Crop the PNG image""); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading image datastream.""); } while (LocaleCompare(image_info->magick,""MNG"") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading all image datastreams.""); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No images found. Inserting a background layer.""); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocation failed, returning NULL.""); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" No beginning""); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""Linked list is corrupted, beginning of list not found"", ""`%s'"",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Corrupt list""); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""Linked list is corrupted; next_image is NULL"",""`%s'"", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" First image null""); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""image->next for first image is NULL but shouldn't be."", ""`%s'"",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No visible images found.""); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,""No visible images in file"",""`%s'"",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" image->delay=%.20g, final_delay=%.20g"",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Before coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g"",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g"",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Coalesce Images""); scene=image->scene; next_image=CoalesceImages(image,exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" After coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g dispose=%.20g"",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g dispose=%.20g"",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" exit ReadOneMNGImage();""); return(image); }",CWE-125,1 0,"void QuotaManager::NotifyStorageModified( QuotaClient::ID client_id, const GURL& origin, StorageType type, int64 delta) { NotifyStorageModifiedInternal(client_id, origin, type, delta, base::Time::Now()); } ",none,24 0,"static std::string WrapWithTD(std::string text) { return """" + text + """"; } ",none,24 0," virtual void RemoveNetworkObserver(const std::string& service_path, NetworkObserver* observer) { DCHECK(observer); DCHECK(service_path.size()); NetworkObserverMap::iterator map_iter = network_observers_.find(service_path); if (map_iter != network_observers_.end()) { map_iter->second->RemoveObserver(observer); if (!map_iter->second->size()) { delete map_iter->second; network_observers_.erase(map_iter++); } } } ",none,24 0,"void QuotaManager::GetStatistics( std::map* statistics) { DCHECK(statistics); if (temporary_storage_evictor_.get()) { std::map stats; temporary_storage_evictor_->GetStatistics(&stats); for (std::map::iterator p = stats.begin(); p != stats.end(); ++p) (*statistics)[p->first] = base::Int64ToString(p->second); } } ",none,24 1,"int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp) { u8 *tail; int nfrags; int esph_offset; struct page *page; struct sk_buff *trailer; int tailen = esp->tailen; if (x->encap) { int err = esp6_output_encap(x, skb, esp); if (err < 0) return err; } if (!skb_cloned(skb)) { if (tailen <= skb_tailroom(skb)) { nfrags = 1; trailer = skb; tail = skb_tail_pointer(trailer); goto skip_cow; } else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS) && !skb_has_frag_list(skb)) { int allocsize; struct sock *sk = skb->sk; struct page_frag *pfrag = &x->xfrag; esp->inplace = false; allocsize = ALIGN(tailen, L1_CACHE_BYTES); spin_lock_bh(&x->lock); if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) { spin_unlock_bh(&x->lock); goto cow; } page = pfrag->page; get_page(page); tail = page_address(page) + pfrag->offset; esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto); nfrags = skb_shinfo(skb)->nr_frags; __skb_fill_page_desc(skb, nfrags, page, pfrag->offset, tailen); skb_shinfo(skb)->nr_frags = ++nfrags; pfrag->offset = pfrag->offset + allocsize; spin_unlock_bh(&x->lock); nfrags++; skb->len += tailen; skb->data_len += tailen; skb->truesize += tailen; if (sk && sk_fullsock(sk)) refcount_add(tailen, &sk->sk_wmem_alloc); goto out; } } cow: esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb); nfrags = skb_cow_data(skb, tailen, &trailer); if (nfrags < 0) goto out; tail = skb_tail_pointer(trailer); esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset); skip_cow: esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto); pskb_put(skb, trailer, tailen); out: return nfrags; }",CWE-787,16 0," std::string host() const { return host_; } ",none,24 0," virtual const WifiNetworkVector& wifi_networks() const { return wifi_networks_; } ",none,24 0," void UpdateCellularDataPlan(const CellularDataPlanList* data_plans) { DCHECK(cellular_); cellular_->SetDataPlans(data_plans); NotifyCellularDataPlanChanged(); } ",none,24 0," void DidGetUsageAndQuotaAdditional( QuotaStatusCode status, int64 usage, int64 quota) { ++additional_callback_count_; } ",none,24 1,"static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev, RzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) { size_t i; const char *comp_dir = NULL; ut64 line_info_offset = UT64_MAX; for (i = 0; i < abbrev->count - 1; i++) { memset(&die->attr_values[i], 0, sizeof(die->attr_values[i])); buf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i], &die->attr_values[i], hdr, debug_str, debug_str_len, big_endian); RzBinDwarfAttrValue *attribute = &die->attr_values[i]; if (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) { comp_dir = attribute->string.content; } if (attribute->attr_name == DW_AT_stmt_list) { if (attribute->kind == DW_AT_KIND_CONSTANT) { line_info_offset = attribute->uconstant; } else if (attribute->kind == DW_AT_KIND_REFERENCE) { line_info_offset = attribute->reference; } } die->count++; } // If this is a compilation unit dir attribute, we want to cache it so the line info parsing // which will need this info can quickly look it up. if (comp_dir && line_info_offset != UT64_MAX) { char *name = strdup(comp_dir); if (name) { if (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) { free(name); } } } return buf; }",CWE-787,16 1,"int digest_generic_verify(struct digest *d, const unsigned char *md) { int ret; int len = digest_length(d); unsigned char *tmp; tmp = xmalloc(len); ret = digest_final(d, tmp); if (ret) goto end; ret = memcmp(md, tmp, len); ret = ret ? -EINVAL : 0; end: free(tmp); return ret; }",CWE-200,4 1," void Compute(OpKernelContext* context) override { // Get the stamp token. const Tensor* stamp_token_t; OP_REQUIRES_OK(context, context->input(""stamp_token"", &stamp_token_t)); int64_t stamp_token = stamp_token_t->scalar()(); // Get the tree ensemble proto. const Tensor* tree_ensemble_serialized_t; OP_REQUIRES_OK(context, context->input(""tree_ensemble_serialized"", &tree_ensemble_serialized_t)); std::unique_ptr result( new BoostedTreesEnsembleResource()); if (!result->InitFromSerialized( tree_ensemble_serialized_t->scalar()(), stamp_token)) { result->Unref(); OP_REQUIRES( context, false, errors::InvalidArgument(""Unable to parse tree ensemble proto."")); } // Only create one, if one does not exist already. Report status for all // other exceptions. auto status = CreateResource(context, HandleFromInput(context, 0), result.release()); if (status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES_OK(context, status); } }",CWE-416,10 0,"void QuotaManagerProxy::NotifyOriginNoLongerInUse( const GURL& origin) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyOriginNoLongerInUse, origin)); return; } if (manager_) manager_->NotifyOriginNoLongerInUse(origin); } ",none,24 0,"std::string WifiNetwork::GetEncryptionString() { switch (encryption_) { case SECURITY_UNKNOWN: break; case SECURITY_NONE: return """"; case SECURITY_WEP: return ""WEP""; case SECURITY_WPA: return ""WPA""; case SECURITY_RSN: return ""RSN""; case SECURITY_8021X: return ""8021X""; } return ""Unknown""; } ",none,24 1,"R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut32 i = 0; RBinJavaBootStrapMethod *bsm = NULL; ut64 offset = 0; RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (attr) { attr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR; attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset); offset += 2; attr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free); for (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) { // bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur); if (offset >= sz) { break; } bsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset); if (bsm) { offset += bsm->size; r_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm); } else { // TODO eprintf Failed to read the %d boot strap method. } } attr->size = offset; } return attr; }",CWE-125,1 0," void DidGetLRUOrigin(const GURL& origin) { lru_origin_ = origin; } ",none,24 1," void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth) { depth++; bool bFirst = true ; // buffer const size_t dirSize = 32; DataBuf dir(dirSize); bool bPrint = option == kpsBasic || option == kpsRecursive; do { // Read top of directory io.seek(start,BasicIo::beg); io.read(dir.pData_, 2); uint16_t dirLength = byteSwap2(dir,0,bSwap); bool tooBig = dirLength > 500; if ( tooBig ) throw Error(55); if ( bFirst && bPrint ) { out << Internal::indent(depth) << Internal::stringFormat(""STRUCTURE OF TIFF FILE (%c%c): "",c,c) << io.path() << std::endl; if ( tooBig ) out << Internal::indent(depth) << ""dirLength = "" << dirLength << std::endl; } // Read the dictionary for ( int i = 0 ; i < dirLength ; i ++ ) { if ( bFirst && bPrint ) { out << Internal::indent(depth) << "" address | tag | "" << "" type | count | offset | value\n""; } bFirst = false; io.read(dir.pData_, 12); uint16_t tag = byteSwap2(dir,0,bSwap); uint16_t type = byteSwap2(dir,2,bSwap); uint32_t count = byteSwap4(dir,4,bSwap); uint32_t offset = byteSwap4(dir,8,bSwap); // Break for unknown tag types else we may segfault. if ( !typeValid(type) ) { std::cerr << ""invalid type value detected in Image::printIFDStructure: "" << type << std::endl; start = 0; // break from do loop throw Error(56); break; // break from for loop } std::string sp = """" ; // output spacer //prepare to print the value uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data : isPrintICC(tag,option) ? count // ditto : isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays : count > 5 ? 5 : count ; uint32_t pad = isStringType(type) ? 1 : 0; uint32_t size = isStringType(type) ? 1 : is2ByteType(type) ? 2 : is4ByteType(type) ? 4 : is8ByteType(type) ? 8 : 1 ; // if ( offset > io.size() ) offset = 0; // Denial of service? DataBuf buf(size*count + pad+20); // allocate a buffer std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings) const bool bOffsetIsPointer = count*size > 4; if ( bOffsetIsPointer ) { // read into buffer size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position io.read(buf.pData_,count*size);// read io.seek(restore,BasicIo::beg); // restore } if ( bPrint ) { const uint32_t address = start + 2 + i*12 ; const std::string offsetString = bOffsetIsPointer? Internal::stringFormat(""%10u"", offset): """"; out << Internal::indent(depth) << Internal::stringFormat(""%8u | %#06x %-28s |%10s |%9u |%10s | "" ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str()); if ( isShortType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap2(buf,k*size,bSwap); sp = "" ""; } } else if ( isLongType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap4(buf,k*size,bSwap); sp = "" ""; } } else if ( isRationalType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { uint32_t a = byteSwap4(buf,k*size+0,bSwap); uint32_t b = byteSwap4(buf,k*size+4,bSwap); out << sp << a << ""/"" << b; sp = "" ""; } } else if ( isStringType(type) ) { out << sp << Internal::binaryToString(buf, kount); } sp = kount == count ? """" : "" ...""; out << sp << std::endl; if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) { for ( size_t k = 0 ; k < count ; k++ ) { size_t restore = io.tell(); uint32_t offset = byteSwap4(buf,k*size,bSwap); printIFDStructure(io,out,option,offset,bSwap,c,depth); io.seek(restore,BasicIo::beg); } } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) { size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position byte* bytes=new byte[count] ; // allocate memory io.read(bytes,count) ; // read io.seek(restore,BasicIo::beg); // restore IptcData::printStructure(out,bytes,count,depth); delete[] bytes; // free } else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) { size_t restore = io.tell(); // save uint32_t jump= 10 ; byte bytes[20] ; const char* chars = (const char*) &bytes[0] ; io.seek(offset,BasicIo::beg); // position io.read(bytes,jump ) ; // read bytes[jump]=0 ; if ( ::strcmp(""Nikon"",chars) == 0 ) { // tag is an embedded tiff byte* bytes=new byte[count-jump] ; // allocate memory io.read(bytes,count-jump) ; // read MemIo memIo(bytes,count-jump) ; // create a file printTiffStructure(memIo,out,option,depth); delete[] bytes ; // free } else { // tag is an IFD io.seek(0,BasicIo::beg); // position printIFDStructure(io,out,option,offset,bSwap,c,depth); } io.seek(restore,BasicIo::beg); // restore } } if ( isPrintXMP(tag,option) ) { buf.pData_[count]=0; out << (char*) buf.pData_; } if ( isPrintICC(tag,option) ) { out.write((const char*)buf.pData_,count); } } if ( start ) { io.read(dir.pData_, 4); start = tooBig ? 0 : byteSwap4(dir,0,bSwap); } } while (start) ; if ( bPrint ) { out << Internal::indent(depth) << ""END "" << io.path() << std::endl; } out.flush(); depth--; }",CWE-125,1 0," virtual bool wifi_connecting() const { return wifi_ ? wifi_->connecting() : false; } ",none,24 0,"Network::Network(const ServiceInfo* service) { type_ = service->type; state_ = service->state; error_ = service->error; service_path_ = SafeString(service->service_path); device_path_ = SafeString(service->device_path); is_active_ = service->is_active; ip_address_.clear(); if (EnsureCrosLoaded() && connected() && service->device_path) { IPConfigStatus* ipconfig_status = ListIPConfigs(service->device_path); if (ipconfig_status) { for (int i = 0; i < ipconfig_status->size; i++) { IPConfig ipconfig = ipconfig_status->ips[i]; if (strlen(ipconfig.address) > 0) ip_address_ = ipconfig.address; } FreeIPConfigStatus(ipconfig_status); } } } ",none,24 1,"win_close(win_T *win, int free_buf) { win_T *wp; int other_buffer = FALSE; int close_curwin = FALSE; int dir; int help_window = FALSE; tabpage_T *prev_curtab = curtab; frame_T *win_frame = win->w_frame->fr_parent; #ifdef FEAT_DIFF int had_diffmode = win->w_p_diff; #endif #ifdef MESSAGE_QUEUE int did_decrement = FALSE; #endif #if defined(FEAT_TERMINAL) && defined(FEAT_PROP_POPUP) // Can close a popup window with a terminal if the job has finished. if (may_close_term_popup() == OK) return OK; #endif if (ERROR_IF_ANY_POPUP_WINDOW) return FAIL; if (last_window()) { emsg(_(e_cannot_close_last_window)); return FAIL; } if (win->w_closing || (win->w_buffer != NULL && win->w_buffer->b_locked > 0)) return FAIL; // window is already being closed if (win_unlisted(win)) { emsg(_(e_cannot_close_autocmd_or_popup_window)); return FAIL; } if ((firstwin == aucmd_win || lastwin == aucmd_win) && one_window()) { emsg(_(e_cannot_close_window_only_autocmd_window_would_remain)); return FAIL; } // When closing the last window in a tab page first go to another tab page // and then close the window and the tab page to avoid that curwin and // curtab are invalid while we are freeing memory. if (close_last_window_tabpage(win, free_buf, prev_curtab)) return FAIL; // When closing the help window, try restoring a snapshot after closing // the window. Otherwise clear the snapshot, it's now invalid. if (bt_help(win->w_buffer)) help_window = TRUE; else clear_snapshot(curtab, SNAP_HELP_IDX); if (win == curwin) { #ifdef FEAT_JOB_CHANNEL leaving_window(curwin); #endif /* * Guess which window is going to be the new current window. * This may change because of the autocommands (sigh). */ wp = frame2win(win_altframe(win, NULL)); /* * Be careful: If autocommands delete the window or cause this window * to be the last one left, return now. */ if (wp->w_buffer != curbuf) { other_buffer = TRUE; win->w_closing = TRUE; apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); if (!win_valid(win)) return FAIL; win->w_closing = FALSE; if (last_window()) return FAIL; } win->w_closing = TRUE; apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf); if (!win_valid(win)) return FAIL; win->w_closing = FALSE; if (last_window()) return FAIL; #ifdef FEAT_EVAL // autocmds may abort script processing if (aborting()) return FAIL; #endif } #ifdef FEAT_GUI // Avoid trouble with scrollbars that are going to be deleted in // win_free(). if (gui.in_use) out_flush(); #endif #ifdef FEAT_PROP_POPUP if (popup_win_closed(win) && !win_valid(win)) return FAIL; #endif // Trigger WinClosed just before starting to free window-related resources. trigger_winclosed(win); // autocmd may have freed the window already. if (!win_valid_any_tab(win)) return OK; win_close_buffer(win, free_buf ? DOBUF_UNLOAD : 0, TRUE); if (only_one_window() && win_valid(win) && win->w_buffer == NULL && (last_window() || curtab != prev_curtab || close_last_window_tabpage(win, free_buf, prev_curtab))) { // Autocommands have closed all windows, quit now. Restore // curwin->w_buffer, otherwise writing viminfo may fail. if (curwin->w_buffer == NULL) curwin->w_buffer = curbuf; getout(0); } // Autocommands may have moved to another tab page. if (curtab != prev_curtab && win_valid_any_tab(win) && win->w_buffer == NULL) { // Need to close the window anyway, since the buffer is NULL. win_close_othertab(win, FALSE, prev_curtab); return FAIL; } // Autocommands may have closed the window already or closed the only // other window. if (!win_valid(win) || last_window() || close_last_window_tabpage(win, free_buf, prev_curtab)) return FAIL; // Now we are really going to close the window. Disallow any autocommand // to split a window to avoid trouble. // Also bail out of parse_queued_messages() to avoid it tries to update the // screen. ++split_disallowed; #ifdef MESSAGE_QUEUE ++dont_parse_messages; #endif // Free the memory used for the window and get the window that received // the screen space. wp = win_free_mem(win, &dir, NULL); if (help_window) { // Closing the help window moves the cursor back to the current window // of the snapshot. win_T *prev_win = get_snapshot_curwin(SNAP_HELP_IDX); if (win_valid(prev_win)) wp = prev_win; } // Make sure curwin isn't invalid. It can cause severe trouble when // printing an error message. For win_equal() curbuf needs to be valid // too. if (win == curwin) { curwin = wp; #ifdef FEAT_QUICKFIX if (wp->w_p_pvw || bt_quickfix(wp->w_buffer)) { /* * If the cursor goes to the preview or the quickfix window, try * finding another window to go to. */ for (;;) { if (wp->w_next == NULL) wp = firstwin; else wp = wp->w_next; if (wp == curwin) break; if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer)) { curwin = wp; break; } } } #endif curbuf = curwin->w_buffer; close_curwin = TRUE; // The cursor position may be invalid if the buffer changed after last // using the window. check_cursor(); } if (p_ea && (*p_ead == 'b' || *p_ead == dir)) // If the frame of the closed window contains the new current window, // only resize that frame. Otherwise resize all windows. win_equal(curwin, curwin->w_frame->fr_parent == win_frame, dir); else win_comp_pos(); if (close_curwin) { // Pass WEE_ALLOW_PARSE_MESSAGES to decrement dont_parse_messages // before autocommands. #ifdef MESSAGE_QUEUE did_decrement = #else (void) #endif win_enter_ext(wp, WEE_CURWIN_INVALID | WEE_TRIGGER_ENTER_AUTOCMDS | WEE_TRIGGER_LEAVE_AUTOCMDS | WEE_ALLOW_PARSE_MESSAGES); if (other_buffer) // careful: after this wp and win may be invalid! apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); } --split_disallowed; #ifdef MESSAGE_QUEUE if (!did_decrement) --dont_parse_messages; #endif /* * If last window has a status line now and we don't want one, * remove the status line. */ last_status(FALSE); // After closing the help window, try restoring the window layout from // before it was opened. if (help_window) restore_snapshot(SNAP_HELP_IDX, close_curwin); #ifdef FEAT_DIFF // If the window had 'diff' set and now there is only one window left in // the tab page with 'diff' set, and ""closeoff"" is in 'diffopt', then // execute "":diffoff!"". if (diffopt_closeoff() && had_diffmode && curtab == prev_curtab) { int diffcount = 0; win_T *dwin; FOR_ALL_WINDOWS(dwin) if (dwin->w_p_diff) ++diffcount; if (diffcount == 1) do_cmdline_cmd((char_u *)""diffoff!""); } #endif #if defined(FEAT_GUI) // When 'guioptions' includes 'L' or 'R' may have to remove scrollbars. if (gui.in_use && !win_hasvertsplit()) gui_init_which_components(NULL); #endif redraw_all_later(NOT_VALID); return OK; }",CWE-787,16 1," void gitn_box_del(GF_Box *s) { u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *)s; if (ptr == NULL) return; for (i=0; inb_entries; i++) { if (ptr->entries[i].name) gf_free(ptr->entries[i].name); } if (ptr->entries) gf_free(ptr->entries); gf_free(ptr);",CWE-476,12 1,"get_lisp_indent(void) { pos_T *pos, realpos, paren; int amount; char_u *that; colnr_T col; colnr_T firsttry; int parencount, quotecount; int vi_lisp; // Set vi_lisp to use the vi-compatible method vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL); realpos = curwin->w_cursor; curwin->w_cursor.col = 0; if ((pos = findmatch(NULL, '(')) == NULL) pos = findmatch(NULL, '['); else { paren = *pos; pos = findmatch(NULL, '['); if (pos == NULL || LT_POSP(pos, &paren)) pos = &paren; } if (pos != NULL) { // Extra trick: Take the indent of the first previous non-white // line that is at the same () level. amount = -1; parencount = 0; while (--curwin->w_cursor.lnum >= pos->lnum) { if (linewhite(curwin->w_cursor.lnum)) continue; for (that = ml_get_curline(); *that != NUL; ++that) { if (*that == ';') { while (*(that + 1) != NUL) ++that; continue; } if (*that == '\\') { if (*(that + 1) != NUL) ++that; continue; } if (*that == '""' && *(that + 1) != NUL) { while (*++that && *that != '""') { // skipping escaped characters in the string if (*that == '\\') { if (*++that == NUL) break; if (that[1] == NUL) { ++that; break; } } } } if (*that == '(' || *that == '[') ++parencount; else if (*that == ')' || *that == ']') --parencount; } if (parencount == 0) { amount = get_indent(); break; } } if (amount == -1) { curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = pos->col; col = pos->col; that = ml_get_curline(); if (vi_lisp && get_indent() == 0) amount = 2; else { char_u *line = that; amount = 0; while (*that && col) { amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); col--; } // Some keywords require ""body"" indenting rules (the // non-standard-lisp ones are Scheme special forms): // // (let ((a 1)) instead (let ((a 1)) // (...)) of (...)) if (!vi_lisp && (*that == '(' || *that == '[') && lisp_match(that + 1)) amount += 2; else { that++; amount++; firsttry = amount; while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize(line, that, (colnr_T)amount); ++that; } if (*that && *that != ';') // not a comment line { // test *that != '(' to accommodate first let/do // argument if it is more than one line if (!vi_lisp && *that != '(' && *that != '[') firsttry++; parencount = 0; quotecount = 0; if (vi_lisp || (*that != '""' && *that != '\'' && *that != '#' && (*that < '0' || *that > '9'))) { while (*that && (!VIM_ISWHITE(*that) || quotecount || parencount) && (!((*that == '(' || *that == '[') && !quotecount && !parencount && vi_lisp))) { if (*that == '""') quotecount = !quotecount; if ((*that == '(' || *that == '[') && !quotecount) ++parencount; if ((*that == ')' || *that == ']') && !quotecount) --parencount; if (*that == '\\' && *(that+1) != NUL) amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); } } while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize( line, that, (colnr_T)amount); that++; } if (!*that || *that == ';') amount = firsttry; } } } } } else amount = 0; // no matching '(' or '[' found, use zero indent curwin->w_cursor = realpos; return amount; }",CWE-787,16 1,"pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file) { /* * The PCX format theoretically allows encoding runs of 63 * identical bytes, but some readers can't handle repetition * counts greater than 15. */ #define MAX_RUN_COUNT 15 int max_run = step * MAX_RUN_COUNT; while (from < end) { byte data = *from; from += step; if (data != *from || from == end) { if (data >= 0xc0) gp_fputc(0xc1, file); } else { const byte *start = from; while ((from < end) && (*from == data)) from += step; /* Now (from - start) / step + 1 is the run length. */ while (from - start >= max_run) { gp_fputc(0xc0 + MAX_RUN_COUNT, file); gp_fputc(data, file); start += max_run; } if (from > start || data >= 0xc0) gp_fputc((from - start) / step + 0xc1, file); } gp_fputc(data, file); } #undef MAX_RUN_COUNT }",CWE-787,16 1,"gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) { char *pos = inbuf; char *lpos = NULL; char *tline = NULL; LOCAL_ARRAY(char, line, TEMP_BUF_SIZE); LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE); char *name = NULL; char *selector = NULL; char *host = NULL; char *port = NULL; char *escaped_selector = NULL; const char *icon_url = NULL; char gtype; StoreEntry *entry = NULL; memset(tmpbuf, '\0', TEMP_BUF_SIZE); memset(line, '\0', TEMP_BUF_SIZE); entry = gopherState->entry; if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, ""Gopher Index %s"", html_url); storeAppendPrintf(entry, ""

This is a searchable Gopher index. Use the search\n"" ""function of your browser to enter search terms.\n"" ""\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, ""CSO Search of %s"", html_url); storeAppendPrintf(entry, ""

A CSO database usually contains a phonebook or\n"" ""directory. Use the search function of your browser to enter\n"" ""search terms.

\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } String outbuf; if (!gopherState->HTML_header_added) { if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT) gopherHTMLHeader(entry, ""CSO Search Result"", NULL); else gopherHTMLHeader(entry, ""Gopher Menu"", NULL); outbuf.append (""
"");

        gopherState->HTML_header_added = 1;

        gopherState->HTML_pre = 1;
    }

    while (pos < inbuf + len) {
        int llen;
        int left = len - (pos - inbuf);
        lpos = (char *)memchr(pos, '\n', left);
        if (lpos) {
            ++lpos;             /* Next line is after \n */
            llen = lpos - pos;
        } else {
            llen = left;
        }
        if (gopherState->len + llen >= TEMP_BUF_SIZE) {
            debugs(10, DBG_IMPORTANT, ""GopherHTML: Buffer overflow. Lost some data on URL: "" << entry->url()  );
            llen = TEMP_BUF_SIZE - gopherState->len - 1;
        }
        if (!lpos) {
            /* there is no complete line in inbuf */
            /* copy it to temp buffer */
            /* note: llen is adjusted above */
            memcpy(gopherState->buf + gopherState->len, pos, llen);
            gopherState->len += llen;
            break;
        }
        if (gopherState->len != 0) {
            /* there is something left from last tx. */
            memcpy(line, gopherState->buf, gopherState->len);
            memcpy(line + gopherState->len, pos, llen);
            llen += gopherState->len;
            gopherState->len = 0;
        } else {
            memcpy(line, pos, llen);
        }
        line[llen + 1] = '\0';
        /* move input to next line */
        pos = lpos;

        /* at this point. We should have one line in buffer to process */

        if (*line == '.') {
            /* skip it */
            memset(line, '\0', TEMP_BUF_SIZE);
            continue;
        }

        switch (gopherState->conversion) {

        case GopherStateData::HTML_INDEX_RESULT:

        case GopherStateData::HTML_DIR: {
            tline = line;
            gtype = *tline;
            ++tline;
            name = tline;
            selector = strchr(tline, TAB);

            if (selector) {
                *selector = '\0';
                ++selector;
                host = strchr(selector, TAB);

                if (host) {
                    *host = '\0';
                    ++host;
                    port = strchr(host, TAB);

                    if (port) {
                        char *junk;
                        port[0] = ':';
                        junk = strchr(host, TAB);

                        if (junk)
                            *junk++ = 0;    /* Chop port */
                        else {
                            junk = strchr(host, '\r');

                            if (junk)
                                *junk++ = 0;    /* Chop port */
                            else {
                                junk = strchr(host, '\n');

                                if (junk)
                                    *junk++ = 0;    /* Chop port */
                            }
                        }

                        if ((port[1] == '0') && (!port[2]))
                            port[0] = 0;    /* 0 means none */
                    }

                    /* escape a selector here */
                    escaped_selector = xstrdup(rfc1738_escape_part(selector));

                    switch (gtype) {

                    case GOPHER_DIRECTORY:
                        icon_url = mimeGetIconURL(""internal-menu"");
                        break;

                    case GOPHER_HTML:

                    case GOPHER_FILE:
                        icon_url = mimeGetIconURL(""internal-text"");
                        break;

                    case GOPHER_INDEX:

                    case GOPHER_CSO:
                        icon_url = mimeGetIconURL(""internal-index"");
                        break;

                    case GOPHER_IMAGE:

                    case GOPHER_GIF:

                    case GOPHER_PLUS_IMAGE:
                        icon_url = mimeGetIconURL(""internal-image"");
                        break;

                    case GOPHER_SOUND:

                    case GOPHER_PLUS_SOUND:
                        icon_url = mimeGetIconURL(""internal-sound"");
                        break;

                    case GOPHER_PLUS_MOVIE:
                        icon_url = mimeGetIconURL(""internal-movie"");
                        break;

                    case GOPHER_TELNET:

                    case GOPHER_3270:
                        icon_url = mimeGetIconURL(""internal-telnet"");
                        break;

                    case GOPHER_BIN:

                    case GOPHER_MACBINHEX:

                    case GOPHER_DOSBIN:

                    case GOPHER_UUENCODED:
                        icon_url = mimeGetIconURL(""internal-binary"");
                        break;

                    case GOPHER_INFO:
                        icon_url = NULL;
                        break;

                    default:
                        icon_url = mimeGetIconURL(""internal-unknown"");
                        break;
                    }

                    memset(tmpbuf, '\0', TEMP_BUF_SIZE);

                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {
                        if (strlen(escaped_selector) != 0)
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, escaped_selector, rfc1738_escape_part(host),
                                     *port ? "":"" : """", port, html_quote(name));
                        else
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, rfc1738_escape_part(host), *port ? "":"" : """",
                                     port, html_quote(name));

                    } else if (gtype == GOPHER_INFO) {
                        snprintf(tmpbuf, TEMP_BUF_SIZE, ""\t%s\n"", html_quote(name));
                    } else {
                        if (strncmp(selector, ""GET /"", 5) == 0) {
                            /* WWW link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));
                        } else {
                            /* Standard link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, gtype, escaped_selector, html_quote(name));
                        }
                    }

                    safe_free(escaped_selector);
                    outbuf.append(tmpbuf);
                } else {
                    memset(line, '\0', TEMP_BUF_SIZE);
                    continue;
                }
            } else {
                memset(line, '\0', TEMP_BUF_SIZE);
                continue;
            }

            break;
            }           /* HTML_DIR, HTML_INDEX_RESULT */

        case GopherStateData::HTML_CSO_RESULT: {
            if (line[0] == '-') {
                int code, recno;
                char *s_code, *s_recno, *result;

                s_code = strtok(line + 1, "":\n"");
                s_recno = strtok(NULL, "":\n"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                recno = atoi(s_recno);

                if (code != 200)
                    break;

                if (gopherState->cso_recno != recno) {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

Record# %d
%s

\n
"", recno, html_quote(result));
                    gopherState->cso_recno = recno;
                } else {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""%s\n"", html_quote(result));
                }

                outbuf.append(tmpbuf);
                break;
            } else {
                int code;
                char *s_code, *result;

                s_code = strtok(line, "":"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                switch (code) {

                case 200: {
                    /* OK */
                    /* Do nothing here */
                    break;
                }

                case 102:   /* Number of matches */

                case 501:   /* No Match */

                case 502: { /* Too Many Matches */
                    /* Print the message the server returns */
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

%s

\n
"", html_quote(result));
                    outbuf.append(tmpbuf);
                    break;
                }

                }
            }

            }           /* HTML_CSO_RESULT */

        default:
            break;      /* do nothing */

        }           /* switch */

    }               /* while loop */

    if (outbuf.size() > 0) {
        entry->append(outbuf.rawBuf(), outbuf.size());
        /* now let start sending stuff to client */
        entry->flush();
    }

    outbuf.clean();
    return;
}",CWE-400,9
1,"append_command(char_u *cmd)
{
    char_u *s = cmd;
    char_u *d;

    STRCAT(IObuff, "": "");
    d = IObuff + STRLEN(IObuff);
    while (*s != NUL && d - IObuff + 5 < IOSIZE)
    {
	if (enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : *s == 0xa0)
	{
	    s += enc_utf8 ? 2 : 1;
	    STRCPY(d, """");
	    d += 4;
	}
	else if (d - IObuff + (*mb_ptr2len)(s) + 1 >= IOSIZE)
	    break;
	else
	    MB_COPY_CHAR(s, d);
    }
    *d = NUL;
}",CWE-787,16
1,"static ssize_t hid_debug_events_read(struct file *file, char __user *buffer,
		size_t count, loff_t *ppos)
{
	struct hid_debug_list *list = file->private_data;
	int ret = 0, len;
	DECLARE_WAITQUEUE(wait, current);

	mutex_lock(&list->read_mutex);
	while (ret == 0) {
		if (list->head == list->tail) {
			add_wait_queue(&list->hdev->debug_wait, &wait);
			set_current_state(TASK_INTERRUPTIBLE);

			while (list->head == list->tail) {
				if (file->f_flags & O_NONBLOCK) {
					ret = -EAGAIN;
					break;
				}
				if (signal_pending(current)) {
					ret = -ERESTARTSYS;
					break;
				}

				if (!list->hdev || !list->hdev->debug) {
					ret = -EIO;
					set_current_state(TASK_RUNNING);
					goto out;
				}

				/* allow O_NONBLOCK from other threads */
				mutex_unlock(&list->read_mutex);
				schedule();
				mutex_lock(&list->read_mutex);
				set_current_state(TASK_INTERRUPTIBLE);
			}

			set_current_state(TASK_RUNNING);
			remove_wait_queue(&list->hdev->debug_wait, &wait);
		}

		if (ret)
			goto out;

		/* pass the ringbuffer contents to userspace */
copy_rest:
		if (list->tail == list->head)
			goto out;
		if (list->tail > list->head) {
			len = list->tail - list->head;

			if (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) {
				ret = -EFAULT;
				goto out;
			}
			ret += len;
			list->head += len;
		} else {
			len = HID_DEBUG_BUFSIZE - list->head;

			if (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) {
				ret = -EFAULT;
				goto out;
			}
			list->head = 0;
			ret += len;
			goto copy_rest;
		}

	}
out:
	mutex_unlock(&list->read_mutex);
	return ret;
}",CWE-787,16
1,"vhost_backend_cleanup(struct virtio_net *dev)
{
	if (dev->mem) {
		free_mem_region(dev);
		rte_free(dev->mem);
		dev->mem = NULL;
	}

	free(dev->guest_pages);
	dev->guest_pages = NULL;

	if (dev->log_addr) {
		munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
		dev->log_addr = 0;
	}

	if (dev->slave_req_fd >= 0) {
		close(dev->slave_req_fd);
		dev->slave_req_fd = -1;
	}

	if (dev->postcopy_ufd >= 0) {
		close(dev->postcopy_ufd);
		dev->postcopy_ufd = -1;
	}

	dev->postcopy_listening = 0;
}",CWE-190,2
1,"do_tag(
    char_u	*tag,		// tag (pattern) to jump to
    int		type,
    int		count,
    int		forceit,	// :ta with !
    int		verbose)	// print ""tag not found"" message
{
    taggy_T	*tagstack = curwin->w_tagstack;
    int		tagstackidx = curwin->w_tagstackidx;
    int		tagstacklen = curwin->w_tagstacklen;
    int		cur_match = 0;
    int		cur_fnum = curbuf->b_fnum;
    int		oldtagstackidx = tagstackidx;
    int		prevtagstackidx = tagstackidx;
    int		prev_num_matches;
    int		new_tag = FALSE;
    int		i;
    int		ic;
    int		no_regexp = FALSE;
    int		error_cur_match = 0;
    int		save_pos = FALSE;
    fmark_T	saved_fmark;
#ifdef FEAT_CSCOPE
    int		jumped_to_tag = FALSE;
#endif
    int		new_num_matches;
    char_u	**new_matches;
    int		use_tagstack;
    int		skip_msg = FALSE;
    char_u	*buf_ffname = curbuf->b_ffname;	    // name to use for
						    // priority computation
    int		use_tfu = 1;

    // remember the matches for the last used tag
    static int		num_matches = 0;
    static int		max_num_matches = 0;  // limit used for match search
    static char_u	**matches = NULL;
    static int		flags;

#ifdef FEAT_EVAL
    if (tfu_in_use)
    {
	emsg(_(e_cannot_modify_tag_stack_within_tagfunc));
	return FALSE;
    }
#endif

#ifdef EXITFREE
    if (type == DT_FREE)
    {
	// remove the list of matches
	FreeWild(num_matches, matches);
# ifdef FEAT_CSCOPE
	cs_free_tags();
# endif
	num_matches = 0;
	return FALSE;
    }
#endif

    if (type == DT_HELP)
    {
	type = DT_TAG;
	no_regexp = TRUE;
	use_tfu = 0;
    }

    prev_num_matches = num_matches;
    free_string_option(nofile_fname);
    nofile_fname = NULL;

    CLEAR_POS(&saved_fmark.mark);	// shutup gcc 4.0
    saved_fmark.fnum = 0;

    /*
     * Don't add a tag to the tagstack if 'tagstack' has been reset.
     */
    if ((!p_tgst && *tag != NUL))
    {
	use_tagstack = FALSE;
	new_tag = TRUE;
#if defined(FEAT_QUICKFIX)
	if (g_do_tagpreview != 0)
	{
	    tagstack_clear_entry(&ptag_entry);
	    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)
		goto end_do_tag;
	}
#endif
    }
    else
    {
#if defined(FEAT_QUICKFIX)
	if (g_do_tagpreview != 0)
	    use_tagstack = FALSE;
	else
#endif
	    use_tagstack = TRUE;

	// new pattern, add to the tag stack
	if (*tag != NUL
		&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP
#ifdef FEAT_QUICKFIX
		    || type == DT_LTAG
#endif
#ifdef FEAT_CSCOPE
		    || type == DT_CSCOPE
#endif
		    ))
	{
#if defined(FEAT_QUICKFIX)
	    if (g_do_tagpreview != 0)
	    {
		if (ptag_entry.tagname != NULL
			&& STRCMP(ptag_entry.tagname, tag) == 0)
		{
		    // Jumping to same tag: keep the current match, so that
		    // the CursorHold autocommand example works.
		    cur_match = ptag_entry.cur_match;
		    cur_fnum = ptag_entry.cur_fnum;
		}
		else
		{
		    tagstack_clear_entry(&ptag_entry);
		    if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)
			goto end_do_tag;
		}
	    }
	    else
#endif
	    {
		/*
		 * If the last used entry is not at the top, delete all tag
		 * stack entries above it.
		 */
		while (tagstackidx < tagstacklen)
		    tagstack_clear_entry(&tagstack[--tagstacklen]);

		// if the tagstack is full: remove oldest entry
		if (++tagstacklen > TAGSTACKSIZE)
		{
		    tagstacklen = TAGSTACKSIZE;
		    tagstack_clear_entry(&tagstack[0]);
		    for (i = 1; i < tagstacklen; ++i)
			tagstack[i - 1] = tagstack[i];
		    --tagstackidx;
		}

		/*
		 * put the tag name in the tag stack
		 */
		if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL)
		{
		    curwin->w_tagstacklen = tagstacklen - 1;
		    goto end_do_tag;
		}
		curwin->w_tagstacklen = tagstacklen;

		save_pos = TRUE;	// save the cursor position below
	    }

	    new_tag = TRUE;
	}
	else
	{
	    if (
#if defined(FEAT_QUICKFIX)
		    g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :
#endif
		    tagstacklen == 0)
	    {
		// empty stack
		emsg(_(e_tag_stack_empty));
		goto end_do_tag;
	    }

	    if (type == DT_POP)		// go to older position
	    {
#ifdef FEAT_FOLDING
		int	old_KeyTyped = KeyTyped;
#endif
		if ((tagstackidx -= count) < 0)
		{
		    emsg(_(e_at_bottom_of_tag_stack));
		    if (tagstackidx + count == 0)
		    {
			// We did [num]^T from the bottom of the stack
			tagstackidx = 0;
			goto end_do_tag;
		    }
		    // We weren't at the bottom of the stack, so jump all the
		    // way to the bottom now.
		    tagstackidx = 0;
		}
		else if (tagstackidx >= tagstacklen)    // count == 0?
		{
		    emsg(_(e_at_top_of_tag_stack));
		    goto end_do_tag;
		}

		// Make a copy of the fmark, autocommands may invalidate the
		// tagstack before it's used.
		saved_fmark = tagstack[tagstackidx].fmark;
		if (saved_fmark.fnum != curbuf->b_fnum)
		{
		    /*
		     * Jump to other file. If this fails (e.g. because the
		     * file was changed) keep original position in tag stack.
		     */
		    if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,
					       GETF_SETMARK, forceit) == FAIL)
		    {
			tagstackidx = oldtagstackidx;  // back to old posn
			goto end_do_tag;
		    }
		    // An BufReadPost autocommand may jump to the '"" mark, but
		    // we don't what that here.
		    curwin->w_cursor.lnum = saved_fmark.mark.lnum;
		}
		else
		{
		    setpcmark();
		    curwin->w_cursor.lnum = saved_fmark.mark.lnum;
		}
		curwin->w_cursor.col = saved_fmark.mark.col;
		curwin->w_set_curswant = TRUE;
		check_cursor();
#ifdef FEAT_FOLDING
		if ((fdo_flags & FDO_TAG) && old_KeyTyped)
		    foldOpenCursor();
#endif

		// remove the old list of matches
		FreeWild(num_matches, matches);
#ifdef FEAT_CSCOPE
		cs_free_tags();
#endif
		num_matches = 0;
		tag_freematch();
		goto end_do_tag;
	    }

	    if (type == DT_TAG
#if defined(FEAT_QUICKFIX)
		    || type == DT_LTAG
#endif
	       )
	    {
#if defined(FEAT_QUICKFIX)
		if (g_do_tagpreview != 0)
		{
		    cur_match = ptag_entry.cur_match;
		    cur_fnum = ptag_entry.cur_fnum;
		}
		else
#endif
		{
		    // "":tag"" (no argument): go to newer pattern
		    save_pos = TRUE;	// save the cursor position below
		    if ((tagstackidx += count - 1) >= tagstacklen)
		    {
			/*
			 * Beyond the last one, just give an error message and
			 * go to the last one.  Don't store the cursor
			 * position.
			 */
			tagstackidx = tagstacklen - 1;
			emsg(_(e_at_top_of_tag_stack));
			save_pos = FALSE;
		    }
		    else if (tagstackidx < 0)	// must have been count == 0
		    {
			emsg(_(e_at_bottom_of_tag_stack));
			tagstackidx = 0;
			goto end_do_tag;
		    }
		    cur_match = tagstack[tagstackidx].cur_match;
		    cur_fnum = tagstack[tagstackidx].cur_fnum;
		}
		new_tag = TRUE;
	    }
	    else				// go to other matching tag
	    {
		// Save index for when selection is cancelled.
		prevtagstackidx = tagstackidx;

#if defined(FEAT_QUICKFIX)
		if (g_do_tagpreview != 0)
		{
		    cur_match = ptag_entry.cur_match;
		    cur_fnum = ptag_entry.cur_fnum;
		}
		else
#endif
		{
		    if (--tagstackidx < 0)
			tagstackidx = 0;
		    cur_match = tagstack[tagstackidx].cur_match;
		    cur_fnum = tagstack[tagstackidx].cur_fnum;
		}
		switch (type)
		{
		    case DT_FIRST: cur_match = count - 1; break;
		    case DT_SELECT:
		    case DT_JUMP:
#ifdef FEAT_CSCOPE
		    case DT_CSCOPE:
#endif
		    case DT_LAST:  cur_match = MAXCOL - 1; break;
		    case DT_NEXT:  cur_match += count; break;
		    case DT_PREV:  cur_match -= count; break;
		}
		if (cur_match >= MAXCOL)
		    cur_match = MAXCOL - 1;
		else if (cur_match < 0)
		{
		    emsg(_(e_cannot_go_before_first_matching_tag));
		    skip_msg = TRUE;
		    cur_match = 0;
		    cur_fnum = curbuf->b_fnum;
		}
	    }
	}

#if defined(FEAT_QUICKFIX)
	if (g_do_tagpreview != 0)
	{
	    if (type != DT_SELECT && type != DT_JUMP)
	    {
		ptag_entry.cur_match = cur_match;
		ptag_entry.cur_fnum = cur_fnum;
	    }
	}
	else
#endif
	{
	    /*
	     * For "":tag [arg]"" or "":tselect"" remember position before the jump.
	     */
	    saved_fmark = tagstack[tagstackidx].fmark;
	    if (save_pos)
	    {
		tagstack[tagstackidx].fmark.mark = curwin->w_cursor;
		tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;
	    }

	    // Curwin will change in the call to jumpto_tag() if "":stag"" was
	    // used or an autocommand jumps to another window; store value of
	    // tagstackidx now.
	    curwin->w_tagstackidx = tagstackidx;
	    if (type != DT_SELECT && type != DT_JUMP)
	    {
		curwin->w_tagstack[tagstackidx].cur_match = cur_match;
		curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;
	    }
	}
    }

    // When not using the current buffer get the name of buffer ""cur_fnum"".
    // Makes sure that the tag order doesn't change when using a remembered
    // position for ""cur_match"".
    if (cur_fnum != curbuf->b_fnum)
    {
	buf_T *buf = buflist_findnr(cur_fnum);

	if (buf != NULL)
	    buf_ffname = buf->b_ffname;
    }

    /*
     * Repeat searching for tags, when a file has not been found.
     */
    for (;;)
    {
	int	other_name;
	char_u	*name;

	/*
	 * When desired match not found yet, try to find it (and others).
	 */
	if (use_tagstack)
	    name = tagstack[tagstackidx].tagname;
#if defined(FEAT_QUICKFIX)
	else if (g_do_tagpreview != 0)
	    name = ptag_entry.tagname;
#endif
	else
	    name = tag;
	other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);
	if (new_tag
		|| (cur_match >= num_matches && max_num_matches != MAXCOL)
		|| other_name)
	{
	    if (other_name)
	    {
		vim_free(tagmatchname);
		tagmatchname = vim_strsave(name);
	    }

	    if (type == DT_SELECT || type == DT_JUMP
#if defined(FEAT_QUICKFIX)
		|| type == DT_LTAG
#endif
		)
		cur_match = MAXCOL - 1;
	    if (type == DT_TAG)
		max_num_matches = MAXCOL;
	    else
		max_num_matches = cur_match + 1;

	    // when the argument starts with '/', use it as a regexp
	    if (!no_regexp && *name == '/')
	    {
		flags = TAG_REGEXP;
		++name;
	    }
	    else
		flags = TAG_NOIC;

#ifdef FEAT_CSCOPE
	    if (type == DT_CSCOPE)
		flags = TAG_CSCOPE;
#endif
	    if (verbose)
		flags |= TAG_VERBOSE;

	    if (!use_tfu)
		flags |= TAG_NO_TAGFUNC;

	    if (find_tags(name, &new_num_matches, &new_matches, flags,
					    max_num_matches, buf_ffname) == OK
		    && new_num_matches < max_num_matches)
		max_num_matches = MAXCOL; // If less than max_num_matches
					  // found: all matches found.

	    // If there already were some matches for the same name, move them
	    // to the start.  Avoids that the order changes when using
	    // "":tnext"" and jumping to another file.
	    if (!new_tag && !other_name)
	    {
		int	    j, k;
		int	    idx = 0;
		tagptrs_T   tagp, tagp2;

		// Find the position of each old match in the new list.  Need
		// to use parse_match() to find the tag line.
		for (j = 0; j < num_matches; ++j)
		{
		    parse_match(matches[j], &tagp);
		    for (i = idx; i < new_num_matches; ++i)
		    {
			parse_match(new_matches[i], &tagp2);
			if (STRCMP(tagp.tagname, tagp2.tagname) == 0)
			{
			    char_u *p = new_matches[i];
			    for (k = i; k > idx; --k)
				new_matches[k] = new_matches[k - 1];
			    new_matches[idx++] = p;
			    break;
			}
		    }
		}
	    }
	    FreeWild(num_matches, matches);
	    num_matches = new_num_matches;
	    matches = new_matches;
	}

	if (num_matches <= 0)
	{
	    if (verbose)
		semsg(_(e_tag_not_found_str), name);
#if defined(FEAT_QUICKFIX)
	    g_do_tagpreview = 0;
#endif
	}
	else
	{
	    int ask_for_selection = FALSE;

#ifdef FEAT_CSCOPE
	    if (type == DT_CSCOPE && num_matches > 1)
	    {
		cs_print_tags();
		ask_for_selection = TRUE;
	    }
	    else
#endif
	    if (type == DT_TAG && *tag != NUL)
		// If a count is supplied to the "":tag "" command, then
		// jump to count'th matching tag.
		cur_match = count > 0 ? count - 1 : 0;
	    else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1))
	    {
		print_tag_list(new_tag, use_tagstack, num_matches, matches);
		ask_for_selection = TRUE;
	    }
#if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL)
	    else if (type == DT_LTAG)
	    {
		if (add_llist_tags(tag, num_matches, matches) == FAIL)
		    goto end_do_tag;
		cur_match = 0;		// Jump to the first tag
	    }
#endif

	    if (ask_for_selection == TRUE)
	    {
		/*
		 * Ask to select a tag from the list.
		 */
		i = prompt_for_number(NULL);
		if (i <= 0 || i > num_matches || got_int)
		{
		    // no valid choice: don't change anything
		    if (use_tagstack)
		    {
			tagstack[tagstackidx].fmark = saved_fmark;
			tagstackidx = prevtagstackidx;
		    }
#ifdef FEAT_CSCOPE
		    cs_free_tags();
		    jumped_to_tag = TRUE;
#endif
		    break;
		}
		cur_match = i - 1;
	    }

	    if (cur_match >= num_matches)
	    {
		// Avoid giving this error when a file wasn't found and we're
		// looking for a match in another file, which wasn't found.
		// There will be an emsg(""file doesn't exist"") below then.
		if ((type == DT_NEXT || type == DT_FIRST)
						      && nofile_fname == NULL)
		{
		    if (num_matches == 1)
			emsg(_(e_there_is_only_one_matching_tag));
		    else
			emsg(_(e_cannot_go_beyond_last_matching_tag));
		    skip_msg = TRUE;
		}
		cur_match = num_matches - 1;
	    }
	    if (use_tagstack)
	    {
		tagptrs_T   tagp;

		tagstack[tagstackidx].cur_match = cur_match;
		tagstack[tagstackidx].cur_fnum = cur_fnum;

		// store user-provided data originating from tagfunc
		if (use_tfu && parse_match(matches[cur_match], &tagp) == OK
			&& tagp.user_data)
		{
		    VIM_CLEAR(tagstack[tagstackidx].user_data);
		    tagstack[tagstackidx].user_data = vim_strnsave(
			  tagp.user_data, tagp.user_data_end - tagp.user_data);
		}

		++tagstackidx;
	    }
#if defined(FEAT_QUICKFIX)
	    else if (g_do_tagpreview != 0)
	    {
		ptag_entry.cur_match = cur_match;
		ptag_entry.cur_fnum = cur_fnum;
	    }
#endif

	    /*
	     * Only when going to try the next match, report that the previous
	     * file didn't exist.  Otherwise an emsg() is given below.
	     */
	    if (nofile_fname != NULL && error_cur_match != cur_match)
		smsg(_(""File \""%s\"" does not exist""), nofile_fname);


	    ic = (matches[cur_match][0] & MT_IC_OFF);
	    if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP
#ifdef FEAT_CSCOPE
		&& type != DT_CSCOPE
#endif
		&& (num_matches > 1 || ic)
		&& !skip_msg)
	    {
		// Give an indication of the number of matching tags
		sprintf((char *)IObuff, _(""tag %d of %d%s""),
				cur_match + 1,
				num_matches,
				max_num_matches != MAXCOL ? _("" or more"") : """");
		if (ic)
		    STRCAT(IObuff, _(""  Using tag with different case!""));
		if ((num_matches > prev_num_matches || new_tag)
							   && num_matches > 1)
		{
		    if (ic)
			msg_attr((char *)IObuff, HL_ATTR(HLF_W));
		    else
			msg((char *)IObuff);
		    msg_scroll = TRUE;	// don't overwrite this message
		}
		else
		    give_warning(IObuff, ic);
		if (ic && !msg_scrolled && msg_silent == 0)
		{
		    out_flush();
		    ui_delay(1007L, TRUE);
		}
	    }

#if defined(FEAT_EVAL)
	    // Let the SwapExists event know what tag we are jumping to.
	    vim_snprintf((char *)IObuff, IOSIZE, "":ta %s\r"", name);
	    set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1);
#endif

	    /*
	     * Jump to the desired match.
	     */
	    i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);

#if defined(FEAT_EVAL)
	    set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
#endif

	    if (i == NOTAGFILE)
	    {
		// File not found: try again with another matching tag
		if ((type == DT_PREV && cur_match > 0)
			|| ((type == DT_TAG || type == DT_NEXT
							  || type == DT_FIRST)
			    && (max_num_matches != MAXCOL
					     || cur_match < num_matches - 1)))
		{
		    error_cur_match = cur_match;
		    if (use_tagstack)
			--tagstackidx;
		    if (type == DT_PREV)
			--cur_match;
		    else
		    {
			type = DT_NEXT;
			++cur_match;
		    }
		    continue;
		}
		semsg(_(e_file_str_does_not_exist), nofile_fname);
	    }
	    else
	    {
		// We may have jumped to another window, check that
		// tagstackidx is still valid.
		if (use_tagstack && tagstackidx > curwin->w_tagstacklen)
		    tagstackidx = curwin->w_tagstackidx;
#ifdef FEAT_CSCOPE
		jumped_to_tag = TRUE;
#endif
	    }
	}
	break;
    }

end_do_tag:
    // Only store the new index when using the tagstack and it's valid.
    if (use_tagstack && tagstackidx <= curwin->w_tagstacklen)
	curwin->w_tagstackidx = tagstackidx;
    postponed_split = 0;	// don't split next time
# ifdef FEAT_QUICKFIX
    g_do_tagpreview = 0;	// don't do tag preview next time
# endif

#ifdef FEAT_CSCOPE
    return jumped_to_tag;
#else
    return FALSE;
#endif
}",CWE-416,10
1,"static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
{
    VirtQueueElement elem;
    VirtQueue *vq;

    vq = vser->c_ivq;
    if (!virtio_queue_ready(vq)) {
        return 0;
    }
    if (!virtqueue_pop(vq, &elem)) {
        return 0;
    }

    memcpy(elem.in_sg[0].iov_base, buf, len);

    virtqueue_push(vq, &elem, len);
    virtio_notify(VIRTIO_DEVICE(vser), vq);
    return len;
}",CWE-787,16
0,"NetworkLibrary* NetworkLibrary::GetImpl(bool stub) {
  if (stub)
    return new NetworkLibraryStubImpl();
  else
    return new NetworkLibraryImpl();
}
",none,24
0,"  HostQuotaCallback* NewWaitableHostQuotaCallback() {
    ++waiting_callbacks_;
    return callback_factory_.NewCallback(
            &UsageAndQuotaDispatcherTask::DidGetHostQuota);
  }
",none,24
0,"  void DidGetModifiedOrigins(const std::set& origins, StorageType type) {
    modified_origins_ = origins;
    modified_origins_type_ = type;
  }
",none,24
0,"  void ClearNetworks() {
    if (ethernet_)
      delete ethernet_;
    ethernet_ = NULL;
    wifi_ = NULL;
    cellular_ = NULL;
    STLDeleteElements(&wifi_networks_);
    wifi_networks_.clear();
    STLDeleteElements(&cellular_networks_);
    cellular_networks_.clear();
    STLDeleteElements(&remembered_wifi_networks_);
    remembered_wifi_networks_.clear();
  }
",none,24
1,"Status ValidateInputs(const Tensor *a_indices, const Tensor *a_values,
                      const Tensor *a_shape, const Tensor *b) {
  if (!TensorShapeUtils::IsMatrix(a_indices->shape())) {
    return errors::InvalidArgument(
        ""Input a_indices should be a matrix but received shape: "",
        a_indices->shape().DebugString());
  }
  if (!TensorShapeUtils::IsVector(a_values->shape()) ||
      !TensorShapeUtils::IsVector(a_shape->shape())) {
    return errors::InvalidArgument(
        ""Inputs a_values and a_shape should be vectors ""
        ""but received shapes: "",
        a_values->shape().DebugString(), "" and "",
        a_shape->shape().DebugString());
  }
  if (a_shape->NumElements() != b->dims()) {
    return errors::InvalidArgument(
        ""Two operands have different ranks; received: "", a_shape->NumElements(),
        "" and "", b->dims());
  }
  const auto a_shape_flat = a_shape->flat();
  for (int i = 0; i < b->dims(); ++i) {
    if (a_shape_flat(i) != b->dim_size(i)) {
      return errors::InvalidArgument(
          ""Dimension "", i,
          "" does not equal (no broadcasting is supported): sparse side "",
          a_shape_flat(i), "" vs dense side "", b->dim_size(i));
    }
  }
  return Status::OK();
}",CWE-20,3
0,"  virtual void SaveWifiNetwork(const WifiNetwork* network) {
    DCHECK(network);
    if (!EnsureCrosLoaded() || !network)
      return;
    SetPassphrase(
        network->service_path().c_str(), network->passphrase().c_str());
    SetIdentity(network->service_path().c_str(),
        network->identity().c_str());
    SetCertPath(network->service_path().c_str(),
        network->cert_path().c_str());
    SetAutoConnect(network->service_path().c_str(), network->auto_connect());
  }
",none,24
0,"  virtual void ConnectToWifiNetwork(const WifiNetwork* network,
                                    const std::string& password,
                                    const std::string& identity,
                                    const std::string& certpath) {
    DCHECK(network);
    if (!EnsureCrosLoaded())
      return;
    if (ConnectToNetworkWithCertInfo(network->service_path().c_str(),
        password.empty() ? NULL : password.c_str(),
        identity.empty() ? NULL : identity.c_str(),
        certpath.empty() ? NULL : certpath.c_str())) {
      WifiNetwork* wifi = GetWirelessNetworkByPath(
          wifi_networks_, network->service_path());
      if (wifi) {
        wifi->set_passphrase(password);
        wifi->set_identity(identity);
        wifi->set_cert_path(certpath);
        wifi->set_connecting(true);
        wifi_ = wifi;
      }
      NotifyNetworkManagerChanged();
    }
  }
",none,24
0,"bool CellularNetwork::StartActivation() const {
  if (!EnsureCrosLoaded())
    return false;
  return ActivateCellularModem(service_path_.c_str(), NULL);
}
",none,24
0,"  virtual bool ethernet_enabled() const {
    return enabled_devices_ & (1 << TYPE_ETHERNET);
  }
",none,24
1,"static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
		    unsigned long param)
{
	int drive = (long)bdev->bd_disk->private_data;
	int type = ITYPE(drive_state[drive].fd_device);
	int i;
	int ret;
	int size;
	union inparam {
		struct floppy_struct g;	/* geometry */
		struct format_descr f;
		struct floppy_max_errors max_errors;
		struct floppy_drive_params dp;
	} inparam;		/* parameters coming from user space */
	const void *outparam;	/* parameters passed back to user space */

	/* convert compatibility eject ioctls into floppy eject ioctl.
	 * We do this in order to provide a means to eject floppy disks before
	 * installing the new fdutils package */
	if (cmd == CDROMEJECT ||	/* CD-ROM eject */
	    cmd == 0x6470) {		/* SunOS floppy eject */
		DPRINT(""obsolete eject ioctl\n"");
		DPRINT(""please use floppycontrol --eject\n"");
		cmd = FDEJECT;
	}

	if (!((cmd & 0xff00) == 0x0200))
		return -EINVAL;

	/* convert the old style command into a new style command */
	ret = normalize_ioctl(&cmd, &size);
	if (ret)
		return ret;

	/* permission checks */
	if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||
	    ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
		return -EPERM;

	if (WARN_ON(size < 0 || size > sizeof(inparam)))
		return -EINVAL;

	/* copyin */
	memset(&inparam, 0, sizeof(inparam));
	if (_IOC_DIR(cmd) & _IOC_WRITE) {
		ret = fd_copyin((void __user *)param, &inparam, size);
		if (ret)
			return ret;
	}

	switch (cmd) {
	case FDEJECT:
		if (drive_state[drive].fd_ref != 1)
			/* somebody else has this drive open */
			return -EBUSY;
		if (lock_fdc(drive))
			return -EINTR;

		/* do the actual eject. Fails on
		 * non-Sparc architectures */
		ret = fd_eject(UNIT(drive));

		set_bit(FD_DISK_CHANGED_BIT, &drive_state[drive].flags);
		set_bit(FD_VERIFY_BIT, &drive_state[drive].flags);
		process_fd_request();
		return ret;
	case FDCLRPRM:
		if (lock_fdc(drive))
			return -EINTR;
		current_type[drive] = NULL;
		floppy_sizes[drive] = MAX_DISK_SIZE << 1;
		drive_state[drive].keep_data = 0;
		return invalidate_drive(bdev);
	case FDSETPRM:
	case FDDEFPRM:
		return set_geometry(cmd, &inparam.g, drive, type, bdev);
	case FDGETPRM:
		ret = get_floppy_geometry(drive, type,
					  (struct floppy_struct **)&outparam);
		if (ret)
			return ret;
		memcpy(&inparam.g, outparam,
				offsetof(struct floppy_struct, name));
		outparam = &inparam.g;
		break;
	case FDMSGON:
		drive_params[drive].flags |= FTD_MSG;
		return 0;
	case FDMSGOFF:
		drive_params[drive].flags &= ~FTD_MSG;
		return 0;
	case FDFMTBEG:
		if (lock_fdc(drive))
			return -EINTR;
		if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
			return -EINTR;
		ret = drive_state[drive].flags;
		process_fd_request();
		if (ret & FD_VERIFY)
			return -ENODEV;
		if (!(ret & FD_DISK_WRITABLE))
			return -EROFS;
		return 0;
	case FDFMTTRK:
		if (drive_state[drive].fd_ref != 1)
			return -EBUSY;
		return do_format(drive, &inparam.f);
	case FDFMTEND:
	case FDFLUSH:
		if (lock_fdc(drive))
			return -EINTR;
		return invalidate_drive(bdev);
	case FDSETEMSGTRESH:
		drive_params[drive].max_errors.reporting = (unsigned short)(param & 0x0f);
		return 0;
	case FDGETMAXERRS:
		outparam = &drive_params[drive].max_errors;
		break;
	case FDSETMAXERRS:
		drive_params[drive].max_errors = inparam.max_errors;
		break;
	case FDGETDRVTYP:
		outparam = drive_name(type, drive);
		SUPBOUND(size, strlen((const char *)outparam) + 1);
		break;
	case FDSETDRVPRM:
		if (!valid_floppy_drive_params(inparam.dp.autodetect,
				inparam.dp.native_format))
			return -EINVAL;
		drive_params[drive] = inparam.dp;
		break;
	case FDGETDRVPRM:
		outparam = &drive_params[drive];
		break;
	case FDPOLLDRVSTAT:
		if (lock_fdc(drive))
			return -EINTR;
		if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
			return -EINTR;
		process_fd_request();
		fallthrough;
	case FDGETDRVSTAT:
		outparam = &drive_state[drive];
		break;
	case FDRESET:
		return user_reset_fdc(drive, (int)param, true);
	case FDGETFDCSTAT:
		outparam = &fdc_state[FDC(drive)];
		break;
	case FDWERRORCLR:
		memset(&write_errors[drive], 0, sizeof(write_errors[drive]));
		return 0;
	case FDWERRORGET:
		outparam = &write_errors[drive];
		break;
	case FDRAWCMD:
		if (type)
			return -EINVAL;
		if (lock_fdc(drive))
			return -EINTR;
		set_floppy(drive);
		i = raw_cmd_ioctl(cmd, (void __user *)param);
		if (i == -EINTR)
			return -EINTR;
		process_fd_request();
		return i;
	case FDTWADDLE:
		if (lock_fdc(drive))
			return -EINTR;
		twaddle(current_fdc, current_drive);
		process_fd_request();
		return 0;
	default:
		return -EINVAL;
	}

	if (_IOC_DIR(cmd) & _IOC_READ)
		return fd_copyout((void __user *)param, outparam, size);

	return 0;
}",CWE-416,10
0,"  bool Connecting() const { return false; }
",none,24
0,"QuotaManager::~QuotaManager() {
  DCHECK(io_thread_->BelongsToCurrentThread());
  proxy_->manager_ = NULL;
  std::for_each(clients_.begin(), clients_.end(),
                std::mem_fun(&QuotaClient::OnQuotaManagerDestroyed));
  if (database_.get())
     db_thread_->DeleteSoon(FROM_HERE, database_.release());
 }
",none,24
1,"Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,
                         TensorHandle* tensor_handle, Device** result) {
  Device* cpu_device = ctx.HostCPU();
  string device_name;
  if (tensor_handle->Type() != TensorHandle::LOCAL) {
    Device* device = tensor_handle->device();
    device_name = device != nullptr ? device->name() : cpu_device->name();
    *result = (device == nullptr ? cpu_device : device);
  } else if (tensor_handle->dtype == DT_RESOURCE) {
    // Use the resource's actual device because it is the device that will
    // influence partitioning the multi-device function.
    const Tensor* tensor;
    // TODO(fishx): Avoid blocking here.
    TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));
    const ResourceHandle& handle = tensor->flat()(0);
    device_name = handle.device();

    Device* input_device;
    TF_RETURN_IF_ERROR(
        ctx.FindDeviceFromName(device_name.c_str(), &input_device));
    *result = input_device;
  } else {
    Device* device = tensor_handle->device();
    const bool is_tpu = device != nullptr && device->device_type() == ""TPU"";
    // int32 return values can be placed on TPUs.
    const bool use_host_memory =
        is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)
               : MTypeFromDType(tensor_handle->dtype);
    if (use_host_memory) {
      *result = cpu_device;
    } else {
      // Eager ops executing as functions should have their preferred inputs set
      // to the op's device. This allows us to avoid expensive D2H copies if a
      // mirror of the tensor already exists on the op's device.
      if (!op.is_function() && device != nullptr && device != cpu_device) {
        device = absl::get(op.Device());
      }
      *result = (device == nullptr ? cpu_device : device);
    }
  }
  return Status::OK();
}",CWE-476,12
1,"static json_t * check_attestation_fido_u2f(json_t * j_params, unsigned char * credential_id, size_t credential_id_len, unsigned char * cert_x, size_t cert_x_len, unsigned char * cert_y, size_t cert_y_len, cbor_item_t * att_stmt, unsigned char * rpid_hash, size_t rpid_hash_len, const unsigned char * client_data) {
  json_t * j_error = json_array(), * j_return;
  cbor_item_t * key = NULL, * x5c = NULL, * sig = NULL, * att_cert = NULL;
  int i, ret;
  char * message = NULL;
  gnutls_pubkey_t pubkey = NULL;
  gnutls_x509_crt_t cert = NULL;
  gnutls_datum_t cert_dat, data, signature, cert_issued_by;
  unsigned char data_signed[200], client_data_hash[32], cert_export[32], cert_export_b64[64];
  size_t data_signed_offset = 0, client_data_hash_len = 32, cert_export_len = 32, cert_export_b64_len = 0;
  
  if (j_error != NULL) {
    do {
      if (gnutls_x509_crt_init(&cert)) {
        json_array_append_new(j_error, json_string(""check_attestation_fido_u2f - Error gnutls_x509_crt_init""));
        break;
      }
      if (gnutls_pubkey_init(&pubkey)) {
        json_array_append_new(j_error, json_string(""check_attestation_fido_u2f - Error gnutls_pubkey_init""));
        break;
      }
      
      // Step 1
      if (att_stmt == NULL || !cbor_isa_map(att_stmt) || cbor_map_size(att_stmt) != 2) {
        json_array_append_new(j_error, json_string(""CBOR map value 'attStmt' invalid format""));
        break;
      }
      for (i=0; i<2; i++) {
        key = cbor_map_handle(att_stmt)[i].key;
        if (cbor_isa_string(key)) {
          if (0 == o_strncmp((const char *)cbor_string_handle(key), ""x5c"", MIN(o_strlen(""x5c""), cbor_string_length(key)))) {
            x5c = cbor_map_handle(att_stmt)[i].value;
          } else if (0 == o_strncmp((const char *)cbor_string_handle(key), ""sig"", MIN(o_strlen(""sig""), cbor_string_length(key)))) {
            sig = cbor_map_handle(att_stmt)[i].value;
          } else {
            message = msprintf(""attStmt map element %d key is not valid: '%.*s'"", i, cbor_string_length(key), cbor_string_handle(key));
            json_array_append_new(j_error, json_string(message));
            o_free(message);
            break;
          }
        } else {
          message = msprintf(""attStmt map element %d key is not a string"", i);
          json_array_append_new(j_error, json_string(message));
          o_free(message);
          break;
        }
      }
      if (x5c == NULL || !cbor_isa_array(x5c) || cbor_array_size(x5c) != 1) {
        json_array_append_new(j_error, json_string(""CBOR map value 'x5c' invalid format""));
        break;
      }
      att_cert = cbor_array_get(x5c, 0);
      cert_dat.data = cbor_bytestring_handle(att_cert);
      cert_dat.size = cbor_bytestring_length(att_cert);
      if ((ret = gnutls_x509_crt_import(cert, &cert_dat, GNUTLS_X509_FMT_DER)) < 0) {
        json_array_append_new(j_error, json_string(""Error importing x509 certificate""));
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - Error gnutls_pcert_import_x509_raw: %d"", ret);
        break;
      }
      if (json_object_get(j_params, ""root-ca-list"") != json_null() && validate_certificate_from_root(j_params, cert, x5c) != G_OK) {
        json_array_append_new(j_error, json_string(""Unrecognized certificate authority""));
        if (gnutls_x509_crt_get_issuer_dn2(cert, &cert_issued_by) >= 0) {
          message = msprintf(""Unrecognized certificate autohority: %.*s"", cert_issued_by.size, cert_issued_by.data);
          y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - %s"", message);
          o_free(message);
          gnutls_free(cert_issued_by.data);
        } else {
          y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - Unrecognized certificate autohority (unable to get issuer dn)"");
        }
        break;
      }
      if ((ret = gnutls_pubkey_import_x509(pubkey, cert, 0)) < 0) {
        json_array_append_new(j_error, json_string(""Error importing x509 certificate""));
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - Error gnutls_pubkey_import_x509: %d"", ret);
        break;
      }
      if ((ret = gnutls_x509_crt_get_key_id(cert, GNUTLS_KEYID_USE_SHA256, cert_export, &cert_export_len)) < 0) {
        json_array_append_new(j_error, json_string(""Error exporting x509 certificate""));
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - Error gnutls_x509_crt_get_key_id: %d"", ret);
        break;
      }
      if (!o_base64_encode(cert_export, cert_export_len, cert_export_b64, &cert_export_b64_len)) {
        json_array_append_new(j_error, json_string(""Internal error""));
        y_log_message(Y_LOG_LEVEL_DEBUG, ""check_attestation_fido_u2f - Error o_base64_encode cert_export"");
        break;
      }
      if (!generate_digest_raw(digest_SHA256, client_data, o_strlen((char *)client_data), client_data_hash, &client_data_hash_len)) {
        json_array_append_new(j_error, json_string(""Internal error""));
        y_log_message(Y_LOG_LEVEL_ERROR, ""check_attestation_fido_u2f - Error generate_digest_raw client_data"");
        break;
      }

      if (sig == NULL || !cbor_isa_bytestring(sig)) {
        json_array_append_new(j_error, json_string(""Error sig is not a bytestring""));
        break;
      }
      
      // Build bytestring to verify signature
      data_signed[0] = 0x0;
      data_signed_offset = 1;
      
      memcpy(data_signed+data_signed_offset, rpid_hash, rpid_hash_len);
      data_signed_offset += rpid_hash_len;
      
      memcpy(data_signed+data_signed_offset, client_data_hash, client_data_hash_len);
      data_signed_offset+=client_data_hash_len;
      
      memcpy(data_signed+data_signed_offset, credential_id, credential_id_len);
      data_signed_offset+=credential_id_len;
      
      data_signed[data_signed_offset] = 0x04;
      data_signed_offset++;
      
      memcpy(data_signed+data_signed_offset, cert_x, cert_x_len);
      data_signed_offset+=cert_x_len;
      
      memcpy(data_signed+data_signed_offset, cert_y, cert_y_len);
      data_signed_offset+=cert_y_len;
        
      // Let's verify sig over data_signed
      data.data = data_signed;
      data.size = data_signed_offset;
      
      signature.data = cbor_bytestring_handle(sig);
      signature.size = cbor_bytestring_length(sig);
      
      if (gnutls_pubkey_verify_data2(pubkey, GNUTLS_SIGN_ECDSA_SHA256, 0, &data, &signature)) {
        json_array_append_new(j_error, json_string(""Invalid signature""));
      }
      
    } while (0);
    
    if (json_array_size(j_error)) {
      j_return = json_pack(""{sisO}"", ""result"", G_ERROR_PARAM, ""error"", j_error);
    } else {
      j_return = json_pack(""{sis{ss%}}"", ""result"", G_OK, ""data"", ""certificate"", cert_export_b64, cert_export_b64_len);
    }
    json_decref(j_error);
    gnutls_pubkey_deinit(pubkey);
    gnutls_x509_crt_deinit(cert);
    if (att_cert != NULL) {
      cbor_decref(&att_cert);
    }
    
  } else {
    y_log_message(Y_LOG_LEVEL_ERROR, ""check_attestation_fido_u2f - Error allocating resources for j_error"");
    j_return = json_pack(""{si}"", ""result"", G_ERROR);
  }
  return j_return;
}",CWE-787,16
0,"CellularNetwork::CellularNetwork(const ServiceInfo* service)
    : WirelessNetwork(service) {
  service_name_ = SafeString(service->name);
  activation_state_ = service->activation_state;
  network_technology_ = service->network_technology;
  roaming_state_ = service->roaming_state;
  restricted_pool_ = service->restricted_pool;
  if (service->carrier_info) {
    operator_name_ = SafeString(service->carrier_info->operator_name);
    operator_code_ = SafeString(service->carrier_info->operator_code);
    payment_url_ = SafeString(service->carrier_info->payment_url);
  }
  if (service->device_info) {
    meid_ = SafeString(service->device_info->MEID);
    imei_ = SafeString(service->device_info->IMEI);
    imsi_ = SafeString(service->device_info->IMSI);
    esn_ = SafeString(service->device_info->ESN);
    mdn_ = SafeString(service->device_info->MDN);
    min_ = SafeString(service->device_info->MIN);
    model_id_ = SafeString(service->device_info->model_id);
    manufacturer_ = SafeString(service->device_info->manufacturer);
    firmware_revision_ = SafeString(service->device_info->firmware_revision);
    hardware_revision_ = SafeString(service->device_info->hardware_revision);
    last_update_ = SafeString(service->device_info->last_update);
    prl_version_ = service->device_info->PRL_version;
  }
  type_ = TYPE_CELLULAR;
}
",none,24
1,"getvcol(
    win_T	*wp,
    pos_T	*pos,
    colnr_T	*start,
    colnr_T	*cursor,
    colnr_T	*end)
{
    colnr_T	vcol;
    char_u	*ptr;		// points to current char
    char_u	*posptr;	// points to char at pos->col
    char_u	*line;		// start of the line
    int		incr;
    int		head;
#ifdef FEAT_VARTABS
    int		*vts = wp->w_buffer->b_p_vts_array;
#endif
    int		ts = wp->w_buffer->b_p_ts;
    int		c;

    vcol = 0;
    line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, FALSE);
    if (pos->col == MAXCOL)
	posptr = NULL;  // continue until the NUL
    else
    {
	// Special check for an empty line, which can happen on exit, when
	// ml_get_buf() always returns an empty string.
	if (*ptr == NUL)
	    pos->col = 0;
	posptr = ptr + pos->col;
	if (has_mbyte)
	    // always start on the first byte
	    posptr -= (*mb_head_off)(line, posptr);
    }

    /*
     * This function is used very often, do some speed optimizations.
     * When 'list', 'linebreak', 'showbreak' and 'breakindent' are not set
     * use a simple loop.
     * Also use this when 'list' is set but tabs take their normal size.
     */
    if ((!wp->w_p_list || wp->w_lcs_chars.tab1 != NUL)
#ifdef FEAT_LINEBREAK
	    && !wp->w_p_lbr && *get_showbreak_value(wp) == NUL && !wp->w_p_bri
#endif
       )
    {
	for (;;)
	{
	    head = 0;
	    c = *ptr;
	    // make sure we don't go past the end of the line
	    if (c == NUL)
	    {
		incr = 1;	// NUL at end of line only takes one column
		break;
	    }
	    // A tab gets expanded, depending on the current column
	    if (c == TAB)
#ifdef FEAT_VARTABS
		incr = tabstop_padding(vcol, ts, vts);
#else
		incr = ts - (vcol % ts);
#endif
	    else
	    {
		if (has_mbyte)
		{
		    // For utf-8, if the byte is >= 0x80, need to look at
		    // further bytes to find the cell width.
		    if (enc_utf8 && c >= 0x80)
			incr = utf_ptr2cells(ptr);
		    else
			incr = g_chartab[c] & CT_CELL_MASK;

		    // If a double-cell char doesn't fit at the end of a line
		    // it wraps to the next line, it's like this char is three
		    // cells wide.
		    if (incr == 2 && wp->w_p_wrap && MB_BYTE2LEN(*ptr) > 1
			    && in_win_border(wp, vcol))
		    {
			++incr;
			head = 1;
		    }
		}
		else
		    incr = g_chartab[c] & CT_CELL_MASK;
	    }

	    if (posptr != NULL && ptr >= posptr) // character at pos->col
		break;

	    vcol += incr;
	    MB_PTR_ADV(ptr);
	}
    }
    else
    {
	for (;;)
	{
	    // A tab gets expanded, depending on the current column
	    head = 0;
	    incr = win_lbr_chartabsize(wp, line, ptr, vcol, &head);
	    // make sure we don't go past the end of the line
	    if (*ptr == NUL)
	    {
		incr = 1;	// NUL at end of line only takes one column
		break;
	    }

	    if (posptr != NULL && ptr >= posptr) // character at pos->col
		break;

	    vcol += incr;
	    MB_PTR_ADV(ptr);
	}
    }
    if (start != NULL)
	*start = vcol + head;
    if (end != NULL)
	*end = vcol + incr - 1;
    if (cursor != NULL)
    {
	if (*ptr == TAB
		&& (State & NORMAL)
		&& !wp->w_p_list
		&& !virtual_active()
		&& !(VIsual_active
				&& (*p_sel == 'e' || LTOREQ_POS(*pos, VIsual)))
		)
	    *cursor = vcol + incr - 1;	    // cursor at end
	else
	    *cursor = vcol + head;	    // cursor at start
    }
}",CWE-787,16
1,"net_bind(short unsigned *port, int type, const char *log_service_name)
{
  struct addrinfo hints = { 0 };
  struct addrinfo *servinfo;
  struct addrinfo *ptr;
  const char *cfgaddr;
  char addr[INET6_ADDRSTRLEN];
  char strport[8];
  int yes = 1;
  int no = 0;
  int fd;
  int ret;

  cfgaddr = cfg_getstr(cfg_getsec(cfg, ""general""), ""bind_address"");

  hints.ai_socktype = (type & (SOCK_STREAM | SOCK_DGRAM)); // filter since type can be SOCK_STREAM | SOCK_NONBLOCK
  hints.ai_family = (cfg_getbool(cfg_getsec(cfg, ""general""), ""ipv6"")) ? AF_INET6 : AF_INET;
  hints.ai_flags = cfgaddr ? 0 : AI_PASSIVE;

  snprintf(strport, sizeof(strport), ""%hu"", *port);
  ret = getaddrinfo(cfgaddr, strport, &hints, &servinfo);
  if (ret < 0)
    {
      DPRINTF(E_LOG, L_MISC, ""Failure creating '%s' service, could not resolve '%s' (port %s): %s\n"", log_service_name, cfgaddr ? cfgaddr : ""(ANY)"", strport, gai_strerror(ret));
      return -1;
    }

  for (ptr = servinfo, fd = -1; ptr != NULL; ptr = ptr->ai_next)
    {
      if (fd >= 0)
	close(fd);

      fd = socket(ptr->ai_family, type | SOCK_CLOEXEC, ptr->ai_protocol);
      if (fd < 0)
	continue;

      // TODO libevent sets this, we do the same?
      ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));
      if (ret < 0)
	continue;

      ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
      if (ret < 0)
	continue;

      if (ptr->ai_family == AF_INET6)
	{
	  // We want to be sure the service is dual stack
	  ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));
	  if (ret < 0)
	    continue;
	}

      ret = bind(fd, ptr->ai_addr, ptr->ai_addrlen);
      if (ret < 0)
	continue;

      break;
    }

  freeaddrinfo(servinfo);

  if (!ptr)
    {
      DPRINTF(E_LOG, L_MISC, ""Could not create service '%s' with address %s, port %hu: %s\n"", log_service_name, cfgaddr ? cfgaddr : ""(ANY)"", *port, strerror(errno));
      goto error;
    }

  // Get the port that was assigned
  ret = getsockname(fd, ptr->ai_addr, &ptr->ai_addrlen);
  if (ret < 0)
    {
      DPRINTF(E_LOG, L_MISC, ""Could not find address of service '%s': %s\n"", log_service_name, strerror(errno));
      goto error;
    }

  net_port_get(port, (union net_sockaddr *)ptr->ai_addr);
  net_address_get(addr, sizeof(addr), (union net_sockaddr *)ptr->ai_addr);

  DPRINTF(E_DBG, L_MISC, ""Service '%s' bound to %s, port %hu, socket %d\n"", log_service_name, addr, *port, fd);

  return fd;

 error:
  close(fd);
  return -1;
}",CWE-416,10
0,"  virtual ~AvailableSpaceQueryTask() {}
",none,24
1,"ex_substitute(exarg_T *eap)
{
    linenr_T	lnum;
    long	i = 0;
    regmmatch_T regmatch;
    static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,
							      FALSE, FALSE, 0};
#ifdef FEAT_EVAL
    subflags_T	subflags_save;
#endif
    int		save_do_all;		// remember user specified 'g' flag
    int		save_do_ask;		// remember user specified 'c' flag
    char_u	*pat = NULL, *sub = NULL;	// init for GCC
    int		delimiter;
    int		sublen;
    int		got_quit = FALSE;
    int		got_match = FALSE;
    int		temp;
    int		which_pat;
    char_u	*cmd;
    int		save_State;
    linenr_T	first_line = 0;		// first changed line
    linenr_T	last_line= 0;		// below last changed line AFTER the
					// change
    linenr_T	old_line_count = curbuf->b_ml.ml_line_count;
    linenr_T	line2;
    long	nmatch;			// number of lines in match
    char_u	*sub_firstline;		// allocated copy of first sub line
    int		endcolumn = FALSE;	// cursor in last column when done
    pos_T	old_cursor = curwin->w_cursor;
    int		start_nsubs;
#ifdef FEAT_EVAL
    int		save_ma = 0;
#endif

    cmd = eap->arg;
    if (!global_busy)
    {
	sub_nsubs = 0;
	sub_nlines = 0;
    }
    start_nsubs = sub_nsubs;

    if (eap->cmdidx == CMD_tilde)
	which_pat = RE_LAST;	// use last used regexp
    else
	which_pat = RE_SUBST;	// use last substitute regexp

				// new pattern and substitution
    if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)
		&& vim_strchr((char_u *)""0123456789cegriIp|\"""", *cmd) == NULL)
    {
				// don't accept alphanumeric for separator
	if (check_regexp_delim(*cmd) == FAIL)
	    return;
#ifdef FEAT_EVAL
	if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)
								      == FAIL)
	    return;
#endif

	/*
	 * undocumented vi feature:
	 *  ""\/sub/"" and ""\?sub?"" use last used search pattern (almost like
	 *  //sub/r).  ""\&sub&"" use last substitute pattern (like //sub/).
	 */
	if (*cmd == '\\')
	{
	    ++cmd;
	    if (vim_strchr((char_u *)""/?&"", *cmd) == NULL)
	    {
		emsg(_(e_backslash_should_be_followed_by));
		return;
	    }
	    if (*cmd != '&')
		which_pat = RE_SEARCH;	    // use last '/' pattern
	    pat = (char_u *)"""";		    // empty search pattern
	    delimiter = *cmd++;		    // remember delimiter character
	}
	else		// find the end of the regexp
	{
	    which_pat = RE_LAST;	    // use last used regexp
	    delimiter = *cmd++;		    // remember delimiter character
	    pat = cmd;			    // remember start of search pat
	    cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),
							&eap->arg, NULL, NULL);
	    if (cmd[0] == delimiter)	    // end delimiter found
		*cmd++ = NUL;		    // replace it with a NUL
	}

	/*
	 * Small incompatibility: vi sees '\n' as end of the command, but in
	 * Vim we want to use '\n' to find/substitute a NUL.
	 */
	sub = cmd;	    // remember the start of the substitution
	cmd = skip_substitute(cmd, delimiter);

	if (!eap->skip)
	{
	    // In POSIX vi "":s/pat/%/"" uses the previous subst. string.
	    if (STRCMP(sub, ""%"") == 0
				 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
	    {
		if (old_sub == NULL)	// there is no previous command
		{
		    emsg(_(e_no_previous_substitute_regular_expression));
		    return;
		}
		sub = old_sub;
	    }
	    else
	    {
		vim_free(old_sub);
		old_sub = vim_strsave(sub);
	    }
	}
    }
    else if (!eap->skip)	// use previous pattern and substitution
    {
	if (old_sub == NULL)	// there is no previous command
	{
	    emsg(_(e_no_previous_substitute_regular_expression));
	    return;
	}
	pat = NULL;		// search_regcomp() will use previous pattern
	sub = old_sub;

	// Vi compatibility quirk: repeating with "":s"" keeps the cursor in the
	// last column after using ""$"".
	endcolumn = (curwin->w_curswant == MAXCOL);
    }

    // Recognize "":%s/\n//"" and turn it into a join command, which is much
    // more efficient.
    // TODO: find a generic solution to make line-joining operations more
    // efficient, avoid allocating a string that grows in size.
    if (pat != NULL && STRCMP(pat, ""\\n"") == 0
	    && *sub == NUL
	    && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'
					     || *cmd == 'p' || *cmd == '#'))))
    {
	linenr_T    joined_lines_count;

	if (eap->skip)
	    return;
	curwin->w_cursor.lnum = eap->line1;
	if (*cmd == 'l')
	    eap->flags = EXFLAG_LIST;
	else if (*cmd == '#')
	    eap->flags = EXFLAG_NR;
	else if (*cmd == 'p')
	    eap->flags = EXFLAG_PRINT;

	// The number of lines joined is the number of lines in the range plus
	// one.  One less when the last line is included.
	joined_lines_count = eap->line2 - eap->line1 + 1;
	if (eap->line2 < curbuf->b_ml.ml_line_count)
	    ++joined_lines_count;
	if (joined_lines_count > 1)
	{
	    (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);
	    sub_nsubs = joined_lines_count - 1;
	    sub_nlines = 1;
	    (void)do_sub_msg(FALSE);
	    ex_may_print(eap);
	}

	if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)
	    save_re_pat(RE_SUBST, pat, magic_isset());
	// put pattern in history
	add_to_history(HIST_SEARCH, pat, TRUE, NUL);

	return;
    }

    /*
     * Find trailing options.  When '&' is used, keep old options.
     */
    if (*cmd == '&')
	++cmd;
    else
    {
#ifdef FEAT_EVAL
	if (in_vim9script())
	{
	    // ignore 'gdefault' and 'edcompatible'
	    subflags.do_all = FALSE;
	    subflags.do_ask = FALSE;
	}
	else
#endif
	if (!p_ed)
	{
	    if (p_gd)		// default is global on
		subflags.do_all = TRUE;
	    else
		subflags.do_all = FALSE;
	    subflags.do_ask = FALSE;
	}
	subflags.do_error = TRUE;
	subflags.do_print = FALSE;
	subflags.do_list = FALSE;
	subflags.do_count = FALSE;
	subflags.do_number = FALSE;
	subflags.do_ic = 0;
    }
    while (*cmd)
    {
	/*
	 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
	 * 'r' is never inverted.
	 */
	if (*cmd == 'g')
	    subflags.do_all = !subflags.do_all;
	else if (*cmd == 'c')
	    subflags.do_ask = !subflags.do_ask;
	else if (*cmd == 'n')
	    subflags.do_count = TRUE;
	else if (*cmd == 'e')
	    subflags.do_error = !subflags.do_error;
	else if (*cmd == 'r')	    // use last used regexp
	    which_pat = RE_LAST;
	else if (*cmd == 'p')
	    subflags.do_print = TRUE;
	else if (*cmd == '#')
	{
	    subflags.do_print = TRUE;
	    subflags.do_number = TRUE;
	}
	else if (*cmd == 'l')
	{
	    subflags.do_print = TRUE;
	    subflags.do_list = TRUE;
	}
	else if (*cmd == 'i')	    // ignore case
	    subflags.do_ic = 'i';
	else if (*cmd == 'I')	    // don't ignore case
	    subflags.do_ic = 'I';
	else
	    break;
	++cmd;
    }
    if (subflags.do_count)
	subflags.do_ask = FALSE;

    save_do_all = subflags.do_all;
    save_do_ask = subflags.do_ask;

    /*
     * check for a trailing count
     */
    cmd = skipwhite(cmd);
    if (VIM_ISDIGIT(*cmd))
    {
	i = getdigits(&cmd);
	if (i <= 0 && !eap->skip && subflags.do_error)
	{
	    emsg(_(e_positive_count_required));
	    return;
	}
	eap->line1 = eap->line2;
	eap->line2 += i - 1;
	if (eap->line2 > curbuf->b_ml.ml_line_count)
	    eap->line2 = curbuf->b_ml.ml_line_count;
    }

    /*
     * check for trailing command or garbage
     */
    cmd = skipwhite(cmd);
    if (*cmd && *cmd != '""')	    // if not end-of-line or comment
    {
	set_nextcmd(eap, cmd);
	if (eap->nextcmd == NULL)
	{
	    semsg(_(e_trailing_characters_str), cmd);
	    return;
	}
    }

    if (eap->skip)	    // not executing commands, only parsing
	return;

    if (!subflags.do_count && !curbuf->b_p_ma)
    {
	// Substitution is not allowed in non-'modifiable' buffer
	emsg(_(e_cannot_make_changes_modifiable_is_off));
	return;
    }

    if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)
    {
	if (subflags.do_error)
	    emsg(_(e_invalid_command));
	return;
    }

    // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'
    if (subflags.do_ic == 'i')
	regmatch.rmm_ic = TRUE;
    else if (subflags.do_ic == 'I')
	regmatch.rmm_ic = FALSE;

    sub_firstline = NULL;

    /*
     * ~ in the substitute pattern is replaced with the old pattern.
     * We do it here once to avoid it to be replaced over and over again.
     * But don't do it when it starts with ""\="", then it's an expression.
     */
    if (!(sub[0] == '\\' && sub[1] == '='))
	sub = regtilde(sub, magic_isset());

    /*
     * Check for a match on each line.
     */
    line2 = eap->line2;
    for (lnum = eap->line1; lnum <= line2 && !(got_quit
#if defined(FEAT_EVAL)
		|| aborting()
#endif
		); ++lnum)
    {
	nmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,
						       (colnr_T)0, NULL, NULL);
	if (nmatch)
	{
	    colnr_T	copycol;
	    colnr_T	matchcol;
	    colnr_T	prev_matchcol = MAXCOL;
	    char_u	*new_end, *new_start = NULL;
	    unsigned	new_start_len = 0;
	    char_u	*p1;
	    int		did_sub = FALSE;
	    int		lastone;
	    int		len, copy_len, needed_len;
	    long	nmatch_tl = 0;	// nr of lines matched below lnum
	    int		do_again;	// do it again after joining lines
	    int		skip_match = FALSE;
	    linenr_T	sub_firstlnum;	// nr of first sub line
#ifdef FEAT_PROP_POPUP
	    int		apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;
	    colnr_T	total_added =  0;
#endif

	    /*
	     * The new text is build up step by step, to avoid too much
	     * copying.  There are these pieces:
	     * sub_firstline	The old text, unmodified.
	     * copycol		Column in the old text where we started
	     *			looking for a match; from here old text still
	     *			needs to be copied to the new text.
	     * matchcol		Column number of the old text where to look
	     *			for the next match.  It's just after the
	     *			previous match or one further.
	     * prev_matchcol	Column just after the previous match (if any).
	     *			Mostly equal to matchcol, except for the first
	     *			match and after skipping an empty match.
	     * regmatch.*pos	Where the pattern matched in the old text.
	     * new_start	The new text, all that has been produced so
	     *			far.
	     * new_end		The new text, where to append new text.
	     *
	     * lnum		The line number where we found the start of
	     *			the match.  Can be below the line we searched
	     *			when there is a \n before a \zs in the
	     *			pattern.
	     * sub_firstlnum	The line number in the buffer where to look
	     *			for a match.  Can be different from ""lnum""
	     *			when the pattern or substitute string contains
	     *			line breaks.
	     *
	     * Special situations:
	     * - When the substitute string contains a line break, the part up
	     *   to the line break is inserted in the text, but the copy of
	     *   the original line is kept.  ""sub_firstlnum"" is adjusted for
	     *   the inserted lines.
	     * - When the matched pattern contains a line break, the old line
	     *   is taken from the line at the end of the pattern.  The lines
	     *   in the match are deleted later, ""sub_firstlnum"" is adjusted
	     *   accordingly.
	     *
	     * The new text is built up in new_start[].  It has some extra
	     * room to avoid using alloc()/free() too often.  new_start_len is
	     * the length of the allocated memory at new_start.
	     *
	     * Make a copy of the old line, so it won't be taken away when
	     * updating the screen or handling a multi-line match.  The ""old_""
	     * pointers point into this copy.
	     */
	    sub_firstlnum = lnum;
	    copycol = 0;
	    matchcol = 0;

	    // At first match, remember current cursor position.
	    if (!got_match)
	    {
		setpcmark();
		got_match = TRUE;
	    }

	    /*
	     * Loop until nothing more to replace in this line.
	     * 1. Handle match with empty string.
	     * 2. If do_ask is set, ask for confirmation.
	     * 3. substitute the string.
	     * 4. if do_all is set, find next match
	     * 5. break if there isn't another match in this line
	     */
	    for (;;)
	    {
		// Advance ""lnum"" to the line where the match starts.  The
		// match does not start in the first line when there is a line
		// break before \zs.
		if (regmatch.startpos[0].lnum > 0)
		{
		    lnum += regmatch.startpos[0].lnum;
		    sub_firstlnum += regmatch.startpos[0].lnum;
		    nmatch -= regmatch.startpos[0].lnum;
		    VIM_CLEAR(sub_firstline);
		}

		// Match might be after the last line for ""\n\zs"" matching at
		// the end of the last line.
		if (lnum > curbuf->b_ml.ml_line_count)
		    break;

		if (sub_firstline == NULL)
		{
		    sub_firstline = vim_strsave(ml_get(sub_firstlnum));
		    if (sub_firstline == NULL)
		    {
			vim_free(new_start);
			goto outofmem;
		    }
		}

		// Save the line number of the last change for the final
		// cursor position (just like Vi).
		curwin->w_cursor.lnum = lnum;
		do_again = FALSE;

		/*
		 * 1. Match empty string does not count, except for first
		 * match.  This reproduces the strange vi behaviour.
		 * This also catches endless loops.
		 */
		if (matchcol == prev_matchcol
			&& regmatch.endpos[0].lnum == 0
			&& matchcol == regmatch.endpos[0].col)
		{
		    if (sub_firstline[matchcol] == NUL)
			// We already were at the end of the line.  Don't look
			// for a match in this line again.
			skip_match = TRUE;
		    else
		    {
			 // search for a match at next column
			if (has_mbyte)
			    matchcol += mb_ptr2len(sub_firstline + matchcol);
			else
			    ++matchcol;
		    }
		    goto skip;
		}

		// Normally we continue searching for a match just after the
		// previous match.
		matchcol = regmatch.endpos[0].col;
		prev_matchcol = matchcol;

		/*
		 * 2. If do_count is set only increase the counter.
		 *    If do_ask is set, ask for confirmation.
		 */
		if (subflags.do_count)
		{
		    // For a multi-line match, put matchcol at the NUL at
		    // the end of the line and set nmatch to one, so that
		    // we continue looking for a match on the next line.
		    // Avoids that "":s/\nB\@=//gc"" get stuck.
		    if (nmatch > 1)
		    {
			matchcol = (colnr_T)STRLEN(sub_firstline);
			nmatch = 1;
			skip_match = TRUE;
		    }
		    sub_nsubs++;
		    did_sub = TRUE;
#ifdef FEAT_EVAL
		    // Skip the substitution, unless an expression is used,
		    // then it is evaluated in the sandbox.
		    if (!(sub[0] == '\\' && sub[1] == '='))
#endif
			goto skip;
		}

		if (subflags.do_ask)
		{
		    int typed = 0;

		    // change State to CONFIRM, so that the mouse works
		    // properly
		    save_State = State;
		    State = CONFIRM;
		    setmouse();		// disable mouse in xterm
		    curwin->w_cursor.col = regmatch.startpos[0].col;
		    if (curwin->w_p_crb)
			do_check_cursorbind();

		    // When 'cpoptions' contains ""u"" don't sync undo when
		    // asking for confirmation.
		    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
			++no_u_sync;

		    /*
		     * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
		     */
		    while (subflags.do_ask)
		    {
			if (exmode_active)
			{
			    char_u	*resp;
			    colnr_T	sc, ec;

			    print_line_no_prefix(lnum,
					 subflags.do_number, subflags.do_list);

			    getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
			    curwin->w_cursor.col = regmatch.endpos[0].col - 1;
			    if (curwin->w_cursor.col < 0)
				curwin->w_cursor.col = 0;
			    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
			    curwin->w_cursor.col = regmatch.startpos[0].col;
			    if (subflags.do_number || curwin->w_p_nu)
			    {
				int numw = number_width(curwin) + 1;
				sc += numw;
				ec += numw;
			    }
			    msg_start();
			    for (i = 0; i < (long)sc; ++i)
				msg_putchar(' ');
			    for ( ; i <= (long)ec; ++i)
				msg_putchar('^');

			    resp = getexmodeline('?', NULL, 0, TRUE);
			    if (resp != NULL)
			    {
				typed = *resp;
				vim_free(resp);
			    }
			}
			else
			{
			    char_u *orig_line = NULL;
			    int    len_change = 0;
			    int	   save_p_lz = p_lz;
#ifdef FEAT_FOLDING
			    int save_p_fen = curwin->w_p_fen;

			    curwin->w_p_fen = FALSE;
#endif
			    // Invert the matched string.
			    // Remove the inversion afterwards.
			    temp = RedrawingDisabled;
			    RedrawingDisabled = 0;

			    // avoid calling update_screen() in vgetorpeek()
			    p_lz = FALSE;

			    if (new_start != NULL)
			    {
				// There already was a substitution, we would
				// like to show this to the user.  We cannot
				// really update the line, it would change
				// what matches.  Temporarily replace the line
				// and change it back afterwards.
				orig_line = vim_strsave(ml_get(lnum));
				if (orig_line != NULL)
				{
				    char_u *new_line = concat_str(new_start,
						     sub_firstline + copycol);

				    if (new_line == NULL)
					VIM_CLEAR(orig_line);
				    else
				    {
					// Position the cursor relative to the
					// end of the line, the previous
					// substitute may have inserted or
					// deleted characters before the
					// cursor.
					len_change = (int)STRLEN(new_line)
						     - (int)STRLEN(orig_line);
					curwin->w_cursor.col += len_change;
					ml_replace(lnum, new_line, FALSE);
				    }
				}
			    }

			    search_match_lines = regmatch.endpos[0].lnum
						  - regmatch.startpos[0].lnum;
			    search_match_endcol = regmatch.endpos[0].col
								 + len_change;
			    highlight_match = TRUE;

			    update_topline();
			    validate_cursor();
			    update_screen(SOME_VALID);
			    highlight_match = FALSE;
			    redraw_later(SOME_VALID);

#ifdef FEAT_FOLDING
			    curwin->w_p_fen = save_p_fen;
#endif
			    if (msg_row == Rows - 1)
				msg_didout = FALSE;	// avoid a scroll-up
			    msg_starthere();
			    i = msg_scroll;
			    msg_scroll = 0;		// truncate msg when
							// needed
			    msg_no_more = TRUE;
			    // write message same highlighting as for
			    // wait_return
			    smsg_attr(HL_ATTR(HLF_R),
				_(""replace with %s (y/n/a/q/l/^E/^Y)?""), sub);
			    msg_no_more = FALSE;
			    msg_scroll = i;
			    showruler(TRUE);
			    windgoto(msg_row, msg_col);
			    RedrawingDisabled = temp;

#ifdef USE_ON_FLY_SCROLL
			    dont_scroll = FALSE; // allow scrolling here
#endif
			    ++no_mapping;	// don't map this key
			    ++allow_keys;	// allow special keys
			    typed = plain_vgetc();
			    --allow_keys;
			    --no_mapping;

			    // clear the question
			    msg_didout = FALSE;	// don't scroll up
			    msg_col = 0;
			    gotocmdline(TRUE);
			    p_lz = save_p_lz;

			    // restore the line
			    if (orig_line != NULL)
				ml_replace(lnum, orig_line, FALSE);
			}

			need_wait_return = FALSE; // no hit-return prompt
			if (typed == 'q' || typed == ESC || typed == Ctrl_C
#ifdef UNIX
				|| typed == intr_char
#endif
				)
			{
			    got_quit = TRUE;
			    break;
			}
			if (typed == 'n')
			    break;
			if (typed == 'y')
			    break;
			if (typed == 'l')
			{
			    // last: replace and then stop
			    subflags.do_all = FALSE;
			    line2 = lnum;
			    break;
			}
			if (typed == 'a')
			{
			    subflags.do_ask = FALSE;
			    break;
			}
			if (typed == Ctrl_E)
			    scrollup_clamp();
			else if (typed == Ctrl_Y)
			    scrolldown_clamp();
		    }
		    State = save_State;
		    setmouse();
		    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
			--no_u_sync;

		    if (typed == 'n')
		    {
			// For a multi-line match, put matchcol at the NUL at
			// the end of the line and set nmatch to one, so that
			// we continue looking for a match on the next line.
			// Avoids that "":%s/\nB\@=//gc"" and "":%s/\n/,\r/gc""
			// get stuck when pressing 'n'.
			if (nmatch > 1)
			{
			    matchcol = (colnr_T)STRLEN(sub_firstline);
			    skip_match = TRUE;
			}
			goto skip;
		    }
		    if (got_quit)
			goto skip;
		}

		// Move the cursor to the start of the match, so that we can
		// use ""\=col(""."").
		curwin->w_cursor.col = regmatch.startpos[0].col;

		/*
		 * 3. substitute the string.
		 */
#ifdef FEAT_EVAL
		save_ma = curbuf->b_p_ma;
		if (subflags.do_count)
		{
		    // prevent accidentally changing the buffer by a function
		    curbuf->b_p_ma = FALSE;
		    sandbox++;
		}
		// Save flags for recursion.  They can change for e.g.
		// :s/^/\=execute(""s#^##gn"")
		subflags_save = subflags;
#endif
		// get length of substitution part
		sublen = vim_regsub_multi(®match,
				    sub_firstlnum - regmatch.startpos[0].lnum,
			       sub, sub_firstline, FALSE, magic_isset(), TRUE);
#ifdef FEAT_EVAL
		// If getting the substitute string caused an error, don't do
		// the replacement.
		// Don't keep flags set by a recursive call.
		subflags = subflags_save;
		if (aborting() || subflags.do_count)
		{
		    curbuf->b_p_ma = save_ma;
		    if (sandbox > 0)
			sandbox--;
		    goto skip;
		}
#endif

		// When the match included the ""$"" of the last line it may
		// go beyond the last line of the buffer.
		if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
		{
		    nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
		    skip_match = TRUE;
		}

		// Need room for:
		// - result so far in new_start (not for first sub in line)
		// - original text up to match
		// - length of substituted part
		// - original text after match
		// Adjust text properties here, since we have all information
		// needed.
		if (nmatch == 1)
		{
		    p1 = sub_firstline;
#ifdef FEAT_PROP_POPUP
		    if (curbuf->b_has_textprop)
		    {
			int bytes_added = sublen - 1 - (regmatch.endpos[0].col
						   - regmatch.startpos[0].col);

			// When text properties are changed, need to save for
			// undo first, unless done already.
			if (adjust_prop_columns(lnum,
					total_added + regmatch.startpos[0].col,
						       bytes_added, apc_flags))
			    apc_flags &= ~APC_SAVE_FOR_UNDO;
			// Offset for column byte number of the text property
			// in the resulting buffer afterwards.
			total_added += bytes_added;
		    }
#endif
		}
		else
		{
		    p1 = ml_get(sub_firstlnum + nmatch - 1);
		    nmatch_tl += nmatch - 1;
		}
		copy_len = regmatch.startpos[0].col - copycol;
		needed_len = copy_len + ((unsigned)STRLEN(p1)
				       - regmatch.endpos[0].col) + sublen + 1;
		if (new_start == NULL)
		{
		    /*
		     * Get some space for a temporary buffer to do the
		     * substitution into (and some extra space to avoid
		     * too many calls to alloc()/free()).
		     */
		    new_start_len = needed_len + 50;
		    if ((new_start = alloc(new_start_len)) == NULL)
			goto outofmem;
		    *new_start = NUL;
		    new_end = new_start;
		}
		else
		{
		    /*
		     * Check if the temporary buffer is long enough to do the
		     * substitution into.  If not, make it larger (with a bit
		     * extra to avoid too many calls to alloc()/free()).
		     */
		    len = (unsigned)STRLEN(new_start);
		    needed_len += len;
		    if (needed_len > (int)new_start_len)
		    {
			new_start_len = needed_len + 50;
			if ((p1 = alloc(new_start_len)) == NULL)
			{
			    vim_free(new_start);
			    goto outofmem;
			}
			mch_memmove(p1, new_start, (size_t)(len + 1));
			vim_free(new_start);
			new_start = p1;
		    }
		    new_end = new_start + len;
		}

		/*
		 * copy the text up to the part that matched
		 */
		mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);
		new_end += copy_len;

		(void)vim_regsub_multi(®match,
				    sub_firstlnum - regmatch.startpos[0].lnum,
				      sub, new_end, TRUE, magic_isset(), TRUE);
		sub_nsubs++;
		did_sub = TRUE;

		// Move the cursor to the start of the line, to avoid that it
		// is beyond the end of the line after the substitution.
		curwin->w_cursor.col = 0;

		// For a multi-line match, make a copy of the last matched
		// line and continue in that one.
		if (nmatch > 1)
		{
		    sub_firstlnum += nmatch - 1;
		    vim_free(sub_firstline);
		    sub_firstline = vim_strsave(ml_get(sub_firstlnum));
		    // When going beyond the last line, stop substituting.
		    if (sub_firstlnum <= line2)
			do_again = TRUE;
		    else
			subflags.do_all = FALSE;
		}

		// Remember next character to be copied.
		copycol = regmatch.endpos[0].col;

		if (skip_match)
		{
		    // Already hit end of the buffer, sub_firstlnum is one
		    // less than what it ought to be.
		    vim_free(sub_firstline);
		    sub_firstline = vim_strsave((char_u *)"""");
		    copycol = 0;
		}

		/*
		 * Now the trick is to replace CTRL-M chars with a real line
		 * break.  This would make it impossible to insert a CTRL-M in
		 * the text.  The line break can be avoided by preceding the
		 * CTRL-M with a backslash.  To be able to insert a backslash,
		 * they must be doubled in the string and are halved here.
		 * That is Vi compatible.
		 */
		for (p1 = new_end; *p1; ++p1)
		{
		    if (p1[0] == '\\' && p1[1] != NUL)  // remove backslash
		    {
			STRMOVE(p1, p1 + 1);
#ifdef FEAT_PROP_POPUP
			if (curbuf->b_has_textprop)
			{
			    // When text properties are changed, need to save
			    // for undo first, unless done already.
			    if (adjust_prop_columns(lnum,
					(colnr_T)(p1 - new_start), -1,
					apc_flags))
				apc_flags &= ~APC_SAVE_FOR_UNDO;
			}
#endif
		    }
		    else if (*p1 == CAR)
		    {
			if (u_inssub(lnum) == OK)   // prepare for undo
			{
			    colnr_T	plen = (colnr_T)(p1 - new_start + 1);

			    *p1 = NUL;		    // truncate up to the CR
			    ml_append(lnum - 1, new_start, plen, FALSE);
			    mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
			    if (subflags.do_ask)
				appended_lines(lnum - 1, 1L);
			    else
			    {
				if (first_line == 0)
				    first_line = lnum;
				last_line = lnum + 1;
			    }
#ifdef FEAT_PROP_POPUP
			    adjust_props_for_split(lnum + 1, lnum, plen, 1);
#endif
			    // all line numbers increase
			    ++sub_firstlnum;
			    ++lnum;
			    ++line2;
			    // move the cursor to the new line, like Vi
			    ++curwin->w_cursor.lnum;
			    // copy the rest
			    STRMOVE(new_start, p1 + 1);
			    p1 = new_start - 1;
			}
		    }
		    else if (has_mbyte)
			p1 += (*mb_ptr2len)(p1) - 1;
		}

		/*
		 * 4. If do_all is set, find next match.
		 * Prevent endless loop with patterns that match empty
		 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
		 * But "":s/\n/#/"" is OK.
		 */
skip:
		// We already know that we did the last subst when we are at
		// the end of the line, except that a pattern like
		// ""bar\|\nfoo"" may match at the NUL.  ""lnum"" can be below
		// ""line2"" when there is a \zs in the pattern after a line
		// break.
		lastone = (skip_match
			|| got_int
			|| got_quit
			|| lnum > line2
			|| !(subflags.do_all || do_again)
			|| (sub_firstline[matchcol] == NUL && nmatch <= 1
					 && !re_multiline(regmatch.regprog)));
		nmatch = -1;

		/*
		 * Replace the line in the buffer when needed.  This is
		 * skipped when there are more matches.
		 * The check for nmatch_tl is needed for when multi-line
		 * matching must replace the lines before trying to do another
		 * match, otherwise ""\@<="" won't work.
		 * When the match starts below where we start searching also
		 * need to replace the line first (using \zs after \n).
		 */
		if (lastone
			|| nmatch_tl > 0
			|| (nmatch = vim_regexec_multi(®match, curwin,
							curbuf, sub_firstlnum,
						    matchcol, NULL, NULL)) == 0
			|| regmatch.startpos[0].lnum > 0)
		{
		    if (new_start != NULL)
		    {
			/*
			 * Copy the rest of the line, that didn't match.
			 * ""matchcol"" has to be adjusted, we use the end of
			 * the line as reference, because the substitute may
			 * have changed the number of characters.  Same for
			 * ""prev_matchcol"".
			 */
			STRCAT(new_start, sub_firstline + copycol);
			matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
			prev_matchcol = (colnr_T)STRLEN(sub_firstline)
							      - prev_matchcol;

			if (u_savesub(lnum) != OK)
			    break;
			ml_replace(lnum, new_start, TRUE);

			if (nmatch_tl > 0)
			{
			    /*
			     * Matched lines have now been substituted and are
			     * useless, delete them.  The part after the match
			     * has been appended to new_start, we don't need
			     * it in the buffer.
			     */
			    ++lnum;
			    if (u_savedel(lnum, nmatch_tl) != OK)
				break;
			    for (i = 0; i < nmatch_tl; ++i)
				ml_delete(lnum);
			    mark_adjust(lnum, lnum + nmatch_tl - 1,
						   (long)MAXLNUM, -nmatch_tl);
			    if (subflags.do_ask)
				deleted_lines(lnum, nmatch_tl);
			    --lnum;
			    line2 -= nmatch_tl; // nr of lines decreases
			    nmatch_tl = 0;
			}

			// When asking, undo is saved each time, must also set
			// changed flag each time.
			if (subflags.do_ask)
			    changed_bytes(lnum, 0);
			else
			{
			    if (first_line == 0)
				first_line = lnum;
			    last_line = lnum + 1;
			}

			sub_firstlnum = lnum;
			vim_free(sub_firstline);    // free the temp buffer
			sub_firstline = new_start;
			new_start = NULL;
			matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
			prev_matchcol = (colnr_T)STRLEN(sub_firstline)
							      - prev_matchcol;
			copycol = 0;
		    }
		    if (nmatch == -1 && !lastone)
			nmatch = vim_regexec_multi(®match, curwin, curbuf,
					  sub_firstlnum, matchcol, NULL, NULL);

		    /*
		     * 5. break if there isn't another match in this line
		     */
		    if (nmatch <= 0)
		    {
			// If the match found didn't start where we were
			// searching, do the next search in the line where we
			// found the match.
			if (nmatch == -1)
			    lnum -= regmatch.startpos[0].lnum;
			break;
		    }
		}

		line_breakcheck();
	    }

	    if (did_sub)
		++sub_nlines;
	    vim_free(new_start);	// for when substitute was cancelled
	    VIM_CLEAR(sub_firstline);	// free the copy of the original line
	}

	line_breakcheck();
    }

    if (first_line != 0)
    {
	// Need to subtract the number of added lines from ""last_line"" to get
	// the line number before the change (same as adding the number of
	// deleted lines).
	i = curbuf->b_ml.ml_line_count - old_line_count;
	changed_lines(first_line, 0, last_line - i, i);
    }

outofmem:
    vim_free(sub_firstline); // may have to free allocated copy of the line

    // "":s/pat//n"" doesn't move the cursor
    if (subflags.do_count)
	curwin->w_cursor = old_cursor;

    if (sub_nsubs > start_nsubs)
    {
	if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
	{
	    // Set the '[ and '] marks.
	    curbuf->b_op_start.lnum = eap->line1;
	    curbuf->b_op_end.lnum = line2;
	    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
	}

	if (!global_busy)
	{
	    // when interactive leave cursor on the match
	    if (!subflags.do_ask)
	    {
		if (endcolumn)
		    coladvance((colnr_T)MAXCOL);
		else
		    beginline(BL_WHITE | BL_FIX);
	    }
	    if (!do_sub_msg(subflags.do_count) && subflags.do_ask)
		msg("""");
	}
	else
	    global_need_beginline = TRUE;
	if (subflags.do_print)
	    print_line(curwin->w_cursor.lnum,
					 subflags.do_number, subflags.do_list);
    }
    else if (!global_busy)
    {
	if (got_int)		// interrupted
	    emsg(_(e_interrupted));
	else if (got_match)	// did find something but nothing substituted
	    msg("""");
	else if (subflags.do_error)	// nothing found
	    semsg(_(e_pattern_not_found_str), get_search_pat());
    }

#ifdef FEAT_FOLDING
    if (subflags.do_ask && hasAnyFolding(curwin))
	// Cursor position may require updating
	changed_window_setting();
#endif

    vim_regfree(regmatch.regprog);

    // Restore the flag values, they can be used for "":&&"".
    subflags.do_all = save_do_all;
    subflags.do_ask = save_do_ask;
}",CWE-416,10
1,"static pyc_object *get_complex_object(RzBinPycObj *pyc, RzBuffer *buffer) {
	pyc_object *ret = NULL;
	bool error = false;
	ut32 size = 0;
	ut32 n1 = 0;
	ut32 n2 = 0;

	ret = RZ_NEW0(pyc_object);
	if (!ret) {
		return NULL;
	}

	if ((pyc->magic_int & 0xffff) <= 62061) {
		n1 = get_ut8(buffer, &error);
	} else {
		n1 = get_st32(buffer, &error);
	}
	if (error) {
		free(ret);
		return NULL;
	}
	ut8 *s1 = malloc(n1 + 1);
	if (!s1) {
		return NULL;
	}
	/* object contain string representation of the number */
	size = rz_buf_read(buffer, s1, n1);
	if (size != n1) {
		RZ_FREE(s1);
		RZ_FREE(ret);
		return NULL;
	}
	s1[n1] = '\0';

	if ((pyc->magic_int & 0xffff) <= 62061) {
		n2 = get_ut8(buffer, &error);
	} else
		n2 = get_st32(buffer, &error);
	if (error) {
		return NULL;
	}
	ut8 *s2 = malloc(n2 + 1);
	if (!s2) {
		return NULL;
	}
	/* object contain string representation of the number */
	size = rz_buf_read(buffer, s2, n2);
	if (size != n2) {
		RZ_FREE(s1);
		RZ_FREE(s2);
		RZ_FREE(ret);
		return NULL;
	}
	s2[n2] = '\0';

	ret->type = TYPE_COMPLEX;
	ret->data = rz_str_newf(""%s+%sj"", s1, s2);
	RZ_FREE(s1);
	RZ_FREE(s2);
	if (!ret->data) {
		RZ_FREE(ret);
		return NULL;
	}
	return ret;
}",CWE-787,16
1,"cookedprint(
	int datatype,
	int length,
	const char *data,
	int status,
	int quiet,
	FILE *fp
	)
{
	char *name;
	char *value;
	char output_raw;
	int fmt;
	l_fp lfp;
	sockaddr_u hval;
	u_long uval;
	int narr;
	size_t len;
	l_fp lfparr[8];
	char b[12];
	char bn[2 * MAXVARLEN];
	char bv[2 * MAXVALLEN];

	UNUSED_ARG(datatype);

	if (!quiet)
		fprintf(fp, ""status=%04x %s,\n"", status,
			statustoa(datatype, status));

	startoutput();
	while (nextvar(&length, &data, &name, &value)) {
		fmt = varfmt(name);
		output_raw = 0;
		switch (fmt) {

		case PADDING:
			output_raw = '*';
			break;

		case TS:
			if (!decodets(value, &lfp))
				output_raw = '?';
			else
				output(fp, name, prettydate(&lfp));
			break;

		case HA:	/* fallthru */
		case NA:
			if (!decodenetnum(value, &hval)) {
				output_raw = '?';
			} else if (fmt == HA){
				output(fp, name, nntohost(&hval));
			} else {
				output(fp, name, stoa(&hval));
			}
			break;

		case RF:
			if (decodenetnum(value, &hval)) {
				if (ISREFCLOCKADR(&hval))
					output(fp, name,
					       refnumtoa(&hval));
				else
					output(fp, name, stoa(&hval));
			} else if (strlen(value) <= 4) {
				output(fp, name, value);
			} else {
				output_raw = '?';
			}
			break;

		case LP:
			if (!decodeuint(value, &uval) || uval > 3) {
				output_raw = '?';
			} else {
				b[0] = (0x2 & uval)
					   ? '1'
					   : '0';
				b[1] = (0x1 & uval)
					   ? '1'
					   : '0';
				b[2] = '\0';
				output(fp, name, b);
			}
			break;

		case OC:
			if (!decodeuint(value, &uval)) {
				output_raw = '?';
			} else {
				snprintf(b, sizeof(b), ""%03lo"", uval);
				output(fp, name, b);
			}
			break;

		case AR:
			if (!decodearr(value, &narr, lfparr))
				output_raw = '?';
			else
				outputarr(fp, name, narr, lfparr);
			break;

		case FX:
			if (!decodeuint(value, &uval))
				output_raw = '?';
			else
				output(fp, name, tstflags(uval));
			break;

		default:
			fprintf(stderr, ""Internal error in cookedprint, %s=%s, fmt %d\n"",
				name, value, fmt);
			output_raw = '?';
			break;
		}

		if (output_raw != 0) {
			atoascii(name, MAXVARLEN, bn, sizeof(bn));
			atoascii(value, MAXVALLEN, bv, sizeof(bv));
			if (output_raw != '*') {
				len = strlen(bv);
				bv[len] = output_raw;
				bv[len+1] = '\0';
			}
			output(fp, bn, bv);
		}
	}
	endoutput(fp);
}",CWE-20,3
1,"static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
{
	struct kiocb *kiocb = &req->rw.kiocb;
	struct io_ring_ctx *ctx = req->ctx;
	struct file *file = req->file;
	int ret;

	if (unlikely(!file || !(file->f_mode & mode)))
		return -EBADF;

	if (!io_req_ffs_set(req))
		req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;

	kiocb->ki_flags = iocb_flags(file);
	ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
	if (unlikely(ret))
		return ret;

	/*
	 * If the file is marked O_NONBLOCK, still allow retry for it if it
	 * supports async. Otherwise it's impossible to use O_NONBLOCK files
	 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
	 */
	if ((kiocb->ki_flags & IOCB_NOWAIT) ||
	    ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
		req->flags |= REQ_F_NOWAIT;

	if (ctx->flags & IORING_SETUP_IOPOLL) {
		if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
			return -EOPNOTSUPP;

		kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
		kiocb->ki_complete = io_complete_rw_iopoll;
		req->iopoll_completed = 0;
	} else {
		if (kiocb->ki_flags & IOCB_HIPRI)
			return -EINVAL;
		kiocb->ki_complete = io_complete_rw;
	}

	return 0;
}",CWE-94,23
1,"regmatch(
    char_u	*scan,		    // Current node.
    proftime_T	*tm UNUSED,	    // timeout limit or NULL
    int		*timed_out UNUSED)  // flag set on timeout or NULL
{
  char_u	*next;		// Next node.
  int		op;
  int		c;
  regitem_T	*rp;
  int		no;
  int		status;		// one of the RA_ values:
#ifdef FEAT_RELTIME
  int		tm_count = 0;
#endif

  // Make ""regstack"" and ""backpos"" empty.  They are allocated and freed in
  // bt_regexec_both() to reduce malloc()/free() calls.
  regstack.ga_len = 0;
  backpos.ga_len = 0;

  // Repeat until ""regstack"" is empty.
  for (;;)
  {
    // Some patterns may take a long time to match, e.g., ""\([a-z]\+\)\+Q"".
    // Allow interrupting them with CTRL-C.
    fast_breakcheck();

#ifdef DEBUG
    if (scan != NULL && regnarrate)
    {
	mch_errmsg((char *)regprop(scan));
	mch_errmsg(""(\n"");
    }
#endif

    // Repeat for items that can be matched sequentially, without using the
    // regstack.
    for (;;)
    {
	if (got_int || scan == NULL)
	{
	    status = RA_FAIL;
	    break;
	}
#ifdef FEAT_RELTIME
	// Check for timeout once in a 100 times to avoid overhead.
	if (tm != NULL && ++tm_count == 100)
	{
	    tm_count = 0;
	    if (profile_passed_limit(tm))
	    {
		if (timed_out != NULL)
		    *timed_out = TRUE;
		status = RA_FAIL;
		break;
	    }
	}
#endif
	status = RA_CONT;

#ifdef DEBUG
	if (regnarrate)
	{
	    mch_errmsg((char *)regprop(scan));
	    mch_errmsg(""...\n"");
# ifdef FEAT_SYN_HL
	    if (re_extmatch_in != NULL)
	    {
		int i;

		mch_errmsg(_(""External submatches:\n""));
		for (i = 0; i < NSUBEXP; i++)
		{
		    mch_errmsg(""    \"""");
		    if (re_extmatch_in->matches[i] != NULL)
			mch_errmsg((char *)re_extmatch_in->matches[i]);
		    mch_errmsg(""\""\n"");
		}
	    }
# endif
	}
#endif
	next = regnext(scan);

	op = OP(scan);
	// Check for character class with NL added.
	if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
			     && *rex.input == NUL && rex.lnum <= rex.reg_maxline)
	{
	    reg_nextline();
	}
	else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n')
	{
	    ADVANCE_REGINPUT();
	}
	else
	{
	  if (WITH_NL(op))
	      op -= ADD_NL;
	  if (has_mbyte)
	      c = (*mb_ptr2char)(rex.input);
	  else
	      c = *rex.input;
	  switch (op)
	  {
	  case BOL:
	    if (rex.input != rex.line)
		status = RA_NOMATCH;
	    break;

	  case EOL:
	    if (c != NUL)
		status = RA_NOMATCH;
	    break;

	  case RE_BOF:
	    // We're not at the beginning of the file when below the first
	    // line where we started, not at the start of the line or we
	    // didn't start at the first line of the buffer.
	    if (rex.lnum != 0 || rex.input != rex.line
				       || (REG_MULTI && rex.reg_firstlnum > 1))
		status = RA_NOMATCH;
	    break;

	  case RE_EOF:
	    if (rex.lnum != rex.reg_maxline || c != NUL)
		status = RA_NOMATCH;
	    break;

	  case CURSOR:
	    // Check if the buffer is in a window and compare the
	    // rex.reg_win->w_cursor position to the match position.
	    if (rex.reg_win == NULL
		    || (rex.lnum + rex.reg_firstlnum
						 != rex.reg_win->w_cursor.lnum)
		    || ((colnr_T)(rex.input - rex.line)
						 != rex.reg_win->w_cursor.col))
		status = RA_NOMATCH;
	    break;

	  case RE_MARK:
	    // Compare the mark position to the match position.
	    {
		int	mark = OPERAND(scan)[0];
		int	cmp = OPERAND(scan)[1];
		pos_T	*pos;

		pos = getmark_buf(rex.reg_buf, mark, FALSE);
		if (pos == NULL		     // mark doesn't exist
			|| pos->lnum <= 0)   // mark isn't set in reg_buf
		{
		    status = RA_NOMATCH;
		}
		else
		{
		    colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
							  && pos->col == MAXCOL
				      ? (colnr_T)STRLEN(reg_getline(
						pos->lnum - rex.reg_firstlnum))
				      : pos->col;

		    if ((pos->lnum == rex.lnum + rex.reg_firstlnum
				? (pos_col == (colnr_T)(rex.input - rex.line)
				    ? (cmp == '<' || cmp == '>')
				    : (pos_col < (colnr_T)(rex.input - rex.line)
					? cmp != '>'
					: cmp != '<'))
				: (pos->lnum < rex.lnum + rex.reg_firstlnum
				    ? cmp != '>'
				    : cmp != '<')))
		    status = RA_NOMATCH;
		}
	    }
	    break;

	  case RE_VISUAL:
	    if (!reg_match_visual())
		status = RA_NOMATCH;
	    break;

	  case RE_LNUM:
	    if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum),
									scan))
		status = RA_NOMATCH;
	    break;

	  case RE_COL:
	    if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan))
		status = RA_NOMATCH;
	    break;

	  case RE_VCOL:
	    if (!re_num_cmp((long_u)win_linetabsize(
			    rex.reg_win == NULL ? curwin : rex.reg_win,
			    rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan))
		status = RA_NOMATCH;
	    break;

	  case BOW:	// \ rex.line
				&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))
		    status = RA_NOMATCH;
	    }
	    break;

	  case EOW:	// word\>; rex.input points after d
	    if (rex.input == rex.line)    // Can't match at start of line
		status = RA_NOMATCH;
	    else if (has_mbyte)
	    {
		int this_class, prev_class;

		// Get class of current and previous char (if it exists).
		this_class = mb_get_class_buf(rex.input, rex.reg_buf);
		prev_class = reg_prev_class();
		if (this_class == prev_class
			|| prev_class == 0 || prev_class == 1)
		    status = RA_NOMATCH;
	    }
	    else
	    {
		if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)
			|| (rex.input[0] != NUL
					   && vim_iswordc_buf(c, rex.reg_buf)))
		    status = RA_NOMATCH;
	    }
	    break; // Matched with EOW

	  case ANY:
	    // ANY does not match new lines.
	    if (c == NUL)
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case IDENT:
	    if (!vim_isIDc(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case SIDENT:
	    if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case KWORD:
	    if (!vim_iswordp_buf(rex.input, rex.reg_buf))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case SKWORD:
	    if (VIM_ISDIGIT(*rex.input)
				    || !vim_iswordp_buf(rex.input, rex.reg_buf))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case FNAME:
	    if (!vim_isfilec(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case SFNAME:
	    if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case PRINT:
	    if (!vim_isprintc(PTR2CHAR(rex.input)))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case SPRINT:
	    if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input)))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case WHITE:
	    if (!VIM_ISWHITE(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NWHITE:
	    if (c == NUL || VIM_ISWHITE(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case DIGIT:
	    if (!ri_digit(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NDIGIT:
	    if (c == NUL || ri_digit(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case HEX:
	    if (!ri_hex(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NHEX:
	    if (c == NUL || ri_hex(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case OCTAL:
	    if (!ri_octal(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NOCTAL:
	    if (c == NUL || ri_octal(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case WORD:
	    if (!ri_word(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NWORD:
	    if (c == NUL || ri_word(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case HEAD:
	    if (!ri_head(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NHEAD:
	    if (c == NUL || ri_head(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case ALPHA:
	    if (!ri_alpha(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NALPHA:
	    if (c == NUL || ri_alpha(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case LOWER:
	    if (!ri_lower(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NLOWER:
	    if (c == NUL || ri_lower(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case UPPER:
	    if (!ri_upper(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case NUPPER:
	    if (c == NUL || ri_upper(c))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case EXACTLY:
	    {
		int	len;
		char_u	*opnd;

		opnd = OPERAND(scan);
		// Inline the first byte, for speed.
		if (*opnd != *rex.input
			&& (!rex.reg_ic
			    || (!enc_utf8
			      && MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input))))
		    status = RA_NOMATCH;
		else if (*opnd == NUL)
		{
		    // match empty string always works; happens when ""~"" is
		    // empty.
		}
		else
		{
		    if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic))
		    {
			len = 1;	// matched a single byte above
		    }
		    else
		    {
			// Need to match first byte again for multi-byte.
			len = (int)STRLEN(opnd);
			if (cstrncmp(opnd, rex.input, &len) != 0)
			    status = RA_NOMATCH;
		    }
		    // Check for following composing character, unless %C
		    // follows (skips over all composing chars).
		    if (status != RA_NOMATCH
			    && enc_utf8
			    && UTF_COMPOSINGLIKE(rex.input, rex.input + len)
			    && !rex.reg_icombine
			    && OP(next) != RE_COMPOSING)
		    {
			// raaron: This code makes a composing character get
			// ignored, which is the correct behavior (sometimes)
			// for voweled Hebrew texts.
			status = RA_NOMATCH;
		    }
		    if (status != RA_NOMATCH)
			rex.input += len;
		}
	    }
	    break;

	  case ANYOF:
	  case ANYBUT:
	    if (c == NUL)
		status = RA_NOMATCH;
	    else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
		status = RA_NOMATCH;
	    else
		ADVANCE_REGINPUT();
	    break;

	  case MULTIBYTECODE:
	    if (has_mbyte)
	    {
		int	i, len;
		char_u	*opnd;
		int	opndc = 0, inpc;

		opnd = OPERAND(scan);
		// Safety check (just in case 'encoding' was changed since
		// compiling the program).
		if ((len = (*mb_ptr2len)(opnd)) < 2)
		{
		    status = RA_NOMATCH;
		    break;
		}
		if (enc_utf8)
		    opndc = utf_ptr2char(opnd);
		if (enc_utf8 && utf_iscomposing(opndc))
		{
		    // When only a composing char is given match at any
		    // position where that composing char appears.
		    status = RA_NOMATCH;
		    for (i = 0; rex.input[i] != NUL;
						i += utf_ptr2len(rex.input + i))
		    {
			inpc = utf_ptr2char(rex.input + i);
			if (!utf_iscomposing(inpc))
			{
			    if (i > 0)
				break;
			}
			else if (opndc == inpc)
			{
			    // Include all following composing chars.
			    len = i + utfc_ptr2len(rex.input + i);
			    status = RA_MATCH;
			    break;
			}
		    }
		}
		else
		    for (i = 0; i < len; ++i)
			if (opnd[i] != rex.input[i])
			{
			    status = RA_NOMATCH;
			    break;
			}
		rex.input += len;
	    }
	    else
		status = RA_NOMATCH;
	    break;
	  case RE_COMPOSING:
	    if (enc_utf8)
	    {
		// Skip composing characters.
		while (utf_iscomposing(utf_ptr2char(rex.input)))
		    MB_CPTR_ADV(rex.input);
	    }
	    break;

	  case NOTHING:
	    break;

	  case BACK:
	    {
		int		i;
		backpos_T	*bp;

		// When we run into BACK we need to check if we don't keep
		// looping without matching any input.  The second and later
		// times a BACK is encountered it fails if the input is still
		// at the same position as the previous time.
		// The positions are stored in ""backpos"" and found by the
		// current value of ""scan"", the position in the RE program.
		bp = (backpos_T *)backpos.ga_data;
		for (i = 0; i < backpos.ga_len; ++i)
		    if (bp[i].bp_scan == scan)
			break;
		if (i == backpos.ga_len)
		{
		    // First time at this BACK, make room to store the pos.
		    if (ga_grow(&backpos, 1) == FAIL)
			status = RA_FAIL;
		    else
		    {
			// get ""ga_data"" again, it may have changed
			bp = (backpos_T *)backpos.ga_data;
			bp[i].bp_scan = scan;
			++backpos.ga_len;
		    }
		}
		else if (reg_save_equal(&bp[i].bp_pos))
		    // Still at same position as last time, fail.
		    status = RA_NOMATCH;

		if (status != RA_FAIL && status != RA_NOMATCH)
		    reg_save(&bp[i].bp_pos, &backpos);
	    }
	    break;

	  case MOPEN + 0:   // Match start: \zs
	  case MOPEN + 1:   // \(
	  case MOPEN + 2:
	  case MOPEN + 3:
	  case MOPEN + 4:
	  case MOPEN + 5:
	  case MOPEN + 6:
	  case MOPEN + 7:
	  case MOPEN + 8:
	  case MOPEN + 9:
	    {
		no = op - MOPEN;
		cleanup_subexpr();
		rp = regstack_push(RS_MOPEN, scan);
		if (rp == NULL)
		    status = RA_FAIL;
		else
		{
		    rp->rs_no = no;
		    save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
							  &rex.reg_startp[no]);
		    // We simply continue and handle the result when done.
		}
	    }
	    break;

	  case NOPEN:	    // \%(
	  case NCLOSE:	    // \) after \%(
		if (regstack_push(RS_NOPEN, scan) == NULL)
		    status = RA_FAIL;
		// We simply continue and handle the result when done.
		break;

#ifdef FEAT_SYN_HL
	  case ZOPEN + 1:
	  case ZOPEN + 2:
	  case ZOPEN + 3:
	  case ZOPEN + 4:
	  case ZOPEN + 5:
	  case ZOPEN + 6:
	  case ZOPEN + 7:
	  case ZOPEN + 8:
	  case ZOPEN + 9:
	    {
		no = op - ZOPEN;
		cleanup_zsubexpr();
		rp = regstack_push(RS_ZOPEN, scan);
		if (rp == NULL)
		    status = RA_FAIL;
		else
		{
		    rp->rs_no = no;
		    save_se(&rp->rs_un.sesave, ®_startzpos[no],
							     ®_startzp[no]);
		    // We simply continue and handle the result when done.
		}
	    }
	    break;
#endif

	  case MCLOSE + 0:  // Match end: \ze
	  case MCLOSE + 1:  // \)
	  case MCLOSE + 2:
	  case MCLOSE + 3:
	  case MCLOSE + 4:
	  case MCLOSE + 5:
	  case MCLOSE + 6:
	  case MCLOSE + 7:
	  case MCLOSE + 8:
	  case MCLOSE + 9:
	    {
		no = op - MCLOSE;
		cleanup_subexpr();
		rp = regstack_push(RS_MCLOSE, scan);
		if (rp == NULL)
		    status = RA_FAIL;
		else
		{
		    rp->rs_no = no;
		    save_se(&rp->rs_un.sesave, &rex.reg_endpos[no],
							    &rex.reg_endp[no]);
		    // We simply continue and handle the result when done.
		}
	    }
	    break;

#ifdef FEAT_SYN_HL
	  case ZCLOSE + 1:  // \) after \z(
	  case ZCLOSE + 2:
	  case ZCLOSE + 3:
	  case ZCLOSE + 4:
	  case ZCLOSE + 5:
	  case ZCLOSE + 6:
	  case ZCLOSE + 7:
	  case ZCLOSE + 8:
	  case ZCLOSE + 9:
	    {
		no = op - ZCLOSE;
		cleanup_zsubexpr();
		rp = regstack_push(RS_ZCLOSE, scan);
		if (rp == NULL)
		    status = RA_FAIL;
		else
		{
		    rp->rs_no = no;
		    save_se(&rp->rs_un.sesave, ®_endzpos[no],
							      ®_endzp[no]);
		    // We simply continue and handle the result when done.
		}
	    }
	    break;
#endif

	  case BACKREF + 1:
	  case BACKREF + 2:
	  case BACKREF + 3:
	  case BACKREF + 4:
	  case BACKREF + 5:
	  case BACKREF + 6:
	  case BACKREF + 7:
	  case BACKREF + 8:
	  case BACKREF + 9:
	    {
		int		len;

		no = op - BACKREF;
		cleanup_subexpr();
		if (!REG_MULTI)		// Single-line regexp
		{
		    if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL)
		    {
			// Backref was not set: Match an empty string.
			len = 0;
		    }
		    else
		    {
			// Compare current input with back-ref in the same
			// line.
			len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
			if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0)
			    status = RA_NOMATCH;
		    }
		}
		else				// Multi-line regexp
		{
		    if (rex.reg_startpos[no].lnum < 0
						|| rex.reg_endpos[no].lnum < 0)
		    {
			// Backref was not set: Match an empty string.
			len = 0;
		    }
		    else
		    {
			if (rex.reg_startpos[no].lnum == rex.lnum
				&& rex.reg_endpos[no].lnum == rex.lnum)
			{
			    // Compare back-ref within the current line.
			    len = rex.reg_endpos[no].col
						    - rex.reg_startpos[no].col;
			    if (cstrncmp(rex.line + rex.reg_startpos[no].col,
							  rex.input, &len) != 0)
				status = RA_NOMATCH;
			}
			else
			{
			    // Messy situation: Need to compare between two
			    // lines.
			    int r = match_with_backref(
					    rex.reg_startpos[no].lnum,
					    rex.reg_startpos[no].col,
					    rex.reg_endpos[no].lnum,
					    rex.reg_endpos[no].col,
					    &len);

			    if (r != RA_MATCH)
				status = r;
			}
		    }
		}

		// Matched the backref, skip over it.
		rex.input += len;
	    }
	    break;

#ifdef FEAT_SYN_HL
	  case ZREF + 1:
	  case ZREF + 2:
	  case ZREF + 3:
	  case ZREF + 4:
	  case ZREF + 5:
	  case ZREF + 6:
	  case ZREF + 7:
	  case ZREF + 8:
	  case ZREF + 9:
	    {
		int	len;

		cleanup_zsubexpr();
		no = op - ZREF;
		if (re_extmatch_in != NULL
			&& re_extmatch_in->matches[no] != NULL)
		{
		    len = (int)STRLEN(re_extmatch_in->matches[no]);
		    if (cstrncmp(re_extmatch_in->matches[no],
							  rex.input, &len) != 0)
			status = RA_NOMATCH;
		    else
			rex.input += len;
		}
		else
		{
		    // Backref was not set: Match an empty string.
		}
	    }
	    break;
#endif

	  case BRANCH:
	    {
		if (OP(next) != BRANCH) // No choice.
		    next = OPERAND(scan);	// Avoid recursion.
		else
		{
		    rp = regstack_push(RS_BRANCH, scan);
		    if (rp == NULL)
			status = RA_FAIL;
		    else
			status = RA_BREAK;	// rest is below
		}
	    }
	    break;

	  case BRACE_LIMITS:
	    {
		if (OP(next) == BRACE_SIMPLE)
		{
		    bl_minval = OPERAND_MIN(scan);
		    bl_maxval = OPERAND_MAX(scan);
		}
		else if (OP(next) >= BRACE_COMPLEX
			&& OP(next) < BRACE_COMPLEX + 10)
		{
		    no = OP(next) - BRACE_COMPLEX;
		    brace_min[no] = OPERAND_MIN(scan);
		    brace_max[no] = OPERAND_MAX(scan);
		    brace_count[no] = 0;
		}
		else
		{
		    internal_error(""BRACE_LIMITS"");
		    status = RA_FAIL;
		}
	    }
	    break;

	  case BRACE_COMPLEX + 0:
	  case BRACE_COMPLEX + 1:
	  case BRACE_COMPLEX + 2:
	  case BRACE_COMPLEX + 3:
	  case BRACE_COMPLEX + 4:
	  case BRACE_COMPLEX + 5:
	  case BRACE_COMPLEX + 6:
	  case BRACE_COMPLEX + 7:
	  case BRACE_COMPLEX + 8:
	  case BRACE_COMPLEX + 9:
	    {
		no = op - BRACE_COMPLEX;
		++brace_count[no];

		// If not matched enough times yet, try one more
		if (brace_count[no] <= (brace_min[no] <= brace_max[no]
					     ? brace_min[no] : brace_max[no]))
		{
		    rp = regstack_push(RS_BRCPLX_MORE, scan);
		    if (rp == NULL)
			status = RA_FAIL;
		    else
		    {
			rp->rs_no = no;
			reg_save(&rp->rs_un.regsave, &backpos);
			next = OPERAND(scan);
			// We continue and handle the result when done.
		    }
		    break;
		}

		// If matched enough times, may try matching some more
		if (brace_min[no] <= brace_max[no])
		{
		    // Range is the normal way around, use longest match
		    if (brace_count[no] <= brace_max[no])
		    {
			rp = regstack_push(RS_BRCPLX_LONG, scan);
			if (rp == NULL)
			    status = RA_FAIL;
			else
			{
			    rp->rs_no = no;
			    reg_save(&rp->rs_un.regsave, &backpos);
			    next = OPERAND(scan);
			    // We continue and handle the result when done.
			}
		    }
		}
		else
		{
		    // Range is backwards, use shortest match first
		    if (brace_count[no] <= brace_min[no])
		    {
			rp = regstack_push(RS_BRCPLX_SHORT, scan);
			if (rp == NULL)
			    status = RA_FAIL;
			else
			{
			    reg_save(&rp->rs_un.regsave, &backpos);
			    // We continue and handle the result when done.
			}
		    }
		}
	    }
	    break;

	  case BRACE_SIMPLE:
	  case STAR:
	  case PLUS:
	    {
		regstar_T	rst;

		// Lookahead to avoid useless match attempts when we know
		// what character comes next.
		if (OP(next) == EXACTLY)
		{
		    rst.nextb = *OPERAND(next);
		    if (rex.reg_ic)
		    {
			if (MB_ISUPPER(rst.nextb))
			    rst.nextb_ic = MB_TOLOWER(rst.nextb);
			else
			    rst.nextb_ic = MB_TOUPPER(rst.nextb);
		    }
		    else
			rst.nextb_ic = rst.nextb;
		}
		else
		{
		    rst.nextb = NUL;
		    rst.nextb_ic = NUL;
		}
		if (op != BRACE_SIMPLE)
		{
		    rst.minval = (op == STAR) ? 0 : 1;
		    rst.maxval = MAX_LIMIT;
		}
		else
		{
		    rst.minval = bl_minval;
		    rst.maxval = bl_maxval;
		}

		// When maxval > minval, try matching as much as possible, up
		// to maxval.  When maxval < minval, try matching at least the
		// minimal number (since the range is backwards, that's also
		// maxval!).
		rst.count = regrepeat(OPERAND(scan), rst.maxval);
		if (got_int)
		{
		    status = RA_FAIL;
		    break;
		}
		if (rst.minval <= rst.maxval
			  ? rst.count >= rst.minval : rst.count >= rst.maxval)
		{
		    // It could match.  Prepare for trying to match what
		    // follows.  The code is below.  Parameters are stored in
		    // a regstar_T on the regstack.
		    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
		    {
			emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
			status = RA_FAIL;
		    }
		    else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)
			status = RA_FAIL;
		    else
		    {
			regstack.ga_len += sizeof(regstar_T);
			rp = regstack_push(rst.minval <= rst.maxval
					? RS_STAR_LONG : RS_STAR_SHORT, scan);
			if (rp == NULL)
			    status = RA_FAIL;
			else
			{
			    *(((regstar_T *)rp) - 1) = rst;
			    status = RA_BREAK;	    // skip the restore bits
			}
		    }
		}
		else
		    status = RA_NOMATCH;

	    }
	    break;

	  case NOMATCH:
	  case MATCH:
	  case SUBPAT:
	    rp = regstack_push(RS_NOMATCH, scan);
	    if (rp == NULL)
		status = RA_FAIL;
	    else
	    {
		rp->rs_no = op;
		reg_save(&rp->rs_un.regsave, &backpos);
		next = OPERAND(scan);
		// We continue and handle the result when done.
	    }
	    break;

	  case BEHIND:
	  case NOBEHIND:
	    // Need a bit of room to store extra positions.
	    if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
	    {
		emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
		status = RA_FAIL;
	    }
	    else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)
		status = RA_FAIL;
	    else
	    {
		regstack.ga_len += sizeof(regbehind_T);
		rp = regstack_push(RS_BEHIND1, scan);
		if (rp == NULL)
		    status = RA_FAIL;
		else
		{
		    // Need to save the subexpr to be able to restore them
		    // when there is a match but we don't use it.
		    save_subexpr(((regbehind_T *)rp) - 1);

		    rp->rs_no = op;
		    reg_save(&rp->rs_un.regsave, &backpos);
		    // First try if what follows matches.  If it does then we
		    // check the behind match by looping.
		}
	    }
	    break;

	  case BHPOS:
	    if (REG_MULTI)
	    {
		if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
			|| behind_pos.rs_u.pos.lnum != rex.lnum)
		    status = RA_NOMATCH;
	    }
	    else if (behind_pos.rs_u.ptr != rex.input)
		status = RA_NOMATCH;
	    break;

	  case NEWL:
	    if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
			     || rex.reg_line_lbr)
					   && (c != '\n' || !rex.reg_line_lbr))
		status = RA_NOMATCH;
	    else if (rex.reg_line_lbr)
		ADVANCE_REGINPUT();
	    else
		reg_nextline();
	    break;

	  case END:
	    status = RA_MATCH;	// Success!
	    break;

	  default:
	    iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
	    printf(""Illegal op code %d\n"", op);
#endif
	    status = RA_FAIL;
	    break;
	  }
	}

	// If we can't continue sequentially, break the inner loop.
	if (status != RA_CONT)
	    break;

	// Continue in inner loop, advance to next item.
	scan = next;

    } // end of inner loop

    // If there is something on the regstack execute the code for the state.
    // If the state is popped then loop and use the older state.
    while (regstack.ga_len > 0 && status != RA_FAIL)
    {
	rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
	switch (rp->rs_state)
	{
	  case RS_NOPEN:
	    // Result is passed on as-is, simply pop the state.
	    regstack_pop(&scan);
	    break;

	  case RS_MOPEN:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
		restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
						  &rex.reg_startp[rp->rs_no]);
	    regstack_pop(&scan);
	    break;

#ifdef FEAT_SYN_HL
	  case RS_ZOPEN:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
		restore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],
						 ®_startzp[rp->rs_no]);
	    regstack_pop(&scan);
	    break;
#endif

	  case RS_MCLOSE:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
		restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
						    &rex.reg_endp[rp->rs_no]);
	    regstack_pop(&scan);
	    break;

#ifdef FEAT_SYN_HL
	  case RS_ZCLOSE:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
		restore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],
						   ®_endzp[rp->rs_no]);
	    regstack_pop(&scan);
	    break;
#endif

	  case RS_BRANCH:
	    if (status == RA_MATCH)
		// this branch matched, use it
		regstack_pop(&scan);
	    else
	    {
		if (status != RA_BREAK)
		{
		    // After a non-matching branch: try next one.
		    reg_restore(&rp->rs_un.regsave, &backpos);
		    scan = rp->rs_scan;
		}
		if (scan == NULL || OP(scan) != BRANCH)
		{
		    // no more branches, didn't find a match
		    status = RA_NOMATCH;
		    regstack_pop(&scan);
		}
		else
		{
		    // Prepare to try a branch.
		    rp->rs_scan = regnext(scan);
		    reg_save(&rp->rs_un.regsave, &backpos);
		    scan = OPERAND(scan);
		}
	    }
	    break;

	  case RS_BRCPLX_MORE:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
	    {
		reg_restore(&rp->rs_un.regsave, &backpos);
		--brace_count[rp->rs_no];	// decrement match count
	    }
	    regstack_pop(&scan);
	    break;

	  case RS_BRCPLX_LONG:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
	    {
		// There was no match, but we did find enough matches.
		reg_restore(&rp->rs_un.regsave, &backpos);
		--brace_count[rp->rs_no];
		// continue with the items after ""\{}""
		status = RA_CONT;
	    }
	    regstack_pop(&scan);
	    if (status == RA_CONT)
		scan = regnext(scan);
	    break;

	  case RS_BRCPLX_SHORT:
	    // Pop the state.  Restore pointers when there is no match.
	    if (status == RA_NOMATCH)
		// There was no match, try to match one more item.
		reg_restore(&rp->rs_un.regsave, &backpos);
	    regstack_pop(&scan);
	    if (status == RA_NOMATCH)
	    {
		scan = OPERAND(scan);
		status = RA_CONT;
	    }
	    break;

	  case RS_NOMATCH:
	    // Pop the state.  If the operand matches for NOMATCH or
	    // doesn't match for MATCH/SUBPAT, we fail.  Otherwise backup,
	    // except for SUBPAT, and continue with the next item.
	    if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
		status = RA_NOMATCH;
	    else
	    {
		status = RA_CONT;
		if (rp->rs_no != SUBPAT)	// zero-width
		    reg_restore(&rp->rs_un.regsave, &backpos);
	    }
	    regstack_pop(&scan);
	    if (status == RA_CONT)
		scan = regnext(scan);
	    break;

	  case RS_BEHIND1:
	    if (status == RA_NOMATCH)
	    {
		regstack_pop(&scan);
		regstack.ga_len -= sizeof(regbehind_T);
	    }
	    else
	    {
		// The stuff after BEHIND/NOBEHIND matches.  Now try if
		// the behind part does (not) match before the current
		// position in the input.  This must be done at every
		// position in the input and checking if the match ends at
		// the current position.

		// save the position after the found match for next
		reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);

		// Start looking for a match with operand at the current
		// position.  Go back one character until we find the
		// result, hitting the start of the line or the previous
		// line (for multi-line matching).
		// Set behind_pos to where the match should end, BHPOS
		// will match it.  Save the current value.
		(((regbehind_T *)rp) - 1)->save_behind = behind_pos;
		behind_pos = rp->rs_un.regsave;

		rp->rs_state = RS_BEHIND2;

		reg_restore(&rp->rs_un.regsave, &backpos);
		scan = OPERAND(rp->rs_scan) + 4;
	    }
	    break;

	  case RS_BEHIND2:
	    // Looping for BEHIND / NOBEHIND match.
	    if (status == RA_MATCH && reg_save_equal(&behind_pos))
	    {
		// found a match that ends where ""next"" started
		behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
		if (rp->rs_no == BEHIND)
		    reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
								    &backpos);
		else
		{
		    // But we didn't want a match.  Need to restore the
		    // subexpr, because what follows matched, so they have
		    // been set.
		    status = RA_NOMATCH;
		    restore_subexpr(((regbehind_T *)rp) - 1);
		}
		regstack_pop(&scan);
		regstack.ga_len -= sizeof(regbehind_T);
	    }
	    else
	    {
		long limit;

		// No match or a match that doesn't end where we want it: Go
		// back one character.  May go to previous line once.
		no = OK;
		limit = OPERAND_MIN(rp->rs_scan);
		if (REG_MULTI)
		{
		    if (limit > 0
			    && ((rp->rs_un.regsave.rs_u.pos.lnum
						    < behind_pos.rs_u.pos.lnum
				    ? (colnr_T)STRLEN(rex.line)
				    : behind_pos.rs_u.pos.col)
				- rp->rs_un.regsave.rs_u.pos.col >= limit))
			no = FAIL;
		    else if (rp->rs_un.regsave.rs_u.pos.col == 0)
		    {
			if (rp->rs_un.regsave.rs_u.pos.lnum
					< behind_pos.rs_u.pos.lnum
				|| reg_getline(
					--rp->rs_un.regsave.rs_u.pos.lnum)
								  == NULL)
			    no = FAIL;
			else
			{
			    reg_restore(&rp->rs_un.regsave, &backpos);
			    rp->rs_un.regsave.rs_u.pos.col =
						 (colnr_T)STRLEN(rex.line);
			}
		    }
		    else
		    {
			if (has_mbyte)
			{
			    char_u *line =
				  reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);

			    rp->rs_un.regsave.rs_u.pos.col -=
				(*mb_head_off)(line, line
				    + rp->rs_un.regsave.rs_u.pos.col - 1) + 1;
			}
			else
			    --rp->rs_un.regsave.rs_u.pos.col;
		    }
		}
		else
		{
		    if (rp->rs_un.regsave.rs_u.ptr == rex.line)
			no = FAIL;
		    else
		    {
			MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
			if (limit > 0 && (long)(behind_pos.rs_u.ptr
				     - rp->rs_un.regsave.rs_u.ptr) > limit)
			    no = FAIL;
		    }
		}
		if (no == OK)
		{
		    // Advanced, prepare for finding match again.
		    reg_restore(&rp->rs_un.regsave, &backpos);
		    scan = OPERAND(rp->rs_scan) + 4;
		    if (status == RA_MATCH)
		    {
			// We did match, so subexpr may have been changed,
			// need to restore them for the next try.
			status = RA_NOMATCH;
			restore_subexpr(((regbehind_T *)rp) - 1);
		    }
		}
		else
		{
		    // Can't advance.  For NOBEHIND that's a match.
		    behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
		    if (rp->rs_no == NOBEHIND)
		    {
			reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
								    &backpos);
			status = RA_MATCH;
		    }
		    else
		    {
			// We do want a proper match.  Need to restore the
			// subexpr if we had a match, because they may have
			// been set.
			if (status == RA_MATCH)
			{
			    status = RA_NOMATCH;
			    restore_subexpr(((regbehind_T *)rp) - 1);
			}
		    }
		    regstack_pop(&scan);
		    regstack.ga_len -= sizeof(regbehind_T);
		}
	    }
	    break;

	  case RS_STAR_LONG:
	  case RS_STAR_SHORT:
	    {
		regstar_T	    *rst = ((regstar_T *)rp) - 1;

		if (status == RA_MATCH)
		{
		    regstack_pop(&scan);
		    regstack.ga_len -= sizeof(regstar_T);
		    break;
		}

		// Tried once already, restore input pointers.
		if (status != RA_BREAK)
		    reg_restore(&rp->rs_un.regsave, &backpos);

		// Repeat until we found a position where it could match.
		for (;;)
		{
		    if (status != RA_BREAK)
		    {
			// Tried first position already, advance.
			if (rp->rs_state == RS_STAR_LONG)
			{
			    // Trying for longest match, but couldn't or
			    // didn't match -- back up one char.
			    if (--rst->count < rst->minval)
				break;
			    if (rex.input == rex.line)
			    {
				// backup to last char of previous line
				if (rex.lnum == 0)
				{
				    status = RA_NOMATCH;
				    break;
				}
				--rex.lnum;
				rex.line = reg_getline(rex.lnum);
				// Just in case regrepeat() didn't count
				// right.
				if (rex.line == NULL)
				    break;
				rex.input = rex.line + STRLEN(rex.line);
				fast_breakcheck();
			    }
			    else
				MB_PTR_BACK(rex.line, rex.input);
			}
			else
			{
			    // Range is backwards, use shortest match first.
			    // Careful: maxval and minval are exchanged!
			    // Couldn't or didn't match: try advancing one
			    // char.
			    if (rst->count == rst->minval
				  || regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
				break;
			    ++rst->count;
			}
			if (got_int)
			    break;
		    }
		    else
			status = RA_NOMATCH;

		    // If it could match, try it.
		    if (rst->nextb == NUL || *rex.input == rst->nextb
					     || *rex.input == rst->nextb_ic)
		    {
			reg_save(&rp->rs_un.regsave, &backpos);
			scan = regnext(rp->rs_scan);
			status = RA_CONT;
			break;
		    }
		}
		if (status != RA_CONT)
		{
		    // Failed.
		    regstack_pop(&scan);
		    regstack.ga_len -= sizeof(regstar_T);
		    status = RA_NOMATCH;
		}
	    }
	    break;
	}

	// If we want to continue the inner loop or didn't pop a state
	// continue matching loop
	if (status == RA_CONT || rp == (regitem_T *)
			     ((char *)regstack.ga_data + regstack.ga_len) - 1)
	    break;
    }

    // May need to continue with the inner loop, starting at ""scan"".
    if (status == RA_CONT)
	continue;

    // If the regstack is empty or something failed we are done.
    if (regstack.ga_len == 0 || status == RA_FAIL)
    {
	if (scan == NULL)
	{
	    // We get here only if there's trouble -- normally ""case END"" is
	    // the terminating point.
	    iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
	    printf(""Premature EOL\n"");
#endif
	}
	return (status == RA_MATCH);
    }

  } // End of loop until the regstack is empty.

  // NOTREACHED
}",CWE-416,10
1,"mrb_f_send(mrb_state *mrb, mrb_value self)
{
  mrb_sym name;
  mrb_value block, *regs;
  mrb_method_t m;
  struct RClass *c;
  mrb_callinfo *ci = mrb->c->ci;
  int n = ci->n;

  if (ci->cci > CINFO_NONE) {
  funcall:;
    const mrb_value *argv;
    mrb_int argc;
    mrb_get_args(mrb, ""n*&"", &name, &argv, &argc, &block);
    return mrb_funcall_with_block(mrb, self, name, argc, argv, block);
  }

  regs = mrb->c->ci->stack+1;

  if (n == 0) {
    mrb_argnum_error(mrb, 0, 1, -1);
  }
  else if (n == 15) {
    name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]);
  }
  else {
    name = mrb_obj_to_sym(mrb, regs[0]);
  }

  c = mrb_class(mrb, self);
  m = mrb_method_search_vm(mrb, &c, name);
  if (MRB_METHOD_UNDEF_P(m)) {            /* call method_mising */
    goto funcall;
  }

  ci->mid = name;
  ci->u.target_class = c;
  /* remove first symbol from arguments */
  if (n == 15) {     /* variable length arguments */
    regs[0] = mrb_ary_subseq(mrb, regs[0], 1, RARRAY_LEN(regs[0]) - 1);
  }
  else { /* n > 0 */
    for (int i=0; ink > 0) {
      regs[n+1] = regs[n+2];    /* copy block */
    }
    ci->n--;
  }

  if (MRB_METHOD_CFUNC_P(m)) {
    if (MRB_METHOD_NOARG_P(m)) {
      check_method_noarg(mrb, ci);
    }

    if (MRB_METHOD_PROC_P(m)) {
      mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));
    }
    return MRB_METHOD_CFUNC(m)(mrb, self);
  }
  return exec_irep(mrb, self, MRB_METHOD_PROC(m));
}",CWE-787,16
1,"  void Compute(OpKernelContext* ctx) override {
    const Tensor* hypothesis_indices;
    const Tensor* hypothesis_values;
    const Tensor* hypothesis_shape;
    const Tensor* truth_indices;
    const Tensor* truth_values;
    const Tensor* truth_shape;
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_indices"", &hypothesis_indices));
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_values"", &hypothesis_values));
    OP_REQUIRES_OK(ctx, ctx->input(""hypothesis_shape"", &hypothesis_shape));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_indices"", &truth_indices));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_values"", &truth_values));
    OP_REQUIRES_OK(ctx, ctx->input(""truth_shape"", &truth_shape));

    OP_REQUIRES_OK(
        ctx, ValidateShapes(ctx, *hypothesis_indices, *hypothesis_values,
                            *hypothesis_shape, *truth_indices, *truth_values,
                            *truth_shape));

    TensorShape hypothesis_st_shape;
    OP_REQUIRES_OK(ctx,
                   TensorShapeUtils::MakeShape(
                       hypothesis_shape->vec().data(),
                       hypothesis_shape->NumElements(), &hypothesis_st_shape));
    TensorShape truth_st_shape;
    OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape(
                            truth_shape->vec().data(),
                            truth_shape->NumElements(), &truth_st_shape));

    // Assume indices are sorted in row-major order.
    std::vector sorted_order(truth_st_shape.dims());
    std::iota(sorted_order.begin(), sorted_order.end(), 0);

    sparse::SparseTensor hypothesis;
    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(
                            *hypothesis_indices, *hypothesis_values,
                            hypothesis_st_shape, sorted_order, &hypothesis));

    sparse::SparseTensor truth;
    OP_REQUIRES_OK(ctx, sparse::SparseTensor::Create(
                            *truth_indices, *truth_values, truth_st_shape,
                            sorted_order, &truth));

    // Group dims 0, 1, ..., RANK - 1.  The very last dim is assumed
    // to store the variable length sequences.
    std::vector group_dims(truth_st_shape.dims() - 1);
    std::iota(group_dims.begin(), group_dims.end(), 0);

    TensorShape output_shape;
    for (int d = 0; d < static_cast(group_dims.size()); ++d) {
      output_shape.AddDim(std::max(hypothesis_st_shape.dim_size(d),
                                   truth_st_shape.dim_size(d)));
    }
    const auto output_elements = output_shape.num_elements();
    OP_REQUIRES(
        ctx, output_elements > 0,
        errors::InvalidArgument(""Got output shape "", output_shape.DebugString(),
                                "" which has 0 elements""));

    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(""output"", output_shape, &output));
    auto output_t = output->flat();
    output_t.setZero();

    std::vector output_strides(output_shape.dims());
    output_strides[output_shape.dims() - 1] = 1;
    for (int d = output_shape.dims() - 2; d >= 0; --d) {
      output_strides[d] = output_strides[d + 1] * output_shape.dim_size(d + 1);
    }

    auto hypothesis_grouper = hypothesis.group(group_dims);
    auto truth_grouper = truth.group(group_dims);

    auto hypothesis_iter = hypothesis_grouper.begin();
    auto truth_iter = truth_grouper.begin();

    auto cmp = std::equal_to();

    while (hypothesis_iter != hypothesis_grouper.end() &&
           truth_iter != truth_grouper.end()) {
      sparse::Group truth_i = *truth_iter;
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector g_truth = truth_i.group();
      std::vector g_hypothesis = hypothesis_j.group();
      auto truth_seq = truth_i.values();
      auto hypothesis_seq = hypothesis_j.values();

      if (g_truth == g_hypothesis) {
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) =
            gtl::LevenshteinDistance(truth_seq, hypothesis_seq, cmp);
        if (normalize_) output_t(loc) /= truth_seq.size();

        ++hypothesis_iter;
        ++truth_iter;
      } else if (g_truth > g_hypothesis) {  // zero-length truth
        auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) = hypothesis_seq.size();
        if (normalize_ && output_t(loc) != 0.0f) {
          output_t(loc) = std::numeric_limits::infinity();
        }
        ++hypothesis_iter;
      } else {  // zero-length hypothesis
        auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                      output_strides.begin(), int64_t{0});
        OP_REQUIRES(
            ctx, loc < output_elements,
            errors::Internal(""Got an inner product "", loc,
                             "" which would require in writing to outside of ""
                             ""the buffer for the output tensor (max elements "",
                             output_elements, "")""));
        output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
        ++truth_iter;
      }
    }
    while (hypothesis_iter != hypothesis_grouper.end()) {  // zero-length truths
      sparse::Group hypothesis_j = *hypothesis_iter;
      std::vector g_hypothesis = hypothesis_j.group();
      auto hypothesis_seq = hypothesis_j.values();
      auto loc = std::inner_product(g_hypothesis.begin(), g_hypothesis.end(),
                                    output_strides.begin(), int64_t{0});
      OP_REQUIRES(
          ctx, loc < output_elements,
          errors::Internal(""Got an inner product "", loc,
                           "" which would require in writing to outside of the ""
                           ""buffer for the output tensor (max elements "",
                           output_elements, "")""));
      output_t(loc) = hypothesis_seq.size();
      if (normalize_ && output_t(loc) != 0.0f) {
        output_t(loc) = std::numeric_limits::infinity();
      }
      ++hypothesis_iter;
    }
    while (truth_iter != truth_grouper.end()) {  // missing hypotheses
      sparse::Group truth_i = *truth_iter;
      std::vector g_truth = truth_i.group();
      auto truth_seq = truth_i.values();
      auto loc = std::inner_product(g_truth.begin(), g_truth.end(),
                                    output_strides.begin(), int64_t{0});
      OP_REQUIRES(
          ctx, loc < output_elements,
          errors::Internal(""Got an inner product "", loc,
                           "" which would require in writing to outside of the ""
                           ""buffer for the output tensor (max elements "",
                           output_elements, "")""));
      output_t(loc) = (normalize_) ? 1.0 : truth_seq.size();
      ++truth_iter;
    }
  }",CWE-787,16
1,"HandleCoRREBPP (rfbClient* client, int rx, int ry, int rw, int rh)
{
    rfbRREHeader hdr;
    int i;
    CARDBPP pix;
    uint8_t *ptr;
    int x, y, w, h;

    if (!ReadFromRFBServer(client, (char *)&hdr, sz_rfbRREHeader))
	return FALSE;

    hdr.nSubrects = rfbClientSwap32IfLE(hdr.nSubrects);

    if (!ReadFromRFBServer(client, (char *)&pix, sizeof(pix)))
	return FALSE;

    client->GotFillRect(client, rx, ry, rw, rh, pix);

    if (hdr.nSubrects * (4 + (BPP / 8)) > RFB_BUFFER_SIZE || !ReadFromRFBServer(client, client->buffer, hdr.nSubrects * (4 + (BPP / 8))))
	return FALSE;

    ptr = (uint8_t *)client->buffer;

    for (i = 0; i < hdr.nSubrects; i++) {
	pix = *(CARDBPP *)ptr;
	ptr += BPP/8;
	x = *ptr++;
	y = *ptr++;
	w = *ptr++;
	h = *ptr++;

	client->GotFillRect(client, rx+x, ry+y, w, h, pix);
    }

    return TRUE;
}",CWE-787,16
0,"QuotaManager::UsageAndQuotaDispatcherTask::Create(
    QuotaManager* manager, const std::string& host, StorageType type) {
  switch (type) {
    case kStorageTypeTemporary:
      return new UsageAndQuotaDispatcherTaskForTemporary(
          manager, host);
    case kStorageTypePersistent:
      return new UsageAndQuotaDispatcherTaskForPersistent(
          manager, host);
    default:
      NOTREACHED();
  }
  return NULL;
}
",none,24
0,"    static void NetworkStatusChangedHandler(void* object,
                                            const char* path,
                                            const char* key,
                                            const Value* value) {
      NetworkLibraryImpl* networklib = static_cast(object);
      DCHECK(networklib);
      networklib->UpdateNetworkStatus(path, key, value);
    }
",none,24
0,"    virtual ~NetworkObserverList() {
      if (network_monitor_)
        DisconnectPropertyChangeMonitor(network_monitor_);
    }
",none,24
0,"void QuotaManager::GetLRUOrigin(
    StorageType type,
    GetLRUOriginCallback* callback) {
  LazyInitialize();
  DCHECK(!lru_origin_callback_.get());
  lru_origin_callback_.reset(callback);
  if (db_disabled_) {
    lru_origin_callback_->Run(GURL());
    lru_origin_callback_.reset();
    return;
  }
  scoped_refptr task(new GetLRUOriginTask(
      this, type, origins_in_use_,
      origins_in_error_, callback_factory_.NewCallback(
          &QuotaManager::DidGetDatabaseLRUOrigin)));
  task->Start();
}
",none,24
1,"asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim)
{
	struct rlimit new_rlim, *old_rlim;
	unsigned long it_prof_secs;
	int retval;

	if (resource >= RLIM_NLIMITS)
		return -EINVAL;
	if (copy_from_user(&new_rlim, rlim, sizeof(*rlim)))
		return -EFAULT;
	if (new_rlim.rlim_cur > new_rlim.rlim_max)
		return -EINVAL;
	old_rlim = current->signal->rlim + resource;
	if ((new_rlim.rlim_max > old_rlim->rlim_max) &&
	    !capable(CAP_SYS_RESOURCE))
		return -EPERM;
	if (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN)
		return -EPERM;

	retval = security_task_setrlimit(resource, &new_rlim);
	if (retval)
		return retval;

	task_lock(current->group_leader);
	*old_rlim = new_rlim;
	task_unlock(current->group_leader);

	if (resource != RLIMIT_CPU)
		goto out;

	/*
	 * RLIMIT_CPU handling.   Note that the kernel fails to return an error
	 * code if it rejected the user's attempt to set RLIMIT_CPU.  This is a
	 * very long-standing error, and fixing it now risks breakage of
	 * applications, so we live with it
	 */
	if (new_rlim.rlim_cur == RLIM_INFINITY)
		goto out;

	it_prof_secs = cputime_to_secs(current->signal->it_prof_expires);
	if (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) {
		unsigned long rlim_cur = new_rlim.rlim_cur;
		cputime_t cputime;

		if (rlim_cur == 0) {
			/*
			 * The caller is asking for an immediate RLIMIT_CPU
			 * expiry.  But we use the zero value to mean ""it was
			 * never set"".  So let's cheat and make it one second
			 * instead
			 */
			rlim_cur = 1;
		}
		cputime = secs_to_cputime(rlim_cur);
		read_lock(&tasklist_lock);
		spin_lock_irq(¤t->sighand->siglock);
		set_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL);
		spin_unlock_irq(¤t->sighand->siglock);
		read_unlock(&tasklist_lock);
	}
out:
	return 0;
}",CWE-20,3
0,"  virtual void SaveWifiNetwork(const WifiNetwork* network) {}
",none,24
0,"   void DidGetUsageAndQuota(QuotaStatusCode status, int64 usage, int64 quota) {
     quota_status_ = status;
     usage_ = usage;
    quota_ = quota;
  }
",none,24
0,"  virtual std::string GetHtmlInfo(int refresh) { return std::string(); }
",none,24
1,"  void Compute(tensorflow::OpKernelContext* context) override {
    for (int ngram_width : ngram_widths_) {
      OP_REQUIRES(
          context, ngram_width > 0,
          errors::InvalidArgument(""ngram_widths must contain positive values""));
    }

    const tensorflow::Tensor* data;
    OP_REQUIRES_OK(context, context->input(""data"", &data));
    const auto& input_data = data->flat().data();

    const tensorflow::Tensor* splits;
    OP_REQUIRES_OK(context, context->input(""data_splits"", &splits));
    const auto& splits_vec = splits->flat();

    // Validate that the splits are valid indices into data, only if there are
    // splits specified.
    const int input_data_size = data->flat().size();
    const int splits_vec_size = splits_vec.size();
    if (splits_vec_size > 0) {
      int prev_split = splits_vec(0);
      OP_REQUIRES(context, prev_split == 0,
                  errors::InvalidArgument(""First split value must be 0, got "",
                                          prev_split));
      for (int i = 1; i < splits_vec_size; ++i) {
        bool valid_splits = splits_vec(i) >= prev_split;
        valid_splits = valid_splits && (splits_vec(i) <= input_data_size);
        OP_REQUIRES(context, valid_splits,
                    errors::InvalidArgument(
                        ""Invalid split value "", splits_vec(i), "", must be in ["",
                        prev_split, "", "", input_data_size, ""]""));
        prev_split = splits_vec(i);
      }
      OP_REQUIRES(context, prev_split == input_data_size,
                  errors::InvalidArgument(
                      ""Last split value must be data size. Expected "",
                      input_data_size, "", got "", prev_split));
    }

    int num_batch_items = splits_vec.size() - 1;
    tensorflow::Tensor* ngrams_splits;
    OP_REQUIRES_OK(
        context, context->allocate_output(1, splits->shape(), &ngrams_splits));
    auto ngrams_splits_data = ngrams_splits->flat().data();

    // If there is no data or size, return an empty RT.
    if (data->flat().size() == 0 || splits_vec.size() == 0) {
      tensorflow::Tensor* empty;
      OP_REQUIRES_OK(context,
                     context->allocate_output(0, data->shape(), &empty));
      for (int i = 0; i <= num_batch_items; ++i) {
        ngrams_splits_data[i] = 0;
      }
      return;
    }

    ngrams_splits_data[0] = 0;
    for (int i = 1; i <= num_batch_items; ++i) {
      int length = splits_vec(i) - splits_vec(i - 1);
      int num_ngrams = 0;
      for (int ngram_width : ngram_widths_)
        num_ngrams += get_num_ngrams(length, ngram_width);
      if (preserve_short_ && length > 0 && num_ngrams == 0) {
        num_ngrams = 1;
      }
      ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams;
    }

    tensorflow::Tensor* ngrams;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams));
    auto ngrams_data = ngrams->flat().data();

    for (int i = 0; i < num_batch_items; ++i) {
      auto data_start = &input_data[splits_vec(i)];
      int output_start_idx = ngrams_splits_data[i];
      for (int ngram_width : ngram_widths_) {
        auto output_start = &ngrams_data[output_start_idx];
        int length = splits_vec(i + 1) - splits_vec(i);
        int num_ngrams = get_num_ngrams(length, ngram_width);
        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
        output_start_idx += num_ngrams;
      }
      // If we're preserving short sequences, check to see if no sequence was
      // generated by comparing the current output start idx to the original
      // one (ngram_splits_data). If no ngrams were generated, then they will
      // be equal (since we increment output_start_idx by num_ngrams every
      // time we create a set of ngrams.)
      if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) {
        int data_length = splits_vec(i + 1) - splits_vec(i);
        // One legitimate reason to not have any ngrams when preserve_short_
        // is true is if the sequence itself is empty. In that case, move on.
        if (data_length == 0) {
          continue;
        }
        // We don't have to worry about dynamic padding sizes here: if padding
        // was dynamic, every sequence would have had sufficient padding to
        // generate at least one ngram.
        int ngram_width = data_length + 2 * pad_width_;
        auto output_start = &ngrams_data[output_start_idx];
        int num_ngrams = 1;
        CreateNgrams(data_start, output_start, num_ngrams, ngram_width);
      }
    }
  }",CWE-190,2
1,"    kssl_keytab_is_available(KSSL_CTX *kssl_ctx)
{
    krb5_context		krb5context = NULL;
    krb5_keytab 		krb5keytab = NULL;
    krb5_keytab_entry           entry;
    krb5_principal              princ = NULL;
    krb5_error_code  		krb5rc = KRB5KRB_ERR_GENERIC;
    int rc = 0;

    if ((krb5rc = krb5_init_context(&krb5context)))
        return(0);

    /*	kssl_ctx->keytab_file == NULL ==> use Kerberos default
    */
    if (kssl_ctx->keytab_file)
    {
        krb5rc = krb5_kt_resolve(krb5context, kssl_ctx->keytab_file,
                                  &krb5keytab);
        if (krb5rc)
            goto exit;
    }
    else
    {
        krb5rc = krb5_kt_default(krb5context,&krb5keytab);
        if (krb5rc)
            goto exit;
    }

    /* the host key we are looking for */
    krb5rc = krb5_sname_to_principal(krb5context, NULL, 
                                     kssl_ctx->service_name ? kssl_ctx->service_name: KRB5SVC,
                                     KRB5_NT_SRV_HST, &princ);

    krb5rc = krb5_kt_get_entry(krb5context, krb5keytab, 
                                princ,
                                0 /* IGNORE_VNO */,
                                0 /* IGNORE_ENCTYPE */,
                                &entry);
    if ( krb5rc == KRB5_KT_NOTFOUND ) {
        rc = 1;
        goto exit;
    } else if ( krb5rc )
        goto exit;
    
    krb5_kt_free_entry(krb5context, &entry);
    rc = 1;

  exit:
    if (krb5keytab)     krb5_kt_close(krb5context, krb5keytab);
    if (princ)          krb5_free_principal(krb5context, princ);
    if (krb5context)	krb5_free_context(krb5context);
    return(rc);
}",CWE-20,3
1,"bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)
{
    int		c;
    char_u	buf[NUMBUFLEN + MB_MAXBYTES];
    int		idx = 0;
    char_u	*end = find_termcode((char_u *)""PE"");
    int		ret_char = -1;
    int		save_allow_keys = allow_keys;
    int		save_paste = p_paste;

    // If the end code is too long we can't detect it, read everything.
    if (end != NULL && STRLEN(end) >= NUMBUFLEN)
	end = NULL;
    ++no_mapping;
    allow_keys = 0;
    if (!p_paste)
	// Also have the side effects of setting 'paste' to make it work much
	// faster.
	set_option_value((char_u *)""paste"", TRUE, NULL, 0);

    for (;;)
    {
	// When the end is not defined read everything there is.
	if (end == NULL && vpeekc() == NUL)
	    break;
	do
	    c = vgetc();
	while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
	if (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))
	    // When CTRL-C was encountered the typeahead will be flushed and we
	    // won't get the end sequence.  Except when using "":normal"".
	    break;

	if (has_mbyte)
	    idx += (*mb_char2bytes)(c, buf + idx);
	else
	    buf[idx++] = c;
	buf[idx] = NUL;
	if (end != NULL && STRNCMP(buf, end, idx) == 0)
	{
	    if (end[idx] == NUL)
		break; // Found the end of paste code.
	    continue;
	}
	if (!drop)
	{
	    switch (mode)
	    {
		case PASTE_CMDLINE:
		    put_on_cmdline(buf, idx, TRUE);
		    break;

		case PASTE_EX:
		    if (gap != NULL && ga_grow(gap, idx) == OK)
		    {
			mch_memmove((char *)gap->ga_data + gap->ga_len,
							     buf, (size_t)idx);
			gap->ga_len += idx;
		    }
		    break;

		case PASTE_INSERT:
		    if (stop_arrow() == OK)
		    {
			c = buf[0];
			if (idx == 1 && (c == CAR || c == K_KENTER || c == NL))
			    ins_eol(c);
			else
			{
			    ins_char_bytes(buf, idx);
			    AppendToRedobuffLit(buf, idx);
			}
		    }
		    break;

		case PASTE_ONE_CHAR:
		    if (ret_char == -1)
		    {
			if (has_mbyte)
			    ret_char = (*mb_ptr2char)(buf);
			else
			    ret_char = buf[0];
		    }
		    break;
	    }
	}
	idx = 0;
    }

    --no_mapping;
    allow_keys = save_allow_keys;
    if (!save_paste)
	set_option_value((char_u *)""paste"", FALSE, NULL, 0);

    return ret_char;
}",CWE-787,16
1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
	struct inode **i)
{
	struct squashfs_dir_header dirh;
	char buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]
		__attribute__((aligned));
	struct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;
	long long start;
	long long bytes;
	int dir_count, size;
	struct dir_ent *new_dir;
	struct dir *dir;

	TRACE(""squashfs_opendir: inode start block %d, offset %d\n"",
		block_start, offset);

	*i = read_inode(block_start, offset);

	dir = malloc(sizeof(struct dir));
	if(dir == NULL)
		EXIT_UNSQUASH(""squashfs_opendir: malloc failed!\n"");

	dir->dir_count = 0;
	dir->cur_entry = 0;
	dir->mode = (*i)->mode;
	dir->uid = (*i)->uid;
	dir->guid = (*i)->gid;
	dir->mtime = (*i)->time;
	dir->xattr = (*i)->xattr;
	dir->dirs = NULL;

	if ((*i)->data == 3)
		/*
		 * if the directory is empty, skip the unnecessary
		 * lookup_entry, this fixes the corner case with
		 * completely empty filesystems where lookup_entry correctly
		 * returning -1 is incorrectly treated as an error
		 */
		return dir;

	start = sBlk.s.directory_table_start + (*i)->start;
	bytes = lookup_entry(directory_table_hash, start);

	if(bytes == -1)
		EXIT_UNSQUASH(""squashfs_opendir: directory block %lld not ""
			""found!\n"", start);

	bytes += (*i)->offset;
	size = (*i)->data + bytes - 3;

	while(bytes < size) {			
		SQUASHFS_SWAP_DIR_HEADER(directory_table + bytes, &dirh);
	
		dir_count = dirh.count + 1;
		TRACE(""squashfs_opendir: Read directory header @ byte position ""
			""%d, %d directory entries\n"", bytes, dir_count);
		bytes += sizeof(dirh);

		/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
		if(dir_count > SQUASHFS_DIR_COUNT) {
			ERROR(""File system corrupted: too many entries in directory\n"");
			goto corrupted;
		}

		while(dir_count--) {
			SQUASHFS_SWAP_DIR_ENTRY(directory_table + bytes, dire);

			bytes += sizeof(*dire);

			/* size should never be SQUASHFS_NAME_LEN or larger */
			if(dire->size >= SQUASHFS_NAME_LEN) {
				ERROR(""File system corrupted: filename too long\n"");
				goto corrupted;
			}

			memcpy(dire->name, directory_table + bytes,
				dire->size + 1);
			dire->name[dire->size + 1] = '\0';
			TRACE(""squashfs_opendir: directory entry %s, inode ""
				""%d:%d, type %d\n"", dire->name,
				dirh.start_block, dire->offset, dire->type);
			if((dir->dir_count % DIR_ENT_SIZE) == 0) {
				new_dir = realloc(dir->dirs, (dir->dir_count +
					DIR_ENT_SIZE) * sizeof(struct dir_ent));
				if(new_dir == NULL)
					EXIT_UNSQUASH(""squashfs_opendir: ""
						""realloc failed!\n"");
				dir->dirs = new_dir;
			}
			strcpy(dir->dirs[dir->dir_count].name, dire->name);
			dir->dirs[dir->dir_count].start_block =
				dirh.start_block;
			dir->dirs[dir->dir_count].offset = dire->offset;
			dir->dirs[dir->dir_count].type = dire->type;
			dir->dir_count ++;
			bytes += dire->size + 1;
		}
	}

	return dir;

corrupted:
	free(dir->dirs);
	free(dir);
	return NULL;
}",CWE-22,5
1,"block_insert(
    oparg_T		*oap,
    char_u		*s,
    int			b_insert,
    struct block_def	*bdp)
{
    int		ts_val;
    int		count = 0;	// extra spaces to replace a cut TAB
    int		spaces = 0;	// non-zero if cutting a TAB
    colnr_T	offset;		// pointer along new line
    colnr_T	startcol;	// column where insert starts
    unsigned	s_len;		// STRLEN(s)
    char_u	*newp, *oldp;	// new, old lines
    linenr_T	lnum;		// loop var
    int		oldstate = State;

    State = INSERT;		// don't want REPLACE for State
    s_len = (unsigned)STRLEN(s);

    for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)
    {
	block_prep(oap, bdp, lnum, TRUE);
	if (bdp->is_short && b_insert)
	    continue;	// OP_INSERT, line ends before block start

	oldp = ml_get(lnum);

	if (b_insert)
	{
	    ts_val = bdp->start_char_vcols;
	    spaces = bdp->startspaces;
	    if (spaces != 0)
		count = ts_val - 1; // we're cutting a TAB
	    offset = bdp->textcol;
	}
	else // append
	{
	    ts_val = bdp->end_char_vcols;
	    if (!bdp->is_short) // spaces = padding after block
	    {
		spaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);
		if (spaces != 0)
		    count = ts_val - 1; // we're cutting a TAB
		offset = bdp->textcol + bdp->textlen - (spaces != 0);
	    }
	    else // spaces = padding to block edge
	    {
		// if $ used, just append to EOL (ie spaces==0)
		if (!bdp->is_MAX)
		    spaces = (oap->end_vcol - bdp->end_vcol) + 1;
		count = spaces;
		offset = bdp->textcol + bdp->textlen;
	    }
	}

	if (has_mbyte && spaces > 0)
	{
	    int off;

	    // Avoid starting halfway a multi-byte character.
	    if (b_insert)
	    {
		off = (*mb_head_off)(oldp, oldp + offset + spaces);
		spaces -= off;
		count -= off;
	    }
	    else
	    {
		// spaces fill the gap, the character that's at the edge moves
		// right
		off = (*mb_head_off)(oldp, oldp + offset);
		offset -= off;
	    }
	}
	if (spaces < 0)  // can happen when the cursor was moved
	    spaces = 0;

	// Make sure the allocated size matches what is actually copied below.
	newp = alloc(STRLEN(oldp) + spaces + s_len
		    + (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0)
								  + count + 1);
	if (newp == NULL)
	    continue;

	// copy up to shifted part
	mch_memmove(newp, oldp, (size_t)offset);
	oldp += offset;

	// insert pre-padding
	vim_memset(newp + offset, ' ', (size_t)spaces);
	startcol = offset + spaces;

	// copy the new text
	mch_memmove(newp + startcol, s, (size_t)s_len);
	offset += s_len;

	if (spaces > 0 && !bdp->is_short)
	{
	    if (*oldp == TAB)
	    {
		// insert post-padding
		vim_memset(newp + offset + spaces, ' ',
						    (size_t)(ts_val - spaces));
		// we're splitting a TAB, don't copy it
		oldp++;
		// We allowed for that TAB, remember this now
		count++;
	    }
	    else
		// Not a TAB, no extra spaces
		count = spaces;
	}

	if (spaces > 0)
	    offset += count;
	STRMOVE(newp + offset, oldp);

	ml_replace(lnum, newp, FALSE);

	if (b_insert)
	    // correct any text properties
	    inserted_bytes(lnum, startcol, s_len);

	if (lnum == oap->end.lnum)
	{
	    // Set ""']"" mark to the end of the block instead of the end of
	    // the insert in the first line.
	    curbuf->b_op_end.lnum = oap->end.lnum;
	    curbuf->b_op_end.col = offset;
	}
    } // for all lnum

    changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);

    State = oldstate;
}",CWE-787,16
1,"static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId,
                                                    UINT32 x, UINT32 y, UINT32 width, UINT32 height)
{
	VideoClientContextPriv* priv = video->priv;
	PresentationContext* ret = calloc(1, sizeof(*ret));
	if (!ret)
		return NULL;

	ret->video = video;
	ret->PresentationId = PresentationId;

	ret->h264 = h264_context_new(FALSE);
	if (!ret->h264)
	{
		WLog_ERR(TAG, ""unable to create a h264 context"");
		goto error_h264;
	}
	h264_context_reset(ret->h264, width, height);

	ret->currentSample = Stream_New(NULL, 4096);
	if (!ret->currentSample)
	{
		WLog_ERR(TAG, ""unable to create current packet stream"");
		goto error_currentSample;
	}

	ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4);
	if (!ret->surfaceData)
	{
		WLog_ERR(TAG, ""unable to allocate surfaceData"");
		goto error_surfaceData;
	}

	ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height);
	if (!ret->surface)
	{
		WLog_ERR(TAG, ""unable to create surface"");
		goto error_surface;
	}

	ret->yuv = yuv_context_new(FALSE);
	if (!ret->yuv)
	{
		WLog_ERR(TAG, ""unable to create YUV decoder"");
		goto error_yuv;
	}

	yuv_context_reset(ret->yuv, width, height);
	ret->refCounter = 1;
	return ret;

error_yuv:
	video->deleteSurface(video, ret->surface);
error_surface:
	BufferPool_Return(priv->surfacePool, ret->surfaceData);
error_surfaceData:
	Stream_Free(ret->currentSample, TRUE);
error_currentSample:
	h264_context_free(ret->h264);
error_h264:
	free(ret);
	return NULL;
}",CWE-190,2
0,"  virtual void RequestWifiScan() {}
",none,24
1,"njs_promise_perform_then(njs_vm_t *vm, njs_value_t *value,
    njs_value_t *fulfilled, njs_value_t *rejected,
    njs_promise_capability_t *capability)
{
    njs_int_t               ret;
    njs_value_t             arguments[2];
    njs_promise_t           *promise;
    njs_function_t          *function;
    njs_promise_data_t      *data;
    njs_promise_reaction_t  *fulfilled_reaction, *rejected_reaction;

    if (!njs_is_function(fulfilled)) {
        fulfilled = njs_value_arg(&njs_value_undefined);
    }

    if (!njs_is_function(rejected)) {
        rejected = njs_value_arg(&njs_value_undefined);
    }

    promise = njs_promise(value);
    data = njs_data(&promise->value);

    fulfilled_reaction = njs_mp_alloc(vm->mem_pool,
                                      sizeof(njs_promise_reaction_t));
    if (njs_slow_path(fulfilled_reaction == NULL)) {
        njs_memory_error(vm);
        return NJS_ERROR;
    }

    fulfilled_reaction->capability = capability;
    fulfilled_reaction->handler = *fulfilled;
    fulfilled_reaction->type = NJS_PROMISE_FULFILL;

    rejected_reaction = njs_mp_alloc(vm->mem_pool,
                                     sizeof(njs_promise_reaction_t));
    if (njs_slow_path(rejected_reaction == NULL)) {
        njs_memory_error(vm);
        return NJS_ERROR;
    }

    rejected_reaction->capability = capability;
    rejected_reaction->handler = *rejected;
    rejected_reaction->type = NJS_PROMISE_REJECTED;

    if (data->state == NJS_PROMISE_PENDING) {
        njs_queue_insert_tail(&data->fulfill_queue, &fulfilled_reaction->link);
        njs_queue_insert_tail(&data->reject_queue, &rejected_reaction->link);

    } else {
        function = njs_promise_create_function(vm,
                                               sizeof(njs_promise_context_t));
        function->u.native = njs_promise_reaction_job;

        if (data->state == NJS_PROMISE_REJECTED) {
            njs_set_data(&arguments[0], rejected_reaction, 0);

            ret = njs_promise_host_rejection_tracker(vm, promise,
                                                     NJS_PROMISE_HANDLE);
            if (njs_slow_path(ret != NJS_OK)) {
                return ret;
            }

        } else {
            njs_set_data(&arguments[0], fulfilled_reaction, 0);
        }

        arguments[1] = data->result;

        ret = njs_promise_add_event(vm, function, arguments, 2);
        if (njs_slow_path(ret != NJS_OK)) {
            return ret;
        }
    }

    data->is_handled = 1;

    if (capability == NULL) {
        njs_vm_retval_set(vm, &njs_value_undefined);

    } else {
        njs_vm_retval_set(vm, &capability->promise);
    }

    return NJS_OK;
}",CWE-269,6
1,"R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
	ut64 offset = 6;
	RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
	if (attr) {
		attr->type = R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR;
		attr->info.constant_value_attr.constantvalue_idx = R_BIN_JAVA_USHORT (buffer, offset);
		offset += 2;
		attr->size = offset;
	}
	// IFDBG r_bin_java_print_constant_value_attr_summary(attr);
	return attr;
}",CWE-125,1
1,"static MagickBooleanType ReadPSDChannelPixels(Image *image,
  const size_t channels,const ssize_t row,const ssize_t type,
  const unsigned char *pixels,ExceptionInfo *exception)
{
  Quantum
    pixel;

  const unsigned char
    *p;

  IndexPacket
    *indexes;

  PixelPacket
    *q;

  ssize_t
    x;

  size_t
    packet_size;

  unsigned short
    nibble;

  p=pixels;
  q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
  if (q == (PixelPacket *) NULL)
    return MagickFalse;
  indexes=GetAuthenticIndexQueue(image);
  packet_size=GetPSDPacketSize(image);
  for (x=0; x < (ssize_t) image->columns; x++)
  {
    if (packet_size == 1)
      pixel=ScaleCharToQuantum(*p++);
    else
      if (packet_size == 2)
        {
          p=PushShortPixel(MSBEndian,p,&nibble);
          pixel=ScaleShortToQuantum(nibble);
        }
      else
        {
          MagickFloatType
            nibble;

          p=PushFloatPixel(MSBEndian,p,&nibble);
          pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble);
        }
    if (image->depth > 1)
      {
        SetPSDPixel(image,channels,type,packet_size,pixel,q,indexes,x);
        q++;
      }
    else
      {
        ssize_t
          bit,
          number_bits;

        number_bits=(ssize_t) image->columns-x;
        if (number_bits > 8)
          number_bits=8;
        for (bit=0; bit < number_bits; bit++)
        {
          SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
            & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++);
        }
        if (x != (ssize_t) image->columns)
          x--;
        continue;
      }
  }
  return(SyncAuthenticPixels(image,exception));
}",CWE-190,2
1,"gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)
{
    char *pos = inbuf;
    char *lpos = NULL;
    char *tline = NULL;
    LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);
    LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE);
    char *name = NULL;
    char *selector = NULL;
    char *host = NULL;
    char *port = NULL;
    char *escaped_selector = NULL;
    const char *icon_url = NULL;
    char gtype;
    StoreEntry *entry = NULL;

    memset(tmpbuf, '\0', TEMP_BUF_SIZE);
    memset(line, '\0', TEMP_BUF_SIZE);

    entry = gopherState->entry;

    if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) {
        char *html_url = html_quote(entry->url());
        gopherHTMLHeader(entry, ""Gopher Index %s"", html_url);
        storeAppendPrintf(entry,
                          ""

This is a searchable Gopher index. Use the search\n"" ""function of your browser to enter search terms.\n"" ""\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, ""CSO Search of %s"", html_url); storeAppendPrintf(entry, ""

A CSO database usually contains a phonebook or\n"" ""directory. Use the search function of your browser to enter\n"" ""search terms.

\n""); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } String outbuf; if (!gopherState->HTML_header_added) { if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT) gopherHTMLHeader(entry, ""CSO Search Result"", NULL); else gopherHTMLHeader(entry, ""Gopher Menu"", NULL); outbuf.append (""
"");

        gopherState->HTML_header_added = 1;

        gopherState->HTML_pre = 1;
    }

    while (pos < inbuf + len) {
        int llen;
        int left = len - (pos - inbuf);
        lpos = (char *)memchr(pos, '\n', left);
        if (lpos) {
            ++lpos;             /* Next line is after \n */
            llen = lpos - pos;
        } else {
            llen = left;
        }
        if (gopherState->len + llen >= TEMP_BUF_SIZE) {
            debugs(10, DBG_IMPORTANT, ""GopherHTML: Buffer overflow. Lost some data on URL: "" << entry->url()  );
            llen = TEMP_BUF_SIZE - gopherState->len - 1;
            gopherState->overflowed = true; // may already be true
        }
        if (!lpos) {
            /* there is no complete line in inbuf */
            /* copy it to temp buffer */
            /* note: llen is adjusted above */
            memcpy(gopherState->buf + gopherState->len, pos, llen);
            gopherState->len += llen;
            break;
        }
        if (gopherState->len != 0) {
            /* there is something left from last tx. */
            memcpy(line, gopherState->buf, gopherState->len);
            memcpy(line + gopherState->len, pos, llen);
            llen += gopherState->len;
            gopherState->len = 0;
        } else {
            memcpy(line, pos, llen);
        }
        line[llen + 1] = '\0';
        /* move input to next line */
        pos = lpos;

        /* at this point. We should have one line in buffer to process */

        if (*line == '.') {
            /* skip it */
            memset(line, '\0', TEMP_BUF_SIZE);
            continue;
        }

        switch (gopherState->conversion) {

        case GopherStateData::HTML_INDEX_RESULT:

        case GopherStateData::HTML_DIR: {
            tline = line;
            gtype = *tline;
            ++tline;
            name = tline;
            selector = strchr(tline, TAB);

            if (selector) {
                *selector = '\0';
                ++selector;
                host = strchr(selector, TAB);

                if (host) {
                    *host = '\0';
                    ++host;
                    port = strchr(host, TAB);

                    if (port) {
                        char *junk;
                        port[0] = ':';
                        junk = strchr(host, TAB);

                        if (junk)
                            *junk++ = 0;    /* Chop port */
                        else {
                            junk = strchr(host, '\r');

                            if (junk)
                                *junk++ = 0;    /* Chop port */
                            else {
                                junk = strchr(host, '\n');

                                if (junk)
                                    *junk++ = 0;    /* Chop port */
                            }
                        }

                        if ((port[1] == '0') && (!port[2]))
                            port[0] = 0;    /* 0 means none */
                    }

                    /* escape a selector here */
                    escaped_selector = xstrdup(rfc1738_escape_part(selector));

                    switch (gtype) {

                    case GOPHER_DIRECTORY:
                        icon_url = mimeGetIconURL(""internal-menu"");
                        break;

                    case GOPHER_HTML:

                    case GOPHER_FILE:
                        icon_url = mimeGetIconURL(""internal-text"");
                        break;

                    case GOPHER_INDEX:

                    case GOPHER_CSO:
                        icon_url = mimeGetIconURL(""internal-index"");
                        break;

                    case GOPHER_IMAGE:

                    case GOPHER_GIF:

                    case GOPHER_PLUS_IMAGE:
                        icon_url = mimeGetIconURL(""internal-image"");
                        break;

                    case GOPHER_SOUND:

                    case GOPHER_PLUS_SOUND:
                        icon_url = mimeGetIconURL(""internal-sound"");
                        break;

                    case GOPHER_PLUS_MOVIE:
                        icon_url = mimeGetIconURL(""internal-movie"");
                        break;

                    case GOPHER_TELNET:

                    case GOPHER_3270:
                        icon_url = mimeGetIconURL(""internal-telnet"");
                        break;

                    case GOPHER_BIN:

                    case GOPHER_MACBINHEX:

                    case GOPHER_DOSBIN:

                    case GOPHER_UUENCODED:
                        icon_url = mimeGetIconURL(""internal-binary"");
                        break;

                    case GOPHER_INFO:
                        icon_url = NULL;
                        break;

                    case GOPHER_WWW:
                        icon_url = mimeGetIconURL(""internal-link"");
                        break;

                    default:
                        icon_url = mimeGetIconURL(""internal-unknown"");
                        break;
                    }

                    memset(tmpbuf, '\0', TEMP_BUF_SIZE);

                    if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) {
                        if (strlen(escaped_selector) != 0)
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, escaped_selector, rfc1738_escape_part(host),
                                     *port ? "":"" : """", port, html_quote(name));
                        else
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, rfc1738_escape_part(host), *port ? "":"" : """",
                                     port, html_quote(name));

                    } else if (gtype == GOPHER_INFO) {
                        snprintf(tmpbuf, TEMP_BUF_SIZE, ""\t%s\n"", html_quote(name));
                    } else {
                        if (strncmp(selector, ""GET /"", 5) == 0) {
                            /* WWW link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name));
                        } else if (gtype == GOPHER_WWW) {
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, rfc1738_escape_unescaped(selector), html_quote(name));
                        } else {
                            /* Standard link */
                            snprintf(tmpbuf, TEMP_BUF_SIZE, "" %s\n"",
                                     icon_url, host, gtype, escaped_selector, html_quote(name));
                        }
                    }

                    safe_free(escaped_selector);
                    outbuf.append(tmpbuf);
                } else {
                    memset(line, '\0', TEMP_BUF_SIZE);
                    continue;
                }
            } else {
                memset(line, '\0', TEMP_BUF_SIZE);
                continue;
            }

            break;
            }           /* HTML_DIR, HTML_INDEX_RESULT */

        case GopherStateData::HTML_CSO_RESULT: {
            if (line[0] == '-') {
                int code, recno;
                char *s_code, *s_recno, *result;

                s_code = strtok(line + 1, "":\n"");
                s_recno = strtok(NULL, "":\n"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                recno = atoi(s_recno);

                if (code != 200)
                    break;

                if (gopherState->cso_recno != recno) {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

Record# %d
%s

\n
"", recno, html_quote(result));
                    gopherState->cso_recno = recno;
                } else {
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""%s\n"", html_quote(result));
                }

                outbuf.append(tmpbuf);
                break;
            } else {
                int code;
                char *s_code, *result;

                s_code = strtok(line, "":"");
                result = strtok(NULL, ""\n"");

                if (!result)
                    break;

                code = atoi(s_code);

                switch (code) {

                case 200: {
                    /* OK */
                    /* Do nothing here */
                    break;
                }

                case 102:   /* Number of matches */

                case 501:   /* No Match */

                case 502: { /* Too Many Matches */
                    /* Print the message the server returns */
                    snprintf(tmpbuf, TEMP_BUF_SIZE, ""

%s

\n
"", html_quote(result));
                    outbuf.append(tmpbuf);
                    break;
                }

                }
            }

            break;
            }           /* HTML_CSO_RESULT */
        default:
            break;      /* do nothing */

        }           /* switch */

    }               /* while loop */

    if (outbuf.size() > 0) {
        entry->append(outbuf.rawBuf(), outbuf.size());
        /* now let start sending stuff to client */
        entry->flush();
    }

    outbuf.clean();
    return;
}",CWE-400,9
1,"static Bigint * Balloc(int k)
{
	int x;
	Bigint *rv;

	_THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex);
	if ((rv = freelist[k])) {
		freelist[k] = rv->next;
	} else {
		x = 1 << k;
		rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long));
		rv->k = k;
		rv->maxwds = x;
	}
	_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);
	rv->sign = rv->wds = 0;
	return rv;
}",CWE-119,0
0,"  void GetCachedOrigins(StorageType type, std::set* origins) {
    ASSERT_TRUE(origins != NULL);
    origins->clear();
    quota_manager_->GetCachedOrigins(type, origins);
  }
",none,24
0,"  QuotaManager* manager() const {
    return static_cast(observer());
  }
",none,24
0,"  InitializeTask(
      QuotaManager* manager,
      const FilePath& profile_path,
      bool is_incognito)
      : DatabaseTaskBase(manager),
        profile_path_(profile_path),
        is_incognito_(is_incognito),
        need_initialize_origins_(false),
        temporary_storage_quota_(-1) {
  }
",none,24
1,"gpg_ctx_add_recipient (struct _GpgCtx *gpg,
                       const gchar *keyid)
{
	if (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT)
		return;

	if (!gpg->recipients)
		gpg->recipients = g_ptr_array_new ();

	g_ptr_array_add (gpg->recipients, g_strdup (keyid));
}",CWE-200,4
0,"  const std::string& IPAddress() const {
    const Network* active = active_network();
    if (active != NULL)
      return active->ip_address();
    if (ethernet_)
      return ethernet_->ip_address();
    static std::string null_address(""0.0.0.0"");
    return null_address;
  }
",none,24
1,"bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)
{
  TABLE *table;
  const char *key;
  uint	key_length;
  const char *alias= table_list->alias.str;
  uint flags= ot_ctx->get_flags();
  MDL_ticket *mdl_ticket;
  TABLE_SHARE *share;
  uint gts_flags;
  bool from_share= false;
#ifdef WITH_PARTITION_STORAGE_ENGINE
  int part_names_error=0;
#endif
  DBUG_ENTER(""open_table"");

  /*
    The table must not be opened already. The table can be pre-opened for
    some statements if it is a temporary table.

    open_temporary_table() must be used to open temporary tables.
  */
  DBUG_ASSERT(!table_list->table);

  /* an open table operation needs a lot of the stack space */
  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
    DBUG_RETURN(TRUE);

  if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)
  {
    thd->send_kill_message();
    DBUG_RETURN(TRUE);
  }

  /*
    Check if we're trying to take a write lock in a read only transaction.

    Note that we allow write locks on log tables as otherwise logging
    to general/slow log would be disabled in read only transactions.
  */
  if (table_list->mdl_request.is_write_lock_request() &&
      thd->tx_read_only &&
      !(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))
  {
    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
    DBUG_RETURN(true);
  }

  if (!table_list->db.str)
  {
    my_error(ER_NO_DB_ERROR, MYF(0));
    DBUG_RETURN(true);
  }

  key_length= get_table_def_key(table_list, &key);

  /*
    If we're in pre-locked or LOCK TABLES mode, let's try to find the
    requested table in the list of pre-opened and locked tables. If the
    table is not there, return an error - we can't open not pre-opened
    tables in pre-locked/LOCK TABLES mode.
    TODO: move this block into a separate function.
  */
  if (thd->locked_tables_mode &&
      ! (flags & MYSQL_OPEN_GET_NEW_TABLE))
  {						// Using table locks
    TABLE *best_table= 0;
    int best_distance= INT_MIN;
    for (table=thd->open_tables; table ; table=table->next)
    {
      if (table->s->table_cache_key.length == key_length &&
	  !memcmp(table->s->table_cache_key.str, key, key_length))
      {
        if (!my_strcasecmp(system_charset_info, table->alias.c_ptr(), alias) &&
            table->query_id != thd->query_id && /* skip tables already used */
            (thd->locked_tables_mode == LTM_LOCK_TABLES ||
             table->query_id == 0))
        {
          int distance= ((int) table->reginfo.lock_type -
                         (int) table_list->lock_type);

          /*
            Find a table that either has the exact lock type requested,
            or has the best suitable lock. In case there is no locked
            table that has an equal or higher lock than requested,
            we us the closest matching lock to be able to produce an error
            message about wrong lock mode on the table. The best_table
            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.

            distance <  0 - No suitable lock found
            distance >  0 - we have lock mode higher then we require
            distance == 0 - we have lock mode exactly which we need
          */
          if ((best_distance < 0 && distance > best_distance) ||
              (distance >= 0 && distance < best_distance))
          {
            best_distance= distance;
            best_table= table;
            if (best_distance == 0)
            {
              /*
                We have found a perfect match and can finish iterating
                through open tables list. Check for table use conflict
                between calling statement and SP/trigger is done in
                lock_tables().
              */
              break;
            }
          }
        }
      }
    }
    if (best_table)
    {
      table= best_table;
      table->query_id= thd->query_id;
      table->init(thd, table_list);
      DBUG_PRINT(""info"",(""Using locked table""));
#ifdef WITH_PARTITION_STORAGE_ENGINE
      part_names_error= set_partitions_as_used(table_list, table);
#endif
      goto reset;
    }

    if (is_locked_view(thd, table_list))
    {
      if (table_list->sequence)
      {
        my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
        DBUG_RETURN(true);
      }
      DBUG_RETURN(FALSE); // VIEW
    }

    /*
      No table in the locked tables list. In case of explicit LOCK TABLES
      this can happen if a user did not include the table into the list.
      In case of pre-locked mode locked tables list is generated automatically,
      so we may only end up here if the table did not exist when
      locked tables list was created.
    */
    if (thd->locked_tables_mode == LTM_PRELOCKED)
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db.str, table_list->alias.str);
    else
      my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
    DBUG_RETURN(TRUE);
  }

  /*
    Non pre-locked/LOCK TABLES mode, and the table is not temporary.
    This is the normal use case.
  */

  if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))
  {
    /*
      We are not under LOCK TABLES and going to acquire write-lock/
      modify the base table. We need to acquire protection against
      global read lock until end of this statement in order to have
      this statement blocked by active FLUSH TABLES WITH READ LOCK.

      We don't need to acquire this protection under LOCK TABLES as
      such protection already acquired at LOCK TABLES time and
      not released until UNLOCK TABLES.

      We don't block statements which modify only temporary tables
      as these tables are not preserved by any form of
      backup which uses FLUSH TABLES WITH READ LOCK.

      TODO: The fact that we sometimes acquire protection against
            GRL only when we encounter table to be write-locked
            slightly increases probability of deadlock.
            This problem will be solved once Alik pushes his
            temporary table refactoring patch and we can start
            pre-acquiring metadata locks at the beggining of
            open_tables() call.
    */
    if (table_list->mdl_request.is_write_lock_request() &&
        ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
                    MYSQL_OPEN_FORCE_SHARED_MDL |
                    MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
                    MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&
        ! ot_ctx->has_protection_against_grl())
    {
      MDL_request protection_request;
      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);

      if (thd->global_read_lock.can_acquire_protection())
        DBUG_RETURN(TRUE);

      protection_request.init(MDL_key::GLOBAL, """", """", MDL_INTENTION_EXCLUSIVE,
                              MDL_STATEMENT);

      /*
        Install error handler which if possible will convert deadlock error
        into request to back-off and restart process of opening tables.
      */
      thd->push_internal_handler(&mdl_deadlock_handler);
      bool result= thd->mdl_context.acquire_lock(&protection_request,
                                                 ot_ctx->get_timeout());
      thd->pop_internal_handler();

      if (result)
        DBUG_RETURN(TRUE);

      ot_ctx->set_has_protection_against_grl();
    }

    if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,
                                flags, &mdl_ticket) ||
        mdl_ticket == NULL)
    {
      DEBUG_SYNC(thd, ""before_open_table_wait_refresh"");
      DBUG_RETURN(TRUE);
    }
    DEBUG_SYNC(thd, ""after_open_table_mdl_shared"");
  }
  else
  {
    /*
      Grab reference to the MDL lock ticket that was acquired
      by the caller.
    */
    mdl_ticket= table_list->mdl_request.ticket;
  }

  if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)
  {
    if (!ha_table_exists(thd, &table_list->db, &table_list->table_name))
      DBUG_RETURN(FALSE);
  }
  else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)
    DBUG_RETURN(FALSE);

  /* Table exists. Let us try to open it. */

  if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
    gts_flags= GTS_TABLE;
  else if (table_list->i_s_requested_object &  OPEN_VIEW_ONLY)
    gts_flags= GTS_VIEW;
  else
    gts_flags= GTS_TABLE | GTS_VIEW;

retry_share:

  share= tdc_acquire_share(thd, table_list, gts_flags, &table);

  if (unlikely(!share))
  {
    /*
      Hide ""Table doesn't exist"" errors if the table belongs to a view.
      The check for thd->is_error() is necessary to not push an
      unwanted error in case the error was already silenced.
      @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
    */
    if (thd->is_error())
    {
      if (table_list->parent_l)
      {
        thd->clear_error();
        my_error(ER_WRONG_MRG_TABLE, MYF(0));
      }
      else if (table_list->belong_to_view)
      {
        TABLE_LIST *view= table_list->belong_to_view;
        thd->clear_error();
        my_error(ER_VIEW_INVALID, MYF(0),
                 view->view_db.str, view->view_name.str);
      }
    }
    DBUG_RETURN(TRUE);
  }

  /*
    Check if this TABLE_SHARE-object corresponds to a view. Note, that there is
    no need to check TABLE_SHARE::tdc.flushed as we do for regular tables,
    because view shares are always up to date.
  */
  if (share->is_view)
  {
    /*
      If parent_l of the table_list is non null then a merge table
      has this view as child table, which is not supported.
    */
    if (table_list->parent_l)
    {
      my_error(ER_WRONG_MRG_TABLE, MYF(0));
      goto err_lock;
    }
    if (table_list->sequence)
    {
      my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str,
               table_list->alias.str);
      goto err_lock;
    }
    /*
      This table is a view. Validate its metadata version: in particular,
      that it was a view when the statement was prepared.
    */
    if (check_and_update_table_version(thd, table_list, share))
      goto err_lock;

    /* Open view */
    if (mysql_make_view(thd, share, table_list, false))
      goto err_lock;


    /* TODO: Don't free this */
    tdc_release_share(share);

    DBUG_ASSERT(table_list->view);

    DBUG_RETURN(FALSE);
  }

#ifdef WITH_WSREP
  if (!((flags & MYSQL_OPEN_IGNORE_FLUSH) ||
        (thd->wsrep_applier)))
#else
  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
#endif
  {
    if (share->tdc->flushed)
    {
      DBUG_PRINT(""info"", (""Found old share version: %lld  current: %lld"",
                          share->tdc->version, tdc_refresh_version()));
      /*
        We already have an MDL lock. But we have encountered an old
        version of table in the table definition cache which is possible
        when someone changes the table version directly in the cache
        without acquiring a metadata lock (e.g. this can happen during
        ""rolling"" FLUSH TABLE(S)).
        Release our reference to share, wait until old version of
        share goes away and then try to get new version of table share.
      */
      if (table)
        tc_release_table(table);
      else
        tdc_release_share(share);

      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
      bool wait_result;

      thd->push_internal_handler(&mdl_deadlock_handler);
      wait_result= tdc_wait_for_old_version(thd, table_list->db.str,
                                            table_list->table_name.str,
                                            ot_ctx->get_timeout(),
                                            mdl_ticket->get_deadlock_weight());
      thd->pop_internal_handler();

      if (wait_result)
        DBUG_RETURN(TRUE);

      goto retry_share;
    }

    if (thd->open_tables && thd->open_tables->s->tdc->flushed)
    {
      /*
        If the version changes while we're opening the tables,
        we have to back off, close all the tables opened-so-far,
        and try to reopen them. Note: refresh_version is currently
        changed only during FLUSH TABLES.
      */
      if (table)
        tc_release_table(table);
      else
        tdc_release_share(share);
      (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
                                           NULL);
      DBUG_RETURN(TRUE);
    }
  }

  if (table)
  {
    DBUG_ASSERT(table->file != NULL);
    MYSQL_REBIND_TABLE(table->file);
#ifdef WITH_PARTITION_STORAGE_ENGINE
    part_names_error= set_partitions_as_used(table_list, table);
#endif
  }
  else
  {
    enum open_frm_error error;

    /* make a new table */
    if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
      goto err_lock;

    error= open_table_from_share(thd, share, &table_list->alias,
                                 HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,
                                 EXTRA_RECORD,
                                 thd->open_options, table, FALSE,
                                 IF_PARTITIONING(table_list->partition_names,0));

    if (unlikely(error))
    {
      my_free(table);

      if (error == OPEN_FRM_DISCOVER)
        (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
                                              table_list);
      else if (share->crashed)
      {
        if (!(flags & MYSQL_OPEN_IGNORE_REPAIR))
          (void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,
                                                table_list);
        else
          table_list->crashed= 1;  /* Mark that table was crashed */
      }
      goto err_lock;
    }
    if (open_table_entry_fini(thd, share, table))
    {
      closefrm(table);
      my_free(table);
      goto err_lock;
    }

    /* Add table to the share's used tables list. */
    tc_add_table(thd, table);
    from_share= true;
  }

  table->mdl_ticket= mdl_ticket;
  table->reginfo.lock_type=TL_READ;		/* Assume read */

  table->init(thd, table_list);

  table->next= thd->open_tables;		/* Link into simple list */
  thd->set_open_tables(table);

 reset:
  /*
    Check that there is no reference to a condition from an earlier query
    (cf. Bug#58553). 
  */
  DBUG_ASSERT(table->file->pushed_cond == NULL);
  table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
  table_list->table= table;

  if (!from_share && table->vcol_fix_expr(thd))
    goto err_lock;

#ifdef WITH_PARTITION_STORAGE_ENGINE
  if (unlikely(table->part_info))
  {
    /* Partitions specified were incorrect.*/
    if (part_names_error)
    {
      table->file->print_error(part_names_error, MYF(0));
      DBUG_RETURN(true);
    }
  }
  else if (table_list->partition_names)
  {
    /* Don't allow PARTITION () clause on a nonpartitioned table */
    my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
    DBUG_RETURN(true);
  }
#endif
  if (table_list->sequence && table->s->table_type != TABLE_TYPE_SEQUENCE)
  {
    my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
    DBUG_RETURN(true);
  }

  DBUG_RETURN(FALSE);

err_lock:
  tdc_release_share(share);

  DBUG_PRINT(""exit"", (""failed""));
  DBUG_RETURN(TRUE);
}",CWE-416,10
0,"  void DidDumpQuotaTable(const QuotaTableEntries& entries) {
    quota_entries_ = entries;
  }
",none,24
1,"static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType  1
#define RGBColorType  3

  char
    property[MagickPathExtent];

  CINInfo
    cin;

  Image
    *image;

  MagickBooleanType
    status;

  MagickOffsetType
    offset;

  QuantumInfo
    *quantum_info;

  QuantumType
    quantum_type;

  ssize_t
    i;

  Quantum
    *q;

  size_t
    length;

  ssize_t
    count,
    y;

  unsigned char
    magick[4],
    *pixels;


  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    File information.
  */
  offset=0;
  count=ReadBlob(image,4,magick);
  offset+=count;
  if ((count != 4) ||
      ((LocaleNCompare((char *) magick,""\200\052\137\327"",4) != 0)))
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
  memset(&cin,0,sizeof(cin));
  image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
    (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
  cin.file.image_offset=ReadBlobLong(image);
  offset+=4;
  cin.file.generic_length=ReadBlobLong(image);
  offset+=4;
  cin.file.industry_length=ReadBlobLong(image);
  offset+=4;
  cin.file.user_length=ReadBlobLong(image);
  offset+=4;
  cin.file.file_size=ReadBlobLong(image);
  offset+=4;
  offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
    cin.file.version);
  (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
  (void) SetImageProperty(image,""dpx:file.version"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
    cin.file.filename);
  (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
  (void) SetImageProperty(image,""dpx:file.filename"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
    cin.file.create_date);
  (void) CopyMagickString(property,cin.file.create_date,
    sizeof(cin.file.create_date));
  (void) SetImageProperty(image,""dpx:file.create_date"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
    cin.file.create_time);
  (void) CopyMagickString(property,cin.file.create_time,
    sizeof(cin.file.create_time));
  (void) SetImageProperty(image,""dpx:file.create_time"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
    cin.file.reserve);
  /*
    Image information.
  */
  cin.image.orientation=(unsigned char) ReadBlobByte(image);
  offset++;
  if (cin.image.orientation != (unsigned char) (~0))
    (void) FormatImageProperty(image,""dpx:image.orientation"",""%d"",
      cin.image.orientation);
  switch (cin.image.orientation)
  {
    default:
    case 0: image->orientation=TopLeftOrientation; break;
    case 1: image->orientation=TopRightOrientation; break;
    case 2: image->orientation=BottomLeftOrientation; break;
    case 3: image->orientation=BottomRightOrientation; break;
    case 4: image->orientation=LeftTopOrientation; break;
    case 5: image->orientation=RightTopOrientation; break;
    case 6: image->orientation=LeftBottomOrientation; break;
    case 7: image->orientation=RightBottomOrientation; break;
  }
  cin.image.number_channels=(unsigned char) ReadBlobByte(image);
  offset++;
  offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
    cin.image.reserve1);
  for (i=0; i < 8; i++)
  {
    cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
    offset++;
    cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
    offset++;
    cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
    offset++;
    cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
    offset++;
    cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
    offset+=4;
    cin.image.channel[i].lines_per_image=ReadBlobLong(image);
    offset+=4;
    cin.image.channel[i].min_data=ReadBlobFloat(image);
    offset+=4;
    cin.image.channel[i].min_quantity=ReadBlobFloat(image);
    offset+=4;
    cin.image.channel[i].max_data=ReadBlobFloat(image);
    offset+=4;
    cin.image.channel[i].max_quantity=ReadBlobFloat(image);
    offset+=4;
  }
  cin.image.white_point[0]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
    image->chromaticity.white_point.x=cin.image.white_point[0];
  cin.image.white_point[1]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
    image->chromaticity.white_point.y=cin.image.white_point[1];
  cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
    image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
  cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
    image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
  cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
    image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
  cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
    image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
  cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
    image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
  cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
    image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
  offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
    cin.image.label);
  (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
  (void) SetImageProperty(image,""dpx:image.label"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
    cin.image.reserve);
  /*
    Image data format information.
  */
  cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
  offset++;
  cin.data_format.packing=(unsigned char) ReadBlobByte(image);
  offset++;
  cin.data_format.sign=(unsigned char) ReadBlobByte(image);
  offset++;
  cin.data_format.sense=(unsigned char) ReadBlobByte(image);
  offset++;
  cin.data_format.line_pad=ReadBlobLong(image);
  offset+=4;
  cin.data_format.channel_pad=ReadBlobLong(image);
  offset+=4;
  offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
    cin.data_format.reserve);
  /*
    Image origination information.
  */
  cin.origination.x_offset=ReadBlobSignedLong(image);
  offset+=4;
  if ((size_t) cin.origination.x_offset != ~0UL)
    (void) FormatImageProperty(image,""dpx:origination.x_offset"",""%.20g"",
      (double) cin.origination.x_offset);
  cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
  offset+=4;
  if ((size_t) cin.origination.y_offset != ~0UL)
    (void) FormatImageProperty(image,""dpx:origination.y_offset"",""%.20g"",
      (double) cin.origination.y_offset);
  offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
    cin.origination.filename);
  (void) CopyMagickString(property,cin.origination.filename,
    sizeof(cin.origination.filename));
  (void) SetImageProperty(image,""dpx:origination.filename"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
    cin.origination.create_date);
  (void) CopyMagickString(property,cin.origination.create_date,
    sizeof(cin.origination.create_date));
  (void) SetImageProperty(image,""dpx:origination.create_date"",property,
    exception);
  offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
    cin.origination.create_time);
  (void) CopyMagickString(property,cin.origination.create_time,
    sizeof(cin.origination.create_time));
  (void) SetImageProperty(image,""dpx:origination.create_time"",property,
    exception);
  offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
    cin.origination.device);
  (void) CopyMagickString(property,cin.origination.device,
    sizeof(cin.origination.device));
  (void) SetImageProperty(image,""dpx:origination.device"",property,exception);
  offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
    cin.origination.model);
  (void) CopyMagickString(property,cin.origination.model,
    sizeof(cin.origination.model));
  (void) SetImageProperty(image,""dpx:origination.model"",property,exception);
  (void) memset(cin.origination.serial,0, 
    sizeof(cin.origination.serial));
  offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
    cin.origination.serial);
  (void) CopyMagickString(property,cin.origination.serial,
    sizeof(cin.origination.serial));
  (void) SetImageProperty(image,""dpx:origination.serial"",property,exception);
  cin.origination.x_pitch=ReadBlobFloat(image);
  offset+=4;
  cin.origination.y_pitch=ReadBlobFloat(image);
  offset+=4;
  cin.origination.gamma=ReadBlobFloat(image);
  offset+=4;
  if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
    image->gamma=cin.origination.gamma;
  offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
    cin.origination.reserve);
  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
    {
      int
        c;

      /*
        Image film information.
      */
      cin.film.id=ReadBlobByte(image);
      offset++;
      c=cin.film.id;
      if (c != ~0)
        (void) FormatImageProperty(image,""dpx:film.id"",""%d"",cin.film.id);
      cin.film.type=ReadBlobByte(image);
      offset++;
      c=cin.film.type;
      if (c != ~0)
        (void) FormatImageProperty(image,""dpx:film.type"",""%d"",cin.film.type);
      cin.film.offset=ReadBlobByte(image);
      offset++;
      c=cin.film.offset;
      if (c != ~0)
        (void) FormatImageProperty(image,""dpx:film.offset"",""%d"",
          cin.film.offset);
      cin.film.reserve1=ReadBlobByte(image);
      offset++;
      cin.film.prefix=ReadBlobLong(image);
      offset+=4;
      if (cin.film.prefix != ~0UL)
        (void) FormatImageProperty(image,""dpx:film.prefix"",""%.20g"",(double)
          cin.film.prefix);
      cin.film.count=ReadBlobLong(image);
      offset+=4;
      offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
        cin.film.format);
      (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format));
      (void) SetImageProperty(image,""dpx:film.format"",property,exception);
      cin.film.frame_position=ReadBlobLong(image);
      offset+=4;
      if (cin.film.frame_position != ~0UL)
        (void) FormatImageProperty(image,""dpx:film.frame_position"",""%.20g"",
          (double) cin.film.frame_position);
      cin.film.frame_rate=ReadBlobFloat(image);
      offset+=4;
      if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
        (void) FormatImageProperty(image,""dpx:film.frame_rate"",""%g"",
          cin.film.frame_rate);
      offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
        cin.film.frame_id);
      (void) CopyMagickString(property,cin.film.frame_id,
        sizeof(cin.film.frame_id));
      (void) SetImageProperty(image,""dpx:film.frame_id"",property,exception);
      offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
        cin.film.slate_info);
      (void) CopyMagickString(property,cin.film.slate_info,
        sizeof(cin.film.slate_info));
      (void) SetImageProperty(image,""dpx:film.slate_info"",property,exception);
      offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
        cin.film.reserve);
    }
  if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
    {
      StringInfo
        *profile;

      /*
        User defined data.
      */
      if (cin.file.user_length > GetBlobSize(image))
        ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile"");
      profile=BlobToStringInfo((const unsigned char *) NULL,
        cin.file.user_length);
      if (profile == (StringInfo *) NULL)
        ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");
      offset+=ReadBlob(image,GetStringInfoLength(profile),
        GetStringInfoDatum(profile));
      (void) SetImageProfile(image,""dpx:user.data"",profile,exception);
      profile=DestroyStringInfo(profile);
    }
  image->depth=cin.image.channel[0].bits_per_pixel;
  image->columns=cin.image.channel[0].pixels_per_line;
  image->rows=cin.image.channel[0].lines_per_image;
  if (image_info->ping != MagickFalse)
    {
      (void) CloseBlob(image);
      return(image);
    }
  if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))
    ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile"");
  for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
  {
    int
      c;

    c=ReadBlobByte(image);
    if (c == EOF)
      break;
  }
  if (offset < (MagickOffsetType) cin.file.image_offset)
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
  status=SetImageExtent(image,image->columns,image->rows,exception);
  if (status == MagickFalse)
    return(DestroyImageList(image));
  (void) SetImageBackgroundColor(image,exception);
  /*
    Convert CIN raster image to pixel packets.
  */
  quantum_info=AcquireQuantumInfo(image_info,image);
  if (quantum_info == (QuantumInfo *) NULL)
    ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");
  SetQuantumQuantum(quantum_info,32);
  SetQuantumPack(quantum_info,MagickFalse);
  quantum_type=RGBQuantum;
  length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
  if (cin.image.number_channels == 1)
    {
      quantum_type=GrayQuantum;
      length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
    }
  status=SetQuantumPad(image,quantum_info,0);
  pixels=GetQuantumPixels(quantum_info);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    const void
      *stream;

    q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
    if (q == (Quantum *) NULL)
      break;
    stream=ReadBlobStream(image,length,pixels,&count);
    if ((size_t) count != length)
      break;
    (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
      quantum_type,(unsigned char *) stream,exception);
    if (SyncAuthenticPixels(image,exception) == MagickFalse)
      break;
    if (image->previous == (Image *) NULL)
      {
        status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
          image->rows);
        if (status == MagickFalse)
          break;
      }
  }
  SetQuantumImageType(image,quantum_type);
  quantum_info=DestroyQuantumInfo(quantum_info);
  if (EOFBlob(image) != MagickFalse)
    ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"",
      image->filename);
  SetImageColorspace(image,LogColorspace,exception);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}",CWE-787,16
1,"static int check_passwd(unsigned char *passwd, size_t length)
{
	struct digest *d = NULL;
	unsigned char *passwd1_sum;
	unsigned char *passwd2_sum;
	int ret = 0;
	int hash_len;

	if (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {
		hash_len = PBKDF2_LENGTH;
	} else {
		d = digest_alloc(PASSWD_SUM);
		if (!d) {
			pr_err(""No such digest: %s\n"",
			       PASSWD_SUM ? PASSWD_SUM : ""NULL"");
			return -ENOENT;
		}

		hash_len = digest_length(d);
	}

	passwd1_sum = calloc(hash_len * 2, sizeof(unsigned char));
	if (!passwd1_sum)
		return -ENOMEM;

	passwd2_sum = passwd1_sum + hash_len;

	if (is_passwd_env_enable())
		ret = read_env_passwd(passwd2_sum, hash_len);
	else if (is_passwd_default_enable())
		ret = read_default_passwd(passwd2_sum, hash_len);
	else
		ret = -EINVAL;

	if (ret < 0)
		goto err;

	if (IS_ENABLED(CONFIG_PASSWD_CRYPTO_PBKDF2)) {
		char *key = passwd2_sum + PBKDF2_SALT_LEN;
		char *salt = passwd2_sum;
		int keylen = PBKDF2_LENGTH - PBKDF2_SALT_LEN;

		ret = pkcs5_pbkdf2_hmac_sha1(passwd, length, salt,
			PBKDF2_SALT_LEN, PBKDF2_COUNT, keylen, passwd1_sum);
		if (ret)
			goto err;

		if (strncmp(passwd1_sum, key, keylen) == 0)
			ret = 1;
	} else {
		ret = digest_digest(d, passwd, length, passwd1_sum);

		if (ret)
			goto err;

		if (strncmp(passwd1_sum, passwd2_sum, hash_len) == 0)
			ret = 1;
	}

err:
	free(passwd1_sum);
	digest_free(d);

	return ret;
}",CWE-200,4
1,"ins_compl_add(
    char_u	*str,
    int		len,
    char_u	*fname,
    char_u	**cptext,	    // extra text for popup menu or NULL
    typval_T	*user_data UNUSED,  // ""user_data"" entry or NULL
    int		cdir,
    int		flags_arg,
    int		adup)		// accept duplicate match
{
    compl_T	*match;
    int		dir = (cdir == 0 ? compl_direction : cdir);
    int		flags = flags_arg;

    if (flags & CP_FAST)
	fast_breakcheck();
    else
	ui_breakcheck();
    if (got_int)
	return FAIL;
    if (len < 0)
	len = (int)STRLEN(str);

    // If the same match is already present, don't add it.
    if (compl_first_match != NULL && !adup)
    {
	match = compl_first_match;
	do
	{
	    if (!match_at_original_text(match)
		    && STRNCMP(match->cp_str, str, len) == 0
		    && match->cp_str[len] == NUL)
		return NOTDONE;
	    match = match->cp_next;
	} while (match != NULL && !is_first_match(match));
    }

    // Remove any popup menu before changing the list of matches.
    ins_compl_del_pum();

    // Allocate a new match structure.
    // Copy the values to the new match structure.
    match = ALLOC_CLEAR_ONE(compl_T);
    if (match == NULL)
	return FAIL;
    match->cp_number = -1;
    if (flags & CP_ORIGINAL_TEXT)
	match->cp_number = 0;
    if ((match->cp_str = vim_strnsave(str, len)) == NULL)
    {
	vim_free(match);
	return FAIL;
    }

    // match-fname is:
    // - compl_curr_match->cp_fname if it is a string equal to fname.
    // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
    // - NULL otherwise.	--Acevedo
    if (fname != NULL
	    && compl_curr_match != NULL
	    && compl_curr_match->cp_fname != NULL
	    && STRCMP(fname, compl_curr_match->cp_fname) == 0)
	match->cp_fname = compl_curr_match->cp_fname;
    else if (fname != NULL)
    {
	match->cp_fname = vim_strsave(fname);
	flags |= CP_FREE_FNAME;
    }
    else
	match->cp_fname = NULL;
    match->cp_flags = flags;

    if (cptext != NULL)
    {
	int i;

	for (i = 0; i < CPT_COUNT; ++i)
	    if (cptext[i] != NULL && *cptext[i] != NUL)
		match->cp_text[i] = vim_strsave(cptext[i]);
    }
#ifdef FEAT_EVAL
    if (user_data != NULL)
	match->cp_user_data = *user_data;
#endif

    // Link the new match structure after (FORWARD) or before (BACKWARD) the
    // current match in the list of matches .
    if (compl_first_match == NULL)
	match->cp_next = match->cp_prev = NULL;
    else if (dir == FORWARD)
    {
	match->cp_next = compl_curr_match->cp_next;
	match->cp_prev = compl_curr_match;
    }
    else	// BACKWARD
    {
	match->cp_next = compl_curr_match;
	match->cp_prev = compl_curr_match->cp_prev;
    }
    if (match->cp_next)
	match->cp_next->cp_prev = match;
    if (match->cp_prev)
	match->cp_prev->cp_next = match;
    else	// if there's nothing before, it is the first match
	compl_first_match = match;
    compl_curr_match = match;

    // Find the longest common string if still doing that.
    if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
	ins_compl_longest_match(match);

    return OK;
}",CWE-787,16
0,"  virtual bool wifi_available() const {
    return available_devices_ & (1 << TYPE_WIFI);
  }
",none,24
0,"  void GetUsageAndQuotaForEviction() {
    quota_status_ = kQuotaStatusUnknown;
    usage_ = -1;
    unlimited_usage_ = -1;
    quota_ = -1;
    available_space_ = -1;
    quota_manager_->GetUsageAndQuotaForEviction(
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetUsageAndQuotaForEviction));
  }
",none,24
0,"  virtual bool GetWifiAccessPoints(WifiAccessPointVector* result) {
    if (!EnsureCrosLoaded())
      return false;
    DeviceNetworkList* network_list = GetDeviceNetworkList();
    if (network_list == NULL)
      return false;
    result->clear();
    result->reserve(network_list->network_size);
    const base::Time now = base::Time::Now();
    for (size_t i = 0; i < network_list->network_size; ++i) {
      DCHECK(network_list->networks[i].address);
      DCHECK(network_list->networks[i].name);
      WifiAccessPoint ap;
      ap.mac_address = SafeString(network_list->networks[i].address);
      ap.name = SafeString(network_list->networks[i].name);
      ap.timestamp = now -
          base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds);
      ap.signal_strength = network_list->networks[i].strength;
      ap.channel = network_list->networks[i].channel;
      result->push_back(ap);
    }
    FreeDeviceNetworkList(network_list);
    return true;
  }
",none,24
1,"  void Compute(OpKernelContext* ctx) override {
    const Tensor& a = ctx->input(0);
    const Tensor& b = ctx->input(1);
    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()),
                errors::InvalidArgument(""a is not a matrix""));
    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()),
                errors::InvalidArgument(""b is not a matrix""));

    const int m = transpose_a_ ? a.dim_size(1) : a.dim_size(0);
    const int k = transpose_a_ ? a.dim_size(0) : a.dim_size(1);
    const int n = transpose_b_ ? b.dim_size(0) : b.dim_size(1);
    const int k2 = transpose_b_ ? b.dim_size(1) : b.dim_size(0);

    OP_REQUIRES(ctx, k == k2,
                errors::InvalidArgument(
                    ""Matrix size incompatible: a: "", a.shape().DebugString(),
                    "", b: "", b.shape().DebugString()));
    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({m, n}), &output));

    if (k == 0) {
      // If the inner dimension k in the matrix multiplication is zero, we fill
      // the output with zeros.
      functor::SetZeroFunctor f;
      f(ctx->eigen_device(), output->flat());
      return;
    }

    auto out = output->matrix();

    std::unique_ptr a_float;
    std::unique_ptr b_float;
    if (!a_is_sparse_ && !b_is_sparse_) {
      auto left = &a;
      auto right = &b;
      // TODO(agarwal): multi-thread the conversions from bfloat16 to float.
      if (std::is_same::value) {
        a_float.reset(new Tensor(DT_FLOAT, a.shape()));
        BFloat16ToFloat(a.flat().data(),
                        a_float->flat().data(), a.NumElements());
        left = a_float.get();
      }
      if (std::is_same::value) {
        b_float.reset(new Tensor(DT_FLOAT, b.shape()));
        BFloat16ToFloat(b.flat().data(),
                        b_float->flat().data(), b.NumElements());
        right = b_float.get();
      }
      Eigen::array, 1> dim_pair;
      dim_pair[0].first = transpose_a_ ? 0 : 1;
      dim_pair[0].second = transpose_b_ ? 1 : 0;

      out.device(ctx->template eigen_device()) =
          left->matrix().contract(right->matrix(), dim_pair);
      return;
    }

    auto left = &a;
    auto right = &b;
    bool transpose_output = false;
    bool transpose_a = transpose_a_;
    bool transpose_b = transpose_b_;
    if (!a_is_sparse_) {
      // Swap the order of multiplications using the identity:
      // A * B = (B' *  A')'.
      std::swap(left, right);
      std::swap(transpose_a, transpose_b);
      transpose_a = !transpose_a;
      transpose_b = !transpose_b;
      transpose_output = !transpose_output;
    }

    std::unique_ptr right_tr;
    if (transpose_b) {
      // TODO(agarwal): avoid transposing the matrix here and directly handle
      // transpose in CreateDenseSlices.
      OP_REQUIRES(ctx, right->dim_size(0) != 0,
                  errors::InvalidArgument(""b has an entry 0 in it's shape.""));
      OP_REQUIRES(ctx, right->dim_size(1) != 0,
                  errors::InvalidArgument(""b has an entry 0 in it's shape.""));
      right_tr.reset(
          new Tensor(right->dtype(),
                     TensorShape({right->dim_size(1), right->dim_size(0)})));

      const auto perm = dsizes_10();
      if (transpose_output) {
        right_tr->matrix().device(ctx->template eigen_device()) =
            right->matrix().shuffle(perm);
      } else {
        right_tr->matrix().device(ctx->template eigen_device()) =
            right->matrix().shuffle(perm);
      }
      right = right_tr.get();
    }

    if (transpose_output) {
      DoMatMul::Compute(&this->cache_tr_, left->matrix(),
                                right->matrix(), transpose_a,
                                ctx->device()->tensorflow_cpu_worker_threads(),
                                transpose_output, &out);
    } else {
      DoMatMul::Compute(&this->cache_nt_, left->matrix(),
                                right->matrix(), transpose_a,
                                ctx->device()->tensorflow_cpu_worker_threads(),
                                transpose_output, &out);
    }
  }",CWE-125,1
1,"inbound_cap_ls (server *serv, char *nick, char *extensions_str,
					 const message_tags_data *tags_data)
{
	char buffer[256];	/* buffer for requesting capabilities and emitting the signal */
	guint32 want_cap; /* format the CAP REQ string based on previous capabilities being requested or not */
	guint32 want_sasl; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */
	char **extensions;
	int i;

	EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick,
								  extensions_str, NULL, NULL, 0, tags_data->timestamp);
	want_cap = 0;
	want_sasl = 0;

	extensions = g_strsplit (extensions_str, "" "", 0);

	strcpy (buffer, ""CAP REQ :"");

	for (i=0; extensions[i]; i++)
	{
		const char *extension = extensions[i];

		if (!strcmp (extension, ""identify-msg""))
		{
			strcat (buffer, ""identify-msg "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""multi-prefix""))
		{
			strcat (buffer, ""multi-prefix "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""away-notify""))
		{
			strcat (buffer, ""away-notify "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""account-notify""))
		{
			strcat (buffer, ""account-notify "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""extended-join""))
		{
			strcat (buffer, ""extended-join "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""userhost-in-names""))
		{
			strcat (buffer, ""userhost-in-names "");
			want_cap = 1;
		}

		/* bouncers can prefix a name space to the extension so we should use.
		 * znc <= 1.0 uses ""znc.in/server-time"" and newer use ""znc.in/server-time-iso"".
		 */
		if (!strcmp (extension, ""znc.in/server-time-iso""))
		{
			strcat (buffer, ""znc.in/server-time-iso "");
			want_cap = 1;
		}
		if (!strcmp (extension, ""znc.in/server-time""))
		{
			strcat (buffer, ""znc.in/server-time "");
			want_cap = 1;
		}
		if (prefs.hex_irc_cap_server_time
			 && !strcmp (extension, ""server-time""))
		{
			strcat (buffer, ""server-time "");
			want_cap = 1;
		}
		
		/* if the SASL password is set AND auth mode is set to SASL, request SASL auth */
		if (!strcmp (extension, ""sasl"")
			&& ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0)
			|| (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert)))
		{
			strcat (buffer, ""sasl "");
			want_cap = 1;
			want_sasl = 1;
		}
	}

	g_strfreev (extensions);

	if (want_cap)
	{
		/* buffer + 9 = emit buffer without ""CAP REQ :"" */
		EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session,
									  buffer + 9, NULL, NULL, NULL, 0,
									  tags_data->timestamp);
		tcp_sendf (serv, ""%s\r\n"", g_strchomp (buffer));
	}
	if (!want_sasl)
	{
		/* if we use SASL, CAP END is dealt via raw numerics */
		serv->sent_capend = TRUE;
		tcp_send_len (serv, ""CAP END\r\n"", 9);
	}
}",CWE-22,5
1,"jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)
{
	jp2_box_t *box;
	int found;
	jas_image_t *image;
	jp2_dec_t *dec;
	bool samedtype;
	int dtype;
	unsigned int i;
	jp2_cmap_t *cmapd;
	jp2_pclr_t *pclrd;
	jp2_cdef_t *cdefd;
	unsigned int channo;
	int newcmptno;
	int_fast32_t *lutents;
#if 0
	jp2_cdefchan_t *cdefent;
	int cmptno;
#endif
	jp2_cmapent_t *cmapent;
	jas_icchdr_t icchdr;
	jas_iccprof_t *iccprof;

	dec = 0;
	box = 0;
	image = 0;

	if (!(dec = jp2_dec_create())) {
		goto error;
	}

	/* Get the first box.  This should be a JP box. */
	if (!(box = jp2_box_get(in))) {
		jas_eprintf(""error: cannot get box\n"");
		goto error;
	}
	if (box->type != JP2_BOX_JP) {
		jas_eprintf(""error: expecting signature box\n"");
		goto error;
	}
	if (box->data.jp.magic != JP2_JP_MAGIC) {
		jas_eprintf(""incorrect magic number\n"");
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Get the second box.  This should be a FTYP box. */
	if (!(box = jp2_box_get(in))) {
		goto error;
	}
	if (box->type != JP2_BOX_FTYP) {
		jas_eprintf(""expecting file type box\n"");
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Get more boxes... */
	found = 0;
	while ((box = jp2_box_get(in))) {
		if (jas_getdbglevel() >= 1) {
			jas_eprintf(""box type %s\n"", box->info->name);
		}
		switch (box->type) {
		case JP2_BOX_JP2C:
			found = 1;
			break;
		case JP2_BOX_IHDR:
			if (!dec->ihdr) {
				dec->ihdr = box;
				box = 0;
			}
			break;
		case JP2_BOX_BPCC:
			if (!dec->bpcc) {
				dec->bpcc = box;
				box = 0;
			}
			break;
		case JP2_BOX_CDEF:
			if (!dec->cdef) {
				dec->cdef = box;
				box = 0;
			}
			break;
		case JP2_BOX_PCLR:
			if (!dec->pclr) {
				dec->pclr = box;
				box = 0;
			}
			break;
		case JP2_BOX_CMAP:
			if (!dec->cmap) {
				dec->cmap = box;
				box = 0;
			}
			break;
		case JP2_BOX_COLR:
			if (!dec->colr) {
				dec->colr = box;
				box = 0;
			}
			break;
		}
		if (box) {
			jp2_box_destroy(box);
			box = 0;
		}
		if (found) {
			break;
		}
	}

	if (!found) {
		jas_eprintf(""error: no code stream found\n"");
		goto error;
	}

	if (!(dec->image = jpc_decode(in, optstr))) {
		jas_eprintf(""error: cannot decode code stream\n"");
		goto error;
	}

	/* An IHDR box must be present. */
	if (!dec->ihdr) {
		jas_eprintf(""error: missing IHDR box\n"");
		goto error;
	}

	/* Does the number of components indicated in the IHDR box match
	  the value specified in the code stream? */
	if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
		jas_eprintf(""warning: number of components mismatch\n"");
	}

	/* At least one component must be present. */
	if (!jas_image_numcmpts(dec->image)) {
		jas_eprintf(""error: no components\n"");
		goto error;
	}

	/* Determine if all components have the same data type. */
	samedtype = true;
	dtype = jas_image_cmptdtype(dec->image, 0);
	for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
		if (jas_image_cmptdtype(dec->image, i) != dtype) {
			samedtype = false;
			break;
		}
	}

	/* Is the component data type indicated in the IHDR box consistent
	  with the data in the code stream? */
	if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
	  (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
		jas_eprintf(""warning: component data type mismatch\n"");
	}

	/* Is the compression type supported? */
	if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
		jas_eprintf(""error: unsupported compression type\n"");
		goto error;
	}

	if (dec->bpcc) {
		/* Is the number of components indicated in the BPCC box
		  consistent with the code stream data? */
		if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(
		  dec->image))) {
			jas_eprintf(""warning: number of components mismatch\n"");
		}
		/* Is the component data type information indicated in the BPCC
		  box consistent with the code stream data? */
		if (!samedtype) {
			for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
				if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
					jas_eprintf(""warning: component data type mismatch\n"");
				}
			}
		} else {
			jas_eprintf(""warning: superfluous BPCC box\n"");
		}
	}

	/* A COLR box must be present. */
	if (!dec->colr) {
		jas_eprintf(""error: no COLR box\n"");
		goto error;
	}

	switch (dec->colr->data.colr.method) {
	case JP2_COLR_ENUM:
		jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
		break;
	case JP2_COLR_ICC:
		iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
		  dec->colr->data.colr.iccplen);
		assert(iccprof);
		jas_iccprof_gethdr(iccprof, &icchdr);
		jas_eprintf(""ICC Profile CS %08x\n"", icchdr.colorspc);
		jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
		dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
		assert(dec->image->cmprof_);
		jas_iccprof_destroy(iccprof);
		break;
	}

	/* If a CMAP box is present, a PCLR box must also be present. */
	if (dec->cmap && !dec->pclr) {
		jas_eprintf(""warning: missing PCLR box or superfluous CMAP box\n"");
		jp2_box_destroy(dec->cmap);
		dec->cmap = 0;
	}

	/* If a CMAP box is not present, a PCLR box must not be present. */
	if (!dec->cmap && dec->pclr) {
		jas_eprintf(""warning: missing CMAP box or superfluous PCLR box\n"");
		jp2_box_destroy(dec->pclr);
		dec->pclr = 0;
	}

	/* Determine the number of channels (which is essentially the number
	  of components after any palette mappings have been applied). */
	dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image));

	/* Perform a basic sanity check on the CMAP box if present. */
	if (dec->cmap) {
		for (i = 0; i < dec->numchans; ++i) {
			/* Is the component number reasonable? */
			if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
				jas_eprintf(""error: invalid component number in CMAP box\n"");
				goto error;
			}
			/* Is the LUT index reasonable? */
			if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) {
				jas_eprintf(""error: invalid CMAP LUT index\n"");
				goto error;
			}
		}
	}

	/* Allocate space for the channel-number to component-number LUT. */
	if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) {
		jas_eprintf(""error: no memory\n"");
		goto error;
	}

	if (!dec->cmap) {
		for (i = 0; i < dec->numchans; ++i) {
			dec->chantocmptlut[i] = i;
		}
	} else {
		cmapd = &dec->cmap->data.cmap;
		pclrd = &dec->pclr->data.pclr;
		cdefd = &dec->cdef->data.cdef;
		for (channo = 0; channo < cmapd->numchans; ++channo) {
			cmapent = &cmapd->ents[channo];
			if (cmapent->map == JP2_CMAP_DIRECT) {
				dec->chantocmptlut[channo] = channo;
			} else if (cmapent->map == JP2_CMAP_PALETTE) {
				lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t));
				for (i = 0; i < pclrd->numlutents; ++i) {
					lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
				}
				newcmptno = jas_image_numcmpts(dec->image);
				jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
				dec->chantocmptlut[channo] = newcmptno;
				jas_free(lutents);
#if 0
				if (dec->cdef) {
					cdefent = jp2_cdef_lookup(cdefd, channo);
					if (!cdefent) {
						abort();
					}
				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
				} else {
				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
				}
#endif
			}
		}
	}

	/* Mark all components as being of unknown type. */

	for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
		jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
	}

	/* Determine the type of each component. */
	if (dec->cdef) {
		for (i = 0; i < dec->numchans; ++i) {
			jas_image_setcmpttype(dec->image,
			  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
			  jp2_getct(jas_image_clrspc(dec->image),
			  dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc));
		}
	} else {
		for (i = 0; i < dec->numchans; ++i) {
			jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
			  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
		}
	}

	/* Delete any components that are not of interest. */
	for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
		if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
			jas_image_delcmpt(dec->image, i - 1);
		}
	}

	/* Ensure that some components survived. */
	if (!jas_image_numcmpts(dec->image)) {
		jas_eprintf(""error: no components\n"");
		goto error;
	}
#if 0
jas_eprintf(""no of components is %d\n"", jas_image_numcmpts(dec->image));
#endif

	/* Prevent the image from being destroyed later. */
	image = dec->image;
	dec->image = 0;

	jp2_dec_destroy(dec);

	return image;

error:
	if (box) {
		jp2_box_destroy(box);
	}
	if (dec) {
		jp2_dec_destroy(dec);
	}
	return 0;
}",CWE-119,0
1,"gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)
{
  int idx;
  int type = nint(tree->car);

  switch (type) {
  case NODE_GVAR:
  case NODE_ARG:
  case NODE_LVAR:
  case NODE_IVAR:
  case NODE_CVAR:
  case NODE_CONST:
  case NODE_NIL:
  case NODE_MASGN:
    if (rhs) {
      codegen(s, rhs, VAL);
      pop();
      sp = cursp();
    }
    break;

  case NODE_COLON2:
  case NODE_CALL:
  case NODE_SCALL:
    /* keep evaluation order */
    break;

  case NODE_NVAR:
    codegen_error(s, ""Can't assign to numbered parameter"");
    break;

  default:
    codegen_error(s, ""unknown lhs"");
    break;
  }

  tree = tree->cdr;
  switch (type) {
  case NODE_GVAR:
    gen_setxv(s, OP_SETGV, sp, nsym(tree), val);
    break;
  case NODE_ARG:
  case NODE_LVAR:
    idx = lv_idx(s, nsym(tree));
    if (idx > 0) {
      if (idx != sp) {
        gen_move(s, idx, sp, val);
      }
      break;
    }
    else {                      /* upvar */
      gen_setupvar(s, sp, nsym(tree));
    }
    break;
  case NODE_IVAR:
    gen_setxv(s, OP_SETIV, sp, nsym(tree), val);
    break;
  case NODE_CVAR:
    gen_setxv(s, OP_SETCV, sp, nsym(tree), val);
    break;
  case NODE_CONST:
    gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);
    break;
  case NODE_COLON2:
    if (sp) {
      gen_move(s, cursp(), sp, 0);
    }
    sp = cursp();
    push();
    codegen(s, tree->car, VAL);
    if (rhs) {
      codegen(s, rhs, VAL); pop();
      gen_move(s, sp, cursp(), 0);
    }
    pop_n(2);
    idx = new_sym(s, nsym(tree->cdr));
    genop_2(s, OP_SETMCNST, sp, idx);
    break;

  case NODE_CALL:
  case NODE_SCALL:
    {
      int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;
      mrb_sym mid = nsym(tree->cdr->car);

      top = cursp();
      if (val || sp == cursp()) {
        push();                   /* room for retval */
      }
      call = cursp();
      if (!tree->car) {
        noself = 1;
        push();
      }
      else {
        codegen(s, tree->car, VAL); /* receiver */
      }
      if (safe) {
        int recv = cursp()-1;
        gen_move(s, cursp(), recv, 1);
        skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);
      }
      tree = tree->cdr->cdr->car;
      if (tree) {
        if (tree->car) {            /* positional arguments */
          n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);
          if (n < 0) {              /* variable length */
            n = 15;
            push();
          }
        }
        if (tree->cdr->car) {       /* keyword arguments */
          if (n == 14) {
            pop_n(n);
            genop_2(s, OP_ARRAY, cursp(), n);
            push();
            n = 15;
          }
          gen_hash(s, tree->cdr->car->cdr, VAL, 0);
          if (n < 14) {
            n++;
          }
          else {
            pop_n(2);
            genop_2(s, OP_ARYPUSH, cursp(), 1);
          }
          push();
        }
      }
      if (rhs) {
        codegen(s, rhs, VAL);
        pop();
      }
      else {
        gen_move(s, cursp(), sp, 0);
      }
      if (val) {
        gen_move(s, top, cursp(), 1);
      }
      if (n < 14) {
        n++;
      }
      else {
        pop();
        genop_2(s, OP_ARYPUSH, cursp(), 1);
      }
      s->sp = call;
      if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {
        genop_1(s, OP_SETIDX, cursp());
      }
      else {
        genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);
      }
      if (safe) {
        dispatch(s, skip);
      }
      s->sp = top;
    }
    break;

  case NODE_MASGN:
    gen_vmassignment(s, tree->car, sp, val);
    break;

  /* splat without assignment */
  case NODE_NIL:
    break;

  default:
    codegen_error(s, ""unknown lhs"");
    break;
  }
  if (val) push();
}",CWE-125,1
1,"append_command(char_u *cmd)
{
    char_u *s = cmd;
    char_u *d;

    STRCAT(IObuff, "": "");
    d = IObuff + STRLEN(IObuff);
    while (*s != NUL && d - IObuff < IOSIZE - 7)
    {
	if (enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : *s == 0xa0)
	{
	    s += enc_utf8 ? 2 : 1;
	    STRCPY(d, """");
	    d += 4;
	}
	else
	    MB_COPY_CHAR(s, d);
    }
    *d = NUL;
}",CWE-416,10
1,"search_impl(i_ctx_t *i_ctx_p, bool forward)
{
    os_ptr op = osp;
    os_ptr op1 = op - 1;
    uint size = r_size(op);
    uint count;
    byte *pat;
    byte *ptr;
    byte ch;
    int incr = forward ? 1 : -1;

    check_read_type(*op1, t_string);
    check_read_type(*op, t_string);
    if (size > r_size(op1)) {	/* can't match */
        make_false(op);
        return 0;
    }
    count = r_size(op1) - size;
    ptr = op1->value.bytes;
    if (size == 0)
        goto found;
    if (!forward)
        ptr += count;
    pat = op->value.bytes;
    ch = pat[0];
    do {
        if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))
            goto found;
        ptr += incr;
    }
    while (count--);
    /* No match */
    make_false(op);
    return 0;
found:
    op->tas.type_attrs = op1->tas.type_attrs;
    op->value.bytes = ptr;
    r_set_size(op, size);
    push(2);
    op[-1] = *op1;
    r_set_size(op - 1, ptr - op[-1].value.bytes);
    op1->value.bytes = ptr + size;
    r_set_size(op1, count + (!forward ? (size - 1) : 0));
    make_true(op);
    return 0;
}",CWE-787,16
1,"fill_threshhold_buffer(byte *dest_strip, byte *src_strip, int src_width,
                       int left_offset, int left_width, int num_tiles,
                       int right_width)
{
    byte *ptr_out_temp = dest_strip;
    int ii;

    /* Left part */
    memcpy(dest_strip, src_strip + left_offset, left_width);
    ptr_out_temp += left_width;
    /* Now the full parts */
    for (ii = 0; ii < num_tiles; ii++){
        memcpy(ptr_out_temp, src_strip, src_width);
        ptr_out_temp += src_width;
    }
    /* Now the remainder */
    memcpy(ptr_out_temp, src_strip, right_width);
#ifdef PACIFY_VALGRIND
    ptr_out_temp += right_width;
    ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1);
    if (ii > 0)
        memset(ptr_out_temp, 0, ii);
#endif
}",CWE-119,0
1,"reg_match_visual(void)
{
    pos_T	top, bot;
    linenr_T    lnum;
    colnr_T	col;
    win_T	*wp = rex.reg_win == NULL ? curwin : rex.reg_win;
    int		mode;
    colnr_T	start, end;
    colnr_T	start2, end2;
    colnr_T	cols;
    colnr_T	curswant;

    // Check if the buffer is the current buffer.
    if (rex.reg_buf != curbuf || VIsual.lnum == 0)
	return FALSE;

    if (VIsual_active)
    {
	if (LT_POS(VIsual, wp->w_cursor))
	{
	    top = VIsual;
	    bot = wp->w_cursor;
	}
	else
	{
	    top = wp->w_cursor;
	    bot = VIsual;
	}
	mode = VIsual_mode;
	curswant = wp->w_curswant;
    }
    else
    {
	if (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end))
	{
	    top = curbuf->b_visual.vi_start;
	    bot = curbuf->b_visual.vi_end;
	}
	else
	{
	    top = curbuf->b_visual.vi_end;
	    bot = curbuf->b_visual.vi_start;
	}
	mode = curbuf->b_visual.vi_mode;
	curswant = curbuf->b_visual.vi_curswant;
    }
    lnum = rex.lnum + rex.reg_firstlnum;
    if (lnum < top.lnum || lnum > bot.lnum)
	return FALSE;

    if (mode == 'v')
    {
	col = (colnr_T)(rex.input - rex.line);
	if ((lnum == top.lnum && col < top.col)
		|| (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e')))
	    return FALSE;
    }
    else if (mode == Ctrl_V)
    {
	getvvcol(wp, &top, &start, NULL, &end);
	getvvcol(wp, &bot, &start2, NULL, &end2);
	if (start2 < start)
	    start = start2;
	if (end2 > end)
	    end = end2;
	if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL)
	    end = MAXCOL;
	cols = win_linetabsize(wp, rex.line, (colnr_T)(rex.input - rex.line));
	if (cols < start || cols > end - (*p_sel == 'e'))
	    return FALSE;
    }
    return TRUE;
}",CWE-416,10
0,"bool CellularNetwork::is_gsm() const {
  return network_technology_ != NETWORK_TECHNOLOGY_EVDO &&
      network_technology_ != NETWORK_TECHNOLOGY_1XRTT &&
      network_technology_ != NETWORK_TECHNOLOGY_UNKNOWN;
}
",none,24
1,"int64_t OpLevelCostEstimator::CalculateOutputSize(const OpInfo& op_info,
                                                  bool* found_unknown_shapes) {
  int64_t total_output_size = 0;
  // Use float as default for calculations.
  for (const auto& output : op_info.outputs()) {
    DataType dt = output.dtype();
    const auto& original_output_shape = output.shape();
    int64_t output_size = DataTypeSize(BaseType(dt));
    int num_dims = std::max(1, original_output_shape.dim_size());
    auto output_shape = MaybeGetMinimumShape(original_output_shape, num_dims,
                                             found_unknown_shapes);
    for (const auto& dim : output_shape.dim()) {
      output_size *= dim.size();
    }
    total_output_size += output_size;
    VLOG(1) << ""Output Size: "" << output_size
            << "" Total Output Size:"" << total_output_size;
  }
  return total_output_size;
}",CWE-190,2
0,"  virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {
    DCHECK(observer);
    NetworkObserverMap::iterator map_iter = network_observers_.begin();
    while (map_iter != network_observers_.end()) {
      map_iter->second->RemoveObserver(observer);
      if (!map_iter->second->size()) {
        delete map_iter->second;
        network_observers_.erase(map_iter++);
      } else {
        ++map_iter;
      }
    }
  }
",none,24
1,"tgs_build_reply(astgs_request_t priv,
		hdb_entry_ex *krbtgt,
		krb5_enctype krbtgt_etype,
		const krb5_keyblock *replykey,
		int rk_is_subkey,
		krb5_ticket *ticket,
		const char **e_text,
		AuthorizationData **auth_data,
		const struct sockaddr *from_addr)
{
    krb5_context context = priv->context;
    krb5_kdc_configuration *config = priv->config;
    KDC_REQ *req = &priv->req;
    KDC_REQ_BODY *b = &priv->req.req_body;
    const char *from = priv->from;
    krb5_error_code ret, ret2;
    krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
    krb5_principal krbtgt_out_principal = NULL;
    char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
    hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
    HDB *clientdb, *s4u2self_impersonated_clientdb;
    krb5_realm ref_realm = NULL;
    EncTicketPart *tgt = &ticket->ticket;
    krb5_principals spp = NULL;
    const EncryptionKey *ekey;
    krb5_keyblock sessionkey;
    krb5_kvno kvno;
    krb5_data rspac;
    const char *tgt_realm = /* Realm of TGT issuer */
        krb5_principal_get_realm(context, krbtgt->entry.principal);
    const char *our_realm = /* Realm of this KDC */
        krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
    char **capath = NULL;
    size_t num_capath = 0;

    hdb_entry_ex *krbtgt_out = NULL;

    METHOD_DATA enc_pa_data;

    PrincipalName *s;
    Realm r;
    EncTicketPart adtkt;
    char opt_str[128];
    int signedpath = 0;

    Key *tkey_check;
    Key *tkey_sign;
    int flags = HDB_F_FOR_TGS_REQ;

    memset(&sessionkey, 0, sizeof(sessionkey));
    memset(&adtkt, 0, sizeof(adtkt));
    krb5_data_zero(&rspac);
    memset(&enc_pa_data, 0, sizeof(enc_pa_data));

    s = b->sname;
    r = b->realm;

    /*
     * The canonicalize KDC option is passed as a hint to the backend, but
     * can typically be ignored. Per RFC 6806, names are not canonicalized
     * in response to a TGS request (although we make an exception, see
     * force-canonicalize below).
     */
    if (b->kdc_options.canonicalize)
	flags |= HDB_F_CANON;

    if(b->kdc_options.enc_tkt_in_skey){
	Ticket *t;
	hdb_entry_ex *uu;
	krb5_principal p;
	Key *uukey;
	krb5uint32 second_kvno = 0;
	krb5uint32 *kvno_ptr = NULL;

	if(b->additional_tickets == NULL ||
	   b->additional_tickets->len == 0){
	    ret = KRB5KDC_ERR_BADOPTION; /* ? */
	    kdc_log(context, config, 4,
		    ""No second ticket present in user-to-user request"");
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""No second ticket present in user-to-user request"");
	    goto out;
	}
	t = &b->additional_tickets->val[0];
	if(!get_krbtgt_realm(&t->sname)){
	    kdc_log(context, config, 4,
		    ""Additional ticket is not a ticket-granting ticket"");
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Additional ticket is not a ticket-granting ticket"");
	    ret = KRB5KDC_ERR_POLICY;
	    goto out;
	}
	_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
	ret = krb5_unparse_name(context, p, &tpn);
	if (ret)
		goto out;
	if(t->enc_part.kvno){
	    second_kvno = *t->enc_part.kvno;
	    kvno_ptr = &second_kvno;
	}
	ret = _kdc_db_fetch(context, config, p,
			    HDB_F_GET_KRBTGT, kvno_ptr,
			    NULL, &uu);
	krb5_free_principal(context, p);
	if(ret){
	    if (ret == HDB_ERR_NOENTRY)
		ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""User-to-user service principal (TGS) unknown"");
	    goto out;
	}
	ret = hdb_enctype2key(context, &uu->entry, NULL,
			      t->enc_part.etype, &uukey);
	if(ret){
	    _kdc_free_ent(context, uu);
	    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""User-to-user enctype not supported"");
	    goto out;
	}
	ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
	_kdc_free_ent(context, uu);
	if(ret) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""User-to-user TGT decrypt failure"");
	    goto out;
        }

	ret = verify_flags(context, config, &adtkt, tpn);
	if (ret) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""User-to-user TGT expired or invalid"");
	    goto out;
        }

	s = &adtkt.cname;
	r = adtkt.crealm;
    }

    _krb5_principalname2krb5_principal(context, &sp, *s, r);
    ret = krb5_unparse_name(context, sp, &priv->sname);
    if (ret)
	goto out;
    spn = priv->sname;
    _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
    ret = krb5_unparse_name(context, cp, &priv->cname);
    if (ret)
	goto out;
    cpn = priv->cname;
    unparse_flags (KDCOptions2int(b->kdc_options),
		   asn1_KDCOptions_units(),
		   opt_str, sizeof(opt_str));
    if(*opt_str)
	kdc_log(context, config, 4,
		""TGS-REQ %s from %s for %s [%s]"",
		cpn, from, spn, opt_str);
    else
	kdc_log(context, config, 4,
		""TGS-REQ %s from %s for %s"", cpn, from, spn);

    /*
     * Fetch server
     */

server_lookup:
    ret = _kdc_db_fetch(context, config, sp,
                        HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,
			NULL, NULL, &server);
    priv->server = server;
    if (ret == HDB_ERR_NOT_FOUND_HERE) {
	kdc_log(context, config, 5, ""target %s does not have secrets at this KDC, need to proxy"", spn);
        _kdc_audit_addreason((kdc_request_t)priv, ""Target not found here"");
	goto out;
    } else if (ret == HDB_ERR_WRONG_REALM) {
        free(ref_realm);
	ref_realm = strdup(server->entry.principal->realm);
	if (ref_realm == NULL) {
            ret = krb5_enomem(context);
	    goto out;
	}

	kdc_log(context, config, 4,
		""Returning a referral to realm %s for ""
		""server %s."",
		ref_realm, spn);
	krb5_free_principal(context, sp);
	sp = NULL;
	ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
				  ref_realm, NULL);
	if (ret)
	    goto out;
	free(priv->sname);
        priv->sname = NULL;
	ret = krb5_unparse_name(context, sp, &priv->sname);
	if (ret)
	    goto out;
	spn = priv->sname;

	goto server_lookup;
    } else if (ret) {
	const char *new_rlm, *msg;
	Realm req_rlm;
	krb5_realm *realms;

	if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
            if (capath == NULL) {
                /* With referalls, hierarchical capaths are always enabled */
                ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,
                                         req_rlm, TRUE, &capath, &num_capath);
                if (ret2) {
                    ret = ret2;
                    _kdc_audit_addreason((kdc_request_t)priv,
                                         ""No trusted path from client realm to ours"");
                    goto out;
                }
            }
            new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
            if (new_rlm) {
                kdc_log(context, config, 5, ""krbtgt from %s via %s for ""
                        ""realm %s not found, trying %s"", tgt->crealm,
                        our_realm, req_rlm, new_rlm);

                free(ref_realm);
                ref_realm = strdup(new_rlm);
                if (ref_realm == NULL) {
                    ret = krb5_enomem(context);
                    goto out;
                }

                krb5_free_principal(context, sp);
                sp = NULL;
                krb5_make_principal(context, &sp, r,
                                    KRB5_TGS_NAME, ref_realm, NULL);
                free(priv->sname);
                priv->sname = NULL;
                ret = krb5_unparse_name(context, sp, &priv->sname);
                if (ret)
                    goto out;
                spn = priv->sname;
                goto server_lookup;
            }
	} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
	    if (strcmp(realms[0], sp->realm) != 0) {
		kdc_log(context, config, 4,
			""Returning a referral to realm %s for ""
			""server %s that was not found"",
			realms[0], spn);
		krb5_free_principal(context, sp);
                sp = NULL;
		krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
				    realms[0], NULL);
		free(priv->sname);
                priv->sname = NULL;
		ret = krb5_unparse_name(context, sp, &priv->sname);
		if (ret) {
		    krb5_free_host_realm(context, realms);
		    goto out;
		}
		spn = priv->sname;

                free(ref_realm);
		ref_realm = strdup(realms[0]);

		krb5_free_host_realm(context, realms);
		goto server_lookup;
	    }
	    krb5_free_host_realm(context, realms);
	}
	msg = krb5_get_error_message(context, ret);
	kdc_log(context, config, 3,
		""Server not found in database: %s: %s"", spn, msg);
	krb5_free_error_message(context, msg);
	if (ret == HDB_ERR_NOENTRY)
	    ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
        _kdc_audit_addreason((kdc_request_t)priv,
                             ""Service principal unknown"");
	goto out;
    }

    /*
     * RFC 6806 notes that names MUST NOT be changed in the response to
     * a TGS request. Hence we ignore the setting of the canonicalize
     * KDC option. However, for legacy interoperability we do allow the
     * backend to override this by setting the force-canonicalize HDB
     * flag in the server entry.
     */
    if (server->entry.flags.force_canonicalize)
	rsp = server->entry.principal;
    else
	rsp = sp;

    /*
     * Select enctype, return key and kvno.
     */

    {
	krb5_enctype etype;

	if(b->kdc_options.enc_tkt_in_skey) {
	    size_t i;
	    ekey = &adtkt.key;
	    for(i = 0; i < b->etype.len; i++)
		if (b->etype.val[i] == adtkt.key.keytype)
		    break;
	    if(i == b->etype.len) {
		kdc_log(context, config, 4,
			""Addition ticket have not matching etypes"");
		krb5_clear_error_message(context);
		ret = KRB5KDC_ERR_ETYPE_NOSUPP;
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""No matching enctypes for 2nd ticket"");
		goto out;
	    }
	    etype = b->etype.val[i];
	    kvno = 0;
	} else {
	    Key *skey;

	    ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)
							     ? KFE_IS_TGS : 0,
				  b->etype.val, b->etype.len, &etype, NULL,
				  NULL);
	    if(ret) {
		kdc_log(context, config, 4,
			""Server (%s) has no support for etypes"", spn);
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""Enctype not supported"");
		goto out;
	    }
	    ret = _kdc_get_preferred_key(context, config, server, spn,
					 NULL, &skey);
	    if(ret) {
		kdc_log(context, config, 4,
			""Server (%s) has no supported etypes"", spn);
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""Enctype not supported"");
		goto out;
	    }
	    ekey = &skey->key;
	    kvno = server->entry.kvno;
	}

	ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
	if (ret)
	    goto out;
    }

    /*
     * Check that service is in the same realm as the krbtgt. If it's
     * not the same, it's someone that is using a uni-directional trust
     * backward.
     */

    /*
     * Validate authorization data
     */

    ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
			  krbtgt_etype, &tkey_check);
    if(ret) {
	kdc_log(context, config, 4,
		    ""Failed to find key for krbtgt PAC check"");
        _kdc_audit_addreason((kdc_request_t)priv,
                             ""No key for krbtgt PAC check"");
	goto out;
    }

    /* 
     * Now refetch the primary krbtgt, and get the current kvno (the
     * sign check may have been on an old kvno, and the server may
     * have been an incoming trust)
     */
    
    ret = krb5_make_principal(context,
                              &krbtgt_out_principal,
                              our_realm,
                              KRB5_TGS_NAME,
                              our_realm,
                              NULL);
    if (ret) {
        kdc_log(context, config, 4,
                ""Failed to make krbtgt principal name object for ""
                ""authz-data signatures"");
        goto out;
    }
    ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
    if (ret) {
        kdc_log(context, config, 4,
                ""Failed to make krbtgt principal name object for ""
                ""authz-data signatures"");
        goto out;
    }

    ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
			HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
    if (ret) {
	char *ktpn = NULL;
	ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
	kdc_log(context, config, 4,
		""No such principal %s (needed for authz-data signature keys) ""
		""while processing TGS-REQ for service %s with krbtg %s"",
		krbtgt_out_n, spn, (ret == 0) ? ktpn : """");
	free(ktpn);
	ret = KRB5KRB_AP_ERR_NOT_US;
	goto out;
    }

    /* 
     * The first realm is the realm of the service, the second is
     * krbtgt//@REALM component of the krbtgt DN the request was
     * encrypted to.  The redirection via the krbtgt_out entry allows
     * the DB to possibly correct the case of the realm (Samba4 does
     * this) before the strcmp() 
     */
    if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
	       krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
	char *ktpn;
	ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
	kdc_log(context, config, 4,
		""Request with wrong krbtgt: %s"",
		(ret == 0) ? ktpn : """");
	if(ret == 0)
	    free(ktpn);
	ret = KRB5KRB_AP_ERR_NOT_US;
        _kdc_audit_addreason((kdc_request_t)priv, ""Request with wrong TGT"");
	goto out;
    }

    ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
				 NULL, &tkey_sign);
    if (ret) {
	kdc_log(context, config, 4,
		    ""Failed to find key for krbtgt PAC signature"");
        _kdc_audit_addreason((kdc_request_t)priv,
                             ""Failed to find key for krbtgt PAC signature"");
	goto out;
    }
    ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
			  tkey_sign->key.keytype, &tkey_sign);
    if(ret) {
	kdc_log(context, config, 4,
		    ""Failed to find key for krbtgt PAC signature"");
        _kdc_audit_addreason((kdc_request_t)priv,
                             ""Failed to find key for krbtgt PAC signature"");
	goto out;
    }

    {
        krb5_data verified_cas;

        /*
         * If the client doesn't exist in the HDB but has a TGT and it's
         * obtained with PKINIT then we assume it's a synthetic client -- that
         * is, a client whose name was vouched for by a CA using a PKINIT SAN,
         * but which doesn't exist in the HDB proper.  We'll allow such a
         * client to do TGT requests even though normally we'd reject all
         * clients that don't exist in the HDB.
         */
        ret = krb5_ticket_get_authorization_data_type(context, ticket,
                                                      KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
                                                      &verified_cas);
        if (ret == 0) {
            krb5_data_free(&verified_cas);
            flags |= HDB_F_SYNTHETIC_OK;
        }
    }
    ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
			NULL, &clientdb, &client);
    flags &= ~HDB_F_SYNTHETIC_OK;
    priv->client = client;
    if(ret == HDB_ERR_NOT_FOUND_HERE) {
	/* This is OK, we are just trying to find out if they have
	 * been disabled or deleted in the meantime, missing secrets
	 * is OK */
    } else if(ret){
	const char *krbtgt_realm, *msg;

	/*
	 * If the client belongs to the same realm as our krbtgt, it
	 * should exist in the local database.
	 *
	 */

	krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);

	if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
	    if (ret == HDB_ERR_NOENTRY)
		ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
	    kdc_log(context, config, 4, ""Client no longer in database: %s"",
		    cpn);
            _kdc_audit_addreason((kdc_request_t)priv, ""Client no longer in HDB"");
	    goto out;
	}

	msg = krb5_get_error_message(context, ret);
	kdc_log(context, config, 4, ""Client not found in database: %s"", msg);
        _kdc_audit_addreason((kdc_request_t)priv, ""Client does not exist"");
	krb5_free_error_message(context, msg);
    } else if (ret == 0 &&
               (client->entry.flags.invalid || !client->entry.flags.client)) {
        _kdc_audit_addreason((kdc_request_t)priv, ""Client has invalid bit set"");
        kdc_log(context, config, 4, ""Client has invalid bit set"");
        ret = KRB5KDC_ERR_POLICY;
        goto out;
    }

    ret = check_PAC(context, config, cp, NULL,
		    client, server, krbtgt,
		    &tkey_check->key,
		    ekey, &tkey_sign->key,
		    tgt, &rspac, &signedpath);
    if (ret) {
	const char *msg = krb5_get_error_message(context, ret);
        _kdc_audit_addreason((kdc_request_t)priv, ""PAC check failed"");
	kdc_log(context, config, 4,
		""Verify PAC failed for %s (%s) from %s with %s"",
		spn, cpn, from, msg);
	krb5_free_error_message(context, msg);
	goto out;
    }

    /* also check the krbtgt for signature */
    ret = check_KRB5SignedPath(context,
			       config,
			       krbtgt,
			       cp,
			       tgt,
			       &spp,
			       &signedpath);
    if (ret) {
	const char *msg = krb5_get_error_message(context, ret);
        _kdc_audit_addreason((kdc_request_t)priv, ""KRB5SignedPath check failed"");
	kdc_log(context, config, 4,
		""KRB5SignedPath check failed for %s (%s) from %s with %s"",
		spn, cpn, from, msg);
	krb5_free_error_message(context, msg);
	goto out;
    }

    /*
     * Process request
     */

    /* by default the tgt principal matches the client principal */
    tp = cp;
    tpn = cpn;

    if (client) {
	const PA_DATA *sdata;
	int i = 0;

	sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
	if (sdata) {
	    struct astgs_request_desc imp_req;
	    krb5_crypto crypto;
	    krb5_data datack;
	    PA_S4U2Self self;
	    const char *str;

	    ret = decode_PA_S4U2Self(sdata->padata_value.data,
				     sdata->padata_value.length,
				     &self, NULL);
	    if (ret) {
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""Failed to decode PA-S4U2Self"");
		kdc_log(context, config, 4, ""Failed to decode PA-S4U2Self"");
		goto out;
	    }

	    if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {
		free_PA_S4U2Self(&self);
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""PA-S4U2Self with unkeyed checksum"");
		kdc_log(context, config, 4, ""Reject PA-S4U2Self with unkeyed checksum"");
		ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
		goto out;
	    }

	    ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
	    if (ret)
		goto out;

	    ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
	    if (ret) {
		const char *msg = krb5_get_error_message(context, ret);
		free_PA_S4U2Self(&self);
		krb5_data_free(&datack);
		kdc_log(context, config, 4, ""krb5_crypto_init failed: %s"", msg);
		krb5_free_error_message(context, msg);
		goto out;
	    }

	    /* Allow HMAC_MD5 checksum with any key type */
	    if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {
		struct krb5_crypto_iov iov;
		unsigned char csdata[16];
		Checksum cs;

		cs.checksum.length = sizeof(csdata);
		cs.checksum.data = &csdata;

		iov.data.data = datack.data;
		iov.data.length = datack.length;
		iov.flags = KRB5_CRYPTO_TYPE_DATA;

		ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,
					      KRB5_KU_OTHER_CKSUM, &iov, 1,
					      &cs);
		if (ret == 0 &&
		    krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)
		    ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
	    }
	    else {
		ret = krb5_verify_checksum(context,
					   crypto,
					   KRB5_KU_OTHER_CKSUM,
					   datack.data,
					   datack.length,
					   &self.cksum);
	    }
	    krb5_data_free(&datack);
	    krb5_crypto_destroy(context, crypto);
	    if (ret) {
		const char *msg = krb5_get_error_message(context, ret);
		free_PA_S4U2Self(&self);
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""S4U2Self checksum failed"");
		kdc_log(context, config, 4,
			""krb5_verify_checksum failed for S4U2Self: %s"", msg);
		krb5_free_error_message(context, msg);
		goto out;
	    }

	    ret = _krb5_principalname2krb5_principal(context,
						     &tp,
						     self.name,
						     self.realm);
	    free_PA_S4U2Self(&self);
	    if (ret)
		goto out;

	    ret = krb5_unparse_name(context, tp, &tpn);
	    if (ret)
		goto out;

            /*
             * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients
             * is probably not desirable!
             */
	    ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
				NULL, &s4u2self_impersonated_clientdb,
				&s4u2self_impersonated_client);
	    if (ret) {
		const char *msg;

		/*
		 * If the client belongs to the same realm as our krbtgt, it
		 * should exist in the local database.
		 *
		 */

		if (ret == HDB_ERR_NOENTRY)
		    ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
		msg = krb5_get_error_message(context, ret);
                _kdc_audit_addreason((kdc_request_t)priv,
                                     ""S4U2Self principal to impersonate not found"");
		kdc_log(context, config, 2,
			""S4U2Self principal to impersonate %s not found in database: %s"",
			tpn, msg);
		krb5_free_error_message(context, msg);
		goto out;
	    }

	    /* Ignore require_pwchange and pw_end attributes (as Windows does),
	     * since S4U2Self is not password authentication. */
	    s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;
	    free(s4u2self_impersonated_client->entry.pw_end);
	    s4u2self_impersonated_client->entry.pw_end = NULL;

	    imp_req = *priv;
	    imp_req.client = s4u2self_impersonated_client;
	    imp_req.client_princ = tp;

	    ret = kdc_check_flags(&imp_req, FALSE);
	    if (ret)
		goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */

	    /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
	    if(rspac.data) {
		krb5_pac p = NULL;
		krb5_data_free(&rspac);
		ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
		if (ret) {
                    _kdc_audit_addreason((kdc_request_t)priv,
                                         ""KRB5SignedPath missing"");
		    kdc_log(context, config, 4, ""PAC generation failed for -- %s"",
			    tpn);
		    goto out;
		}
		if (p != NULL) {
		    ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
					 s4u2self_impersonated_client->entry.principal,
					 ekey, &tkey_sign->key,
					 &rspac);
		    krb5_pac_free(context, p);
		    if (ret) {
			kdc_log(context, config, 4, ""PAC signing failed for -- %s"",
				tpn);
			goto out;
		    }
		}
	    }

	    /*
	     * Check that service doing the impersonating is
	     * requesting a ticket to it-self.
	     */
	    ret = check_s4u2self(context, config, clientdb, client, sp);
	    if (ret) {
		kdc_log(context, config, 4, ""S4U2Self: %s is not allowed ""
			""to impersonate to service ""
			""(tried for user %s to service %s)"",
			cpn, tpn, spn);
		goto out;
	    }

	    /*
	     * If the service isn't trusted for authentication to
	     * delegation or if the impersonate client is disallowed
	     * forwardable, remove the forwardable flag.
	     */

	    if (client->entry.flags.trusted_for_delegation &&
		s4u2self_impersonated_client->entry.flags.forwardable) {
		str = ""[forwardable]"";
	    } else {
		b->kdc_options.forwardable = 0;
		str = """";
	    }
	    kdc_log(context, config, 4, ""s4u2self %s impersonating %s to ""
		    ""service %s %s"", cpn, tpn, spn, str);
	}
    }

    /*
     * Constrained delegation
     */

    if (client != NULL
	&& b->additional_tickets != NULL
	&& b->additional_tickets->len != 0
	&& b->kdc_options.cname_in_addl_tkt
	&& b->kdc_options.enc_tkt_in_skey == 0)
    {
	int ad_signedpath = 0;
	Key *clientkey;
	Ticket *t;

	/*
	 * Require that the KDC have issued the service's krbtgt (not
	 * self-issued ticket with kimpersonate(1).
	 */
	if (!signedpath) {
	    ret = KRB5KDC_ERR_BADOPTION;
            _kdc_audit_addreason((kdc_request_t)priv, ""KRB5SignedPath missing"");
	    kdc_log(context, config, 4,
		    ""Constrained delegation done on service ticket %s/%s"",
		    cpn, spn);
	    goto out;
	}

	t = &b->additional_tickets->val[0];

	ret = hdb_enctype2key(context, &client->entry,
			      hdb_kvno2keys(context, &client->entry,
					    t->enc_part.kvno ? * t->enc_part.kvno : 0),
			      t->enc_part.etype, &clientkey);
	if(ret){
	    ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
	    goto out;
	}

	ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
	if (ret) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Failed to decrypt constrained delegation ticket"");
	    kdc_log(context, config, 4,
		    ""failed to decrypt ticket for ""
		    ""constrained delegation from %s to %s "", cpn, spn);
	    goto out;
	}

	ret = _krb5_principalname2krb5_principal(context,
						 &tp,
						 adtkt.cname,
						 adtkt.crealm);
	if (ret)
	    goto out;

	ret = krb5_unparse_name(context, tp, &tpn);
	if (ret)
	    goto out;

        _kdc_audit_addkv((kdc_request_t)priv, 0, ""impersonatee"", ""%s"", tpn);

	ret = _krb5_principalname2krb5_principal(context,
						 &dp,
						 t->sname,
						 t->realm);
	if (ret)
	    goto out;

	ret = krb5_unparse_name(context, dp, &dpn);
	if (ret)
	    goto out;

	/* check that ticket is valid */
	if (adtkt.flags.forwardable == 0) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Missing forwardable flag on ticket for constrained delegation"");
	    kdc_log(context, config, 4,
		    ""Missing forwardable flag on ticket for ""
		    ""constrained delegation from %s (%s) as %s to %s "",
		    cpn, dpn, tpn, spn);
	    ret = KRB5KDC_ERR_BADOPTION;
	    goto out;
	}

	ret = check_constrained_delegation(context, config, clientdb,
					   client, server, sp);
	if (ret) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Constrained delegation not allowed"");
	    kdc_log(context, config, 4,
		    ""constrained delegation from %s (%s) as %s to %s not allowed"",
		    cpn, dpn, tpn, spn);
	    goto out;
	}

	ret = verify_flags(context, config, &adtkt, tpn);
	if (ret) {
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Constrained delegation ticket expired or invalid"");
	    goto out;
	}

	krb5_data_free(&rspac);

	/*
	 * generate the PAC for the user.
	 *
	 * TODO: pass in t->sname and t->realm and build
	 * a S4U_DELEGATION_INFO blob to the PAC.
	 */
	ret = check_PAC(context, config, tp, dp,
			client, server, krbtgt,
			&clientkey->key,
			ekey, &tkey_sign->key,
			&adtkt, &rspac, &ad_signedpath);
	if (ret) {
	    const char *msg = krb5_get_error_message(context, ret);
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Constrained delegation ticket PAC check failed"");
	    kdc_log(context, config, 4,
		    ""Verify delegated PAC failed to %s for client""
		    ""%s (%s) as %s from %s with %s"",
		    spn, cpn, dpn, tpn, from, msg);
	    krb5_free_error_message(context, msg);
	    goto out;
	}

	/*
	 * Check that the KDC issued the user's ticket.
	 */
	ret = check_KRB5SignedPath(context,
				   config,
				   krbtgt,
				   cp,
				   &adtkt,
				   NULL,
				   &ad_signedpath);
	if (ret) {
	    const char *msg = krb5_get_error_message(context, ret);
	    kdc_log(context, config, 4,
		    ""KRB5SignedPath check from service %s failed ""
		    ""for delegation to %s for client %s (%s)""
		    ""from %s failed with %s"",
		    spn, tpn, dpn, cpn, from, msg);
	    krb5_free_error_message(context, msg);
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""KRB5SignedPath check failed"");
	    goto out;
	}

	if (!ad_signedpath) {
	    ret = KRB5KDC_ERR_BADOPTION;
	    kdc_log(context, config, 4,
		    ""Ticket not signed with PAC nor SignedPath service %s failed ""
		    ""for delegation to %s for client %s (%s)""
		    ""from %s"",
		    spn, tpn, dpn, cpn, from);
            _kdc_audit_addreason((kdc_request_t)priv,
                                 ""Constrained delegation ticket not signed"");
	    goto out;
	}

	kdc_log(context, config, 4, ""constrained delegation for %s ""
		""from %s (%s) to %s"", tpn, cpn, dpn, spn);
    }

    /*
     * Check flags
     */

    ret = kdc_check_flags(priv, FALSE);
    if(ret)
	goto out;

    if((b->kdc_options.validate || b->kdc_options.renew) &&
       !krb5_principal_compare(context,
			       krbtgt->entry.principal,
			       server->entry.principal)){
        _kdc_audit_addreason((kdc_request_t)priv, ""Inconsistent request"");
	kdc_log(context, config, 4, ""Inconsistent request."");
	ret = KRB5KDC_ERR_SERVER_NOMATCH;
	goto out;
    }

    /* check for valid set of addresses */
    if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {
        if (config->check_ticket_addresses) {
            ret = KRB5KRB_AP_ERR_BADADDR;
            _kdc_audit_addkv((kdc_request_t)priv, 0, ""wrongaddr"", ""yes"");
            kdc_log(context, config, 4, ""Request from wrong address"");
            _kdc_audit_addreason((kdc_request_t)priv, ""Request from wrong address"");
            goto out;
        } else if (config->warn_ticket_addresses) {
            _kdc_audit_addkv((kdc_request_t)priv, 0, ""wrongaddr"", ""yes"");
        }
    }

    /* check local and per-principal anonymous ticket issuance policy */
    if (is_anon_tgs_request_p(b, tgt)) {
	ret = _kdc_check_anon_policy(priv);
	if (ret)
	    goto out;
    }

    /*
     * If this is an referral, add server referral data to the
     * auth_data reply .
     */
    if (ref_realm) {
	PA_DATA pa;
	krb5_crypto crypto;

	kdc_log(context, config, 3,
		""Adding server referral to %s"", ref_realm);

	ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
	if (ret)
	    goto out;

	ret = build_server_referral(context, config, crypto, ref_realm,
				    NULL, s, &pa.padata_value);
	krb5_crypto_destroy(context, crypto);
	if (ret) {
            _kdc_audit_addreason((kdc_request_t)priv, ""Referral build failed"");
	    kdc_log(context, config, 4,
		    ""Failed building server referral"");
	    goto out;
	}
	pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;

	ret = add_METHOD_DATA(&enc_pa_data, &pa);
	krb5_data_free(&pa.padata_value);
	if (ret) {
	    kdc_log(context, config, 4,
		    ""Add server referral METHOD-DATA failed"");
	    goto out;
	}
    }

    /*
     *
     */

    ret = tgs_make_reply(priv,
			 tp,
			 tgt,
			 replykey,
			 rk_is_subkey,
			 ekey,
			 &sessionkey,
			 kvno,
			 *auth_data,
			 server,
			 rsp,
			 client,
			 cp,
                         tgt_realm,
			 krbtgt_out,
			 tkey_sign->key.keytype,
			 spp,
			 &rspac,
			 &enc_pa_data);

out:
    if (tpn != cpn)
	    free(tpn);
    free(dpn);
    free(krbtgt_out_n);
    _krb5_free_capath(context, capath);

    krb5_data_free(&rspac);
    krb5_free_keyblock_contents(context, &sessionkey);
    if(krbtgt_out)
	_kdc_free_ent(context, krbtgt_out);
    if(server)
	_kdc_free_ent(context, server);
    if(client)
	_kdc_free_ent(context, client);
    if(s4u2self_impersonated_client)
	_kdc_free_ent(context, s4u2self_impersonated_client);

    if (tp && tp != cp)
	krb5_free_principal(context, tp);
    krb5_free_principal(context, cp);
    krb5_free_principal(context, dp);
    krb5_free_principal(context, sp);
    krb5_free_principal(context, krbtgt_out_principal);
    free(ref_realm);
    free_METHOD_DATA(&enc_pa_data);

    free_EncTicketPart(&adtkt);

    return ret;
}",CWE-476,12
1,"int hw_atl_utils_fw_rpc_wait(struct aq_hw_s *self,
			     struct hw_atl_utils_fw_rpc **rpc)
{
	struct aq_hw_atl_utils_fw_rpc_tid_s sw;
	struct aq_hw_atl_utils_fw_rpc_tid_s fw;
	int err = 0;

	do {
		sw.val = aq_hw_read_reg(self, HW_ATL_RPC_CONTROL_ADR);

		self->rpc_tid = sw.tid;

		err = readx_poll_timeout_atomic(hw_atl_utils_rpc_state_get,
						self, fw.val,
						sw.tid == fw.tid,
						1000U, 100000U);
		if (err < 0)
			goto err_exit;

		err = aq_hw_err_from_flags(self);
		if (err < 0)
			goto err_exit;

		if (fw.len == 0xFFFFU) {
			err = hw_atl_utils_fw_rpc_call(self, sw.len);
			if (err < 0)
				goto err_exit;
		}
	} while (sw.tid != fw.tid || 0xFFFFU == fw.len);

	if (rpc) {
		if (fw.len) {
			err =
			hw_atl_utils_fw_downld_dwords(self,
						      self->rpc_addr,
						      (u32 *)(void *)
						      &self->rpc,
						      (fw.len + sizeof(u32) -
						       sizeof(u8)) /
						      sizeof(u32));
			if (err < 0)
				goto err_exit;
		}

		*rpc = &self->rpc;
	}

err_exit:
	return err;
}",CWE-787,16
1,"parse_command_modifiers(
	exarg_T	    *eap,
	char	    **errormsg,
	cmdmod_T    *cmod,
	int	    skip_only)
{
    char_u  *orig_cmd = eap->cmd;
    char_u  *cmd_start = NULL;
    int	    use_plus_cmd = FALSE;
    int	    starts_with_colon = FALSE;
    int	    vim9script = in_vim9script();
    int	    has_visual_range = FALSE;

    CLEAR_POINTER(cmod);
    cmod->cmod_flags = sticky_cmdmod_flags;

    if (STRNCMP(eap->cmd, ""'<,'>"", 5) == 0)
    {
	// The automatically inserted Visual area range is skipped, so that
	// typing "":cmdmod cmd"" in Visual mode works without having to move the
	// range to after the modififiers. The command will be
	// ""'<,'>cmdmod cmd"", parse ""cmdmod cmd"" and then put back ""'<,'>""
	// before ""cmd"" below.
	eap->cmd += 5;
	cmd_start = eap->cmd;
	has_visual_range = TRUE;
    }

    // Repeat until no more command modifiers are found.
    for (;;)
    {
	char_u  *p;

	while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':')
	{
	    if (*eap->cmd == ':')
		starts_with_colon = TRUE;
	    ++eap->cmd;
	}

	// in ex mode, an empty command (after modifiers) works like :+
	if (*eap->cmd == NUL && exmode_active
		   && (getline_equal(eap->getline, eap->cookie, getexmodeline)
		       || getline_equal(eap->getline, eap->cookie, getexline))
			&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
	{
	    use_plus_cmd = TRUE;
	    if (!skip_only)
		ex_pressedreturn = TRUE;
	    break;  // no modifiers following
	}

	// ignore comment and empty lines
	if (comment_start(eap->cmd, starts_with_colon))
	{
	    // a comment ends at a NL
	    if (eap->nextcmd == NULL)
	    {
		eap->nextcmd = vim_strchr(eap->cmd, '\n');
		if (eap->nextcmd != NULL)
		    ++eap->nextcmd;
	    }
	    if (vim9script && has_cmdmod(cmod, FALSE))
		*errormsg = _(e_command_modifier_without_command);
	    return FAIL;
	}
	if (*eap->cmd == NUL)
	{
	    if (!skip_only)
	    {
		ex_pressedreturn = TRUE;
		if (vim9script && has_cmdmod(cmod, FALSE))
		    *errormsg = _(e_command_modifier_without_command);
	    }
	    return FAIL;
	}

	p = skip_range(eap->cmd, TRUE, NULL);

	// In Vim9 script a variable can shadow a command modifier:
	//   verbose = 123
	//   verbose += 123
	//   silent! verbose = func()
	//   verbose.member = 2
	//   verbose[expr] = 2
	// But not:
	//   verbose [a, b] = list
	if (vim9script)
	{
	    char_u *s, *n;

	    for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)
		;
	    n = skipwhite(s);
	    if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')
		    || *s == '[')
		break;
	}

	switch (*p)
	{
	    // When adding an entry, also modify cmd_exists().
	    case 'a':	if (!checkforcmd_noparen(&eap->cmd, ""aboveleft"", 3))
			    break;
			cmod->cmod_split |= WSP_ABOVE;
			continue;

	    case 'b':	if (checkforcmd_noparen(&eap->cmd, ""belowright"", 3))
			{
			    cmod->cmod_split |= WSP_BELOW;
			    continue;
			}
			if (checkforcmd_opt(&eap->cmd, ""browse"", 3, TRUE))
			{
#ifdef FEAT_BROWSE_CMD
			    cmod->cmod_flags |= CMOD_BROWSE;
#endif
			    continue;
			}
			if (!checkforcmd_noparen(&eap->cmd, ""botright"", 2))
			    break;
			cmod->cmod_split |= WSP_BOT;
			continue;

	    case 'c':	if (!checkforcmd_opt(&eap->cmd, ""confirm"", 4, TRUE))
			    break;
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
			cmod->cmod_flags |= CMOD_CONFIRM;
#endif
			continue;

	    case 'k':	if (checkforcmd_noparen(&eap->cmd, ""keepmarks"", 3))
			{
			    cmod->cmod_flags |= CMOD_KEEPMARKS;
			    continue;
			}
			if (checkforcmd_noparen(&eap->cmd, ""keepalt"", 5))
			{
			    cmod->cmod_flags |= CMOD_KEEPALT;
			    continue;
			}
			if (checkforcmd_noparen(&eap->cmd, ""keeppatterns"", 5))
			{
			    cmod->cmod_flags |= CMOD_KEEPPATTERNS;
			    continue;
			}
			if (!checkforcmd_noparen(&eap->cmd, ""keepjumps"", 5))
			    break;
			cmod->cmod_flags |= CMOD_KEEPJUMPS;
			continue;

	    case 'f':	// only accept "":filter {pat} cmd""
			{
			    char_u  *reg_pat;
			    char_u  *nulp = NULL;
			    int	    c = 0;

			    if (!checkforcmd_noparen(&p, ""filter"", 4)
				    || *p == NUL
				    || (ends_excmd(*p)
#ifdef FEAT_EVAL
					// in "":filter #pat# cmd"" # does not
					// start a comment
				     && (!vim9script || VIM_ISWHITE(p[1]))
#endif
				     ))
				break;
			    if (*p == '!')
			    {
				cmod->cmod_filter_force = TRUE;
				p = skipwhite(p + 1);
				if (*p == NUL || ends_excmd(*p))
				    break;
			    }
#ifdef FEAT_EVAL
			    // Avoid that ""filter(arg)"" is recognized.
			    if (vim9script && !VIM_ISWHITE(p[-1]))
				break;
#endif
			    if (skip_only)
				p = skip_vimgrep_pat(p, NULL, NULL);
			    else
				// NOTE: This puts a NUL after the pattern.
				p = skip_vimgrep_pat_ext(p, ®_pat, NULL,
								    &nulp, &c);
			    if (p == NULL || *p == NUL)
				break;
			    if (!skip_only)
			    {
				cmod->cmod_filter_regmatch.regprog =
						vim_regcomp(reg_pat, RE_MAGIC);
				if (cmod->cmod_filter_regmatch.regprog == NULL)
				    break;
				// restore the character overwritten by NUL
				if (nulp != NULL)
				    *nulp = c;
			    }
			    eap->cmd = p;
			    continue;
			}

			// "":hide"" and "":hide | cmd"" are not modifiers
	    case 'h':	if (p != eap->cmd || !checkforcmd_noparen(&p, ""hide"", 3)
					       || *p == NUL || ends_excmd(*p))
			    break;
			eap->cmd = p;
			cmod->cmod_flags |= CMOD_HIDE;
			continue;

	    case 'l':	if (checkforcmd_noparen(&eap->cmd, ""lockmarks"", 3))
			{
			    cmod->cmod_flags |= CMOD_LOCKMARKS;
			    continue;
			}
			if (checkforcmd_noparen(&eap->cmd, ""legacy"", 3))
			{
			    if (ends_excmd2(p, eap->cmd))
			    {
				*errormsg =
				      _(e_legacy_must_be_followed_by_command);
				return FAIL;
			    }
			    cmod->cmod_flags |= CMOD_LEGACY;
			    continue;
			}

			if (!checkforcmd_noparen(&eap->cmd, ""leftabove"", 5))
			    break;
			cmod->cmod_split |= WSP_ABOVE;
			continue;

	    case 'n':	if (checkforcmd_noparen(&eap->cmd, ""noautocmd"", 3))
			{
			    cmod->cmod_flags |= CMOD_NOAUTOCMD;
			    continue;
			}
			if (!checkforcmd_noparen(&eap->cmd, ""noswapfile"", 3))
			    break;
			cmod->cmod_flags |= CMOD_NOSWAPFILE;
			continue;

	    case 'r':	if (!checkforcmd_noparen(&eap->cmd, ""rightbelow"", 6))
			    break;
			cmod->cmod_split |= WSP_BELOW;
			continue;

	    case 's':	if (checkforcmd_noparen(&eap->cmd, ""sandbox"", 3))
			{
			    cmod->cmod_flags |= CMOD_SANDBOX;
			    continue;
			}
			if (!checkforcmd_noparen(&eap->cmd, ""silent"", 3))
			    break;
			cmod->cmod_flags |= CMOD_SILENT;
			if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))
			{
			    // "":silent!"", but not ""silent !cmd""
			    eap->cmd = skipwhite(eap->cmd + 1);
			    cmod->cmod_flags |= CMOD_ERRSILENT;
			}
			continue;

	    case 't':	if (checkforcmd_noparen(&p, ""tab"", 3))
			{
			    if (!skip_only)
			    {
				long tabnr = get_address(eap, &eap->cmd,
						    ADDR_TABS, eap->skip,
						    skip_only, FALSE, 1);
				if (tabnr == MAXLNUM)
				    cmod->cmod_tab = tabpage_index(curtab) + 1;
				else
				{
				    if (tabnr < 0 || tabnr > LAST_TAB_NR)
				    {
					*errormsg = _(e_invalid_range);
					return FAIL;
				    }
				    cmod->cmod_tab = tabnr + 1;
				}
			    }
			    eap->cmd = p;
			    continue;
			}
			if (!checkforcmd_noparen(&eap->cmd, ""topleft"", 2))
			    break;
			cmod->cmod_split |= WSP_TOP;
			continue;

	    case 'u':	if (!checkforcmd_noparen(&eap->cmd, ""unsilent"", 3))
			    break;
			cmod->cmod_flags |= CMOD_UNSILENT;
			continue;

	    case 'v':	if (checkforcmd_noparen(&eap->cmd, ""vertical"", 4))
			{
			    cmod->cmod_split |= WSP_VERT;
			    continue;
			}
			if (checkforcmd_noparen(&eap->cmd, ""vim9cmd"", 4))
			{
			    if (ends_excmd2(p, eap->cmd))
			    {
				*errormsg =
				      _(e_vim9cmd_must_be_followed_by_command);
				return FAIL;
			    }
			    cmod->cmod_flags |= CMOD_VIM9CMD;
			    continue;
			}
			if (!checkforcmd_noparen(&p, ""verbose"", 4))
			    break;
			if (vim_isdigit(*eap->cmd))
			{
			    // zero means not set, one is verbose == 0, etc.
			    cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;
			}
			else
			    cmod->cmod_verbose = 2;  // default: verbose == 1
			eap->cmd = p;
			continue;
	}
	break;
    }

    if (has_visual_range)
    {
	if (eap->cmd > cmd_start)
	{
	    // Move the '<,'> range to after the modifiers and insert a colon.
	    // Since the modifiers have been parsed put the colon on top of the
	    // space: ""'<,'>mod cmd"" -> ""mod:'<,'>cmd
	    // Put eap->cmd after the colon.
	    if (use_plus_cmd)
	    {
		size_t len = STRLEN(cmd_start);

		// Special case: empty command uses ""+"":
		//  ""'<,'>mods"" -> ""mods'<,'>+
		mch_memmove(orig_cmd, cmd_start, len);
		STRCPY(orig_cmd + len, ""'<,'>+"");
	    }
	    else
	    {
		mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);
		eap->cmd -= 5;
		mch_memmove(eap->cmd - 1, "":'<,'>"", 6);
	    }
	}
	else
	    // No modifiers, move the pointer back.
	    // Special case: change empty command to ""+"".
	    if (use_plus_cmd)
		eap->cmd = (char_u *)""'<,'>+"";
	    else
		eap->cmd = orig_cmd;
    }
    else if (use_plus_cmd)
	eap->cmd = (char_u *)""+"";

    return OK;
}",CWE-787,16
1,"stl_remove_degenerate(stl_file *stl, int facet) {
  int edge1;
  int edge2;
  int edge3;
  int neighbor1;
  int neighbor2;
  int neighbor3;
  int vnot1;
  int vnot2;
  int vnot3;

  if (stl->error) return;

  if(   !memcmp(&stl->facet_start[facet].vertex[0],
                &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))
        && !memcmp(&stl->facet_start[facet].vertex[1],
                   &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {
    /* all 3 vertices are equal.  Just remove the facet.  I don't think*/
    /* this is really possible, but just in case... */
    printf(""removing a facet in stl_remove_degenerate\n"");

    stl_remove_facet(stl, facet);
    return;
  }

  if(!memcmp(&stl->facet_start[facet].vertex[0],
             &stl->facet_start[facet].vertex[1], sizeof(stl_vertex))) {
    edge1 = 1;
    edge2 = 2;
    edge3 = 0;
  } else if(!memcmp(&stl->facet_start[facet].vertex[1],
                    &stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {
    edge1 = 0;
    edge2 = 2;
    edge3 = 1;
  } else if(!memcmp(&stl->facet_start[facet].vertex[2],
                    &stl->facet_start[facet].vertex[0], sizeof(stl_vertex))) {
    edge1 = 0;
    edge2 = 1;
    edge3 = 2;
  } else {
    /* No degenerate. Function shouldn't have been called. */
    return;
  }
  neighbor1 = stl->neighbors_start[facet].neighbor[edge1];
  neighbor2 = stl->neighbors_start[facet].neighbor[edge2];

  if(neighbor1 == -1) {
    stl_update_connects_remove_1(stl, neighbor2);
  }
  if(neighbor2 == -1) {
    stl_update_connects_remove_1(stl, neighbor1);
  }


  neighbor3 = stl->neighbors_start[facet].neighbor[edge3];
  vnot1 = stl->neighbors_start[facet].which_vertex_not[edge1];
  vnot2 = stl->neighbors_start[facet].which_vertex_not[edge2];
  vnot3 = stl->neighbors_start[facet].which_vertex_not[edge3];

  if(neighbor1 != -1){
    stl->neighbors_start[neighbor1].neighbor[(vnot1 + 1) % 3] = neighbor2;
    stl->neighbors_start[neighbor1].which_vertex_not[(vnot1 + 1) % 3] = vnot2;
  }
  if(neighbor2 != -1){
    stl->neighbors_start[neighbor2].neighbor[(vnot2 + 1) % 3] = neighbor1;
    stl->neighbors_start[neighbor2].which_vertex_not[(vnot2 + 1) % 3] = vnot1;
  }

  stl_remove_facet(stl, facet);

  if(neighbor3 != -1) {
    stl_update_connects_remove_1(stl, neighbor3);
    stl->neighbors_start[neighbor3].neighbor[(vnot3 + 1) % 3] = -1;
  }
}",CWE-125,1
0,"  InitializeTemporaryOriginsInfoTask(
      QuotaManager* manager,
      UsageTracker* temporary_usage_tracker)
      : DatabaseTaskBase(manager),
        has_registered_origins_(false) {
    DCHECK(temporary_usage_tracker);
    temporary_usage_tracker->GetCachedOrigins(&origins_);
  }
",none,24
1,"raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,
                                       raptor_xml_element* element,
                                       int auto_empty)
{
  raptor_iostream* iostr = xml_writer->iostr;
  raptor_namespace_stack *nstack = xml_writer->nstack;
  int depth = xml_writer->depth;
  int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);
  struct nsd *nspace_declarations = NULL;
  size_t nspace_declarations_count = 0;  
  unsigned int i;

  /* max is 1 per element and 1 for each attribute + size of declared */
  if(nstack) {
    int nspace_max_count = element->attribute_count+1;
    if(element->declared_nspaces)
      nspace_max_count += raptor_sequence_size(element->declared_nspaces);
    if(element->xml_language)
      nspace_max_count++;

    nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,
                                        sizeof(struct nsd));
    if(!nspace_declarations)
      return 1;
  }

  if(element->name->nspace) {
    if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {
      nspace_declarations[0].declaration=
        raptor_namespace_format_as_xml(element->name->nspace,
                                       &nspace_declarations[0].length);
      if(!nspace_declarations[0].declaration)
        goto error;
      nspace_declarations[0].nspace = element->name->nspace;
      nspace_declarations_count++;
    }
  }

  if(nstack && element->attributes) {
    for(i = 0; i < element->attribute_count; i++) {
      /* qname */
      if(element->attributes[i]->nspace) {
        /* Check if we need a namespace declaration attribute */
        if(nstack && 
           !raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {
          /* not in scope and not same as element (so already going to be declared)*/
          unsigned int j;
          int declare_me = 1;
          
          /* check it wasn't an earlier declaration too */
          for(j = 0; j < nspace_declarations_count; j++)
            if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {
              declare_me = 0;
              break;
            }
            
          if(declare_me) {
            nspace_declarations[nspace_declarations_count].declaration=
              raptor_namespace_format_as_xml(element->attributes[i]->nspace,
                                             &nspace_declarations[nspace_declarations_count].length);
            if(!nspace_declarations[nspace_declarations_count].declaration)
              goto error;
            nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;
            nspace_declarations_count++;
          }
        }
      }

      /* Add the attribute + value */
      nspace_declarations[nspace_declarations_count].declaration=
        raptor_qname_format_as_xml(element->attributes[i],
                                   &nspace_declarations[nspace_declarations_count].length);
      if(!nspace_declarations[nspace_declarations_count].declaration)
        goto error;
      nspace_declarations[nspace_declarations_count].nspace = NULL;
      nspace_declarations_count++;

    }
  }

  if(nstack && element->declared_nspaces &&
     raptor_sequence_size(element->declared_nspaces) > 0) {
    for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {
      raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);
      unsigned int j;
      int declare_me = 1;
      
      /* check it wasn't an earlier declaration too */
      for(j = 0; j < nspace_declarations_count; j++)
        if(nspace_declarations[j].nspace == nspace) {
          declare_me = 0;
          break;
        }
      
      if(declare_me) {
        nspace_declarations[nspace_declarations_count].declaration=
          raptor_namespace_format_as_xml(nspace,
                                         &nspace_declarations[nspace_declarations_count].length);
        if(!nspace_declarations[nspace_declarations_count].declaration)
          goto error;
        nspace_declarations[nspace_declarations_count].nspace = nspace;
        nspace_declarations_count++;
      }

    }
  }

  if(nstack && element->xml_language) {
    size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));
#define XML_LANG_PREFIX_LEN 10
    size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;
    unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);
    const char quote = '\""';
    unsigned char* p;

    memcpy(buffer, ""xml:lang=\"""", XML_LANG_PREFIX_LEN);
    p = buffer + XML_LANG_PREFIX_LEN;
    p += raptor_xml_escape_string(xml_writer->world,
                                  element->xml_language, lang_len,
                                  p, buf_length, quote);
    *p++ = quote;
    *p = '\0';

    nspace_declarations[nspace_declarations_count].declaration = buffer;
    nspace_declarations[nspace_declarations_count].length = buf_length;
    nspace_declarations[nspace_declarations_count].nspace = NULL;
    nspace_declarations_count++;
  }
  

  raptor_iostream_write_byte('<', iostr);

  if(element->name->nspace && element->name->nspace->prefix_length > 0) {
    raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix, 
                                         element->name->nspace->prefix_length,
                                         iostr);
    raptor_iostream_write_byte(':', iostr);
  }
  raptor_iostream_counted_string_write((const char*)element->name->local_name,
                                       element->name->local_name_length,
                                       iostr);

  /* declare namespaces and attributes */
  if(nspace_declarations_count) {
    int need_indent = 0;
    
    /* sort them into the canonical order */
    qsort((void*)nspace_declarations, 
          nspace_declarations_count, sizeof(struct nsd),
          raptor_xml_writer_nsd_compare);

    /* declare namespaces first */
    for(i = 0; i < nspace_declarations_count; i++) {
      if(!nspace_declarations[i].nspace)
        continue;

      if(auto_indent && need_indent) {
        /* indent attributes */
        raptor_xml_writer_newline(xml_writer);
        xml_writer->depth++;
        raptor_xml_writer_indent(xml_writer);
        xml_writer->depth--;
      }
      raptor_iostream_write_byte(' ', iostr);
      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
                                           nspace_declarations[i].length,
                                           iostr);
      RAPTOR_FREE(char*, nspace_declarations[i].declaration);
      nspace_declarations[i].declaration = NULL;
      need_indent = 1;
      
      if(raptor_namespace_stack_start_namespace(nstack,
                                                (raptor_namespace*)nspace_declarations[i].nspace,
                                                depth))
        goto error;
    }

    /* declare attributes */
    for(i = 0; i < nspace_declarations_count; i++) {
      if(nspace_declarations[i].nspace)
        continue;

      if(auto_indent && need_indent) {
        /* indent attributes */
        raptor_xml_writer_newline(xml_writer);
        xml_writer->depth++;
        raptor_xml_writer_indent(xml_writer);
        xml_writer->depth--;
      }
      raptor_iostream_write_byte(' ', iostr);
      raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
                                           nspace_declarations[i].length,
                                           iostr);
      need_indent = 1;

      RAPTOR_FREE(char*, nspace_declarations[i].declaration);
      nspace_declarations[i].declaration = NULL;
    }
  }

  if(!auto_empty)
    raptor_iostream_write_byte('>', iostr);

  if(nstack)
    RAPTOR_FREE(stringarray, nspace_declarations);

  return 0;

  /* Clean up nspace_declarations on error */
  error:

  for(i = 0; i < nspace_declarations_count; i++) {
    if(nspace_declarations[i].declaration)
      RAPTOR_FREE(char*, nspace_declarations[i].declaration);
  }

  RAPTOR_FREE(stringarray, nspace_declarations);

  return 1;
}",CWE-787,16
1,"lprn_is_black(gx_device_printer * pdev, int r, int h, int bx)
{
    gx_device_lprn *const lprn = (gx_device_lprn *) pdev;

    int bh = lprn->nBh;
    int bpl = gdev_mem_bytes_per_scan_line(pdev);
    int x, y, y0;
    byte *p;
    int maxY = lprn->BlockLine / lprn->nBh * lprn->nBh;

    y0 = (r + h - bh) % maxY;
    for (y = 0; y < bh; y++) {
        p = &lprn->ImageBuf[(y0 + y) * bpl + bx * lprn->nBw];
        for (x = 0; x < lprn->nBw; x++)
            if (p[x] != 0)
                return 1;
    }
    return 0;
}",CWE-787,16
0,"  virtual bool cellular_connected() const {
    return cellular_ ? cellular_->connected() : false;
  }
",none,24
0,"QuotaManagerProxy::QuotaManagerProxy(
    QuotaManager* manager, base::MessageLoopProxy* io_thread)
    : manager_(manager), io_thread_(io_thread) {
}
",none,24
0,"static NetworkTechnology ParseNetworkTechnology(
    const std::string& technology) {
    if (technology == kNetworkTechnology1Xrtt)
    return NETWORK_TECHNOLOGY_1XRTT;
  if (technology == kNetworkTechnologyEvdo)
    return NETWORK_TECHNOLOGY_EVDO;
  if (technology == kNetworkTechnologyGprs)
    return NETWORK_TECHNOLOGY_GPRS;
  if (technology == kNetworkTechnologyEdge)
    return NETWORK_TECHNOLOGY_EDGE;
  if (technology == kNetworkTechnologyUmts)
    return NETWORK_TECHNOLOGY_UMTS;
  if (technology == kNetworkTechnologyHspa)
    return NETWORK_TECHNOLOGY_HSPA;
  if (technology == kNetworkTechnologyHspaPlus)
    return NETWORK_TECHNOLOGY_HSPA_PLUS;
  if (technology == kNetworkTechnologyLte)
    return NETWORK_TECHNOLOGY_LTE;
  if (technology == kNetworkTechnologyLteAdvanced)
    return NETWORK_TECHNOLOGY_LTE_ADVANCED;
  return NETWORK_TECHNOLOGY_UNKNOWN;
}
",none,24
0,"  virtual bool ethernet_connected() const { return true; }
",none,24
1,"disable_priv_mode ()
{
  int e;

  if (setuid (current_user.uid) < 0)
    {
      e = errno;
      sys_error (_(""cannot set uid to %d: effective uid %d""), current_user.uid, current_user.euid);
#if defined (EXIT_ON_SETUID_FAILURE)
      if (e == EAGAIN)
	exit (e);
#endif
    }
  if (setgid (current_user.gid) < 0)
    sys_error (_(""cannot set gid to %d: effective gid %d""), current_user.gid, current_user.egid);

  current_user.euid = current_user.uid;
  current_user.egid = current_user.gid;
}",CWE-787,16
0,"  ~NetworkLibraryImpl() {
    network_manager_observers_.Clear();
    if (network_manager_monitor_)
      DisconnectPropertyChangeMonitor(network_manager_monitor_);
    data_plan_observers_.Clear();
    if (data_plan_monitor_)
      DisconnectDataPlanUpdateMonitor(data_plan_monitor_);
    STLDeleteValues(&network_observers_);
    ClearNetworks();
  }
",none,24
0,"  StorageType type() const { return type_; }
",none,24
0,"  virtual void RefreshCellularDataPlans(const CellularNetwork* network) {}
",none,24
1,"gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
  int lastBorder;
  /* Seek left */
  int leftLimit, rightLimit;
  int i;
  leftLimit = (-1);
  if (border < 0)
    {
      /* Refuse to fill to a non-solid border */
      return;
    }
  for (i = x; (i >= 0); i--)
    {
      if (gdImageGetPixel (im, i, y) == border)
	{
	  break;
	}
      gdImageSetPixel (im, i, y, color);
      leftLimit = i;
    }
  if (leftLimit == (-1))
    {
      return;
    }
  /* Seek right */
  rightLimit = x;
  for (i = (x + 1); (i < im->sx); i++)
    {
      if (gdImageGetPixel (im, i, y) == border)
	{
	  break;
	}
      gdImageSetPixel (im, i, y, color);
      rightLimit = i;
    }
  /* Look at lines above and below and start paints */
  /* Above */
  if (y > 0)
    {
      lastBorder = 1;
      for (i = leftLimit; (i <= rightLimit); i++)
	{
	  int c;
	  c = gdImageGetPixel (im, i, y - 1);
	  if (lastBorder)
	    {
	      if ((c != border) && (c != color))
		{
		  gdImageFillToBorder (im, i, y - 1,
				       border, color);
		  lastBorder = 0;
		}
	    }
	  else if ((c == border) || (c == color))
	    {
	      lastBorder = 1;
	    }
	}
    }
  /* Below */
  if (y < ((im->sy) - 1))
    {
      lastBorder = 1;
      for (i = leftLimit; (i <= rightLimit); i++)
	{
	  int c;
	  c = gdImageGetPixel (im, i, y + 1);
	  if (lastBorder)
	    {
	      if ((c != border) && (c != color))
		{
		  gdImageFillToBorder (im, i, y + 1,
				       border, color);
		  lastBorder = 0;
		}
	    }
	  else if ((c == border) || (c == color))
	    {
	      lastBorder = 1;
	    }
	}
    }
}",CWE-119,0
0,"void QuotaManager::DumpOriginInfoTable(
    DumpOriginInfoTableCallback* callback) {
  make_scoped_refptr(new DumpOriginInfoTableTask(this, callback))->Start();
}
",none,24
1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
	struct inode **i)
{
	squashfs_dir_header_2 dirh;
	char buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]
		__attribute__((aligned));
	squashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;
	long long start;
	int bytes;
	int dir_count, size;
	struct dir_ent *new_dir;
	struct dir *dir;

	TRACE(""squashfs_opendir: inode start block %d, offset %d\n"",
		block_start, offset);

	*i = read_inode(block_start, offset);

	dir = malloc(sizeof(struct dir));
	if(dir == NULL)
		EXIT_UNSQUASH(""squashfs_opendir: malloc failed!\n"");

	dir->dir_count = 0;
	dir->cur_entry = 0;
	dir->mode = (*i)->mode;
	dir->uid = (*i)->uid;
	dir->guid = (*i)->gid;
	dir->mtime = (*i)->time;
	dir->xattr = (*i)->xattr;
	dir->dirs = NULL;

	if ((*i)->data == 0)
		/*
		 * if the directory is empty, skip the unnecessary
		 * lookup_entry, this fixes the corner case with
		 * completely empty filesystems where lookup_entry correctly
		 * returning -1 is incorrectly treated as an error
		 */
		return dir;
		
	start = sBlk.s.directory_table_start + (*i)->start;
	bytes = lookup_entry(directory_table_hash, start);
	if(bytes == -1)
		EXIT_UNSQUASH(""squashfs_opendir: directory block %d not ""
			""found!\n"", block_start);

	bytes += (*i)->offset;
	size = (*i)->data + bytes;

	while(bytes < size) {			
		if(swap) {
			squashfs_dir_header_2 sdirh;
			memcpy(&sdirh, directory_table + bytes, sizeof(sdirh));
			SQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);
		} else
			memcpy(&dirh, directory_table + bytes, sizeof(dirh));
	
		dir_count = dirh.count + 1;
		TRACE(""squashfs_opendir: Read directory header @ byte position ""
			""%d, %d directory entries\n"", bytes, dir_count);
		bytes += sizeof(dirh);

		/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
		if(dir_count > SQUASHFS_DIR_COUNT) {
			ERROR(""File system corrupted: too many entries in directory\n"");
			goto corrupted;
		}

		while(dir_count--) {
			if(swap) {
				squashfs_dir_entry_2 sdire;
				memcpy(&sdire, directory_table + bytes,
					sizeof(sdire));
				SQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);
			} else
				memcpy(dire, directory_table + bytes,
					sizeof(*dire));
			bytes += sizeof(*dire);

			/* size should never be SQUASHFS_NAME_LEN or larger */
			if(dire->size >= SQUASHFS_NAME_LEN) {
				ERROR(""File system corrupted: filename too long\n"");
				goto corrupted;
			}

			memcpy(dire->name, directory_table + bytes,
				dire->size + 1);
			dire->name[dire->size + 1] = '\0';
			TRACE(""squashfs_opendir: directory entry %s, inode ""
				""%d:%d, type %d\n"", dire->name,
				dirh.start_block, dire->offset, dire->type);
			if((dir->dir_count % DIR_ENT_SIZE) == 0) {
				new_dir = realloc(dir->dirs, (dir->dir_count +
					DIR_ENT_SIZE) * sizeof(struct dir_ent));
				if(new_dir == NULL)
					EXIT_UNSQUASH(""squashfs_opendir: ""
						""realloc failed!\n"");
				dir->dirs = new_dir;
			}
			strcpy(dir->dirs[dir->dir_count].name, dire->name);
			dir->dirs[dir->dir_count].start_block =
				dirh.start_block;
			dir->dirs[dir->dir_count].offset = dire->offset;
			dir->dirs[dir->dir_count].type = dire->type;
			dir->dir_count ++;
			bytes += dire->size + 1;
		}
	}

	return dir;

corrupted:
	free(dir->dirs);
	free(dir);
	return NULL;
}",CWE-22,5
0,"  const std::string& IPAddress() const { return ip_address_; }
",none,24
1,"RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut64 off, int bits, char * file_name) {
	RCoreSymCacheElement *result = NULL;
	ut8 *b = NULL;
	RCoreSymCacheElementHdr *hdr = r_coresym_cache_element_header_new (buf, off, bits);
	if (!hdr) {
		return NULL;
	}
	if (hdr->version != 1) {
		eprintf (""Unsupported CoreSymbolication cache version (%d)\n"", hdr->version);
		goto beach;
	}
	if (hdr->size == 0 || hdr->size > r_buf_size (buf) - off) {
		eprintf (""Corrupted CoreSymbolication header: size out of bounds (0x%x)\n"", hdr->size);
		goto beach;
	}
	result = R_NEW0 (RCoreSymCacheElement);
	if (!result) {
		goto beach;
	}
	result->hdr = hdr;
	b = malloc (hdr->size);
	if (!b) {
		goto beach;
	}
	if (r_buf_read_at (buf, off, b, hdr->size) != hdr->size) {
		goto beach;
	}
	ut8 *end = b + hdr->size;
	if (file_name) {
		result->file_name = file_name;
	} else if (hdr->file_name_off) {
		result->file_name = str_dup_safe (b, b + (size_t)hdr->file_name_off, end);
	}
	if (hdr->version_off) {
		result->binary_version = str_dup_safe (b, b + (size_t)hdr->version_off, end);
	}
	const size_t word_size = bits / 8;
	const ut64 start_of_sections = (ut64)hdr->n_segments * R_CS_EL_SIZE_SEG + R_CS_EL_OFF_SEGS;
	const ut64 sect_size = (bits == 32) ? R_CS_EL_SIZE_SECT_32 : R_CS_EL_SIZE_SECT_64;
	const ut64 start_of_symbols = start_of_sections + (ut64)hdr->n_sections * sect_size;
	const ut64 start_of_lined_symbols = start_of_symbols + (ut64)hdr->n_symbols * R_CS_EL_SIZE_SYM;
	const ut64 start_of_line_info = start_of_lined_symbols + (ut64)hdr->n_lined_symbols * R_CS_EL_SIZE_LSYM;
	const ut64 start_of_unknown_pairs = start_of_line_info + (ut64)hdr->n_line_info * R_CS_EL_SIZE_LINFO;
	const ut64 start_of_strings = start_of_unknown_pairs + (ut64)hdr->n_symbols * 8;

	ut64 page_zero_size = 0;
	size_t page_zero_idx = 0;
	if (UT32_MUL_OVFCHK (hdr->n_segments, sizeof (RCoreSymCacheElementSegment))) {
		goto beach;
	} else if (UT32_MUL_OVFCHK (hdr->n_sections, sizeof (RCoreSymCacheElementSection))) {
		goto beach;
	} else if (UT32_MUL_OVFCHK (hdr->n_symbols, sizeof (RCoreSymCacheElementSymbol))) {
		goto beach;
	} else if (UT32_MUL_OVFCHK (hdr->n_lined_symbols, sizeof (RCoreSymCacheElementLinedSymbol))) {
		goto beach;
	} else if (UT32_MUL_OVFCHK (hdr->n_line_info, sizeof (RCoreSymCacheElementLineInfo))) {
		goto beach;
	}
	if (hdr->n_segments > 0) {
		result->segments = R_NEWS0 (RCoreSymCacheElementSegment, hdr->n_segments);
		if (!result->segments) {
			goto beach;
		}
		size_t i;
		ut8 *cursor = b + R_CS_EL_OFF_SEGS;
		for (i = 0; i < hdr->n_segments && cursor + sizeof (RCoreSymCacheElementSegment) < end; i++) {
			RCoreSymCacheElementSegment *seg = &result->segments[i];
			seg->paddr = seg->vaddr = r_read_le64 (cursor);
			cursor += 8;
			if (cursor >= end) {
				break;
			}
			seg->size = seg->vsize = r_read_le64 (cursor);
			cursor += 8;
			if (cursor >= end) {
				break;
			}
			seg->name = str_dup_safe_fixed (b, cursor, 16, end);
			cursor += 16;
			if (!seg->name) {
				continue;
			}

			if (!strcmp (seg->name, ""__PAGEZERO"")) {
				page_zero_size = seg->size;
				page_zero_idx = i;
				seg->paddr = seg->vaddr = 0;
				seg->size = 0;
			}
		}
		for (i = 0; i < hdr->n_segments && page_zero_size > 0; i++) {
			if (i == page_zero_idx) {
				continue;
			}
			RCoreSymCacheElementSegment *seg = &result->segments[i];
			if (seg->vaddr < page_zero_size) {
				seg->vaddr += page_zero_size;
			}
		}
	}
	bool relative_to_strings = false;
	ut8* string_origin;
	if (hdr->n_sections > 0) {
		result->sections = R_NEWS0 (RCoreSymCacheElementSection, hdr->n_sections);
		if (!result->sections) {
			goto beach;
		}
		size_t i;
		ut8 *cursor = b + start_of_sections;
		for (i = 0; i < hdr->n_sections && cursor < end; i++) {
			ut8 *sect_start = cursor;
			RCoreSymCacheElementSection *sect = &result->sections[i];
			sect->vaddr = sect->paddr = r_read_ble (cursor, false, bits);
			if (sect->vaddr < page_zero_size) {
				sect->vaddr += page_zero_size;
			}
			cursor += word_size;
			if (cursor >= end) {
				break;
			}
			sect->size = r_read_ble (cursor, false, bits);
			cursor += word_size;
			if (cursor >= end) {
				break;
			}
			ut64 sect_name_off = r_read_ble (cursor, false, bits);
			if (!i && !sect_name_off) {
				relative_to_strings = true;
			}
			cursor += word_size;
			if (bits == 32) {
				cursor += word_size;
			}
			string_origin = relative_to_strings? b + start_of_strings : sect_start;
			sect->name = str_dup_safe (b, string_origin + (size_t)sect_name_off, end);
		}
	}
	if (hdr->n_symbols) {
		result->symbols = R_NEWS0 (RCoreSymCacheElementSymbol, hdr->n_symbols);
		if (!result->symbols) {
			goto beach;
		}
		size_t i;
		ut8 *cursor = b + start_of_symbols;
		for (i = 0; i < hdr->n_symbols && cursor + R_CS_EL_SIZE_SYM <= end; i++) {
			RCoreSymCacheElementSymbol *sym = &result->symbols[i];
			sym->paddr = r_read_le32 (cursor);
			sym->size = r_read_le32 (cursor + 0x4);
			sym->unk1 = r_read_le32 (cursor + 0x8);
			size_t name_off = r_read_le32 (cursor + 0xc);
			size_t mangled_name_off = r_read_le32 (cursor + 0x10);
			sym->unk2 = (st32)r_read_le32 (cursor + 0x14);
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			sym->name = str_dup_safe (b, string_origin + name_off, end);
			if (!sym->name) {
				cursor += R_CS_EL_SIZE_SYM;
				continue;
			}
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			sym->mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);
			if (!sym->mangled_name) {
				cursor += R_CS_EL_SIZE_SYM;
				continue;
			}
			cursor += R_CS_EL_SIZE_SYM;
		}
	}
	if (hdr->n_lined_symbols) {
		result->lined_symbols = R_NEWS0 (RCoreSymCacheElementLinedSymbol, hdr->n_lined_symbols);
		if (!result->lined_symbols) {
			goto beach;
		}
		size_t i;
		ut8 *cursor = b + start_of_lined_symbols;
		for (i = 0; i < hdr->n_lined_symbols && cursor + R_CS_EL_SIZE_LSYM <= end; i++) {
			RCoreSymCacheElementLinedSymbol *lsym = &result->lined_symbols[i];
			lsym->sym.paddr = r_read_le32 (cursor);
			lsym->sym.size = r_read_le32 (cursor + 0x4);
			lsym->sym.unk1 = r_read_le32 (cursor + 0x8);
			size_t name_off = r_read_le32 (cursor + 0xc);
			size_t mangled_name_off = r_read_le32 (cursor + 0x10);
			lsym->sym.unk2 = (st32)r_read_le32 (cursor + 0x14);
			size_t file_name_off = r_read_le32 (cursor + 0x18);
			lsym->flc.line = r_read_le32 (cursor + 0x1c);
			lsym->flc.col = r_read_le32 (cursor + 0x20);
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			lsym->sym.name = str_dup_safe (b, string_origin + name_off, end);
			if (!lsym->sym.name) {
				cursor += R_CS_EL_SIZE_LSYM;
				continue;
			}
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			lsym->sym.mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);
			if (!lsym->sym.mangled_name) {
				cursor += R_CS_EL_SIZE_LSYM;
				continue;
			}
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			lsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end);
			if (!lsym->flc.file) {
				cursor += R_CS_EL_SIZE_LSYM;
				continue;
			}
			cursor += R_CS_EL_SIZE_LSYM;
			meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, lsym->sym.paddr), lsym->sym.size, &lsym->flc);
		}
	}
	if (hdr->n_line_info) {
		result->line_info = R_NEWS0 (RCoreSymCacheElementLineInfo, hdr->n_line_info);
		if (!result->line_info) {
			goto beach;
		}
		size_t i;
		ut8 *cursor = b + start_of_line_info;
		for (i = 0; i < hdr->n_line_info && cursor + R_CS_EL_SIZE_LINFO <= end; i++) {
			RCoreSymCacheElementLineInfo *info = &result->line_info[i];
			info->paddr = r_read_le32 (cursor);
			info->size = r_read_le32 (cursor + 4);
			size_t file_name_off = r_read_le32 (cursor + 8);
			info->flc.line = r_read_le32 (cursor + 0xc);
			info->flc.col = r_read_le32 (cursor + 0x10);
			string_origin = relative_to_strings? b + start_of_strings : cursor;
			info->flc.file = str_dup_safe (b, string_origin + file_name_off, end);
			if (!info->flc.file) {
				break;
			}
			cursor += R_CS_EL_SIZE_LINFO;
			meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, info->paddr), info->size, &info->flc);
		}
	}

	/*
	 * TODO:
	 * Figure out the meaning of the 2 arrays of hdr->n_symbols
	 * 32-bit integers located at the end of line info.
	 * Those are the last info before the strings at the end.
	 */

beach:
	free (b);
	return result;
}",CWE-787,16
0,"void QuotaManager::DumpQuotaTable(DumpQuotaTableCallback* callback) {
  make_scoped_refptr(new DumpQuotaTableTask(this, callback))->Start();
}
",none,24
0,"WirelessNetwork::WirelessNetwork(const WirelessNetwork& network)
    : Network(network) {
  name_ = network.name();
  strength_ = network.strength();
  auto_connect_ = network.auto_connect();
  favorite_ = network.favorite();
}
",none,24
0,"  DumpQuotaTableTask(
      QuotaManager* manager,
      Callback* callback)
      : DatabaseTaskBase(manager),
        callback_(callback) {
  }
",none,24
1,"gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
{
  GstCaps *caps;
  guint avail;
  GstFlowReturn res = GST_FLOW_OK;

  GstFlxDec *flxdec;
  FlxHeader *flxh;

  g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
  flxdec = (GstFlxDec *) parent;
  g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR);

  gst_adapter_push (flxdec->adapter, buf);
  avail = gst_adapter_available (flxdec->adapter);

  if (flxdec->state == GST_FLXDEC_READ_HEADER) {
    if (avail >= FlxHeaderSize) {
      const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize);
      GstCaps *templ;

      memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize);
      FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr));
      gst_adapter_unmap (flxdec->adapter);
      gst_adapter_flush (flxdec->adapter, FlxHeaderSize);

      flxh = &flxdec->hdr;

      /* check header */
      if (flxh->type != FLX_MAGICHDR_FLI &&
          flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX)
        goto wrong_type;

      GST_LOG (""size      :  %d"", flxh->size);
      GST_LOG (""frames    :  %d"", flxh->frames);
      GST_LOG (""width     :  %d"", flxh->width);
      GST_LOG (""height    :  %d"", flxh->height);
      GST_LOG (""depth     :  %d"", flxh->depth);
      GST_LOG (""speed     :  %d"", flxh->speed);

      flxdec->next_time = 0;

      if (flxh->type == FLX_MAGICHDR_FLI) {
        flxdec->frame_time = JIFFIE * flxh->speed;
      } else if (flxh->speed == 0) {
        flxdec->frame_time = GST_SECOND / 70;
      } else {
        flxdec->frame_time = flxh->speed * GST_MSECOND;
      }

      flxdec->duration = flxh->frames * flxdec->frame_time;
      GST_LOG (""duration   :  %"" GST_TIME_FORMAT,
          GST_TIME_ARGS (flxdec->duration));

      templ = gst_pad_get_pad_template_caps (flxdec->srcpad);
      caps = gst_caps_copy (templ);
      gst_caps_unref (templ);
      gst_caps_set_simple (caps,
          ""width"", G_TYPE_INT, flxh->width,
          ""height"", G_TYPE_INT, flxh->height,
          ""framerate"", GST_TYPE_FRACTION, (gint) GST_MSECOND,
          (gint) flxdec->frame_time / 1000, NULL);

      gst_pad_set_caps (flxdec->srcpad, caps);
      gst_caps_unref (caps);

      if (flxh->depth <= 8)
        flxdec->converter =
            flx_colorspace_converter_new (flxh->width, flxh->height);

      if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) {
        GST_LOG (""(FLC) aspect_dx :  %d"", flxh->aspect_dx);
        GST_LOG (""(FLC) aspect_dy :  %d"", flxh->aspect_dy);
        GST_LOG (""(FLC) oframe1   :  0x%08x"", flxh->oframe1);
        GST_LOG (""(FLC) oframe2   :  0x%08x"", flxh->oframe2);
      }

      flxdec->size = ((guint) flxh->width * (guint) flxh->height);

      /* create delta and output frame */
      flxdec->frame_data = g_malloc (flxdec->size);
      flxdec->delta_data = g_malloc (flxdec->size);

      flxdec->state = GST_FLXDEC_PLAYING;
    }
  } else if (flxdec->state == GST_FLXDEC_PLAYING) {
    GstBuffer *out;

    /* while we have enough data in the adapter */
    while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) {
      FlxFrameChunk flxfh;
      guchar *chunk;
      const guint8 *data;
      GstMapInfo map;

      chunk = NULL;
      data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize);
      memcpy (&flxfh, data, FlxFrameChunkSize);
      FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh);
      gst_adapter_unmap (flxdec->adapter);

      switch (flxfh.id) {
        case FLX_FRAME_TYPE:
          /* check if we have the complete frame */
          if (avail < flxfh.size)
            goto need_more_data;

          /* flush header */
          gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize);

          chunk = gst_adapter_take (flxdec->adapter,
              flxfh.size - FlxFrameChunkSize);
          FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk);
          if (((FlxFrameType *) chunk)->chunks == 0)
            break;

          /* create 32 bits output frame */
//          res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad,
//              GST_BUFFER_OFFSET_NONE,
//              flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out);
//          if (res != GST_FLOW_OK)
//            break;

          out = gst_buffer_new_and_alloc (flxdec->size * 4);

          /* decode chunks */
          if (!flx_decode_chunks (flxdec,
                  ((FlxFrameType *) chunk)->chunks,
                  chunk + FlxFrameTypeSize, flxdec->frame_data)) {
            GST_ELEMENT_ERROR (flxdec, STREAM, DECODE,
                (""%s"", ""Could not decode chunk""), NULL);
            return GST_FLOW_ERROR;
          }

          /* save copy of the current frame for possible delta. */
          memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size);

          gst_buffer_map (out, &map, GST_MAP_WRITE);
          /* convert current frame. */
          flx_colorspace_convert (flxdec->converter, flxdec->frame_data,
              map.data);
          gst_buffer_unmap (out, &map);

          GST_BUFFER_TIMESTAMP (out) = flxdec->next_time;
          flxdec->next_time += flxdec->frame_time;

          res = gst_pad_push (flxdec->srcpad, out);
          break;
        default:
          /* check if we have the complete frame */
          if (avail < flxfh.size)
            goto need_more_data;

          gst_adapter_flush (flxdec->adapter, flxfh.size);
          break;
      }

      g_free (chunk);

      avail = gst_adapter_available (flxdec->adapter);
    }
  }
need_more_data:
  return res;

  /* ERRORS */
wrong_type:
  {
    GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL),
        (""not a flx file (type %x)"", flxh->type));
    gst_object_unref (flxdec);
    return GST_FLOW_ERROR;
  }
}",CWE-125,1
1,"ins_compl_stop(int c, int prev_mode, int retval)
{
    char_u	*ptr;
    int		want_cindent;

    // Get here when we have finished typing a sequence of ^N and
    // ^P or other completion characters in CTRL-X mode.  Free up
    // memory that was used, and make sure we can redo the insert.
    if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
    {
	// If any of the original typed text has been changed, eg when
	// ignorecase is set, we must add back-spaces to the redo
	// buffer.  We add as few as necessary to delete just the part
	// of the original text that has changed.
	// When using the longest match, edited the match or used
	// CTRL-E then don't use the current match.
	if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
	    ptr = compl_curr_match->cp_str;
	else
	    ptr = NULL;
	ins_compl_fixRedoBufForLeader(ptr);
    }

    want_cindent = (get_can_cindent() && cindent_on());

    // When completing whole lines: fix indent for 'cindent'.
    // Otherwise, break line if it's too long.
    if (compl_cont_mode == CTRL_X_WHOLE_LINE)
    {
	// re-indent the current line
	if (want_cindent)
	{
	    do_c_expr_indent();
	    want_cindent = FALSE;	// don't do it again
	}
    }
    else
    {
	int prev_col = curwin->w_cursor.col;

	// put the cursor on the last char, for 'tw' formatting
	if (prev_col > 0)
	    dec_cursor();
	// only format when something was inserted
	if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
	    insertchar(NUL, 0, -1);
	if (prev_col > 0
		&& ml_get_curline()[curwin->w_cursor.col] != NUL)
	    inc_cursor();
    }

    // If the popup menu is displayed pressing CTRL-Y means accepting
    // the selection without inserting anything.  When
    // compl_enter_selects is set the Enter key does the same.
    if ((c == Ctrl_Y || (compl_enter_selects
		    && (c == CAR || c == K_KENTER || c == NL)))
	    && pum_visible())
	retval = TRUE;

    // CTRL-E means completion is Ended, go back to the typed text.
    // but only do this, if the Popup is still visible
    if (c == Ctrl_E)
    {
	ins_compl_delete();
	if (compl_leader != NULL)
	    ins_bytes(compl_leader + get_compl_len());
	else if (compl_first_match != NULL)
	    ins_bytes(compl_orig_text + get_compl_len());
	retval = TRUE;
    }

    auto_format(FALSE, TRUE);

    // Trigger the CompleteDonePre event to give scripts a chance to
    // act upon the completion before clearing the info, and restore
    // ctrl_x_mode, so that complete_info() can be used.
    ctrl_x_mode = prev_mode;
    ins_apply_autocmds(EVENT_COMPLETEDONEPRE);

    ins_compl_free();
    compl_started = FALSE;
    compl_matches = 0;
    if (!shortmess(SHM_COMPLETIONMENU))
	msg_clr_cmdline();	// necessary for ""noshowmode""
    ctrl_x_mode = CTRL_X_NORMAL;
    compl_enter_selects = FALSE;
    if (edit_submode != NULL)
    {
	edit_submode = NULL;
	showmode();
    }

#ifdef FEAT_CMDWIN
    if (c == Ctrl_C && cmdwin_type != 0)
	// Avoid the popup menu remains displayed when leaving the
	// command line window.
	update_screen(0);
#endif
    // Indent now if a key was typed that is in 'cinkeys'.
    if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
	do_c_expr_indent();
    // Trigger the CompleteDone event to give scripts a chance to act
    // upon the end of completion.
    ins_apply_autocmds(EVENT_COMPLETEDONE);

    return retval;
}",CWE-125,1
0,"  virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {
    DCHECK(network);
    if (!EnsureCrosLoaded() || !network)
      return;
    if (DisconnectFromNetwork(network->service_path().c_str())) {
      if (network->type() == TYPE_WIFI) {
        WifiNetwork* wifi = GetWirelessNetworkByPath(
            wifi_networks_, network->service_path());
        if (wifi) {
          wifi->set_connected(false);
          wifi_ = NULL;
        }
      } else if (network->type() == TYPE_CELLULAR) {
        CellularNetwork* cellular = GetWirelessNetworkByPath(
            cellular_networks_, network->service_path());
        if (cellular) {
          cellular->set_connected(false);
          cellular_ = NULL;
        }
      }
      NotifyNetworkManagerChanged();
    }
  }
",none,24
1,"static int do_i2c_md(struct cmd_tbl *cmdtp, int flag, int argc,
		     char *const argv[])
{
	uint	chip;
	uint	addr, length;
	int alen;
	int	j, nbytes, linebytes;
	int ret;
#if CONFIG_IS_ENABLED(DM_I2C)
	struct udevice *dev;
#endif

	/* We use the last specified parameters, unless new ones are
	 * entered.
	 */
	chip   = i2c_dp_last_chip;
	addr   = i2c_dp_last_addr;
	alen   = i2c_dp_last_alen;
	length = i2c_dp_last_length;

	if (argc < 3)
		return CMD_RET_USAGE;

	if ((flag & CMD_FLAG_REPEAT) == 0) {
		/*
		 * New command specified.
		 */

		/*
		 * I2C chip address
		 */
		chip = hextoul(argv[1], NULL);

		/*
		 * I2C data address within the chip.  This can be 1 or
		 * 2 bytes long.  Some day it might be 3 bytes long :-).
		 */
		addr = hextoul(argv[2], NULL);
		alen = get_alen(argv[2], DEFAULT_ADDR_LEN);
		if (alen > 3)
			return CMD_RET_USAGE;

		/*
		 * If another parameter, it is the length to display.
		 * Length is the number of objects, not number of bytes.
		 */
		if (argc > 3)
			length = hextoul(argv[3], NULL);
	}

#if CONFIG_IS_ENABLED(DM_I2C)
	ret = i2c_get_cur_bus_chip(chip, &dev);
	if (!ret && alen != -1)
		ret = i2c_set_chip_offset_len(dev, alen);
	if (ret)
		return i2c_report_err(ret, I2C_ERR_READ);
#endif

	/*
	 * Print the lines.
	 *
	 * We buffer all read data, so we can make sure data is read only
	 * once.
	 */
	nbytes = length;
	do {
		unsigned char	linebuf[DISP_LINE_LEN];
		unsigned char	*cp;

		linebytes = (nbytes > DISP_LINE_LEN) ? DISP_LINE_LEN : nbytes;

#if CONFIG_IS_ENABLED(DM_I2C)
		ret = dm_i2c_read(dev, addr, linebuf, linebytes);
#else
		ret = i2c_read(chip, addr, alen, linebuf, linebytes);
#endif
		if (ret)
			return i2c_report_err(ret, I2C_ERR_READ);
		else {
			printf(""%04x:"", addr);
			cp = linebuf;
			for (j=0; j 0x7e))
					puts (""."");
				else
					printf(""%c"", *cp);
				cp++;
			}
			putc ('\n');
		}
		nbytes -= linebytes;
	} while (nbytes > 0);

	i2c_dp_last_chip   = chip;
	i2c_dp_last_addr   = addr;
	i2c_dp_last_alen   = alen;
	i2c_dp_last_length = length;

	return 0;
}",CWE-787,16
1,"String string_number_format(double d, int dec,
                            const String& dec_point,
                            const String& thousand_sep) {
  char *tmpbuf = nullptr, *resbuf;
  char *s, *t;  /* source, target */
  char *dp;
  int integral;
  int tmplen, reslen=0;
  int count=0;
  int is_negative=0;

  if (d < 0) {
    is_negative = 1;
    d = -d;
  }

  if (dec < 0) dec = 0;
  d = php_math_round(d, dec);

  // departure from PHP: we got rid of dependencies on spprintf() here.
  String tmpstr(63, ReserveString);
  tmpbuf = tmpstr.mutableData();
  tmplen = snprintf(tmpbuf, 64, ""%.*F"", dec, d);
  if (tmplen < 0) return empty_string();
  if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {
    tmpstr.setSize(tmplen);
    return tmpstr;
  }
  if (tmplen >= 64) {
    // Uncommon, asked for more than 64 chars worth of precision
    tmpstr = String(tmplen, ReserveString);
    tmpbuf = tmpstr.mutableData();
    tmplen = snprintf(tmpbuf, tmplen + 1, ""%.*F"", dec, d);
    if (tmplen < 0) return empty_string();
    if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {
      tmpstr.setSize(tmplen);
      return tmpstr;
    }
  }

  /* find decimal point, if expected */
  if (dec) {
    dp = strpbrk(tmpbuf, "".,"");
  } else {
    dp = nullptr;
  }

  /* calculate the length of the return buffer */
  if (dp) {
    integral = dp - tmpbuf;
  } else {
    /* no decimal point was found */
    integral = tmplen;
  }

  /* allow for thousand separators */
  if (!thousand_sep.empty()) {
    if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) {
      /* overflow */
      raise_error(""String overflow"");
    }

    integral += ((integral-1) / 3) * thousand_sep.size();
  }

  reslen = integral;

  if (dec) {
    reslen += dec;

    if (!dec_point.empty()) {
      if (reslen + dec_point.size() < dec_point.size()) {
        /* overflow */
        raise_error(""String overflow"");
      }
      reslen += dec_point.size();
    }
  }

  /* add a byte for minus sign */
  if (is_negative) {
    reslen++;
  }
  String resstr(reslen, ReserveString);
  resbuf = resstr.mutableData();

  s = tmpbuf+tmplen-1;
  t = resbuf+reslen-1;

  /* copy the decimal places.
   * Take care, as the sprintf implementation may return less places than
   * we requested due to internal buffer limitations */
  if (dec) {
    int declen = dp ? s - dp : 0;
    int topad = dec > declen ? dec - declen : 0;

    /* pad with '0's */
    while (topad--) {
      *t-- = '0';
    }

    if (dp) {
      s -= declen + 1; /* +1 to skip the point */
      t -= declen;

      /* now copy the chars after the point */
      memcpy(t + 1, dp + 1, declen);
    }

    /* add decimal point */
    if (!dec_point.empty()) {
      memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size());
      t -= dec_point.size();
    }
  }

  /* copy the numbers before the decimal point, adding thousand
   * separator every three digits */
  while(s >= tmpbuf) {
    *t-- = *s--;
    if (thousand_sep && (++count%3)==0 && s>=tmpbuf) {
      memcpy(t + (1 - thousand_sep.size()),
             thousand_sep.data(),
             thousand_sep.size());
      t -= thousand_sep.size();
    }
  }

  /* and a minus sign, if needed */
  if (is_negative) {
    *t-- = '-';
  }

  resstr.setSize(reslen);
  return resstr;
}",CWE-119,0
1,"static GF_Err BM_ParseGlobalQuantizer(GF_BifsDecoder *codec, GF_BitStream *bs, GF_List *com_list)
{
	GF_Node *node;
	GF_Command *com;
	GF_CommandField *inf;
	node = gf_bifs_dec_node(codec, bs, NDT_SFWorldNode);
	if (!node) return GF_NON_COMPLIANT_BITSTREAM;

	/*reset global QP*/
	if (codec->scenegraph->global_qp) {
		gf_node_unregister(codec->scenegraph->global_qp, NULL);
	}
	codec->ActiveQP = NULL;
	codec->scenegraph->global_qp = NULL;

	if (gf_node_get_tag(node) != TAG_MPEG4_QuantizationParameter) {
		gf_node_unregister(node, NULL);
		return GF_NON_COMPLIANT_BITSTREAM;
	}

	/*register global QP*/
	codec->ActiveQP = (M_QuantizationParameter *) node;
	codec->ActiveQP->isLocal = 0;
	codec->scenegraph->global_qp = node;

	/*register TWICE: once for the command, and for the scenegraph globalQP*/
	node->sgprivate->num_instances = 2;

	com = gf_sg_command_new(codec->current_graph, GF_SG_GLOBAL_QUANTIZER);
	inf = gf_sg_command_field_new(com);
	inf->new_node = node;
	inf->field_ptr = &inf->new_node;
	inf->fieldType = GF_SG_VRML_SFNODE;
	gf_list_add(com_list, com);
	return GF_OK;
}",CWE-416,10
1,"bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{

  if (!((options & SELECT_DISTINCT) && !group_list.elements))
    hidden_bit_fields= 0;

  // find_order_in_list() may need some extra space, so multiply by two.
  order_group_num*= 2;

  /*
    We have to create array in prepared statement memory if it is a
    prepared statement
  */
  Query_arena *arena= thd->stmt_arena;
  const uint n_elems= (n_sum_items +
                       n_child_sum_items +
                       item_list.elements +
                       select_n_reserved +
                       select_n_having_items +
                       select_n_where_fields +
                       order_group_num +
                       hidden_bit_fields +
                       fields_in_window_functions) * 5;
  if (!ref_pointer_array.is_null())
  {
    /*
      We need to take 'n_sum_items' into account when allocating the array,
      and this may actually increase during the optimization phase due to
      MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
      In the usual case we can reuse the array from the prepare phase.
      If we need a bigger array, we must allocate a new one.
     */
    if (ref_pointer_array.size() >= n_elems)
      return false;
   }
  Item **array= static_cast(arena->alloc(sizeof(Item*) * n_elems));
  if (array != NULL)
    ref_pointer_array= Ref_ptr_array(array, n_elems);

  return array == NULL;
}",CWE-190,2
1,"njs_function_frame_save(njs_vm_t *vm, njs_frame_t *frame, u_char *pc)
{
    size_t              value_count, n;
    njs_value_t         *start, *end, *p, **new, *value, **local;
    njs_function_t      *function;
    njs_native_frame_t  *active, *native;

    *frame = *vm->active_frame;
    frame->previous_active_frame = NULL;

    native = &frame->native;

    active = &vm->active_frame->native;
    value_count = njs_function_frame_value_count(active);

    function = active->function;

    new = (njs_value_t **) ((u_char *) native + NJS_FRAME_SIZE);
    value = (njs_value_t *) (new + value_count
                             + function->u.lambda->temp);


    native->arguments = value;
    native->arguments_offset = value + (function->args_offset - 1);
    native->local = new + njs_function_frame_args_count(active);
    native->temp = new + value_count;
    native->pc = pc;

    start = njs_function_frame_values(active, &end);
    p = native->arguments;

    while (start < end) {
        *p = *start++;
        *new++ = p++;
    }

    /* Move all arguments. */

    p = native->arguments;
    local = native->local + function->args_offset;

    for (n = 0; n < function->args_count; n++) {
        if (!njs_is_valid(p)) {
            njs_set_undefined(p);
        }

        *local++ = p++;
    }

    return NJS_OK;
}",CWE-416,10
0,"  UsageAndQuotaDispatcherTaskForTemporary(
      QuotaManager* manager, const std::string& host)
      : UsageAndQuotaDispatcherTask(manager, host, kStorageTypeTemporary) {}
",none,24
0,"static std::string ToHtmlTableRow(Network* network) {
  std::string str;
  if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
    WirelessNetwork* wireless = static_cast(network);
    str += WrapWithTD(wireless->name()) +
        WrapWithTD(base::IntToString(wireless->auto_connect())) +
        WrapWithTD(base::IntToString(wireless->strength()));
    if (network->type() == TYPE_WIFI) {
      WifiNetwork* wifi = static_cast(network);
      str += WrapWithTD(wifi->GetEncryptionString()) +
          WrapWithTD(std::string(wifi->passphrase().length(), '*')) +
          WrapWithTD(wifi->identity()) + WrapWithTD(wifi->cert_path());
    }
  }
  str += WrapWithTD(network->GetStateString()) +
      WrapWithTD(network->failed() ? network->GetErrorString() : """") +
      WrapWithTD(network->ip_address());
  return str;
}
",none,24
1,"    QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength,
                                       const UBaseType_t uxItemSize,
                                       const uint8_t ucQueueType )
    {
        Queue_t * pxNewQueue;
        size_t xQueueSizeInBytes;
        uint8_t * pucQueueStorage;

        configASSERT( uxQueueLength > ( UBaseType_t ) 0 );

        /* Allocate enough space to hold the maximum number of items that
         * can be in the queue at any time.  It is valid for uxItemSize to be
         * zero in the case the queue is used as a semaphore. */
        xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */

        /* Check for multiplication overflow. */
        configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) );

        /* Allocate the queue and storage area.  Justification for MISRA
         * deviation as follows:  pvPortMalloc() always ensures returned memory
         * blocks are aligned per the requirements of the MCU stack.  In this case
         * pvPortMalloc() must return a pointer that is guaranteed to meet the
         * alignment requirements of the Queue_t structure - which in this case
         * is an int8_t *.  Therefore, whenever the stack alignment requirements
         * are greater than or equal to the pointer to char requirements the cast
         * is safe.  In other cases alignment requirements are not strict (one or
         * two bytes). */
        pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */

        if( pxNewQueue != NULL )
        {
            /* Jump past the queue structure to find the location of the queue
             * storage area. */
            pucQueueStorage = ( uint8_t * ) pxNewQueue;
            pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */

            #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
                {
                    /* Queues can be created either statically or dynamically, so
                     * note this task was created dynamically in case it is later
                     * deleted. */
                    pxNewQueue->ucStaticallyAllocated = pdFALSE;
                }
            #endif /* configSUPPORT_STATIC_ALLOCATION */

            prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );
        }
        else
        {
            traceQUEUE_CREATE_FAILED( ucQueueType );
            mtCOVERAGE_TEST_MARKER();
        }

        return pxNewQueue;
    }
",CWE-200,4
1,"bgp_capability_msg_parse (struct peer *peer, u_char *pnt, bgp_size_t length)
{
  u_char *end;
  struct capability cap;
  u_char action;
  struct bgp *bgp;
  afi_t afi;
  safi_t safi;

  bgp = peer->bgp;
  end = pnt + length;

  while (pnt < end)
    {
      /* We need at least action, capability code and capability length. */
      if (pnt + 3 > end)
        {
          zlog_info (""%s Capability length error"", peer->host);
          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
          return -1;
        }

      action = *pnt;

      /* Fetch structure to the byte stream. */
      memcpy (&cap, pnt + 1, sizeof (struct capability));

      /* Action value check.  */
      if (action != CAPABILITY_ACTION_SET
	  && action != CAPABILITY_ACTION_UNSET)
        {
          zlog_info (""%s Capability Action Value error %d"",
		     peer->host, action);
          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
          return -1;
        }

      if (BGP_DEBUG (normal, NORMAL))
	zlog_debug (""%s CAPABILITY has action: %d, code: %u, length %u"",
		   peer->host, action, cap.code, cap.length);

      /* Capability length check. */
      if (pnt + (cap.length + 3) > end)
        {
          zlog_info (""%s Capability length error"", peer->host);
          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
          return -1;
        }

      /* We know MP Capability Code. */
      if (cap.code == CAPABILITY_CODE_MP)
        {
	  afi = ntohs (cap.mpc.afi);
	  safi = cap.mpc.safi;

          /* Ignore capability when override-capability is set. */
          if (CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))
	    continue;

	  /* Address family check.  */
	  if ((afi == AFI_IP 
	       || afi == AFI_IP6)
	      && (safi == SAFI_UNICAST 
		  || safi == SAFI_MULTICAST 
		  || safi == BGP_SAFI_VPNV4))
	    {
	      if (BGP_DEBUG (normal, NORMAL))
		zlog_debug (""%s CAPABILITY has %s MP_EXT CAP for afi/safi: %u/%u"",
			   peer->host,
			   action == CAPABILITY_ACTION_SET 
			   ? ""Advertising"" : ""Removing"",
			   ntohs(cap.mpc.afi) , cap.mpc.safi);
		  
	      /* Adjust safi code. */
	      if (safi == BGP_SAFI_VPNV4)
		safi = SAFI_MPLS_VPN;
	      
	      if (action == CAPABILITY_ACTION_SET)
		{
		  peer->afc_recv[afi][safi] = 1;
		  if (peer->afc[afi][safi])
		    {
		      peer->afc_nego[afi][safi] = 1;
		      bgp_announce_route (peer, afi, safi);
		    }
		}
	      else
		{
		  peer->afc_recv[afi][safi] = 0;
		  peer->afc_nego[afi][safi] = 0;

		  if (peer_active_nego (peer))
		    bgp_clear_route (peer, afi, safi);
		  else
		    BGP_EVENT_ADD (peer, BGP_Stop);
		} 
	    }
        }
      else
        {
          zlog_warn (""%s unrecognized capability code: %d - ignored"",
                     peer->host, cap.code);
        }
      pnt += cap.length + 3;
    }
  return 0;
}",CWE-125,1
1,"PHP_MINIT_FUNCTION(snmp)
{
	netsnmp_log_handler *logh;
	zend_class_entry ce, cex;

	le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);

	init_snmp(""snmpapp"");

#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE
	/* Prevent update of the snmpapp.conf file */
	netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);
#endif

	/* Disable logging, use exit status'es and related variabled to detect errors */
	shutdown_snmp_logging();
	logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);
	if (logh) {
		logh->pri_max = LOG_ERR;
	}

	memcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
	php_snmp_object_handlers.read_property = php_snmp_read_property;
	php_snmp_object_handlers.write_property = php_snmp_write_property;
	php_snmp_object_handlers.has_property = php_snmp_has_property;
	php_snmp_object_handlers.get_properties = php_snmp_get_properties;

	/* Register SNMP Class */
	INIT_CLASS_ENTRY(ce, ""SNMP"", php_snmp_class_methods);
	ce.create_object = php_snmp_object_new;
	php_snmp_object_handlers.clone_obj = NULL;
	php_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);

	/* Register SNMP Class properties */
	zend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);
	PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);

	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_SUFFIX"",	NETSNMP_OID_OUTPUT_SUFFIX,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_MODULE"",	NETSNMP_OID_OUTPUT_MODULE,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_FULL"",		NETSNMP_OID_OUTPUT_FULL,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_NUMERIC"",	NETSNMP_OID_OUTPUT_NUMERIC,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_UCD"",		NETSNMP_OID_OUTPUT_UCD,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OID_OUTPUT_NONE"",		NETSNMP_OID_OUTPUT_NONE,	CONST_CS | CONST_PERSISTENT);

	REGISTER_LONG_CONSTANT(""SNMP_VALUE_LIBRARY"",	SNMP_VALUE_LIBRARY,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_VALUE_PLAIN"",	SNMP_VALUE_PLAIN,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_VALUE_OBJECT"",	SNMP_VALUE_OBJECT,	CONST_CS | CONST_PERSISTENT);

	REGISTER_LONG_CONSTANT(""SNMP_BIT_STR"",		ASN_BIT_STR,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OCTET_STR"",	ASN_OCTET_STR,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OPAQUE"",		ASN_OPAQUE,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_NULL"",		ASN_NULL,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_OBJECT_ID"",	ASN_OBJECT_ID,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_IPADDRESS"",	ASN_IPADDRESS,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_COUNTER"",		ASN_GAUGE,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_UNSIGNED"",		ASN_UNSIGNED,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_TIMETICKS"",	ASN_TIMETICKS,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_UINTEGER"",		ASN_UINTEGER,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_INTEGER"",		ASN_INTEGER,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT(""SNMP_COUNTER64"",	ASN_COUNTER64,	CONST_CS | CONST_PERSISTENT);

	REGISTER_SNMP_CLASS_CONST_LONG(""VERSION_1"",			SNMP_VERSION_1);
	REGISTER_SNMP_CLASS_CONST_LONG(""VERSION_2c"",			SNMP_VERSION_2c);
	REGISTER_SNMP_CLASS_CONST_LONG(""VERSION_2C"",			SNMP_VERSION_2c);
	REGISTER_SNMP_CLASS_CONST_LONG(""VERSION_3"",			SNMP_VERSION_3);

	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_NOERROR"",			PHP_SNMP_ERRNO_NOERROR);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_ANY"",			PHP_SNMP_ERRNO_ANY);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_GENERIC"",			PHP_SNMP_ERRNO_GENERIC);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_TIMEOUT"",			PHP_SNMP_ERRNO_TIMEOUT);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_ERROR_IN_REPLY"",		PHP_SNMP_ERRNO_ERROR_IN_REPLY);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_OID_NOT_INCREASING"",	PHP_SNMP_ERRNO_OID_NOT_INCREASING);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_OID_PARSING_ERROR"",	PHP_SNMP_ERRNO_OID_PARSING_ERROR);
	REGISTER_SNMP_CLASS_CONST_LONG(""ERRNO_MULTIPLE_SET_QUERIES"",	PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);

	/* Register SNMPException class */
	INIT_CLASS_ENTRY(cex, ""SNMPException"", NULL);
#ifdef HAVE_SPL
	php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);
#else
	php_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
#endif

	return SUCCESS;
}",CWE-416,10
1,"static RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) {
	RzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos);
	if (!result) {
		return NULL;
	}

	if (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) {
		ut32 total_slide_infos = 0;
		ut32 n_slide_infos[MAX_N_HDR];

		ut32 i;
		for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {
			ut64 hdr_offset = cache->hdr_offset[i];
			if (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) {
				goto beach;
			}
			total_slide_infos += n_slide_infos[i];
		}

		if (!total_slide_infos) {
			goto beach;
		}

		RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos);
		if (!infos) {
			goto beach;
		}

		ut32 k = 0;
		for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) {
			ut64 hdr_offset = cache->hdr_offset[i];
			if (!n_slide_infos[i]) {
				continue;
			}
			ut32 sio;
			if (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) {
				continue;
			}
			ut64 slide_infos_offset = sio;
			if (!slide_infos_offset) {
				continue;
			}
			slide_infos_offset += hdr_offset;

			ut32 j;
			RzDyldRebaseInfo *prev_info = NULL;
			for (j = 0; j < n_slide_infos[i]; j++) {
				ut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide);
				cache_mapping_slide entry;
				if (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, ""6lii"", 1) != sizeof(cache_mapping_slide)) {
					break;
				}

				if (entry.slideInfoOffset && entry.slideInfoSize) {
					infos[k].start = entry.fileOffset + hdr_offset;
					infos[k].end = infos[k].start + entry.size;
					ut64 slide = prev_info ? prev_info->slide : UT64_MAX;
					infos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide);
					prev_info = infos[k].info;
					k++;
				}
			}
		}

		if (!k) {
			free(infos);
			goto beach;
		}

		if (k < total_slide_infos) {
			RzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k);
			if (!pruned_infos) {
				free(infos);
				goto beach;
			}

			memcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k);
			free(infos);
			infos = pruned_infos;
		}

		result->entries = infos;
		result->length = k;
		return result;
	}

	if (cache->hdr->mappingCount > 1) {
		RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1);
		if (!infos) {
			goto beach;
		}

		infos[0].start = cache->maps[1].fileOffset;
		infos[0].end = infos[0].start + cache->maps[1].size;
		infos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX);

		result->entries = infos;
		result->length = 1;
		return result;
	}

beach:
	free(result);
	return NULL;
}",CWE-787,16
0,"  void DidGetHostQuota(QuotaStatusCode status,
                       const std::string& host,
                       StorageType type,
                       int64 quota) {
    quota_status_ = status;
    host_ = host;
    type_ = type;
    quota_ = quota;
  }
",none,24
0,"  virtual void EnableEthernetNetworkDevice(bool enable) {}
",none,24
1,"gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val)
{
  int idx;
  int type = nint(tree->car);

  switch (type) {
  case NODE_GVAR:
  case NODE_ARG:
  case NODE_LVAR:
  case NODE_IVAR:
  case NODE_CVAR:
  case NODE_CONST:
  case NODE_NIL:
  case NODE_MASGN:
    if (rhs) {
      codegen(s, rhs, VAL);
      pop();
      sp = cursp();
    }
    break;

  case NODE_COLON2:
  case NODE_CALL:
  case NODE_SCALL:
    /* keep evaluation order */
    break;

  case NODE_NVAR:
    codegen_error(s, ""Can't assign to numbered parameter"");
    break;

  default:
    codegen_error(s, ""unknown lhs"");
    break;
  }

  tree = tree->cdr;
  switch (type) {
  case NODE_GVAR:
    gen_setxv(s, OP_SETGV, sp, nsym(tree), val);
    break;
  case NODE_ARG:
  case NODE_LVAR:
    idx = lv_idx(s, nsym(tree));
    if (idx > 0) {
      if (idx != sp) {
        gen_move(s, idx, sp, val);
      }
      break;
    }
    else {                      /* upvar */
      gen_setupvar(s, sp, nsym(tree));
    }
    break;
  case NODE_IVAR:
    gen_setxv(s, OP_SETIV, sp, nsym(tree), val);
    break;
  case NODE_CVAR:
    gen_setxv(s, OP_SETCV, sp, nsym(tree), val);
    break;
  case NODE_CONST:
    gen_setxv(s, OP_SETCONST, sp, nsym(tree), val);
    break;
  case NODE_COLON2:
    if (sp) {
      gen_move(s, cursp(), sp, 0);
    }
    sp = cursp();
    push();
    codegen(s, tree->car, VAL);
    if (rhs) {
      codegen(s, rhs, VAL); pop();
      gen_move(s, sp, cursp(), 0);
    }
    pop_n(2);
    idx = new_sym(s, nsym(tree->cdr));
    genop_2(s, OP_SETMCNST, sp, idx);
    break;

  case NODE_CALL:
  case NODE_SCALL:
    {
      int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0;
      mrb_sym mid = nsym(tree->cdr->car);

      top = cursp();
      if (val || sp == cursp()) {
        push();                   /* room for retval */
      }
      call = cursp();
      if (!tree->car) {
        noself = 1;
        push();
      }
      else {
        codegen(s, tree->car, VAL); /* receiver */
      }
      if (safe) {
        int recv = cursp()-1;
        gen_move(s, cursp(), recv, 1);
        skip = genjmp2_0(s, OP_JMPNIL, cursp(), val);
      }
      tree = tree->cdr->cdr->car;
      if (tree) {
        if (tree->car) {            /* positional arguments */
          n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14);
          if (n < 0) {              /* variable length */
            n = 15;
            push();
          }
        }
        if (tree->cdr->car) {       /* keyword arguments */
          if (n == 14) {
            pop_n(n);
            genop_2(s, OP_ARRAY, cursp(), n);
            push();
            n = 15;
          }
          gen_hash(s, tree->cdr->car->cdr, VAL, 0);
          if (n < 14) {
            n++;
          }
          else {
            pop_n(2);
            genop_2(s, OP_ARYPUSH, cursp(), 1);
          }
          push();
        }
      }
      if (rhs) {
        codegen(s, rhs, VAL);
        pop();
      }
      else {
        gen_move(s, cursp(), sp, 0);
      }
      if (val) {
        gen_move(s, top, cursp(), 1);
      }
      if (n < 15) {
        n++;
        if (n == 15) {
          pop_n(14);
          genop_2(s, OP_ARRAY, cursp(), 15);
        }
      }
      else {
        pop();
        genop_2(s, OP_ARYPUSH, cursp(), 1);
      }
      s->sp = call;
      if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) {
        genop_1(s, OP_SETIDX, cursp());
      }
      else {
        genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n);
      }
      if (safe) {
        dispatch(s, skip);
      }
      s->sp = top;
    }
    break;

  case NODE_MASGN:
    gen_massignment(s, tree->car, sp, val);
    break;

  /* splat without assignment */
  case NODE_NIL:
    break;

  default:
    codegen_error(s, ""unknown lhs"");
    break;
  }
  if (val) push();
}",CWE-125,1
0,"  UpdateAccessTimeTask(
      QuotaManager* manager,
      const GURL& origin,
      StorageType type,
      base::Time accessed_time)
      : DatabaseTaskBase(manager),
        origin_(origin),
        type_(type),
        accessed_time_(accessed_time) {}
",none,24
1,"u32 GetHintFormat(GF_TrackBox *trak)
{
	GF_HintMediaHeaderBox *hmhd = (GF_HintMediaHeaderBox *)trak->Media->information->InfoHeader;
	if (hmhd->type != GF_ISOM_BOX_TYPE_HMHD)
		return 0;
		
	if (!hmhd || !hmhd->subType) {
		GF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->child_boxes, 0);
		if (!hmhd) return a ? a->type : 0;
		if (a) hmhd->subType = a->type;
		return hmhd->subType;
	}
	return hmhd->subType;
}",CWE-476,12
1,"LogFilePrep(const char *fname, const char *backup, const char *idstring)
{
    char *logFileName = NULL;

    if (asprintf(&logFileName, fname, idstring) == -1)
        FatalError(""Cannot allocate space for the log file name\n"");

    if (backup && *backup) {
        struct stat buf;

        if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) {
            char *suffix;
            char *oldLog;

            if ((asprintf(&suffix, backup, idstring) == -1) ||
                (asprintf(&oldLog, ""%s%s"", logFileName, suffix) == -1)) {
                FatalError(""Cannot allocate space for the log file name\n"");
            }
            free(suffix);

            if (rename(logFileName, oldLog) == -1) {
                FatalError(""Cannot move old log file \""%s\"" to \""%s\""\n"",
                           logFileName, oldLog);
            }
            free(oldLog);
        }
    }
    else {
        if (remove(logFileName) != 0 && errno != ENOENT) {
            FatalError(""Cannot remove old log file \""%s\"": %s\n"",
                       logFileName, strerror(errno));
        }
    }

    return logFileName;
}",CWE-863,20
0,"  virtual WifiNetwork* wifi_network() { return wifi_; }
",none,24
1,"do_arg_all(
    int	count,
    int	forceit,		// hide buffers in current windows
    int keep_tabs)		// keep current tabs, for "":tab drop file""
{
    int		i;
    win_T	*wp, *wpnext;
    char_u	*opened;	// Array of weight for which args are open:
				//  0: not opened
				//  1: opened in other tab
				//  2: opened in curtab
				//  3: opened in curtab and curwin
				//
    int		opened_len;	// length of opened[]
    int		use_firstwin = FALSE;	// use first window for arglist
    int		tab_drop_empty_window = FALSE;
    int		split_ret = OK;
    int		p_ea_save;
    alist_T	*alist;		// argument list to be used
    buf_T	*buf;
    tabpage_T	*tpnext;
    int		had_tab = cmdmod.cmod_tab;
    win_T	*old_curwin, *last_curwin;
    tabpage_T	*old_curtab, *last_curtab;
    win_T	*new_curwin = NULL;
    tabpage_T	*new_curtab = NULL;

#ifdef FEAT_CMDWIN
    if (cmdwin_type != 0)
    {
	emsg(_(e_invalid_in_cmdline_window));
	return;
    }
#endif
    if (ARGCOUNT <= 0)
    {
	// Don't give an error message.  We don't want it when the "":all""
	// command is in the .vimrc.
	return;
    }
    setpcmark();

    opened_len = ARGCOUNT;
    opened = alloc_clear(opened_len);
    if (opened == NULL)
	return;

    // Autocommands may do anything to the argument list.  Make sure it's not
    // freed while we are working here by ""locking"" it.  We still have to
    // watch out for its size to be changed.
    alist = curwin->w_alist;
    ++alist->al_refcount;

    old_curwin = curwin;
    old_curtab = curtab;

# ifdef FEAT_GUI
    need_mouse_correct = TRUE;
# endif

    // Try closing all windows that are not in the argument list.
    // Also close windows that are not full width;
    // When 'hidden' or ""forceit"" set the buffer becomes hidden.
    // Windows that have a changed buffer and can't be hidden won't be closed.
    // When the "":tab"" modifier was used do this for all tab pages.
    if (had_tab > 0)
	goto_tabpage_tp(first_tabpage, TRUE, TRUE);
    for (;;)
    {
	tpnext = curtab->tp_next;
	for (wp = firstwin; wp != NULL; wp = wpnext)
	{
	    wpnext = wp->w_next;
	    buf = wp->w_buffer;
	    if (buf->b_ffname == NULL
		    || (!keep_tabs && (buf->b_nwindows > 1
			    || wp->w_width != Columns)))
		i = opened_len;
	    else
	    {
		// check if the buffer in this window is in the arglist
		for (i = 0; i < opened_len; ++i)
		{
		    if (i < alist->al_ga.ga_len
			    && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum
				|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),
					buf->b_ffname, TRUE, TRUE) & FPC_SAME))
		    {
			int weight = 1;

			if (old_curtab == curtab)
			{
			    ++weight;
			    if (old_curwin == wp)
				++weight;
			}

			if (weight > (int)opened[i])
			{
			    opened[i] = (char_u)weight;
			    if (i == 0)
			    {
				if (new_curwin != NULL)
				    new_curwin->w_arg_idx = opened_len;
				new_curwin = wp;
				new_curtab = curtab;
			    }
			}
			else if (keep_tabs)
			    i = opened_len;

			if (wp->w_alist != alist)
			{
			    // Use the current argument list for all windows
			    // containing a file from it.
			    alist_unlink(wp->w_alist);
			    wp->w_alist = alist;
			    ++wp->w_alist->al_refcount;
			}
			break;
		    }
		}
	    }
	    wp->w_arg_idx = i;

	    if (i == opened_len && !keep_tabs)// close this window
	    {
		if (buf_hide(buf) || forceit || buf->b_nwindows > 1
							|| !bufIsChanged(buf))
		{
		    // If the buffer was changed, and we would like to hide it,
		    // try autowriting.
		    if (!buf_hide(buf) && buf->b_nwindows <= 1
							 && bufIsChanged(buf))
		    {
			bufref_T    bufref;

			set_bufref(&bufref, buf);

			(void)autowrite(buf, FALSE);

			// check if autocommands removed the window
			if (!win_valid(wp) || !bufref_valid(&bufref))
			{
			    wpnext = firstwin;	// start all over...
			    continue;
			}
		    }
		    // don't close last window
		    if (ONE_WINDOW
			    && (first_tabpage->tp_next == NULL || !had_tab))
			use_firstwin = TRUE;
		    else
		    {
			win_close(wp, !buf_hide(buf) && !bufIsChanged(buf));

			// check if autocommands removed the next window
			if (!win_valid(wpnext))
			    wpnext = firstwin;	// start all over...
		    }
		}
	    }
	}

	// Without the "":tab"" modifier only do the current tab page.
	if (had_tab == 0 || tpnext == NULL)
	    break;

	// check if autocommands removed the next tab page
	if (!valid_tabpage(tpnext))
	    tpnext = first_tabpage;	// start all over...

	goto_tabpage_tp(tpnext, TRUE, TRUE);
    }

    // Open a window for files in the argument list that don't have one.
    // ARGCOUNT may change while doing this, because of autocommands.
    if (count > opened_len || count <= 0)
	count = opened_len;

    // Don't execute Win/Buf Enter/Leave autocommands here.
    ++autocmd_no_enter;
    ++autocmd_no_leave;
    last_curwin = curwin;
    last_curtab = curtab;
    win_enter(lastwin, FALSE);
    // "":tab drop file"" should re-use an empty window to avoid ""--remote-tab""
    // leaving an empty tab page when executed locally.
    if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1
			    && curbuf->b_ffname == NULL && !curbuf->b_changed)
    {
	use_firstwin = TRUE;
	tab_drop_empty_window = TRUE;
    }

    for (i = 0; i < count && !got_int; ++i)
    {
	if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)
	    arg_had_last = TRUE;
	if (opened[i] > 0)
	{
	    // Move the already present window to below the current window
	    if (curwin->w_arg_idx != i)
	    {
		FOR_ALL_WINDOWS(wpnext)
		{
		    if (wpnext->w_arg_idx == i)
		    {
			if (keep_tabs)
			{
			    new_curwin = wpnext;
			    new_curtab = curtab;
			}
			else if (wpnext->w_frame->fr_parent
						 != curwin->w_frame->fr_parent)
			{
			    emsg(_(""E249: window layout changed unexpectedly""));
			    i = count;
			    break;
			}
			else
			    win_move_after(wpnext, curwin);
			break;
		    }
		}
	    }
	}
	else if (split_ret == OK)
	{
	    // trigger events for tab drop
	    if (tab_drop_empty_window && i == count - 1)
		--autocmd_no_enter;
	    if (!use_firstwin)		// split current window
	    {
		p_ea_save = p_ea;
		p_ea = TRUE;		// use space from all windows
		split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
		p_ea = p_ea_save;
		if (split_ret == FAIL)
		    continue;
	    }
	    else    // first window: do autocmd for leaving this buffer
		--autocmd_no_leave;

	    // edit file ""i""
	    curwin->w_arg_idx = i;
	    if (i == 0)
	    {
		new_curwin = curwin;
		new_curtab = curtab;
	    }
	    (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,
		      ECMD_ONE,
		      ((buf_hide(curwin->w_buffer)
			   || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)
						       + ECMD_OLDBUF, curwin);
	    if (tab_drop_empty_window && i == count - 1)
		++autocmd_no_enter;
	    if (use_firstwin)
		++autocmd_no_leave;
	    use_firstwin = FALSE;
	}
	ui_breakcheck();

	// When "":tab"" was used open a new tab for a new window repeatedly.
	if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
	    cmdmod.cmod_tab = 9999;
    }

    // Remove the ""lock"" on the argument list.
    alist_unlink(alist);

    --autocmd_no_enter;

    // restore last referenced tabpage's curwin
    if (last_curtab != new_curtab)
    {
	if (valid_tabpage(last_curtab))
	    goto_tabpage_tp(last_curtab, TRUE, TRUE);
	if (win_valid(last_curwin))
	    win_enter(last_curwin, FALSE);
    }
    // to window with first arg
    if (valid_tabpage(new_curtab))
	goto_tabpage_tp(new_curtab, TRUE, TRUE);
    if (win_valid(new_curwin))
	win_enter(new_curwin, FALSE);

    --autocmd_no_leave;
    vim_free(opened);
}",CWE-416,10
1,"mrb_remove_method(mrb_state *mrb, struct RClass *c, mrb_sym mid)
{
  mt_tbl *h;

  MRB_CLASS_ORIGIN(c);
  h = c->mt;

  if (h && mt_del(mrb, h, mid)) return;
  mrb_name_error(mrb, mid, ""method '%n' not defined in %C"", mid, c);
}",CWE-787,16
0,"  void GetOriginsModifiedSince(StorageType type, base::Time modified_since) {
    modified_origins_.clear();
    modified_origins_type_ = kStorageTypeUnknown;
    quota_manager_->GetOriginsModifiedSince(type, modified_since,
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetModifiedOrigins));
  }
",none,24
0,"  void GetAvailableSpace() {
    quota_status_ = kQuotaStatusUnknown;
    available_space_ = -1;
    quota_manager_->GetAvailableSpace(
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetAvailableSpace));
  }
",none,24
1,"drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
			gerbv_image_t *image, ssize_t file_line)
{
    int tool_num;
    gboolean done = FALSE;
    int temp;
    double size;
    gerbv_drill_stats_t *stats = image->drill_stats;
    gerbv_aperture_t *apert;
    gchar *tmps;
    gchar *string;

    dprintf(""---> entering %s()...\n"", __FUNCTION__);

    /* Sneak a peek at what's hiding after the 'T'. Ugly fix for
       broken headers from Orcad, which is crap */
    temp = gerb_fgetc(fd);
    dprintf(""  Found a char '%s' (0x%02x) after the T\n"",
	    gerbv_escape_char(temp), temp);
    
    /* might be a tool tool change stop switch on/off*/
    if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){
    	if(gerb_fgetc(fd) == 'S'){
    	    if (gerb_fgetc(fd) == 'T' ){
    	  	fd->ptr -= 4;
    	  	tmps = get_line(fd++);
    	  	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
			_(""Tool change stop switch found \""%s\"" ""
			    ""at line %ld in file \""%s\""""),
			tmps, file_line, fd->filename);
	  	g_free (tmps);

	  	return -1;
	    }
	    gerb_ungetc(fd);
	}
	gerb_ungetc(fd);
    }

    if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) {
	if(temp != EOF) {
	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
		   _(""OrCAD bug: Junk text found in place of tool definition""));
	    tmps = get_line(fd);
	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
		    _(""Junk text \""%s\"" ""
			""at line %ld in file \""%s\""""),
		    tmps, file_line, fd->filename);
	    g_free (tmps);
	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
				  _(""Ignoring junk text""));
	}
	return -1;
    }
    gerb_ungetc(fd);

    tool_num = (int) gerb_fgetint(fd, NULL);
    dprintf (""  Handling tool T%d at line %ld\n"", tool_num, file_line);

    if (tool_num == 0) 
	return tool_num; /* T00 is a command to unload the drill */

    if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) {
	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
		_(""Out of bounds drill number %d ""
		    ""at line %ld in file \""%s\""""),
		tool_num, file_line, fd->filename);
    }

    /* Set the current tool to the correct one */
    state->current_tool = tool_num;
    apert = image->aperture[tool_num];

    /* Check for a size definition */
    temp = gerb_fgetc(fd);

    /* This bit of code looks for a tool definition by scanning for strings
     * of form TxxC, TxxF, TxxS.  */
    while (!done) {
	switch((char)temp) {
	case 'C':
	    size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);
	    dprintf (""  Read a size of %g\n"", size);

	    if (state->unit == GERBV_UNIT_MM) {
		size /= 25.4;
	    } else if(size >= 4.0) {
		/* If the drill size is >= 4 inches, assume that this
		   must be wrong and that the units are mils.
		   The limit being 4 inches is because the smallest drill
		   I've ever seen used is 0,3mm(about 12mil). Half of that
		   seemed a bit too small a margin, so a third it is */

		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
			_(""Read a drill of diameter %g inches ""
			    ""at line %ld in file \""%s\""""),
			    size, file_line, fd->filename);
		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
			_(""Assuming units are mils""));
		size /= 1000.0;
	    }

	    if (size <= 0. || size >= 10000.) {
		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
			_(""Unreasonable drill size %g found for drill %d ""
			    ""at line %ld in file \""%s\""""),
			    size, tool_num, file_line, fd->filename);
	    } else {
		if (apert != NULL) {
		    /* allow a redefine of a tool only if the new definition is exactly the same.
		     * This avoid lots of spurious complaints with the output of some cad
		     * tools while keeping complaints if there is a true problem
		     */
		    if (apert->parameter[0] != size
		    ||  apert->type != GERBV_APTYPE_CIRCLE
		    ||  apert->nuf_parameters != 1
		    ||  apert->unit != GERBV_UNIT_INCH) {

			gerbv_stats_printf(stats->error_list,
				GERBV_MESSAGE_ERROR, -1,
				_(""Found redefinition of drill %d ""
				""at line %ld in file \""%s\""""),
				tool_num, file_line, fd->filename);
		    }
		} else {
		    apert = image->aperture[tool_num] =
						g_new0(gerbv_aperture_t, 1);
		    if (apert == NULL)
			GERB_FATAL_ERROR(""malloc tool failed in %s()"",
					__FUNCTION__);

		    /* There's really no way of knowing what unit the tools
		       are defined in without sneaking a peek in the rest of
		       the file first. That's done in drill_guess_format() */
		    apert->parameter[0] = size;
		    apert->type = GERBV_APTYPE_CIRCLE;
		    apert->nuf_parameters = 1;
		    apert->unit = GERBV_UNIT_INCH;
		}
	    }
	    
	    /* Add the tool whose definition we just found into the list
	     * of tools for this layer used to generate statistics. */
	    stats = image->drill_stats;
	    string = g_strdup_printf(""%s"", (state->unit == GERBV_UNIT_MM ? _(""mm"") : _(""inch"")));
	    drill_stats_add_to_drill_list(stats->drill_list, 
					  tool_num, 
					  state->unit == GERBV_UNIT_MM ? size*25.4 : size, 
					  string);
	    g_free(string);
	    break;

	case 'F':
	case 'S' :
	    /* Silently ignored. They're not important. */
	    gerb_fgetint(fd, NULL);
	    break;

	default:
	    /* Stop when finding anything but what's expected
	       (and put it back) */
	    gerb_ungetc(fd);
	    done = TRUE;
	    break;
	}  /* switch((char)temp) */

	temp = gerb_fgetc(fd);
	if (EOF == temp) {
	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
		    _(""Unexpected EOF encountered in header of ""
			""drill file \""%s\""""), fd->filename);

	/* Restore new line character for processing */
	if ('\n' == temp || '\r' == temp)
	    gerb_ungetc(fd);
	}
    }   /* while(!done) */  /* Done looking at tool definitions */

    /* Catch the tools that aren't defined.
       This isn't strictly a good thing, but at least something is shown */
    if (apert == NULL) {
        double dia;

	apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);
	if (apert == NULL)
	    GERB_FATAL_ERROR(""malloc tool failed in %s()"", __FUNCTION__);

        /* See if we have the tool table */
        dia = gerbv_get_tool_diameter(tool_num);
        if (dia <= 0) {
            /*
             * There is no tool. So go out and make some.
             * This size calculation is, of course, totally bogus.
             */
            dia = (double)(16 + 8 * tool_num) / 1000;
            /*
             * Oooh, this is sooo ugly. But some CAD systems seem to always
             * use T00 at the end of the file while others that don't have
             * tool definitions inside the file never seem to use T00 at all.
             */
            if (tool_num != 0) {
		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
			_(""Tool %02d used without being defined ""
			    ""at line %ld in file \""%s\""""),
			tool_num, file_line, fd->filename);
		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
			_(""Setting a default size of %g\""""), dia);
            }
	}

	apert->type = GERBV_APTYPE_CIRCLE;
	apert->nuf_parameters = 1;
	apert->parameter[0] = dia;

	/* Add the tool whose definition we just found into the list
	 * of tools for this layer used to generate statistics. */
	if (tool_num != 0) {  /* Only add non-zero tool nums.  
			       * Zero = unload command. */
	    stats = image->drill_stats;
	    string = g_strdup_printf(""%s"", 
				     (state->unit == GERBV_UNIT_MM ? _(""mm"") : _(""inch"")));
	    drill_stats_add_to_drill_list(stats->drill_list, 
					  tool_num, 
					  state->unit == GERBV_UNIT_MM ? dia*25.4 : dia,
					  string);
	    g_free(string);
	}
    } /* if(image->aperture[tool_num] == NULL) */	
    
    dprintf(""<----  ...leaving %s()\n"", __FUNCTION__);

    return tool_num;
} /* drill_parse_T_code() */",CWE-787,16
0,"  void DidGetUsageAndQuotaForEviction(QuotaStatusCode status,
      int64 usage, int64 unlimited_usage, int64 quota, int64 available_space) {
    quota_status_ = status;
    usage_ = usage;
    unlimited_usage_ = unlimited_usage;
    quota_ = quota;
    available_space_ = available_space;
  }
",none,24
0,"  virtual void DisconnectFromWirelessNetwork(const WirelessNetwork* network) {}
",none,24
0,"  void DidGetGlobalUsage(StorageType type, int64 usage,
                         int64 unlimited_usage) {
    DCHECK_EQ(type_, type);
    DCHECK_GE(usage, unlimited_usage);
    global_usage_ = usage;
    global_unlimited_usage_ = unlimited_usage;
    CheckCompleted();
  }
",none,24
0,"  CallbackList& callbacks() { return callbacks_; }
",none,24
1,"static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
	struct elo_priv *priv;
	int ret;
	struct usb_device *udev;

	if (!hid_is_usb(hdev))
		return -EINVAL;

	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
	if (!priv)
		return -ENOMEM;

	INIT_DELAYED_WORK(&priv->work, elo_work);
	udev = interface_to_usbdev(to_usb_interface(hdev->dev.parent));
	priv->usbdev = usb_get_dev(udev);

	hid_set_drvdata(hdev, priv);

	ret = hid_parse(hdev);
	if (ret) {
		hid_err(hdev, ""parse failed\n"");
		goto err_free;
	}

	ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
	if (ret) {
		hid_err(hdev, ""hw start failed\n"");
		goto err_free;
	}

	if (elo_broken_firmware(priv->usbdev)) {
		hid_info(hdev, ""broken firmware found, installing workaround\n"");
		queue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL);
	}

	return 0;
err_free:
	kfree(priv);
	return ret;
}",CWE-200,4
0,"CellularNetwork::CellularNetwork()
    : WirelessNetwork(),
      activation_state_(ACTIVATION_STATE_UNKNOWN),
      network_technology_(NETWORK_TECHNOLOGY_UNKNOWN),
      roaming_state_(ROAMING_STATE_UNKNOWN),
      restricted_pool_(false),
      prl_version_(0) {
  type_ = TYPE_CELLULAR;
}
",none,24
1,"int main(int argc, char **argv)
{
	int c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;
	struct libmnt_context *cxt;
	struct libmnt_table *fstab = NULL;
	char *srcbuf = NULL;
	char *types = NULL;
	unsigned long oper = 0;

	enum {
		MOUNT_OPT_SHARED = CHAR_MAX + 1,
		MOUNT_OPT_SLAVE,
		MOUNT_OPT_PRIVATE,
		MOUNT_OPT_UNBINDABLE,
		MOUNT_OPT_RSHARED,
		MOUNT_OPT_RSLAVE,
		MOUNT_OPT_RPRIVATE,
		MOUNT_OPT_RUNBINDABLE,
		MOUNT_OPT_TARGET,
		MOUNT_OPT_SOURCE
	};

	static const struct option longopts[] = {
		{ ""all"", 0, 0, 'a' },
		{ ""fake"", 0, 0, 'f' },
		{ ""fstab"", 1, 0, 'T' },
		{ ""fork"", 0, 0, 'F' },
		{ ""help"", 0, 0, 'h' },
		{ ""no-mtab"", 0, 0, 'n' },
		{ ""read-only"", 0, 0, 'r' },
		{ ""ro"", 0, 0, 'r' },
		{ ""verbose"", 0, 0, 'v' },
		{ ""version"", 0, 0, 'V' },
		{ ""read-write"", 0, 0, 'w' },
		{ ""rw"", 0, 0, 'w' },
		{ ""options"", 1, 0, 'o' },
		{ ""test-opts"", 1, 0, 'O' },
		{ ""pass-fd"", 1, 0, 'p' },
		{ ""types"", 1, 0, 't' },
		{ ""uuid"", 1, 0, 'U' },
		{ ""label"", 1, 0, 'L'},
		{ ""bind"", 0, 0, 'B' },
		{ ""move"", 0, 0, 'M' },
		{ ""rbind"", 0, 0, 'R' },
		{ ""make-shared"", 0, 0, MOUNT_OPT_SHARED },
		{ ""make-slave"", 0, 0, MOUNT_OPT_SLAVE },
		{ ""make-private"", 0, 0, MOUNT_OPT_PRIVATE },
		{ ""make-unbindable"", 0, 0, MOUNT_OPT_UNBINDABLE },
		{ ""make-rshared"", 0, 0, MOUNT_OPT_RSHARED },
		{ ""make-rslave"", 0, 0, MOUNT_OPT_RSLAVE },
		{ ""make-rprivate"", 0, 0, MOUNT_OPT_RPRIVATE },
		{ ""make-runbindable"", 0, 0, MOUNT_OPT_RUNBINDABLE },
		{ ""no-canonicalize"", 0, 0, 'c' },
		{ ""internal-only"", 0, 0, 'i' },
		{ ""show-labels"", 0, 0, 'l' },
		{ ""target"", 1, 0, MOUNT_OPT_TARGET },
		{ ""source"", 1, 0, MOUNT_OPT_SOURCE },
		{ NULL, 0, 0, 0 }
	};

	static const ul_excl_t excl[] = {       /* rows and cols in in ASCII order */
		{ 'B','M','R',			/* bind,move,rbind */
		   MOUNT_OPT_SHARED,   MOUNT_OPT_SLAVE,
		   MOUNT_OPT_PRIVATE,  MOUNT_OPT_UNBINDABLE,
		   MOUNT_OPT_RSHARED,  MOUNT_OPT_RSLAVE,
		   MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },

		{ 'L','U', MOUNT_OPT_SOURCE },	/* label,uuid,source */
		{ 0 }
	};
	int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;

	sanitize_env();
	setlocale(LC_ALL, """");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	mnt_init_debug(0);
	cxt = mnt_new_context();
	if (!cxt)
		err(MOUNT_EX_SYSERR, _(""libmount context allocation failed""));

	mnt_context_set_tables_errcb(cxt, table_parser_errcb);

	while ((c = getopt_long(argc, argv, ""aBcfFhilL:Mno:O:p:rRsU:vVwt:T:"",
					longopts, NULL)) != -1) {

		/* only few options are allowed for non-root users */
		if (mnt_context_is_restricted(cxt) &&
		    !strchr(""hlLUVvpris"", c) &&
		    c != MOUNT_OPT_TARGET &&
		    c != MOUNT_OPT_SOURCE)
			exit_non_root(option_to_longopt(c, longopts));

		err_exclusive_options(c, longopts, excl, excl_st);

		switch(c) {
		case 'a':
			all = 1;
			break;
		case 'c':
			mnt_context_disable_canonicalize(cxt, TRUE);
			break;
		case 'f':
			mnt_context_enable_fake(cxt, TRUE);
			break;
		case 'F':
			mnt_context_enable_fork(cxt, TRUE);
			break;
		case 'h':
			usage(stdout);
			break;
		case 'i':
			mnt_context_disable_helpers(cxt, TRUE);
			break;
		case 'n':
			mnt_context_disable_mtab(cxt, TRUE);
			break;
		case 'r':
			if (mnt_context_append_options(cxt, ""ro""))
				err(MOUNT_EX_SYSERR, _(""failed to append options""));
			readwrite = 0;
			break;
		case 'v':
			mnt_context_enable_verbose(cxt, TRUE);
			break;
		case 'V':
			print_version();
			break;
		case 'w':
			if (mnt_context_append_options(cxt, ""rw""))
				err(MOUNT_EX_SYSERR, _(""failed to append options""));
			readwrite = 1;
			break;
		case 'o':
			if (mnt_context_append_options(cxt, optarg))
				err(MOUNT_EX_SYSERR, _(""failed to append options""));
			break;
		case 'O':
			if (mnt_context_set_options_pattern(cxt, optarg))
				err(MOUNT_EX_SYSERR, _(""failed to set options pattern""));
			break;
		case 'p':
                        warnx(_(""--pass-fd is no longer supported""));
			break;
		case 'L':
			xasprintf(&srcbuf, ""LABEL=\""%s\"""", optarg);
			mnt_context_disable_swapmatch(cxt, 1);
			mnt_context_set_source(cxt, srcbuf);
			free(srcbuf);
			break;
		case 'U':
			xasprintf(&srcbuf, ""UUID=\""%s\"""", optarg);
			mnt_context_disable_swapmatch(cxt, 1);
			mnt_context_set_source(cxt, srcbuf);
			free(srcbuf);
			break;
		case 'l':
			show_labels = 1;
			break;
		case 't':
			types = optarg;
			break;
		case 'T':
			fstab = append_fstab(cxt, fstab, optarg);
			break;
		case 's':
			mnt_context_enable_sloppy(cxt, TRUE);
			break;
		case 'B':
			oper |= MS_BIND;
			break;
		case 'M':
			oper |= MS_MOVE;
			break;
		case 'R':
			oper |= (MS_BIND | MS_REC);
			break;
		case MOUNT_OPT_SHARED:
			oper |= MS_SHARED;
			break;
		case MOUNT_OPT_SLAVE:
			oper |= MS_SLAVE;
			break;
		case MOUNT_OPT_PRIVATE:
			oper |= MS_PRIVATE;
			break;
		case MOUNT_OPT_UNBINDABLE:
			oper |= MS_UNBINDABLE;
			break;
		case MOUNT_OPT_RSHARED:
			oper |= (MS_SHARED | MS_REC);
			break;
		case MOUNT_OPT_RSLAVE:
			oper |= (MS_SLAVE | MS_REC);
			break;
		case MOUNT_OPT_RPRIVATE:
			oper |= (MS_PRIVATE | MS_REC);
			break;
		case MOUNT_OPT_RUNBINDABLE:
			oper |= (MS_UNBINDABLE | MS_REC);
			break;
		case MOUNT_OPT_TARGET:
			mnt_context_disable_swapmatch(cxt, 1);
			mnt_context_set_target(cxt, optarg);
			break;
		case MOUNT_OPT_SOURCE:
			mnt_context_disable_swapmatch(cxt, 1);
			mnt_context_set_source(cxt, optarg);
			break;
		default:
			usage(stderr);
			break;
		}
	}

	argc -= optind;
	argv += optind;

	if (fstab && !mnt_context_is_nocanonicalize(cxt)) {
		/*
		 * We have external (context independent) fstab instance, let's
		 * make a connection between the fstab and the canonicalization
		 * cache.
		 */
		struct libmnt_cache *cache = mnt_context_get_cache(cxt);
		mnt_table_set_cache(fstab, cache);
	}

	if (!mnt_context_get_source(cxt) &&
	    !mnt_context_get_target(cxt) &&
	    !argc &&
	    !all) {
		if (oper)
			usage(stderr);
		print_all(cxt, types, show_labels);
		goto done;
	}

	if (oper && (types || all || mnt_context_get_source(cxt)))
		usage(stderr);

	if (types && (all || strchr(types, ',') ||
			     strncmp(types, ""no"", 2) == 0))
		mnt_context_set_fstype_pattern(cxt, types);
	else if (types)
		mnt_context_set_fstype(cxt, types);

	if (all) {
		/*
		 * A) Mount all
		 */
		rc = mount_all(cxt);
		goto done;

	} else if (argc == 0 && (mnt_context_get_source(cxt) ||
				 mnt_context_get_target(cxt))) {
		/*
		 * B) mount -L|-U|--source|--target
		 */
		if (mnt_context_is_restricted(cxt) &&
		    mnt_context_get_source(cxt) &&
		    mnt_context_get_target(cxt))
			exit_non_root(NULL);

	} else if (argc == 1) {
		/*
		 * C) mount [-L|-U|--source] 
		 *    mount 
		 *
		 * non-root may specify source *or* target, but not both
		 */
		if (mnt_context_is_restricted(cxt) &&
		    mnt_context_get_source(cxt))
			exit_non_root(NULL);

		mnt_context_set_target(cxt, argv[0]);

	} else if (argc == 2 && !mnt_context_get_source(cxt)
			     && !mnt_context_get_target(cxt)) {
		/*
		 * D) mount  
		 */
		if (mnt_context_is_restricted(cxt))
			exit_non_root(NULL);
		mnt_context_set_source(cxt, argv[0]);
		mnt_context_set_target(cxt, argv[1]);

	} else
		usage(stderr);

	if (oper) {
		/* MS_PROPAGATION operations, let's set the mount flags */
		mnt_context_set_mflags(cxt, oper);

		/* For -make* or --bind is fstab unnecessary */
		mnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);
	}

	rc = mnt_context_mount(cxt);
	rc = mk_exit_code(cxt, rc);

	if (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))
		success_message(cxt);
done:
	mnt_free_context(cxt);
	mnt_free_table(fstab);
	return rc;
}",CWE-200,4
1," */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
	st_entry 			*ent1, *ent2;
	wddx_stack 			*stack = (wddx_stack *)user_data;
	HashTable 			*target_hash;
	zend_class_entry 	*pce;
	zval				obj;

/* OBJECTS_FIXME */
	if (stack->top == 0) {
		return;
	}

	if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||
		!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||
	  	!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||
		!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||
		!strcmp((char *)name, EL_DATETIME)) {
		wddx_stack_top(stack, (void**)&ent1);

		if (Z_TYPE(ent1->data) == IS_UNDEF) {
			if (stack->top > 1) {
				stack->top--;
			} else {
				stack->done = 1;
			}
			efree(ent1);
			return;
		}

		if (!strcmp((char *)name, EL_BINARY)) {
			zend_string *new_str = php_base64_decode(
				(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
			zval_ptr_dtor(&ent1->data);
			ZVAL_STR(&ent1->data, new_str);
		}

		/* Call __wakeup() method on the object. */
		if (Z_TYPE(ent1->data) == IS_OBJECT) {
			zval fname, retval;

			ZVAL_STRING(&fname, ""__wakeup"");

			call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);

			zval_ptr_dtor(&fname);
			zval_ptr_dtor(&retval);
		}

		if (stack->top > 1) {
			stack->top--;
			wddx_stack_top(stack, (void**)&ent2);

			/* if non-existent field */
			if (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) {
				zval_ptr_dtor(&ent1->data);
				efree(ent1);
				return;
			}

			if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {
				target_hash = HASH_OF(&ent2->data);

				if (ent1->varname) {
					if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
						Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&
						ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {
						zend_bool incomplete_class = 0;

						zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						zend_string_forget_hash_val(Z_STR(ent1->data));
						if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {
							incomplete_class = 1;
							pce = PHP_IC_ENTRY;
						}

						/* Initialize target object */
						object_init_ex(&obj, pce);

						/* Merge current hashtable with object's default properties */
						zend_hash_merge(Z_OBJPROP(obj),
										Z_ARRVAL(ent2->data),
										zval_add_ref, 0);

						if (incomplete_class) {
							php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						}

						/* Clean up old array entry */
						zval_ptr_dtor(&ent2->data);

						/* Set stack entry to point to the newly created object */
						ZVAL_COPY_VALUE(&ent2->data, &obj);

						/* Clean up class name var entry */
						zval_ptr_dtor(&ent1->data);
					} else if (Z_TYPE(ent2->data) == IS_OBJECT) {
						zend_class_entry *old_scope = EG(scope);

						EG(scope) = Z_OBJCE(ent2->data);
						add_property_zval(&ent2->data, ent1->varname, &ent1->data);
						if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);
						EG(scope) = old_scope;
					} else {
						zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);
					}
					efree(ent1->varname);
				} else	{
					zend_hash_next_index_insert(target_hash, &ent1->data);
				}
			}
			efree(ent1);
		} else {
			stack->done = 1;
		}
	} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {
		efree(stack->varname);
		stack->varname = NULL;
	} else if (!strcmp((char *)name, EL_FIELD)) {
		st_entry *ent;
		wddx_stack_top(stack, (void **)&ent);
		efree(ent);
		stack->top--;
	}",CWE-476,12
0,"  void set_db_disabled(bool db_disabled) {
    db_disabled_ = db_disabled;
  }
",none,24
1,"static int em28xx_usb_probe(struct usb_interface *intf,
			    const struct usb_device_id *id)
{
	struct usb_device *udev;
	struct em28xx *dev = NULL;
	int retval;
	bool has_vendor_audio = false, has_video = false, has_dvb = false;
	int i, nr, try_bulk;
	const int ifnum = intf->altsetting[0].desc.bInterfaceNumber;
	char *speed;

	udev = usb_get_dev(interface_to_usbdev(intf));

	/* Check to see next free device and mark as used */
	do {
		nr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS);
		if (nr >= EM28XX_MAXBOARDS) {
			/* No free device slots */
			dev_err(&intf->dev,
				""Driver supports up to %i em28xx boards.\n"",
			       EM28XX_MAXBOARDS);
			retval = -ENOMEM;
			goto err_no_slot;
		}
	} while (test_and_set_bit(nr, em28xx_devused));

	/* Don't register audio interfaces */
	if (intf->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
		dev_info(&intf->dev,
			""audio device (%04x:%04x): interface %i, class %i\n"",
			le16_to_cpu(udev->descriptor.idVendor),
			le16_to_cpu(udev->descriptor.idProduct),
			ifnum,
			intf->altsetting[0].desc.bInterfaceClass);

		retval = -ENODEV;
		goto err;
	}

	/* allocate memory for our device state and initialize it */
	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev) {
		retval = -ENOMEM;
		goto err;
	}

	/* compute alternate max packet sizes */
	dev->alt_max_pkt_size_isoc = kcalloc(intf->num_altsetting,
					     sizeof(dev->alt_max_pkt_size_isoc[0]),
					     GFP_KERNEL);
	if (!dev->alt_max_pkt_size_isoc) {
		kfree(dev);
		retval = -ENOMEM;
		goto err;
	}

	/* Get endpoints */
	for (i = 0; i < intf->num_altsetting; i++) {
		int ep;

		for (ep = 0;
		     ep < intf->altsetting[i].desc.bNumEndpoints;
		     ep++)
			em28xx_check_usb_descriptor(dev, udev, intf,
						    i, ep,
						    &has_vendor_audio,
						    &has_video,
						    &has_dvb);
	}

	if (!(has_vendor_audio || has_video || has_dvb)) {
		retval = -ENODEV;
		goto err_free;
	}

	switch (udev->speed) {
	case USB_SPEED_LOW:
		speed = ""1.5"";
		break;
	case USB_SPEED_UNKNOWN:
	case USB_SPEED_FULL:
		speed = ""12"";
		break;
	case USB_SPEED_HIGH:
		speed = ""480"";
		break;
	default:
		speed = ""unknown"";
	}

	dev_info(&intf->dev,
		""New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\n"",
		udev->manufacturer ? udev->manufacturer : """",
		udev->product ? udev->product : """",
		speed,
		le16_to_cpu(udev->descriptor.idVendor),
		le16_to_cpu(udev->descriptor.idProduct),
		ifnum,
		intf->altsetting->desc.bInterfaceNumber);

	/*
	 * Make sure we have 480 Mbps of bandwidth, otherwise things like
	 * video stream wouldn't likely work, since 12 Mbps is generally
	 * not enough even for most Digital TV streams.
	 */
	if (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {
		dev_err(&intf->dev, ""Device initialization failed.\n"");
		dev_err(&intf->dev,
			""Device must be connected to a high-speed USB 2.0 port.\n"");
		retval = -ENODEV;
		goto err_free;
	}

	dev->devno = nr;
	dev->model = id->driver_info;
	dev->alt   = -1;
	dev->is_audio_only = has_vendor_audio && !(has_video || has_dvb);
	dev->has_video = has_video;
	dev->ifnum = ifnum;

	dev->ts = PRIMARY_TS;
	snprintf(dev->name, 28, ""em28xx"");
	dev->dev_next = NULL;

	if (has_vendor_audio) {
		dev_info(&intf->dev,
			""Audio interface %i found (Vendor Class)\n"", ifnum);
		dev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR;
	}
	/* Checks if audio is provided by a USB Audio Class intf */
	for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
		struct usb_interface *uif = udev->config->interface[i];

		if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
			if (has_vendor_audio)
				dev_err(&intf->dev,
					""em28xx: device seems to have vendor AND usb audio class interfaces !\n""
					""\t\tThe vendor interface will be ignored. Please contact the developers \n"");
			dev->usb_audio_type = EM28XX_USB_AUDIO_CLASS;
			break;
		}
	}

	if (has_video)
		dev_info(&intf->dev, ""Video interface %i found:%s%s\n"",
			ifnum,
			dev->analog_ep_bulk ? "" bulk"" : """",
			dev->analog_ep_isoc ? "" isoc"" : """");
	if (has_dvb)
		dev_info(&intf->dev, ""DVB interface %i found:%s%s\n"",
			ifnum,
			dev->dvb_ep_bulk ? "" bulk"" : """",
			dev->dvb_ep_isoc ? "" isoc"" : """");

	dev->num_alt = intf->num_altsetting;

	if ((unsigned int)card[nr] < em28xx_bcount)
		dev->model = card[nr];

	/* save our data pointer in this intf device */
	usb_set_intfdata(intf, dev);

	/* allocate device struct and check if the device is a webcam */
	mutex_init(&dev->lock);
	retval = em28xx_init_dev(dev, udev, intf, nr);
	if (retval)
		goto err_free;

	if (usb_xfer_mode < 0) {
		if (dev->is_webcam)
			try_bulk = 1;
		else
			try_bulk = 0;
	} else {
		try_bulk = usb_xfer_mode > 0;
	}

	/* Disable V4L2 if the device doesn't have a decoder or image sensor */
	if (has_video &&
	    dev->board.decoder == EM28XX_NODECODER &&
	    dev->em28xx_sensor == EM28XX_NOSENSOR) {
		dev_err(&intf->dev,
			""Currently, V4L2 is not supported on this model\n"");
		has_video = false;
		dev->has_video = false;
	}

	if (dev->board.has_dual_ts &&
	    (dev->tuner_type != TUNER_ABSENT || INPUT(0)->type)) {
		/*
		 * The logic with sets alternate is not ready for dual-tuners
		 * which analog modes.
		 */
		dev_err(&intf->dev,
			""We currently don't support analog TV or stream capture on dual tuners.\n"");
		has_video = false;
	}

	/* Select USB transfer types to use */
	if (has_video) {
		if (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk))
			dev->analog_xfer_bulk = 1;
		dev_info(&intf->dev, ""analog set to %s mode.\n"",
			dev->analog_xfer_bulk ? ""bulk"" : ""isoc"");
	}
	if (has_dvb) {
		if (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk))
			dev->dvb_xfer_bulk = 1;
		dev_info(&intf->dev, ""dvb set to %s mode.\n"",
			dev->dvb_xfer_bulk ? ""bulk"" : ""isoc"");
	}

	if (dev->board.has_dual_ts && em28xx_duplicate_dev(dev) == 0) {
		dev->dev_next->ts = SECONDARY_TS;
		dev->dev_next->alt   = -1;
		dev->dev_next->is_audio_only = has_vendor_audio &&
						!(has_video || has_dvb);
		dev->dev_next->has_video = false;
		dev->dev_next->ifnum = ifnum;
		dev->dev_next->model = id->driver_info;

		mutex_init(&dev->dev_next->lock);
		retval = em28xx_init_dev(dev->dev_next, udev, intf,
					 dev->dev_next->devno);
		if (retval)
			goto err_free;

		dev->dev_next->board.ir_codes = NULL; /* No IR for 2nd tuner */
		dev->dev_next->board.has_ir_i2c = 0; /* No IR for 2nd tuner */

		if (usb_xfer_mode < 0) {
			if (dev->dev_next->is_webcam)
				try_bulk = 1;
			else
				try_bulk = 0;
		} else {
			try_bulk = usb_xfer_mode > 0;
		}

		/* Select USB transfer types to use */
		if (has_dvb) {
			if (!dev->dvb_ep_isoc_ts2 ||
			    (try_bulk && dev->dvb_ep_bulk_ts2))
				dev->dev_next->dvb_xfer_bulk = 1;
			dev_info(&dev->intf->dev, ""dvb ts2 set to %s mode.\n"",
				 dev->dev_next->dvb_xfer_bulk ? ""bulk"" : ""isoc"");
		}

		dev->dev_next->dvb_ep_isoc = dev->dvb_ep_isoc_ts2;
		dev->dev_next->dvb_ep_bulk = dev->dvb_ep_bulk_ts2;
		dev->dev_next->dvb_max_pkt_size_isoc = dev->dvb_max_pkt_size_isoc_ts2;
		dev->dev_next->dvb_alt_isoc = dev->dvb_alt_isoc;

		/* Configure hardware to support TS2*/
		if (dev->dvb_xfer_bulk) {
			/* The ep4 and ep5 are configured for BULK */
			em28xx_write_reg(dev, 0x0b, 0x96);
			mdelay(100);
			em28xx_write_reg(dev, 0x0b, 0x80);
			mdelay(100);
		} else {
			/* The ep4 and ep5 are configured for ISO */
			em28xx_write_reg(dev, 0x0b, 0x96);
			mdelay(100);
			em28xx_write_reg(dev, 0x0b, 0x82);
			mdelay(100);
		}

		kref_init(&dev->dev_next->ref);
	}

	kref_init(&dev->ref);

	request_modules(dev);

	/*
	 * Do it at the end, to reduce dynamic configuration changes during
	 * the device init. Yet, as request_modules() can be async, the
	 * topology will likely change after the load of the em28xx subdrivers.
	 */
#ifdef CONFIG_MEDIA_CONTROLLER
	retval = media_device_register(dev->media_dev);
#endif

	return 0;

err_free:
	kfree(dev->alt_max_pkt_size_isoc);
	kfree(dev);

err:
	clear_bit(nr, em28xx_devused);

err_no_slot:
	usb_put_dev(udev);
	return retval;
}",CWE-416,10
1,"get_visual_text(
    cmdarg_T	*cap,
    char_u	**pp,	    // return: start of selected text
    int		*lenp)	    // return: length of selected text
{
    if (VIsual_mode != 'V')
	unadjust_for_sel();
    if (VIsual.lnum != curwin->w_cursor.lnum)
    {
	if (cap != NULL)
	    clearopbeep(cap->oap);
	return FAIL;
    }
    if (VIsual_mode == 'V')
    {
	*pp = ml_get_curline();
	*lenp = (int)STRLEN(*pp);
    }
    else
    {
	if (LT_POS(curwin->w_cursor, VIsual))
	{
	    *pp = ml_get_pos(&curwin->w_cursor);
	    *lenp = VIsual.col - curwin->w_cursor.col + 1;
	}
	else
	{
	    *pp = ml_get_pos(&VIsual);
	    *lenp = curwin->w_cursor.col - VIsual.col + 1;
	}
	if (**pp == NUL)
	    *lenp = 0;
	if (has_mbyte && *lenp > 0)
	    // Correct the length to include all bytes of the last character.
	    *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
    }
    reset_VIsual_and_resel();
    return OK;
}",CWE-787,16
1,"_fr_window_ask_overwrite_dialog (OverwriteData *odata)
{
	if ((odata->edata->overwrite == FR_OVERWRITE_ASK) && (odata->current_file != NULL)) {
		const char *base_name;
		GFile      *destination;

		base_name = _g_path_get_relative_basename ((char *) odata->current_file->data, odata->edata->base_dir, odata->edata->junk_paths);
		destination = g_file_get_child (odata->edata->destination, base_name);
		g_file_query_info_async (destination,
					 G_FILE_ATTRIBUTE_STANDARD_TYPE "","" G_FILE_ATTRIBUTE_STANDARD_NAME "","" G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
					 G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
					 G_PRIORITY_DEFAULT,
					 odata->window->priv->cancellable,
					 query_info_ready_for_overwrite_dialog_cb,
					 odata);

		g_object_unref (destination);

		return;
	}

	if (odata->edata->file_list != NULL) {
		/* speed optimization: passing NULL when extracting all the
		 * files is faster if the command supports the
		 * propCanExtractAll property. */
		if (odata->extract_all) {
			_g_string_list_free (odata->edata->file_list);
			odata->edata->file_list = NULL;
		}
		odata->edata->overwrite = FR_OVERWRITE_YES;
		_fr_window_archive_extract_from_edata (odata->window, odata->edata);
	}
	else {
		GtkWidget *d;

		d = _gtk_message_dialog_new (GTK_WINDOW (odata->window),
					     0,
					     GTK_STOCK_DIALOG_WARNING,
					     _(""Extraction not performed""),
					     NULL,
					     GTK_STOCK_OK, GTK_RESPONSE_OK,
					     NULL);
		gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK);
		fr_window_show_error_dialog (odata->window, d, GTK_WINDOW (odata->window), _(""Extraction not performed""));

		fr_window_stop_batch (odata->window);
	}

	g_free (odata);
}",CWE-22,5
0,"  virtual void EnableEthernetNetworkDevice(bool enable) {
    EnableNetworkDeviceType(TYPE_ETHERNET, enable);
  }
",none,24
0,"    NetworkObserverList(NetworkLibraryImpl* library,
                        const std::string& service_path) {
      network_monitor_ = MonitorNetworkService(&NetworkStatusChangedHandler,
                                               service_path.c_str(),
                                               library);
    }
",none,24
0,"  bool db_disabled() const { return db_disabled_; }
",none,24
1,"static int bgp_capability_msg_parse(struct peer *peer, uint8_t *pnt,
				    bgp_size_t length)
{
	uint8_t *end;
	struct capability_mp_data mpc;
	struct capability_header *hdr;
	uint8_t action;
	iana_afi_t pkt_afi;
	afi_t afi;
	iana_safi_t pkt_safi;
	safi_t safi;

	end = pnt + length;

	while (pnt < end) {
		/* We need at least action, capability code and capability
		 * length. */
		if (pnt + 3 > end) {
			zlog_info(""%s Capability length error"", peer->host);
			bgp_notify_send(peer, BGP_NOTIFY_CEASE,
					BGP_NOTIFY_SUBCODE_UNSPECIFIC);
			return BGP_Stop;
		}
		action = *pnt;
		hdr = (struct capability_header *)(pnt + 1);

		/* Action value check.  */
		if (action != CAPABILITY_ACTION_SET
		    && action != CAPABILITY_ACTION_UNSET) {
			zlog_info(""%s Capability Action Value error %d"",
				  peer->host, action);
			bgp_notify_send(peer, BGP_NOTIFY_CEASE,
					BGP_NOTIFY_SUBCODE_UNSPECIFIC);
			return BGP_Stop;
		}

		if (bgp_debug_neighbor_events(peer))
			zlog_debug(
				""%s CAPABILITY has action: %d, code: %u, length %u"",
				peer->host, action, hdr->code, hdr->length);

		/* Capability length check. */
		if ((pnt + hdr->length + 3) > end) {
			zlog_info(""%s Capability length error"", peer->host);
			bgp_notify_send(peer, BGP_NOTIFY_CEASE,
					BGP_NOTIFY_SUBCODE_UNSPECIFIC);
			return BGP_Stop;
		}

		/* Fetch structure to the byte stream. */
		memcpy(&mpc, pnt + 3, sizeof(struct capability_mp_data));
		pnt += hdr->length + 3;

		/* We know MP Capability Code. */
		if (hdr->code == CAPABILITY_CODE_MP) {
			pkt_afi = ntohs(mpc.afi);
			pkt_safi = mpc.safi;

			/* Ignore capability when override-capability is set. */
			if (CHECK_FLAG(peer->flags,
				       PEER_FLAG_OVERRIDE_CAPABILITY))
				continue;

			/* Convert AFI, SAFI to internal values. */
			if (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi,
						      &safi)) {
				if (bgp_debug_neighbor_events(peer))
					zlog_debug(
						""%s Dynamic Capability MP_EXT afi/safi invalid (%s/%s)"",
						peer->host,
						iana_afi2str(pkt_afi),
						iana_safi2str(pkt_safi));
				continue;
			}

			/* Address family check.  */
			if (bgp_debug_neighbor_events(peer))
				zlog_debug(
					""%s CAPABILITY has %s MP_EXT CAP for afi/safi: %s/%s"",
					peer->host,
					action == CAPABILITY_ACTION_SET
						? ""Advertising""
						: ""Removing"",
					iana_afi2str(pkt_afi),
					iana_safi2str(pkt_safi));

			if (action == CAPABILITY_ACTION_SET) {
				peer->afc_recv[afi][safi] = 1;
				if (peer->afc[afi][safi]) {
					peer->afc_nego[afi][safi] = 1;
					bgp_announce_route(peer, afi, safi,
							   false);
				}
			} else {
				peer->afc_recv[afi][safi] = 0;
				peer->afc_nego[afi][safi] = 0;

				if (peer_active_nego(peer))
					bgp_clear_route(peer, afi, safi);
				else
					return BGP_Stop;
			}
		} else {
			flog_warn(
				EC_BGP_UNRECOGNIZED_CAPABILITY,
				""%s unrecognized capability code: %d - ignored"",
				peer->host, hdr->code);
		}
	}

	/* No FSM action necessary */
	return BGP_PACKET_NOOP;
}",CWE-125,1
0,"  virtual void RemoveCellularDataPlanObserver(
      CellularDataPlanObserver* observer) {}
",none,24
0,"  void CheckCompleted() {
    if (--waiting_callbacks_ <= 0) {
      DispatchCallbacks();
      DCHECK(callbacks_.empty());
      DCHECK(unlimited_callbacks_.empty());

      UsageAndQuotaDispatcherTaskMap& dispatcher_map =
          manager()->usage_and_quota_dispatchers_;
      DCHECK(dispatcher_map.find(std::make_pair(host_, type_)) !=
             dispatcher_map.end());
      dispatcher_map.erase(std::make_pair(host_, type_));
      CallCompleted();
    }
  }
",none,24
0,"  void DeleteOriginData(const GURL& origin,
                        StorageType type) {
    quota_status_ = kQuotaStatusUnknown;
    quota_manager_->DeleteOriginData(origin, type,
        callback_factory_.NewCallback(
            &QuotaManagerTest::StatusCallback));
  }
",none,24
0,"void QuotaManager::DidGetDatabaseLRUOrigin(const GURL& origin) {
  if (origins_in_use_.find(origin) != origins_in_use_.end() ||
      access_notified_origins_.find(origin) != access_notified_origins_.end())
    lru_origin_callback_->Run(GURL());
  else
    lru_origin_callback_->Run(origin);
  access_notified_origins_.clear();
  lru_origin_callback_.reset();
}
",none,24
0,"  virtual bool ethernet_enabled() const { return true; }
",none,24
0,"CellularNetwork::~CellularNetwork() {
}
",none,24
0,"  void DidGetHostUsage(const std::string& host,
                       StorageType type,
                       int64 usage) {
    DCHECK_EQ(host_, host);
    DCHECK_EQ(type_, type);
    host_usage_ = usage;
    CheckCompleted();
  }
",none,24
0,"  DumpOriginInfoTableTask(
      QuotaManager* manager,
      Callback* callback)
      : DatabaseTaskBase(manager),
        callback_(callback) {
  }
",none,24
1,"ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
{
    linenr_T	count;
    char_u	*p;

    count = line2 - line1 + 1;
    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
    {
	curbuf->b_op_start.lnum = n + 1;
	curbuf->b_op_end.lnum = n + count;
	curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
    }

    /*
     * there are three situations:
     * 1. destination is above line1
     * 2. destination is between line1 and line2
     * 3. destination is below line2
     *
     * n = destination (when starting)
     * curwin->w_cursor.lnum = destination (while copying)
     * line1 = start of source (while copying)
     * line2 = end of source (while copying)
     */
    if (u_save(n, n + 1) == FAIL)
	return;

    curwin->w_cursor.lnum = n;
    while (line1 <= line2)
    {
	// need to use vim_strsave() because the line will be unlocked within
	// ml_append()
	p = vim_strsave(ml_get(line1));
	if (p != NULL)
	{
	    ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
	    vim_free(p);
	}
	// situation 2: skip already copied lines
	if (line1 == n)
	    line1 = curwin->w_cursor.lnum;
	++line1;
	if (curwin->w_cursor.lnum < line1)
	    ++line1;
	if (curwin->w_cursor.lnum < line2)
	    ++line2;
	++curwin->w_cursor.lnum;
    }

    appended_lines_mark(n, count);

    msgmore((long)count);
}",CWE-787,16
1,"static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
{
	struct sock *sk = sock->sk;
	struct net *net = sock_net(sk);
	struct tipc_sock *tsk = tipc_sk(sk);
	struct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name;
	long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
	struct list_head *clinks = &tsk->cong_links;
	bool syn = !tipc_sk_type_connectionless(sk);
	struct tipc_group *grp = tsk->group;
	struct tipc_msg *hdr = &tsk->phdr;
	struct tipc_socket_addr skaddr;
	struct sk_buff_head pkts;
	int atype, mtu, rc;

	if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
		return -EMSGSIZE;

	if (ua) {
		if (!tipc_uaddr_valid(ua, m->msg_namelen))
			return -EINVAL;
		atype = ua->addrtype;
	}

	/* If socket belongs to a communication group follow other paths */
	if (grp) {
		if (!ua)
			return tipc_send_group_bcast(sock, m, dlen, timeout);
		if (atype == TIPC_SERVICE_ADDR)
			return tipc_send_group_anycast(sock, m, dlen, timeout);
		if (atype == TIPC_SOCKET_ADDR)
			return tipc_send_group_unicast(sock, m, dlen, timeout);
		if (atype == TIPC_SERVICE_RANGE)
			return tipc_send_group_mcast(sock, m, dlen, timeout);
		return -EINVAL;
	}

	if (!ua) {
		ua = (struct tipc_uaddr *)&tsk->peer;
		if (!syn && ua->family != AF_TIPC)
			return -EDESTADDRREQ;
		atype = ua->addrtype;
	}

	if (unlikely(syn)) {
		if (sk->sk_state == TIPC_LISTEN)
			return -EPIPE;
		if (sk->sk_state != TIPC_OPEN)
			return -EISCONN;
		if (tsk->published)
			return -EOPNOTSUPP;
		if (atype == TIPC_SERVICE_ADDR)
			tsk->conn_addrtype = atype;
		msg_set_syn(hdr, 1);
	}

	/* Determine destination */
	if (atype == TIPC_SERVICE_RANGE) {
		return tipc_sendmcast(sock, ua, m, dlen, timeout);
	} else if (atype == TIPC_SERVICE_ADDR) {
		skaddr.node = ua->lookup_node;
		ua->scope = tipc_node2scope(skaddr.node);
		if (!tipc_nametbl_lookup_anycast(net, ua, &skaddr))
			return -EHOSTUNREACH;
	} else if (atype == TIPC_SOCKET_ADDR) {
		skaddr = ua->sk;
	} else {
		return -EINVAL;
	}

	/* Block or return if destination link is congested */
	rc = tipc_wait_for_cond(sock, &timeout,
				!tipc_dest_find(clinks, skaddr.node, 0));
	if (unlikely(rc))
		return rc;

	/* Finally build message header */
	msg_set_destnode(hdr, skaddr.node);
	msg_set_destport(hdr, skaddr.ref);
	if (atype == TIPC_SERVICE_ADDR) {
		msg_set_type(hdr, TIPC_NAMED_MSG);
		msg_set_hdr_sz(hdr, NAMED_H_SIZE);
		msg_set_nametype(hdr, ua->sa.type);
		msg_set_nameinst(hdr, ua->sa.instance);
		msg_set_lookup_scope(hdr, ua->scope);
	} else { /* TIPC_SOCKET_ADDR */
		msg_set_type(hdr, TIPC_DIRECT_MSG);
		msg_set_lookup_scope(hdr, 0);
		msg_set_hdr_sz(hdr, BASIC_H_SIZE);
	}

	/* Add message body */
	__skb_queue_head_init(&pkts);
	mtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true);
	rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
	if (unlikely(rc != dlen))
		return rc;
	if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {
		__skb_queue_purge(&pkts);
		return -ENOMEM;
	}

	/* Send message */
	trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, "" "");
	rc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid);
	if (unlikely(rc == -ELINKCONG)) {
		tipc_dest_push(clinks, skaddr.node, 0);
		tsk->cong_link_cnt++;
		rc = 0;
	}

	if (unlikely(syn && !rc)) {
		tipc_set_sk_state(sk, TIPC_CONNECTING);
		if (dlen && timeout) {
			timeout = msecs_to_jiffies(timeout);
			tipc_wait_for_connect(sock, &timeout);
		}
	}

	return rc ? rc : dlen;
}",CWE-200,4
1,"MOBI_RET mobi_decode_infl(unsigned char *decoded, int *decoded_size, const unsigned char *rule) {
    int pos = *decoded_size;
    char mod = 'i';
    char dir = '<';
    char olddir;
    unsigned char c;
    while ((c = *rule++)) {
        if (c <= 4) {
            mod = (c <= 2) ? 'i' : 'd'; /* insert, delete */
            olddir = dir;
            dir = (c & 2) ? '<' : '>'; /* left, right */
            if (olddir != dir && olddir) {
                pos = (c & 2) ? *decoded_size : 0;
            }
        }
        else if (c > 10 && c < 20) {
            if (dir == '>') {
                pos = *decoded_size;
            }
            pos -= c - 10;
            dir = 0;
            if (pos < 0 || pos > *decoded_size) {
                debug_print(""Position setting failed (%s)\n"", decoded);
                return MOBI_DATA_CORRUPT;
            }
        }
        else {
            if (mod == 'i') {
                const unsigned char *s = decoded + pos;
                unsigned char *d = decoded + pos + 1;
                const int l = *decoded_size - pos;
                if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {
                    debug_print(""Out of buffer in %s at pos: %i\n"", decoded, pos);
                    return MOBI_DATA_CORRUPT;
                }
                memmove(d, s, (size_t) l);
                decoded[pos] = c;
                (*decoded_size)++;
                if (dir == '>') { pos++; }
            } else {
                if (dir == '<') { pos--; }
                const unsigned char *s = decoded + pos + 1;
                unsigned char *d = decoded + pos;
                const int l = *decoded_size - pos;
                if (l < 0 || d + l > decoded + INDX_INFLBUF_SIZEMAX) {
                    debug_print(""Out of buffer in %s at pos: %i\n"", decoded, pos);
                    return MOBI_DATA_CORRUPT;
                }
                if (decoded[pos] != c) {
                    debug_print(""Character mismatch in %s at pos: %i (%c != %c)\n"", decoded, pos, decoded[pos], c);
                    return MOBI_DATA_CORRUPT;
                }
                memmove(d, s, (size_t) l);
                (*decoded_size)--;
            }
        }
    }
    return MOBI_SUCCESS;
}",CWE-787,16
1,"static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
	unsigned int u = 0;
	LineContribType *res;
	int overflow_error = 0;

	res = (LineContribType *) gdMalloc(sizeof(LineContribType));
	if (!res) {
		return NULL;
	}
	res->WindowSize = windows_size;
	res->LineLength = line_length;
	if (overflow2(line_length, sizeof(ContributionType))) {
		gdFree(res);
		return NULL;
	}
	res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
	if (res->ContribRow == NULL) {
		gdFree(res);
		return NULL;
	}
	for (u = 0 ; u < line_length ; u++) {
		if (overflow2(windows_size, sizeof(double))) {
			overflow_error = 1;
		} else {
			res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
		}
		if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {
			u--;
			while (u >= 0) {
				gdFree(res->ContribRow[u].Weights);
				u--;
			}
			return NULL;
		}
	}
	return res;
}",CWE-119,0
0,"  virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path,
                                             std::string* hardware_address) {
    hardware_address->clear();
    return NetworkIPConfigVector();
  }
",none,24
1,"static int FNAME(cmpxchg_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
			       pt_element_t __user *ptep_user, unsigned index,
			       pt_element_t orig_pte, pt_element_t new_pte)
{
	int npages;
	pt_element_t ret;
	pt_element_t *table;
	struct page *page;

	npages = get_user_pages_fast((unsigned long)ptep_user, 1, FOLL_WRITE, &page);
	if (likely(npages == 1)) {
		table = kmap_atomic(page);
		ret = CMPXCHG(&table[index], orig_pte, new_pte);
		kunmap_atomic(table);

		kvm_release_page_dirty(page);
	} else {
		struct vm_area_struct *vma;
		unsigned long vaddr = (unsigned long)ptep_user & PAGE_MASK;
		unsigned long pfn;
		unsigned long paddr;

		mmap_read_lock(current->mm);
		vma = find_vma_intersection(current->mm, vaddr, vaddr + PAGE_SIZE);
		if (!vma || !(vma->vm_flags & VM_PFNMAP)) {
			mmap_read_unlock(current->mm);
			return -EFAULT;
		}
		pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
		paddr = pfn << PAGE_SHIFT;
		table = memremap(paddr, PAGE_SIZE, MEMREMAP_WB);
		if (!table) {
			mmap_read_unlock(current->mm);
			return -EFAULT;
		}
		ret = CMPXCHG(&table[index], orig_pte, new_pte);
		memunmap(table);
		mmap_read_unlock(current->mm);
	}

	return (ret != orig_pte);
}",CWE-416,10
0,"   void GetUsageAndQuota(const GURL& origin, StorageType type) {
     quota_status_ = kQuotaStatusUnknown;
     usage_ = -1;
    quota_ = -1;
    quota_manager_->GetUsageAndQuota(origin, type,
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetUsageAndQuota));
  }
",none,24
1,"expand_case_fold_string(Node* node, regex_t* reg)
{
#define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION  8

  int r, n, len, alt_num;
  UChar *start, *end, *p;
  Node *top_root, *root, *snode, *prev_node;
  OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM];
  StrNode* sn = STR_(node);

  if (NODE_STRING_IS_AMBIG(node)) return 0;

  start = sn->s;
  end   = sn->end;
  if (start >= end) return 0;

  r = 0;
  top_root = root = prev_node = snode = NULL_NODE;
  alt_num = 1;
  p = start;
  while (p < end) {
    n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end,
                                           items);
    if (n < 0) {
      r = n;
      goto err;
    }

    len = enclen(reg->enc, p);

    if (n == 0) {
      if (IS_NULL(snode)) {
        if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {
          top_root = root = onig_node_list_add(NULL_NODE, prev_node);
          if (IS_NULL(root)) {
            onig_node_free(prev_node);
            goto mem_err;
          }
        }

        prev_node = snode = onig_node_new_str(NULL, NULL);
        if (IS_NULL(snode)) goto mem_err;
        if (IS_NOT_NULL(root)) {
          if (IS_NULL(onig_node_list_add(root, snode))) {
            onig_node_free(snode);
            goto mem_err;
          }
        }
      }

      r = onig_node_str_cat(snode, p, p + len);
      if (r != 0) goto err;
    }
    else {
      alt_num *= (n + 1);
      if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break;

      if (IS_NULL(root) && IS_NOT_NULL(prev_node)) {
        top_root = root = onig_node_list_add(NULL_NODE, prev_node);
        if (IS_NULL(root)) {
          onig_node_free(prev_node);
          goto mem_err;
        }
      }

      r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node);
      if (r < 0) goto mem_err;
      if (r == 1) {
        if (IS_NULL(root)) {
          top_root = prev_node;
        }
        else {
          if (IS_NULL(onig_node_list_add(root, prev_node))) {
            onig_node_free(prev_node);
            goto mem_err;
          }
        }

        root = NODE_CAR(prev_node);
      }
      else { /* r == 0 */
        if (IS_NOT_NULL(root)) {
          if (IS_NULL(onig_node_list_add(root, prev_node))) {
            onig_node_free(prev_node);
            goto mem_err;
          }
        }
      }

      snode = NULL_NODE;
    }

    p += len;
  }

  if (p < end) {
    Node *srem;

    r = expand_case_fold_make_rem_string(&srem, p, end, reg);
    if (r != 0) goto mem_err;

    if (IS_NOT_NULL(prev_node) && IS_NULL(root)) {
      top_root = root = onig_node_list_add(NULL_NODE, prev_node);
      if (IS_NULL(root)) {
        onig_node_free(srem);
        onig_node_free(prev_node);
        goto mem_err;
      }
    }

    if (IS_NULL(root)) {
      prev_node = srem;
    }
    else {
      if (IS_NULL(onig_node_list_add(root, srem))) {
        onig_node_free(srem);
        goto mem_err;
      }
    }
  }

  /* ending */
  top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node);
  swap_node(node, top_root);
  onig_node_free(top_root);
  return 0;

 mem_err:
  r = ONIGERR_MEMORY;

 err:
  onig_node_free(top_root);
  return r;
}",CWE-125,1
1,"display_dollar(colnr_T col)
{
    colnr_T save_col;

    if (!redrawing())
	return;

    cursor_off();
    save_col = curwin->w_cursor.col;
    curwin->w_cursor.col = col;
    if (has_mbyte)
    {
	char_u *p;

	// If on the last byte of a multi-byte move to the first byte.
	p = ml_get_curline();
	curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
    }
    curs_columns(FALSE);	    // recompute w_wrow and w_wcol
    if (curwin->w_wcol < curwin->w_width)
    {
	edit_putchar('$', FALSE);
	dollar_vcol = curwin->w_virtcol;
    }
    curwin->w_cursor.col = save_col;
}",CWE-787,16
1,"GF_Err afra_box_read(GF_Box *s, GF_BitStream *bs)
{
	unsigned int i;
	GF_AdobeFragRandomAccessBox *ptr = (GF_AdobeFragRandomAccessBox *)s;

	ISOM_DECREASE_SIZE(ptr, 9)
	ptr->long_ids = gf_bs_read_int(bs, 1);
	ptr->long_offsets = gf_bs_read_int(bs, 1);
	ptr->global_entries = gf_bs_read_int(bs, 1);
	ptr->reserved = gf_bs_read_int(bs, 5);
	ptr->time_scale = gf_bs_read_u32(bs);

	ptr->entry_count = gf_bs_read_u32(bs);
	if (ptr->size / ( (ptr->long_offsets ? 16 : 12) ) < ptr->entry_count)
		return GF_ISOM_INVALID_FILE;

	for (i=0; ientry_count; i++) {
		GF_AfraEntry *ae = gf_malloc(sizeof(GF_AfraEntry));
		if (!ae) return GF_OUT_OF_MEM;

		ISOM_DECREASE_SIZE(ptr, 8)
		ae->time = gf_bs_read_u64(bs);
		if (ptr->long_offsets) {
			ISOM_DECREASE_SIZE(ptr, 8)
			ae->offset = gf_bs_read_u64(bs);
		} else {
			ISOM_DECREASE_SIZE(ptr, 4)
			ae->offset = gf_bs_read_u32(bs);
		}

		gf_list_insert(ptr->local_access_entries, ae, i);
	}

	if (ptr->global_entries) {
		ISOM_DECREASE_SIZE(ptr, 4)
		ptr->global_entry_count = gf_bs_read_u32(bs);
		for (i=0; iglobal_entry_count; i++) {
			GF_GlobalAfraEntry *ae = gf_malloc(sizeof(GF_GlobalAfraEntry));
			if (!ae) return GF_OUT_OF_MEM;
			ISOM_DECREASE_SIZE(ptr, 8)
			ae->time = gf_bs_read_u64(bs);
			if (ptr->long_ids) {
				ISOM_DECREASE_SIZE(ptr, 8)
				ae->segment = gf_bs_read_u32(bs);
				ae->fragment = gf_bs_read_u32(bs);
			} else {
				ISOM_DECREASE_SIZE(ptr, 4)
				ae->segment = gf_bs_read_u16(bs);
				ae->fragment = gf_bs_read_u16(bs);
			}
			if (ptr->long_offsets) {
				ISOM_DECREASE_SIZE(ptr, 16)
				ae->afra_offset = gf_bs_read_u64(bs);
				ae->offset_from_afra = gf_bs_read_u64(bs);
			} else {
				ISOM_DECREASE_SIZE(ptr, 8)
				ae->afra_offset = gf_bs_read_u32(bs);
				ae->offset_from_afra = gf_bs_read_u32(bs);
			}

			gf_list_insert(ptr->global_access_entries, ae, i);
		}
	}

	return GF_OK;
}",CWE-787,16
0,"std::string CellularNetwork::GetActivationStateString() const {
  return ActivationStateToString(this->activation_state_);
}
",none,24
1,"DeepTiledInputFile::initialize ()
{
    if (_data->partNumber == -1)
        if (_data->header.type() != DEEPTILE)
            throw IEX_NAMESPACE::ArgExc (""Expected a deep tiled file but the file is not deep tiled."");
   if(_data->header.version()!=1)
   {
       THROW(IEX_NAMESPACE::ArgExc, ""Version "" << _data->header.version() << "" not supported for deeptiled images in this version of the library"");
   }
        
    _data->header.sanityCheck (true);

    //
    // before allocating memory for tile offsets, confirm file is large enough
    // to contain tile offset table
    // (for multipart files, the chunk offset table has already been read)
    //
    if (!isMultiPart(_data->version))
    {
        _data->validateStreamSize();
    }


    _data->tileDesc = _data->header.tileDescription();
    _data->lineOrder = _data->header.lineOrder();

    //
    // Save the dataWindow information
    //

    const Box2i &dataWindow = _data->header.dataWindow();
    _data->minX = dataWindow.min.x;
    _data->maxX = dataWindow.max.x;
    _data->minY = dataWindow.min.y;
    _data->maxY = dataWindow.max.y;

    //
    // Precompute level and tile information to speed up utility functions
    //

    precalculateTileInfo (_data->tileDesc,
                          _data->minX, _data->maxX,
                          _data->minY, _data->maxY,
                          _data->numXTiles, _data->numYTiles,
                          _data->numXLevels, _data->numYLevels);

    //
    // Create all the TileBuffers and allocate their internal buffers
    //

    _data->tileOffsets = TileOffsets (_data->tileDesc.mode,
                                      _data->numXLevels,
                                      _data->numYLevels,
                                      _data->numXTiles,
                                      _data->numYTiles);

    for (size_t i = 0; i < _data->tileBuffers.size(); i++)
        _data->tileBuffers[i] = new TileBuffer ();

    _data->maxSampleCountTableSize = _data->tileDesc.ySize *
                                     _data->tileDesc.xSize *
                                     sizeof(int);

    _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize);

    _data->sampleCountTableComp = newCompressor(_data->header.compression(),
                                                _data->maxSampleCountTableSize,
                                                _data->header);
                                                
                                                
    const ChannelList & c=_data->header.channels();
    _data->combinedSampleSize=0;
    for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++)
    {
        switch( i.channel().type )
        {
            case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF  :
                _data->combinedSampleSize+=Xdr::size();
                break;
            case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
                _data->combinedSampleSize+=Xdr::size();
                break;
            case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT  :
                _data->combinedSampleSize+=Xdr::size();
                break;
            default :
                THROW(IEX_NAMESPACE::ArgExc, ""Bad type for channel "" << i.name() << "" initializing deepscanline reader"");
        }
    }
                                                  
}",CWE-125,1
1,"get_lisp_indent(void)
{
    pos_T	*pos, realpos, paren;
    int		amount;
    char_u	*that;
    colnr_T	col;
    colnr_T	firsttry;
    int		parencount, quotecount;
    int		vi_lisp;

    // Set vi_lisp to use the vi-compatible method
    vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);

    realpos = curwin->w_cursor;
    curwin->w_cursor.col = 0;

    if ((pos = findmatch(NULL, '(')) == NULL)
	pos = findmatch(NULL, '[');
    else
    {
	paren = *pos;
	pos = findmatch(NULL, '[');
	if (pos == NULL || LT_POSP(pos, &paren))
	    pos = &paren;
    }
    if (pos != NULL)
    {
	// Extra trick: Take the indent of the first previous non-white
	// line that is at the same () level.
	amount = -1;
	parencount = 0;

	while (--curwin->w_cursor.lnum >= pos->lnum)
	{
	    if (linewhite(curwin->w_cursor.lnum))
		continue;
	    for (that = ml_get_curline(); *that != NUL; ++that)
	    {
		if (*that == ';')
		{
		    while (*(that + 1) != NUL)
			++that;
		    continue;
		}
		if (*that == '\\')
		{
		    if (*(that + 1) != NUL)
			++that;
		    continue;
		}
		if (*that == '""' && *(that + 1) != NUL)
		{
		    while (*++that && *that != '""')
		    {
			// skipping escaped characters in the string
			if (*that == '\\')
			{
			    if (*++that == NUL)
				break;
			    if (that[1] == NUL)
			    {
				++that;
				break;
			    }
			}
		    }
		    if (*that == NUL)
			break;
		}
		if (*that == '(' || *that == '[')
		    ++parencount;
		else if (*that == ')' || *that == ']')
		    --parencount;
	    }
	    if (parencount == 0)
	    {
		amount = get_indent();
		break;
	    }
	}

	if (amount == -1)
	{
	    curwin->w_cursor.lnum = pos->lnum;
	    curwin->w_cursor.col = pos->col;
	    col = pos->col;

	    that = ml_get_curline();

	    if (vi_lisp && get_indent() == 0)
		amount = 2;
	    else
	    {
		char_u *line = that;

		amount = 0;
		while (*that && col)
		{
		    amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);
		    col--;
		}

		// Some keywords require ""body"" indenting rules (the
		// non-standard-lisp ones are Scheme special forms):
		//
		// (let ((a 1))    instead    (let ((a 1))
		//   (...))	      of	   (...))

		if (!vi_lisp && (*that == '(' || *that == '[')
						      && lisp_match(that + 1))
		    amount += 2;
		else
		{
		    that++;
		    amount++;
		    firsttry = amount;

		    while (VIM_ISWHITE(*that))
		    {
			amount += lbr_chartabsize(line, that, (colnr_T)amount);
			++that;
		    }

		    if (*that && *that != ';') // not a comment line
		    {
			// test *that != '(' to accommodate first let/do
			// argument if it is more than one line
			if (!vi_lisp && *that != '(' && *that != '[')
			    firsttry++;

			parencount = 0;
			quotecount = 0;

			if (vi_lisp
				|| (*that != '""'
				    && *that != '\''
				    && *that != '#'
				    && (*that < '0' || *that > '9')))
			{
			    while (*that
				    && (!VIM_ISWHITE(*that)
					|| quotecount
					|| parencount)
				    && (!((*that == '(' || *that == '[')
					    && !quotecount
					    && !parencount
					    && vi_lisp)))
			    {
				if (*that == '""')
				    quotecount = !quotecount;
				if ((*that == '(' || *that == '[')
							       && !quotecount)
				    ++parencount;
				if ((*that == ')' || *that == ']')
							       && !quotecount)
				    --parencount;
				if (*that == '\\' && *(that+1) != NUL)
				    amount += lbr_chartabsize_adv(
						line, &that, (colnr_T)amount);
				amount += lbr_chartabsize_adv(
						line, &that, (colnr_T)amount);
			    }
			}
			while (VIM_ISWHITE(*that))
			{
			    amount += lbr_chartabsize(
						 line, that, (colnr_T)amount);
			    that++;
			}
			if (!*that || *that == ';')
			    amount = firsttry;
		    }
		}
	    }
	}
    }
    else
	amount = 0;	// no matching '(' or '[' found, use zero indent

    curwin->w_cursor = realpos;

    return amount;
}",CWE-125,1
0,"  virtual bool wifi_enabled() const {
    return enabled_devices_ & (1 << TYPE_WIFI);
  }
",none,24
0,"  void GetGlobalUsage(StorageType type) {
    type_ = kStorageTypeUnknown;
    usage_ = -1;
    unlimited_usage_ = -1;
    quota_manager_->GetGlobalUsage(type,
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetGlobalUsage));
  }
",none,24
1,"int ZEXPORT inflate(strm, flush)
z_streamp strm;
int flush;
{
    struct inflate_state FAR *state;
    z_const unsigned char FAR *next;    /* next input */
    unsigned char FAR *put;     /* next output */
    unsigned have, left;        /* available input and output */
    unsigned long hold;         /* bit buffer */
    unsigned bits;              /* bits in bit buffer */
    unsigned in, out;           /* save starting available input and output */
    unsigned copy;              /* number of stored or match bytes to copy */
    unsigned char FAR *from;    /* where to copy match bytes from */
    code here;                  /* current decoding table entry */
    code last;                  /* parent table entry */
    unsigned len;               /* length to copy for repeats, bits to drop */
    int ret;                    /* return code */
#ifdef GUNZIP
    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
#endif
    static const unsigned short order[19] = /* permutation of code lengths */
        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};

    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
        (strm->next_in == Z_NULL && strm->avail_in != 0))
        return Z_STREAM_ERROR;

    state = (struct inflate_state FAR *)strm->state;
    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
    LOAD();
    in = have;
    out = left;
    ret = Z_OK;
    for (;;)
        switch (state->mode) {
        case HEAD:
            if (state->wrap == 0) {
                state->mode = TYPEDO;
                break;
            }
            NEEDBITS(16);
#ifdef GUNZIP
            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
                if (state->wbits == 0)
                    state->wbits = 15;
                state->check = crc32(0L, Z_NULL, 0);
                CRC2(state->check, hold);
                INITBITS();
                state->mode = FLAGS;
                break;
            }
            if (state->head != Z_NULL)
                state->head->done = -1;
            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
#else
            if (
#endif
                ((BITS(8) << 8) + (hold >> 8)) % 31) {
                strm->msg = (char *)""incorrect header check"";
                state->mode = BAD;
                break;
            }
            if (BITS(4) != Z_DEFLATED) {
                strm->msg = (char *)""unknown compression method"";
                state->mode = BAD;
                break;
            }
            DROPBITS(4);
            len = BITS(4) + 8;
            if (state->wbits == 0)
                state->wbits = len;
            if (len > 15 || len > state->wbits) {
                strm->msg = (char *)""invalid window size"";
                state->mode = BAD;
                break;
            }
            state->dmax = 1U << len;
            state->flags = 0;               /* indicate zlib header */
            Tracev((stderr, ""inflate:   zlib header ok\n""));
            strm->adler = state->check = adler32(0L, Z_NULL, 0);
            state->mode = hold & 0x200 ? DICTID : TYPE;
            INITBITS();
            break;
#ifdef GUNZIP
        case FLAGS:
            NEEDBITS(16);
            state->flags = (int)(hold);
            if ((state->flags & 0xff) != Z_DEFLATED) {
                strm->msg = (char *)""unknown compression method"";
                state->mode = BAD;
                break;
            }
            if (state->flags & 0xe000) {
                strm->msg = (char *)""unknown header flags set"";
                state->mode = BAD;
                break;
            }
            if (state->head != Z_NULL)
                state->head->text = (int)((hold >> 8) & 1);
            if ((state->flags & 0x0200) && (state->wrap & 4))
                CRC2(state->check, hold);
            INITBITS();
            state->mode = TIME;
                /* fallthrough */
        case TIME:
            NEEDBITS(32);
            if (state->head != Z_NULL)
                state->head->time = hold;
            if ((state->flags & 0x0200) && (state->wrap & 4))
                CRC4(state->check, hold);
            INITBITS();
            state->mode = OS;
                /* fallthrough */
        case OS:
            NEEDBITS(16);
            if (state->head != Z_NULL) {
                state->head->xflags = (int)(hold & 0xff);
                state->head->os = (int)(hold >> 8);
            }
            if ((state->flags & 0x0200) && (state->wrap & 4))
                CRC2(state->check, hold);
            INITBITS();
            state->mode = EXLEN;
                /* fallthrough */
        case EXLEN:
            if (state->flags & 0x0400) {
                NEEDBITS(16);
                state->length = (unsigned)(hold);
                if (state->head != Z_NULL)
                    state->head->extra_len = (unsigned)hold;
                if ((state->flags & 0x0200) && (state->wrap & 4))
                    CRC2(state->check, hold);
                INITBITS();
            }
            else if (state->head != Z_NULL)
                state->head->extra = Z_NULL;
            state->mode = EXTRA;
                /* fallthrough */
        case EXTRA:
            if (state->flags & 0x0400) {
                copy = state->length;
                if (copy > have) copy = have;
                if (copy) {
                    if (state->head != Z_NULL &&
                        state->head->extra != Z_NULL) {
                        len = state->head->extra_len - state->length;
                        zmemcpy(state->head->extra + len, next,
                                len + copy > state->head->extra_max ?
                                state->head->extra_max - len : copy);
                    }
                    if ((state->flags & 0x0200) && (state->wrap & 4))
                        state->check = crc32(state->check, next, copy);
                    have -= copy;
                    next += copy;
                    state->length -= copy;
                }
                if (state->length) goto inf_leave;
            }
            state->length = 0;
            state->mode = NAME;
                /* fallthrough */
        case NAME:
            if (state->flags & 0x0800) {
                if (have == 0) goto inf_leave;
                copy = 0;
                do {
                    len = (unsigned)(next[copy++]);
                    if (state->head != Z_NULL &&
                            state->head->name != Z_NULL &&
                            state->length < state->head->name_max)
                        state->head->name[state->length++] = (Bytef)len;
                } while (len && copy < have);
                if ((state->flags & 0x0200) && (state->wrap & 4))
                    state->check = crc32(state->check, next, copy);
                have -= copy;
                next += copy;
                if (len) goto inf_leave;
            }
            else if (state->head != Z_NULL)
                state->head->name = Z_NULL;
            state->length = 0;
            state->mode = COMMENT;
                /* fallthrough */
        case COMMENT:
            if (state->flags & 0x1000) {
                if (have == 0) goto inf_leave;
                copy = 0;
                do {
                    len = (unsigned)(next[copy++]);
                    if (state->head != Z_NULL &&
                            state->head->comment != Z_NULL &&
                            state->length < state->head->comm_max)
                        state->head->comment[state->length++] = (Bytef)len;
                } while (len && copy < have);
                if ((state->flags & 0x0200) && (state->wrap & 4))
                    state->check = crc32(state->check, next, copy);
                have -= copy;
                next += copy;
                if (len) goto inf_leave;
            }
            else if (state->head != Z_NULL)
                state->head->comment = Z_NULL;
            state->mode = HCRC;
                /* fallthrough */
        case HCRC:
            if (state->flags & 0x0200) {
                NEEDBITS(16);
                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
                    strm->msg = (char *)""header crc mismatch"";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
            }
            if (state->head != Z_NULL) {
                state->head->hcrc = (int)((state->flags >> 9) & 1);
                state->head->done = 1;
            }
            strm->adler = state->check = crc32(0L, Z_NULL, 0);
            state->mode = TYPE;
            break;
#endif
        case DICTID:
            NEEDBITS(32);
            strm->adler = state->check = ZSWAP32(hold);
            INITBITS();
            state->mode = DICT;
                /* fallthrough */
        case DICT:
            if (state->havedict == 0) {
                RESTORE();
                return Z_NEED_DICT;
            }
            strm->adler = state->check = adler32(0L, Z_NULL, 0);
            state->mode = TYPE;
                /* fallthrough */
        case TYPE:
            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
                /* fallthrough */
        case TYPEDO:
            if (state->last) {
                BYTEBITS();
                state->mode = CHECK;
                break;
            }
            NEEDBITS(3);
            state->last = BITS(1);
            DROPBITS(1);
            switch (BITS(2)) {
            case 0:                             /* stored block */
                Tracev((stderr, ""inflate:     stored block%s\n"",
                        state->last ? "" (last)"" : """"));
                state->mode = STORED;
                break;
            case 1:                             /* fixed block */
                fixedtables(state);
                Tracev((stderr, ""inflate:     fixed codes block%s\n"",
                        state->last ? "" (last)"" : """"));
                state->mode = LEN_;             /* decode codes */
                if (flush == Z_TREES) {
                    DROPBITS(2);
                    goto inf_leave;
                }
                break;
            case 2:                             /* dynamic block */
                Tracev((stderr, ""inflate:     dynamic codes block%s\n"",
                        state->last ? "" (last)"" : """"));
                state->mode = TABLE;
                break;
            case 3:
                strm->msg = (char *)""invalid block type"";
                state->mode = BAD;
            }
            DROPBITS(2);
            break;
        case STORED:
            BYTEBITS();                         /* go to byte boundary */
            NEEDBITS(32);
            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
                strm->msg = (char *)""invalid stored block lengths"";
                state->mode = BAD;
                break;
            }
            state->length = (unsigned)hold & 0xffff;
            Tracev((stderr, ""inflate:       stored length %u\n"",
                    state->length));
            INITBITS();
            state->mode = COPY_;
            if (flush == Z_TREES) goto inf_leave;
                /* fallthrough */
        case COPY_:
            state->mode = COPY;
                /* fallthrough */
        case COPY:
            copy = state->length;
            if (copy) {
                if (copy > have) copy = have;
                if (copy > left) copy = left;
                if (copy == 0) goto inf_leave;
                zmemcpy(put, next, copy);
                have -= copy;
                next += copy;
                left -= copy;
                put += copy;
                state->length -= copy;
                break;
            }
            Tracev((stderr, ""inflate:       stored end\n""));
            state->mode = TYPE;
            break;
        case TABLE:
            NEEDBITS(14);
            state->nlen = BITS(5) + 257;
            DROPBITS(5);
            state->ndist = BITS(5) + 1;
            DROPBITS(5);
            state->ncode = BITS(4) + 4;
            DROPBITS(4);
#ifndef PKZIP_BUG_WORKAROUND
            if (state->nlen > 286 || state->ndist > 30) {
                strm->msg = (char *)""too many length or distance symbols"";
                state->mode = BAD;
                break;
            }
#endif
            Tracev((stderr, ""inflate:       table sizes ok\n""));
            state->have = 0;
            state->mode = LENLENS;
                /* fallthrough */
        case LENLENS:
            while (state->have < state->ncode) {
                NEEDBITS(3);
                state->lens[order[state->have++]] = (unsigned short)BITS(3);
                DROPBITS(3);
            }
            while (state->have < 19)
                state->lens[order[state->have++]] = 0;
            state->next = state->codes;
            state->lencode = (const code FAR *)(state->next);
            state->lenbits = 7;
            ret = inflate_table(CODES, state->lens, 19, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)""invalid code lengths set"";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, ""inflate:       code lengths ok\n""));
            state->have = 0;
            state->mode = CODELENS;
                /* fallthrough */
        case CODELENS:
            while (state->have < state->nlen + state->ndist) {
                for (;;) {
                    here = state->lencode[BITS(state->lenbits)];
                    if ((unsigned)(here.bits) <= bits) break;
                    PULLBYTE();
                }
                if (here.val < 16) {
                    DROPBITS(here.bits);
                    state->lens[state->have++] = here.val;
                }
                else {
                    if (here.val == 16) {
                        NEEDBITS(here.bits + 2);
                        DROPBITS(here.bits);
                        if (state->have == 0) {
                            strm->msg = (char *)""invalid bit length repeat"";
                            state->mode = BAD;
                            break;
                        }
                        len = state->lens[state->have - 1];
                        copy = 3 + BITS(2);
                        DROPBITS(2);
                    }
                    else if (here.val == 17) {
                        NEEDBITS(here.bits + 3);
                        DROPBITS(here.bits);
                        len = 0;
                        copy = 3 + BITS(3);
                        DROPBITS(3);
                    }
                    else {
                        NEEDBITS(here.bits + 7);
                        DROPBITS(here.bits);
                        len = 0;
                        copy = 11 + BITS(7);
                        DROPBITS(7);
                    }
                    if (state->have + copy > state->nlen + state->ndist) {
                        strm->msg = (char *)""invalid bit length repeat"";
                        state->mode = BAD;
                        break;
                    }
                    while (copy--)
                        state->lens[state->have++] = (unsigned short)len;
                }
            }

            /* handle error breaks in while */
            if (state->mode == BAD) break;

            /* check for end-of-block code (better have one) */
            if (state->lens[256] == 0) {
                strm->msg = (char *)""invalid code -- missing end-of-block"";
                state->mode = BAD;
                break;
            }

            /* build code tables -- note: do not change the lenbits or distbits
               values here (9 and 6) without reading the comments in inftrees.h
               concerning the ENOUGH constants, which depend on those values */
            state->next = state->codes;
            state->lencode = (const code FAR *)(state->next);
            state->lenbits = 9;
            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)""invalid literal/lengths set"";
                state->mode = BAD;
                break;
            }
            state->distcode = (const code FAR *)(state->next);
            state->distbits = 6;
            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
                            &(state->next), &(state->distbits), state->work);
            if (ret) {
                strm->msg = (char *)""invalid distances set"";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, ""inflate:       codes ok\n""));
            state->mode = LEN_;
            if (flush == Z_TREES) goto inf_leave;
                /* fallthrough */
        case LEN_:
            state->mode = LEN;
                /* fallthrough */
        case LEN:
            if (have >= 6 && left >= 258) {
                RESTORE();
                inflate_fast(strm, out);
                LOAD();
                if (state->mode == TYPE)
                    state->back = -1;
                break;
            }
            state->back = 0;
            for (;;) {
                here = state->lencode[BITS(state->lenbits)];
                if ((unsigned)(here.bits) <= bits) break;
                PULLBYTE();
            }
            if (here.op && (here.op & 0xf0) == 0) {
                last = here;
                for (;;) {
                    here = state->lencode[last.val +
                            (BITS(last.bits + last.op) >> last.bits)];
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                    PULLBYTE();
                }
                DROPBITS(last.bits);
                state->back += last.bits;
            }
            DROPBITS(here.bits);
            state->back += here.bits;
            state->length = (unsigned)here.val;
            if ((int)(here.op) == 0) {
                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                        ""inflate:         literal '%c'\n"" :
                        ""inflate:         literal 0x%02x\n"", here.val));
                state->mode = LIT;
                break;
            }
            if (here.op & 32) {
                Tracevv((stderr, ""inflate:         end of block\n""));
                state->back = -1;
                state->mode = TYPE;
                break;
            }
            if (here.op & 64) {
                strm->msg = (char *)""invalid literal/length code"";
                state->mode = BAD;
                break;
            }
            state->extra = (unsigned)(here.op) & 15;
            state->mode = LENEXT;
                /* fallthrough */
        case LENEXT:
            if (state->extra) {
                NEEDBITS(state->extra);
                state->length += BITS(state->extra);
                DROPBITS(state->extra);
                state->back += state->extra;
            }
            Tracevv((stderr, ""inflate:         length %u\n"", state->length));
            state->was = state->length;
            state->mode = DIST;
                /* fallthrough */
        case DIST:
            for (;;) {
                here = state->distcode[BITS(state->distbits)];
                if ((unsigned)(here.bits) <= bits) break;
                PULLBYTE();
            }
            if ((here.op & 0xf0) == 0) {
                last = here;
                for (;;) {
                    here = state->distcode[last.val +
                            (BITS(last.bits + last.op) >> last.bits)];
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                    PULLBYTE();
                }
                DROPBITS(last.bits);
                state->back += last.bits;
            }
            DROPBITS(here.bits);
            state->back += here.bits;
            if (here.op & 64) {
                strm->msg = (char *)""invalid distance code"";
                state->mode = BAD;
                break;
            }
            state->offset = (unsigned)here.val;
            state->extra = (unsigned)(here.op) & 15;
            state->mode = DISTEXT;
                /* fallthrough */
        case DISTEXT:
            if (state->extra) {
                NEEDBITS(state->extra);
                state->offset += BITS(state->extra);
                DROPBITS(state->extra);
                state->back += state->extra;
            }
#ifdef INFLATE_STRICT
            if (state->offset > state->dmax) {
                strm->msg = (char *)""invalid distance too far back"";
                state->mode = BAD;
                break;
            }
#endif
            Tracevv((stderr, ""inflate:         distance %u\n"", state->offset));
            state->mode = MATCH;
                /* fallthrough */
        case MATCH:
            if (left == 0) goto inf_leave;
            copy = out - left;
            if (state->offset > copy) {         /* copy from window */
                copy = state->offset - copy;
                if (copy > state->whave) {
                    if (state->sane) {
                        strm->msg = (char *)""invalid distance too far back"";
                        state->mode = BAD;
                        break;
                    }
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
                    Trace((stderr, ""inflate.c too far\n""));
                    copy -= state->whave;
                    if (copy > state->length) copy = state->length;
                    if (copy > left) copy = left;
                    left -= copy;
                    state->length -= copy;
                    do {
                        *put++ = 0;
                    } while (--copy);
                    if (state->length == 0) state->mode = LEN;
                    break;
#endif
                }
                if (copy > state->wnext) {
                    copy -= state->wnext;
                    from = state->window + (state->wsize - copy);
                }
                else
                    from = state->window + (state->wnext - copy);
                if (copy > state->length) copy = state->length;
            }
            else {                              /* copy from output */
                from = put - state->offset;
                copy = state->length;
            }
            if (copy > left) copy = left;
            left -= copy;
            state->length -= copy;
            do {
                *put++ = *from++;
            } while (--copy);
            if (state->length == 0) state->mode = LEN;
            break;
        case LIT:
            if (left == 0) goto inf_leave;
            *put++ = (unsigned char)(state->length);
            left--;
            state->mode = LEN;
            break;
        case CHECK:
            if (state->wrap) {
                NEEDBITS(32);
                out -= left;
                strm->total_out += out;
                state->total += out;
                if ((state->wrap & 4) && out)
                    strm->adler = state->check =
                        UPDATE_CHECK(state->check, put - out, out);
                out = left;
                if ((state->wrap & 4) && (
#ifdef GUNZIP
                     state->flags ? hold :
#endif
                     ZSWAP32(hold)) != state->check) {
                    strm->msg = (char *)""incorrect data check"";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
                Tracev((stderr, ""inflate:   check matches trailer\n""));
            }
#ifdef GUNZIP
            state->mode = LENGTH;
                /* fallthrough */
        case LENGTH:
            if (state->wrap && state->flags) {
                NEEDBITS(32);
                if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
                    strm->msg = (char *)""incorrect length check"";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
                Tracev((stderr, ""inflate:   length matches trailer\n""));
            }
#endif
            state->mode = DONE;
                /* fallthrough */
        case DONE:
            ret = Z_STREAM_END;
            goto inf_leave;
        case BAD:
            ret = Z_DATA_ERROR;
            goto inf_leave;
        case MEM:
            return Z_MEM_ERROR;
        case SYNC:
                /* fallthrough */
        default:
            return Z_STREAM_ERROR;
        }

    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */
  inf_leave:
    RESTORE();
    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
            (state->mode < CHECK || flush != Z_FINISH)))
        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
            state->mode = MEM;
            return Z_MEM_ERROR;
        }
    in -= strm->avail_in;
    out -= strm->avail_out;
    strm->total_in += in;
    strm->total_out += out;
    state->total += out;
    if ((state->wrap & 4) && out)
        strm->adler = state->check =
            UPDATE_CHECK(state->check, strm->next_out - out, out);
    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
                      (state->mode == TYPE ? 128 : 0) +
                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
        ret = Z_BUF_ERROR;
    return ret;
}",CWE-787,16
1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
	struct inode **i)
{
	squashfs_dir_header_3 dirh;
	char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]
		__attribute__((aligned));
	squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;
	long long start;
	int bytes;
	int dir_count, size;
	struct dir_ent *new_dir;
	struct dir *dir;

	TRACE(""squashfs_opendir: inode start block %d, offset %d\n"",
		block_start, offset);

	*i = read_inode(block_start, offset);

	dir = malloc(sizeof(struct dir));
	if(dir == NULL)
		EXIT_UNSQUASH(""squashfs_opendir: malloc failed!\n"");

	dir->dir_count = 0;
	dir->cur_entry = 0;
	dir->mode = (*i)->mode;
	dir->uid = (*i)->uid;
	dir->guid = (*i)->gid;
	dir->mtime = (*i)->time;
	dir->xattr = (*i)->xattr;
	dir->dirs = NULL;

	if ((*i)->data == 3)
		/*
		 * if the directory is empty, skip the unnecessary
		 * lookup_entry, this fixes the corner case with
		 * completely empty filesystems where lookup_entry correctly
		 * returning -1 is incorrectly treated as an error
		 */
		return dir;

	start = sBlk.s.directory_table_start + (*i)->start;
	bytes = lookup_entry(directory_table_hash, start);

	if(bytes == -1)
		EXIT_UNSQUASH(""squashfs_opendir: directory block %d not ""
			""found!\n"", block_start);

	bytes += (*i)->offset;
	size = (*i)->data + bytes - 3;

	while(bytes < size) {			
		if(swap) {
			squashfs_dir_header_3 sdirh;
			memcpy(&sdirh, directory_table + bytes, sizeof(sdirh));
			SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);
		} else
			memcpy(&dirh, directory_table + bytes, sizeof(dirh));
	
		dir_count = dirh.count + 1;
		TRACE(""squashfs_opendir: Read directory header @ byte position ""
			""%d, %d directory entries\n"", bytes, dir_count);
		bytes += sizeof(dirh);

		/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
		if(dir_count > SQUASHFS_DIR_COUNT) {
			ERROR(""File system corrupted: too many entries in directory\n"");
			goto corrupted;
		}

		while(dir_count--) {
			if(swap) {
				squashfs_dir_entry_3 sdire;
				memcpy(&sdire, directory_table + bytes,
					sizeof(sdire));
				SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);
			} else
				memcpy(dire, directory_table + bytes,
					sizeof(*dire));
			bytes += sizeof(*dire);

			/* size should never be SQUASHFS_NAME_LEN or larger */
			if(dire->size >= SQUASHFS_NAME_LEN) {
				ERROR(""File system corrupted: filename too long\n"");
				goto corrupted;
			}

			memcpy(dire->name, directory_table + bytes,
				dire->size + 1);
			dire->name[dire->size + 1] = '\0';
			TRACE(""squashfs_opendir: directory entry %s, inode ""
				""%d:%d, type %d\n"", dire->name,
				dirh.start_block, dire->offset, dire->type);
			if((dir->dir_count % DIR_ENT_SIZE) == 0) {
				new_dir = realloc(dir->dirs, (dir->dir_count +
					DIR_ENT_SIZE) * sizeof(struct dir_ent));
				if(new_dir == NULL)
					EXIT_UNSQUASH(""squashfs_opendir: ""
						""realloc failed!\n"");
				dir->dirs = new_dir;
			}
			strcpy(dir->dirs[dir->dir_count].name, dire->name);
			dir->dirs[dir->dir_count].start_block =
				dirh.start_block;
			dir->dirs[dir->dir_count].offset = dire->offset;
			dir->dirs[dir->dir_count].type = dire->type;
			dir->dir_count ++;
			bytes += dire->size + 1;
		}
	}

	return dir;

corrupted:
	free(dir->dirs);
	free(dir);
	return NULL;
}",CWE-22,5
1,"static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)
{
	int rlen, remain;
	dpIOCtxPtr dctx;
	dynamicPtr *dp;

	dctx = (dpIOCtxPtr) ctx;
	dp = dctx->dp;

	remain = dp->logicalSize - dp->pos;
	if (remain >= len) {
		rlen = len;
	} else {
		if (remain == 0) {
			return EOF;
		}
		rlen = remain;
	}

	memcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);
	dp->pos += rlen;

	return rlen;
}",CWE-119,0
0,"  void GetTemporaryGlobalQuota() {
    quota_status_ = kQuotaStatusUnknown;
    quota_ = -1;
    quota_manager_->GetTemporaryGlobalQuota(
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetQuota));
  }
",none,24
1,"composite_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
{
	struct usb_composite_dev	*cdev = get_gadget_data(gadget);
	struct usb_request		*req = cdev->req;
	int				value = -EOPNOTSUPP;
	int				status = 0;
	u16				w_index = le16_to_cpu(ctrl->wIndex);
	u8				intf = w_index & 0xFF;
	u16				w_value = le16_to_cpu(ctrl->wValue);
	u16				w_length = le16_to_cpu(ctrl->wLength);
	struct usb_function		*f = NULL;
	u8				endp;

	if (w_length > USB_COMP_EP0_BUFSIZ) {
		if (ctrl->bRequestType & USB_DIR_IN) {
			/* Cast away the const, we are going to overwrite on purpose. */
			__le16 *temp = (__le16 *)&ctrl->wLength;

			*temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
			w_length = USB_COMP_EP0_BUFSIZ;
		} else {
			goto done;
		}
	}

	/* partial re-init of the response message; the function or the
	 * gadget might need to intercept e.g. a control-OUT completion
	 * when we delegate to it.
	 */
	req->zero = 0;
	req->context = cdev;
	req->complete = composite_setup_complete;
	req->length = 0;
	gadget->ep0->driver_data = cdev;

	/*
	 * Don't let non-standard requests match any of the cases below
	 * by accident.
	 */
	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD)
		goto unknown;

	switch (ctrl->bRequest) {

	/* we handle all standard USB descriptors */
	case USB_REQ_GET_DESCRIPTOR:
		if (ctrl->bRequestType != USB_DIR_IN)
			goto unknown;
		switch (w_value >> 8) {

		case USB_DT_DEVICE:
			cdev->desc.bNumConfigurations =
				count_configs(cdev, USB_DT_DEVICE);
			cdev->desc.bMaxPacketSize0 =
				cdev->gadget->ep0->maxpacket;
			if (gadget_is_superspeed(gadget)) {
				if (gadget->speed >= USB_SPEED_SUPER) {
					cdev->desc.bcdUSB = cpu_to_le16(0x0320);
					cdev->desc.bMaxPacketSize0 = 9;
				} else {
					cdev->desc.bcdUSB = cpu_to_le16(0x0210);
				}
			} else {
				if (gadget->lpm_capable)
					cdev->desc.bcdUSB = cpu_to_le16(0x0201);
				else
					cdev->desc.bcdUSB = cpu_to_le16(0x0200);
			}

			value = min(w_length, (u16) sizeof cdev->desc);
			memcpy(req->buf, &cdev->desc, value);
			break;
		case USB_DT_DEVICE_QUALIFIER:
			if (!gadget_is_dualspeed(gadget) ||
			    gadget->speed >= USB_SPEED_SUPER)
				break;
			device_qual(cdev);
			value = min_t(int, w_length,
				sizeof(struct usb_qualifier_descriptor));
			break;
		case USB_DT_OTHER_SPEED_CONFIG:
			if (!gadget_is_dualspeed(gadget) ||
			    gadget->speed >= USB_SPEED_SUPER)
				break;
			fallthrough;
		case USB_DT_CONFIG:
			value = config_desc(cdev, w_value);
			if (value >= 0)
				value = min(w_length, (u16) value);
			break;
		case USB_DT_STRING:
			value = get_string(cdev, req->buf,
					w_index, w_value & 0xff);
			if (value >= 0)
				value = min(w_length, (u16) value);
			break;
		case USB_DT_BOS:
			if (gadget_is_superspeed(gadget) ||
			    gadget->lpm_capable) {
				value = bos_desc(cdev);
				value = min(w_length, (u16) value);
			}
			break;
		case USB_DT_OTG:
			if (gadget_is_otg(gadget)) {
				struct usb_configuration *config;
				int otg_desc_len = 0;

				if (cdev->config)
					config = cdev->config;
				else
					config = list_first_entry(
							&cdev->configs,
						struct usb_configuration, list);
				if (!config)
					goto done;

				if (gadget->otg_caps &&
					(gadget->otg_caps->otg_rev >= 0x0200))
					otg_desc_len += sizeof(
						struct usb_otg20_descriptor);
				else
					otg_desc_len += sizeof(
						struct usb_otg_descriptor);

				value = min_t(int, w_length, otg_desc_len);
				memcpy(req->buf, config->descriptors[0], value);
			}
			break;
		}
		break;

	/* any number of configs can work */
	case USB_REQ_SET_CONFIGURATION:
		if (ctrl->bRequestType != 0)
			goto unknown;
		if (gadget_is_otg(gadget)) {
			if (gadget->a_hnp_support)
				DBG(cdev, ""HNP available\n"");
			else if (gadget->a_alt_hnp_support)
				DBG(cdev, ""HNP on another port\n"");
			else
				VDBG(cdev, ""HNP inactive\n"");
		}
		spin_lock(&cdev->lock);
		value = set_config(cdev, ctrl, w_value);
		spin_unlock(&cdev->lock);
		break;
	case USB_REQ_GET_CONFIGURATION:
		if (ctrl->bRequestType != USB_DIR_IN)
			goto unknown;
		if (cdev->config)
			*(u8 *)req->buf = cdev->config->bConfigurationValue;
		else
			*(u8 *)req->buf = 0;
		value = min(w_length, (u16) 1);
		break;

	/* function drivers must handle get/set altsetting */
	case USB_REQ_SET_INTERFACE:
		if (ctrl->bRequestType != USB_RECIP_INTERFACE)
			goto unknown;
		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
			break;
		f = cdev->config->interface[intf];
		if (!f)
			break;

		/*
		 * If there's no get_alt() method, we know only altsetting zero
		 * works. There is no need to check if set_alt() is not NULL
		 * as we check this in usb_add_function().
		 */
		if (w_value && !f->get_alt)
			break;

		spin_lock(&cdev->lock);
		value = f->set_alt(f, w_index, w_value);
		if (value == USB_GADGET_DELAYED_STATUS) {
			DBG(cdev,
			 ""%s: interface %d (%s) requested delayed status\n"",
					__func__, intf, f->name);
			cdev->delayed_status++;
			DBG(cdev, ""delayed_status count %d\n"",
					cdev->delayed_status);
		}
		spin_unlock(&cdev->lock);
		break;
	case USB_REQ_GET_INTERFACE:
		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
			goto unknown;
		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
			break;
		f = cdev->config->interface[intf];
		if (!f)
			break;
		/* lots of interfaces only need altsetting zero... */
		value = f->get_alt ? f->get_alt(f, w_index) : 0;
		if (value < 0)
			break;
		*((u8 *)req->buf) = value;
		value = min(w_length, (u16) 1);
		break;
	case USB_REQ_GET_STATUS:
		if (gadget_is_otg(gadget) && gadget->hnp_polling_support &&
						(w_index == OTG_STS_SELECTOR)) {
			if (ctrl->bRequestType != (USB_DIR_IN |
							USB_RECIP_DEVICE))
				goto unknown;
			*((u8 *)req->buf) = gadget->host_request_flag;
			value = 1;
			break;
		}

		/*
		 * USB 3.0 additions:
		 * Function driver should handle get_status request. If such cb
		 * wasn't supplied we respond with default value = 0
		 * Note: function driver should supply such cb only for the
		 * first interface of the function
		 */
		if (!gadget_is_superspeed(gadget))
			goto unknown;
		if (ctrl->bRequestType != (USB_DIR_IN | USB_RECIP_INTERFACE))
			goto unknown;
		value = 2;	/* This is the length of the get_status reply */
		put_unaligned_le16(0, req->buf);
		if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
			break;
		f = cdev->config->interface[intf];
		if (!f)
			break;
		status = f->get_status ? f->get_status(f) : 0;
		if (status < 0)
			break;
		put_unaligned_le16(status & 0x0000ffff, req->buf);
		break;
	/*
	 * Function drivers should handle SetFeature/ClearFeature
	 * (FUNCTION_SUSPEND) request. function_suspend cb should be supplied
	 * only for the first interface of the function
	 */
	case USB_REQ_CLEAR_FEATURE:
	case USB_REQ_SET_FEATURE:
		if (!gadget_is_superspeed(gadget))
			goto unknown;
		if (ctrl->bRequestType != (USB_DIR_OUT | USB_RECIP_INTERFACE))
			goto unknown;
		switch (w_value) {
		case USB_INTRF_FUNC_SUSPEND:
			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
				break;
			f = cdev->config->interface[intf];
			if (!f)
				break;
			value = 0;
			if (f->func_suspend)
				value = f->func_suspend(f, w_index >> 8);
			if (value < 0) {
				ERROR(cdev,
				      ""func_suspend() returned error %d\n"",
				      value);
				value = 0;
			}
			break;
		}
		break;
	default:
unknown:
		/*
		 * OS descriptors handling
		 */
		if (cdev->use_os_string && cdev->os_desc_config &&
		    (ctrl->bRequestType & USB_TYPE_VENDOR) &&
		    ctrl->bRequest == cdev->b_vendor_code) {
			struct usb_configuration	*os_desc_cfg;
			u8				*buf;
			int				interface;
			int				count = 0;

			req = cdev->os_desc_req;
			req->context = cdev;
			req->complete = composite_setup_complete;
			buf = req->buf;
			os_desc_cfg = cdev->os_desc_config;
			w_length = min_t(u16, w_length, USB_COMP_EP0_OS_DESC_BUFSIZ);
			memset(buf, 0, w_length);
			buf[5] = 0x01;
			switch (ctrl->bRequestType & USB_RECIP_MASK) {
			case USB_RECIP_DEVICE:
				if (w_index != 0x4 || (w_value >> 8))
					break;
				buf[6] = w_index;
				/* Number of ext compat interfaces */
				count = count_ext_compat(os_desc_cfg);
				buf[8] = count;
				count *= 24; /* 24 B/ext compat desc */
				count += 16; /* header */
				put_unaligned_le32(count, buf);
				value = w_length;
				if (w_length > 0x10) {
					value = fill_ext_compat(os_desc_cfg, buf);
					value = min_t(u16, w_length, value);
				}
				break;
			case USB_RECIP_INTERFACE:
				if (w_index != 0x5 || (w_value >> 8))
					break;
				interface = w_value & 0xFF;
				buf[6] = w_index;
				count = count_ext_prop(os_desc_cfg,
					interface);
				put_unaligned_le16(count, buf + 8);
				count = len_ext_prop(os_desc_cfg,
					interface);
				put_unaligned_le32(count, buf);
				value = w_length;
				if (w_length > 0x0A) {
					value = fill_ext_prop(os_desc_cfg,
							      interface, buf);
					if (value >= 0)
						value = min_t(u16, w_length, value);
				}
				break;
			}

			goto check_value;
		}

		VDBG(cdev,
			""non-core control req%02x.%02x v%04x i%04x l%d\n"",
			ctrl->bRequestType, ctrl->bRequest,
			w_value, w_index, w_length);

		/* functions always handle their interfaces and endpoints...
		 * punt other recipients (other, WUSB, ...) to the current
		 * configuration code.
		 */
		if (cdev->config) {
			list_for_each_entry(f, &cdev->config->functions, list)
				if (f->req_match &&
				    f->req_match(f, ctrl, false))
					goto try_fun_setup;
		} else {
			struct usb_configuration *c;
			list_for_each_entry(c, &cdev->configs, list)
				list_for_each_entry(f, &c->functions, list)
					if (f->req_match &&
					    f->req_match(f, ctrl, true))
						goto try_fun_setup;
		}
		f = NULL;

		switch (ctrl->bRequestType & USB_RECIP_MASK) {
		case USB_RECIP_INTERFACE:
			if (!cdev->config || intf >= MAX_CONFIG_INTERFACES)
				break;
			f = cdev->config->interface[intf];
			break;

		case USB_RECIP_ENDPOINT:
			if (!cdev->config)
				break;
			endp = ((w_index & 0x80) >> 3) | (w_index & 0x0f);
			list_for_each_entry(f, &cdev->config->functions, list) {
				if (test_bit(endp, f->endpoints))
					break;
			}
			if (&f->list == &cdev->config->functions)
				f = NULL;
			break;
		}
try_fun_setup:
		if (f && f->setup)
			value = f->setup(f, ctrl);
		else {
			struct usb_configuration	*c;

			c = cdev->config;
			if (!c)
				goto done;

			/* try current config's setup */
			if (c->setup) {
				value = c->setup(c, ctrl);
				goto done;
			}

			/* try the only function in the current config */
			if (!list_is_singular(&c->functions))
				goto done;
			f = list_first_entry(&c->functions, struct usb_function,
					     list);
			if (f->setup)
				value = f->setup(f, ctrl);
		}

		goto done;
	}

check_value:
	/* respond with data transfer before status phase? */
	if (value >= 0 && value != USB_GADGET_DELAYED_STATUS) {
		req->length = value;
		req->context = cdev;
		req->zero = value < w_length;
		value = composite_ep0_queue(cdev, req, GFP_ATOMIC);
		if (value < 0) {
			DBG(cdev, ""ep_queue --> %d\n"", value);
			req->status = 0;
			composite_setup_complete(gadget->ep0, req);
		}
	} else if (value == USB_GADGET_DELAYED_STATUS && w_length != 0) {
		WARN(cdev,
			""%s: Delayed status not supported for w_length != 0"",
			__func__);
	}

done:
	/* device either stalls (value < 0) or reports success */
	return value;
}",CWE-476,12
0,"void QuotaManagerProxy::NotifyOriginInUse(
    const GURL& origin) {
  if (!io_thread_->BelongsToCurrentThread()) {
    io_thread_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &QuotaManagerProxy::NotifyOriginInUse, origin));
    return;
  }
  if (manager_)
    manager_->NotifyOriginInUse(origin);
}
",none,24
1,"void vrend_renderer_blit(struct vrend_context *ctx,
                         uint32_t dst_handle, uint32_t src_handle,
                         const struct pipe_blit_info *info)
{
   struct vrend_resource *src_res, *dst_res;
   src_res = vrend_renderer_ctx_res_lookup(ctx, src_handle);
   dst_res = vrend_renderer_ctx_res_lookup(ctx, dst_handle);

   if (!src_res) {
      report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, src_handle);
      return;
   }
   if (!dst_res) {
      report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, dst_handle);
      return;
   }

   if (ctx->in_error)
      return;

   if (info->render_condition_enable == false)
      vrend_pause_render_condition(ctx, true);

   VREND_DEBUG(dbg_blit, ctx, ""BLIT: rc:%d scissor:%d filter:%d alpha:%d mask:0x%x\n""
                                   ""  From %s(%s) ms:%d [%d, %d, %d]+[%d, %d, %d] lvl:%d\n""
                                   ""  To   %s(%s) ms:%d [%d, %d, %d]+[%d, %d, %d] lvl:%d\n"",
                                   info->render_condition_enable, info->scissor_enable,
                                   info->filter, info->alpha_blend, info->mask,
                                   util_format_name(src_res->base.format),
                                   util_format_name(info->src.format),
                                   src_res->base.nr_samples,
                                   info->src.box.x, info->src.box.y, info->src.box.z,
                                   info->src.box.width, info->src.box.height, info->src.box.depth,
                                   info->src.level,
                                   util_format_name(dst_res->base.format),
                                   util_format_name(info->dst.format),
                                   dst_res->base.nr_samples,
                                   info->dst.box.x, info->dst.box.y, info->dst.box.z,
                                   info->dst.box.width, info->dst.box.height, info->dst.box.depth,
                                   info->dst.level);

   /* The Gallium blit function can be called for a general blit that may
    * scale, convert the data, and apply some rander states, or it is called via
    * glCopyImageSubData. If the src or the dst image are equal, or the two
    * images formats are the same, then Galliums such calles are redirected
    * to resource_copy_region, in this case and if no render states etx need
    * to be applied, forward the call to glCopyImageSubData, otherwise do a
    * normal blit. */
   if (has_feature(feat_copy_image) &&
       (!info->render_condition_enable || !ctx->sub->cond_render_gl_mode) &&
       format_is_copy_compatible(info->src.format,info->dst.format, false) &&
       !info->scissor_enable && (info->filter == PIPE_TEX_FILTER_NEAREST) &&
       !info->alpha_blend && (info->mask == PIPE_MASK_RGBA) &&
       src_res->base.nr_samples == dst_res->base.nr_samples &&
       info->src.box.width == info->dst.box.width &&
       info->src.box.height == info->dst.box.height &&
       info->src.box.depth == info->dst.box.depth) {
      VREND_DEBUG(dbg_blit, ctx,  ""  Use glCopyImageSubData\n"");
      vrend_copy_sub_image(src_res, dst_res, info->src.level, &info->src.box,
                           info->dst.level, info->dst.box.x, info->dst.box.y,
                           info->dst.box.z);
   } else {
      VREND_DEBUG(dbg_blit, ctx, ""  Use blit_int\n"");
      vrend_renderer_blit_int(ctx, src_res, dst_res, info);
   }

   if (info->render_condition_enable == false)
      vrend_pause_render_condition(ctx, false);
}",CWE-125,1
0,"  virtual void EnableCellularNetworkDevice(bool enable) {
    EnableNetworkDeviceType(TYPE_CELLULAR, enable);
  }
",none,24
1,"Status BuildXlaCompilationCache(DeviceBase* device, FunctionLibraryRuntime* flr,
                                const XlaPlatformInfo& platform_info,
                                XlaCompilationCache** cache) {
  if (platform_info.xla_device_metadata()) {
    *cache = new XlaCompilationCache(
        platform_info.xla_device_metadata()->client(),
        platform_info.xla_device_metadata()->jit_device_type());
    return Status::OK();
  }

  auto platform =
      se::MultiPlatformManager::PlatformWithId(platform_info.platform_id());
  if (!platform.ok()) {
    return platform.status();
  }

  StatusOr compiler_for_platform =
      xla::Compiler::GetForPlatform(platform.ValueOrDie());
  if (!compiler_for_platform.ok()) {
    // In some rare cases (usually in unit tests with very small clusters) we
    // may end up transforming an XLA cluster with at least one GPU operation
    // (which would normally force the cluster to be compiled using XLA:GPU)
    // into an XLA cluster with no GPU operations (i.e. containing only CPU
    // operations).  Such a cluster can fail compilation (in way that
    // MarkForCompilation could not have detected) if the CPU JIT is not linked
    // in.
    //
    // So bail out of _XlaCompile in this case, and let the executor handle the
    // situation for us.
    const Status& status = compiler_for_platform.status();
    if (status.code() == error::NOT_FOUND) {
      return errors::Unimplemented(""Could not find compiler for platform "",
                                   platform.ValueOrDie()->Name(), "": "",
                                   status.ToString());
    }
  }

  xla::LocalClientOptions client_options;
  client_options.set_platform(platform.ValueOrDie());
  client_options.set_intra_op_parallelism_threads(
      device->tensorflow_cpu_worker_threads()->num_threads);

  string allowed_gpus =
      flr->config_proto()->gpu_options().visible_device_list();
  TF_ASSIGN_OR_RETURN(absl::optional> gpu_ids,
                      ParseVisibleDeviceList(allowed_gpus));
  client_options.set_allowed_devices(gpu_ids);

  auto client = xla::ClientLibrary::GetOrCreateLocalClient(client_options);
  if (!client.ok()) {
    return client.status();
  }
  const XlaOpRegistry::DeviceRegistration* registration;
  if (!XlaOpRegistry::GetCompilationDevice(platform_info.device_type().type(),
                                           ®istration)) {
    return errors::InvalidArgument(""No JIT device registered for "",
                                   platform_info.device_type().type());
  }
  *cache = new XlaCompilationCache(
      client.ValueOrDie(), DeviceType(registration->compilation_device_name));
  return Status::OK();
}",CWE-476,12
0,"  virtual bool cellular_connecting() const { return false; }
",none,24
1,"static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {
	st64 ptr = 0;
	char *addr, *esil_buf = NULL;
	const st64 maxstackframe = 1024 * 8; 

	r_return_if_fail (anal && fcn && op && reg);

	size_t i;
	for (i = 0; i < R_ARRAY_SIZE (op->src); i++) {
		if (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {
			if (!strcmp (reg, op->src[i]->reg->name)) {
				st64 delta = op->src[i]->delta;
				if ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {
					ptr = R_ABS (op->src[i]->delta);
					break;
				}
			}
		}
	}

	if (!ptr) {
		const char *op_esil = r_strbuf_get (&op->esil);
		if (!op_esil) {
			return;
		}
		esil_buf = strdup (op_esil);
		if (!esil_buf) {
			return;
		}
		r_strf_var (esilexpr, 64, "",%s,%s,"", reg, sign);
		char *ptr_end = strstr (esil_buf, esilexpr);
		if (!ptr_end) {
			free (esil_buf);
			return;
		}
		*ptr_end = 0;
		addr = ptr_end;
		while ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {
			addr--;
		}
		if (strncmp (addr, ""0x"", 2)) {
			//XXX: This is a workaround for inconsistent esil
			if (!op->stackop && op->dst) {
				const char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);
				const char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);
				const char *rn = op->dst->reg ? op->dst->reg->name : NULL;
				if (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {
					if (anal->verbose) {
						eprintf (""Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%"" PFMT64x "".\n"", op->addr);
					}
					goto beach;
				}
			}
			if (*addr == ',') {
				addr++;
			}
			if (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP
				&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {
				ptr = (st64)r_num_get (NULL, addr);
				if (ptr && op->src[0] && ptr == op->src[0]->imm) {
					goto beach;
				}
			} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {
				if (op->ptr % 4) {
					goto beach;
				}
				ptr = R_ABS (op->ptr);
			} else {
				goto beach;
			}
		} else {
			ptr = (st64)r_num_get (NULL, addr);
		}
	}

	if (anal->verbose && (!op->src[0] || !op->dst)) {
		eprintf (""Warning: Analysis didn't fill op->src/dst at 0x%"" PFMT64x "".\n"", op->addr);
	}

	int rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;
	if (*sign == '+') {
		const bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;
		const char *pfx = isarg ? ARGPREFIX : VARPREFIX;
		st64 frame_off;
		if (type == R_ANAL_VAR_KIND_SPV) {
			frame_off = ptr - fcn->stack;
		} else {
			frame_off = ptr - fcn->bp_off;
		}
		if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
			goto beach;
		}
		RAnalVar *var = get_stack_var (fcn, frame_off);
		if (var) {
			r_anal_var_set_access (var, reg, op->addr, rw, ptr);
			goto beach;
		}
		char *varname = NULL, *vartype = NULL;
		if (isarg) {
			const char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;
			bool stack_rev = place ? !strcmp (place, ""stack_rev"") : false;
			char *fname = r_type_func_guess (anal->sdb_types, fcn->name);
			if (fname) {
				ut64 sum_sz = 0;
				size_t from, to, i;
				if (stack_rev) {
					const size_t cnt = r_type_func_args_count (anal->sdb_types, fname);
					from = cnt ? cnt - 1 : cnt;
					to = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
				} else {
					from = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
					to = r_type_func_args_count (anal->sdb_types, fname);
				}
				const int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;
				for (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {
					char *tp = r_type_func_args_type (anal->sdb_types, fname, i);
					if (!tp) {
						break;
					}
					if (sum_sz == frame_off) {
						vartype = tp;
						varname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));
						break;
					}
					ut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);
					sum_sz += bit_sz ? bit_sz / 8 : bytes;
					sum_sz = R_ROUND (sum_sz, bytes);
					free (tp);
				}
				free (fname);
			}
		}
		if (!varname) {
			if (anal->opt.varname_stack) {
				varname = r_str_newf (""%s_%"" PFMT64x ""h"", pfx, R_ABS (frame_off));
			} else {
				varname = r_anal_function_autoname_var (fcn, type, pfx, ptr);
			}
		}
		if (varname) {
#if 0
			if (isarg && frame_off > 48) {
				free (varname);
				goto beach;
			}
#endif
			RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);
			if (var) {
				r_anal_var_set_access (var, reg, op->addr, rw, ptr);
			}
			free (varname);
		}
		free (vartype);
	} else {
		st64 frame_off = -(ptr + fcn->bp_off);
		if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
			goto beach;
		}
		RAnalVar *var = get_stack_var (fcn, frame_off);
		if (var) {
			r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
			goto beach;
		}
		char *varname = anal->opt.varname_stack
			? r_str_newf (""%s_%"" PFMT64x ""h"", VARPREFIX, R_ABS (frame_off))
			: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);
		if (varname) {
			RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);
			if (var) {
				r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
			}
			free (varname);
		}
	}
beach:
	free (esil_buf);
}",CWE-416,10
1,"void sdb_edit(procinfo *pi)
{
  char * filename = omStrDup(""/tmp/sd000000"");
  sprintf(filename+7,""%d"",getpid());
  FILE *fp=fopen(filename,""w"");
  if (fp==NULL)
  {
    Print(""cannot open %s\n"",filename);
    omFree(filename);
    return;
  }
  if (pi->language!= LANG_SINGULAR)
  {
    Print(""cannot edit type %d\n"",pi->language);
    fclose(fp);
    fp=NULL;
  }
  else
  {
    const char *editor=getenv(""EDITOR"");
    if (editor==NULL)
      editor=getenv(""VISUAL"");
    if (editor==NULL)
      editor=""vi"";
    editor=omStrDup(editor);

    if (pi->data.s.body==NULL)
    {
      iiGetLibProcBuffer(pi);
      if (pi->data.s.body==NULL)
      {
        PrintS(""cannot get the procedure body\n"");
        fclose(fp);
        si_unlink(filename);
        omFree(filename);
        return;
      }
    }

    fwrite(pi->data.s.body,1,strlen(pi->data.s.body),fp);
    fclose(fp);

    int pid=fork();
    if (pid!=0)
    {
      si_wait(&pid);
    }
    else if(pid==0)
    {
      if (strchr(editor,' ')==NULL)
      {
        execlp(editor,editor,filename,NULL);
        Print(""cannot exec %s\n"",editor);
      }
      else
      {
        char *p=(char *)omAlloc(strlen(editor)+strlen(filename)+2);
        sprintf(p,""%s %s"",editor,filename);
        system(p);
      }
      exit(0);
    }
    else
    {
      PrintS(""cannot fork\n"");
    }

    fp=fopen(filename,""r"");
    if (fp==NULL)
    {
      Print(""cannot read from %s\n"",filename);
    }
    else
    {
      fseek(fp,0L,SEEK_END);
      long len=ftell(fp);
      fseek(fp,0L,SEEK_SET);

      omFree((ADDRESS)pi->data.s.body);
      pi->data.s.body=(char *)omAlloc((int)len+1);
      myfread( pi->data.s.body, len, 1, fp);
      pi->data.s.body[len]='\0';
      fclose(fp);
    }
  }
  si_unlink(filename);
  omFree(filename);
}",CWE-269,6
0,"  virtual bool cellular_available() const {
    return available_devices_ & (1 << TYPE_CELLULAR);
  }
",none,24
1,"  void Compute(OpKernelContext* context) override {
    const Tensor* input_indices;
    const Tensor* input_values;
    const Tensor* input_shape;
    SparseTensorsMap* map;

    OP_REQUIRES_OK(context, context->input(""sparse_indices"", &input_indices));
    OP_REQUIRES_OK(context, context->input(""sparse_values"", &input_values));
    OP_REQUIRES_OK(context, context->input(""sparse_shape"", &input_shape));
    OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));

    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),
                errors::InvalidArgument(
                    ""Input indices should be a matrix but received shape "",
                    input_indices->shape().DebugString()));

    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),
                errors::InvalidArgument(
                    ""Input values should be a vector but received shape "",
                    input_values->shape().DebugString()));

    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),
                errors::InvalidArgument(
                    ""Input shape should be a vector but received shape "",
                    input_shape->shape().DebugString()));

    int rank = input_shape->NumElements();

    OP_REQUIRES(
        context, rank > 1,
        errors::InvalidArgument(
            ""Rank of input SparseTensor should be > 1, but saw rank: "", rank));

    auto input_shape_vec = input_shape->vec();
    int new_num_elements = 1;
    bool overflow_ocurred = false;
    for (int i = 0; i < input_shape_vec.size(); i++) {
      new_num_elements =
          MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i));
      if (new_num_elements < 0) {
        overflow_ocurred = true;
        break;
      }
    }

    OP_REQUIRES(
        context, !overflow_ocurred,
        errors::Internal(""Encountered overflow from large input shape.""));

    TensorShape tensor_input_shape(input_shape_vec);
    gtl::InlinedVector std_order(rank);
    std::iota(std_order.begin(), std_order.end(), 0);
    SparseTensor input_st;
    OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,
                                                 tensor_input_shape, std_order,
                                                 &input_st));

    const int64_t N = input_shape_vec(0);

    Tensor sparse_handles(DT_INT64, TensorShape({N}));
    auto sparse_handles_t = sparse_handles.vec();

    OP_REQUIRES_OK(context, input_st.IndicesValid());

    // We can generate the output shape proto string now, for all
    // minibatch entries.
    TensorShape output_shape;
    OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(
                                input_shape_vec.data() + 1,
                                input_shape->NumElements() - 1, &output_shape));

    // Get groups by minibatch dimension
    std::unordered_set visited;
    sparse::GroupIterable minibatch = input_st.group({0});
    for (const auto& subset : minibatch) {
      const int64_t b = subset.group()[0];
      visited.insert(b);
      OP_REQUIRES(
          context, b > -1 && b < N,
          errors::InvalidArgument(
              ""Received unexpected column 0 value in input SparseTensor: "", b,
              "" < 0 or >= N (= "", N, "")""));

      const auto indices = subset.indices();
      const auto values = subset.values();
      const int64_t num_entries = values.size();

      Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});
      Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});

      auto output_indices_t = output_indices.matrix();
      auto output_values_t = output_values.vec();

      for (int i = 0; i < num_entries; ++i) {
        for (int d = 1; d < rank; ++d) {
          output_indices_t(i, d - 1) = indices(i, d);
        }
        output_values_t(i) = values(i);
      }

      SparseTensor st_i;
      OP_REQUIRES_OK(context,
                     SparseTensor::Create(output_indices, output_values,
                                          output_shape, &st_i));
      int64_t handle;
      OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));
      sparse_handles_t(b) = handle;
    }

    // Fill in any gaps; we must provide an empty ST for batch entries
    // the grouper didn't find.
    if (visited.size() < N) {
      Tensor empty_indices(DT_INT64, {0, rank - 1});
      Tensor empty_values(DataTypeToEnum::value, {0});
      SparseTensor empty_st;
      OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,
                                                   output_shape, &empty_st));

      for (int64_t b = 0; b < N; ++b) {
        // We skipped this batch entry.
        if (visited.find(b) == visited.end()) {
          int64_t handle;
          OP_REQUIRES_OK(context,
                         map->AddSparseTensor(context, empty_st, &handle));
          sparse_handles_t(b) = handle;
        }
      }
    }

    context->set_output(0, sparse_handles);
  }",CWE-190,2
1,"at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)
{
  FILE *fd;
  unsigned char buffer[64];
  int ColormapSize, rowbytes, Maps;
  gboolean Grey = FALSE;
  unsigned char ColorMap[256][3];
  at_bitmap image = at_bitmap_init(0, 0, 0, 1);
  unsigned char *image_storage;
  at_exception_type exp = at_exception_new(msg_func, msg_data);
  char magick[2];
  Bitmap_Channel masks[4];

  fd = fopen(filename, ""rb"");

  if (!fd) {
    LOG(""Can't open \""%s\""\n"", filename);
    at_exception_fatal(&exp, ""bmp: cannot open input file"");
    goto cleanup;
  }

  /* It is a File. Now is it a Bitmap? Read the shortest possible header. */

  if (!ReadOK(fd, magick, 2) ||
	  !(!strncmp(magick, ""BA"", 2) ||
		  !strncmp(magick, ""BM"", 2) ||
		  !strncmp(magick, ""IC"", 2) ||
		  !strncmp(magick, ""PT"", 2) ||
		  !strncmp(magick, ""CI"", 2) ||
		  !strncmp(magick, ""CP"", 2)))
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  while (!strncmp(magick, ""BA"", 2))
  {
	  if (!ReadOK(fd, buffer, 12))
	  {
		  LOG(""%s is not a valid BMP file"", filename);
		  at_exception_fatal(&exp, ""bmp: invalid input file"");
		  goto cleanup;
	  }

	  if (!ReadOK(fd, magick, 2))
	  {
		  LOG(""%s is not a valid BMP file"", filename);
		  at_exception_fatal(&exp, ""bmp: invalid input file"");
		  goto cleanup;
	  }
  }

  if (!ReadOK(fd, buffer, 12))////
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  /* bring them to the right byteorder. Not too nice, but it should work */

  Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);
  Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);
  Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);
  Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);

  if (!ReadOK(fd, buffer, 4))
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  Bitmap_File_Head.biSize = ToL(&buffer[0x00]);

  /* What kind of bitmap is it? */

  if (Bitmap_File_Head.biSize == 12) {  /* OS/2 1.x ? */
    if (!ReadOK(fd, buffer, 8)) {
      LOG(""Error reading BMP file header\n"");
      at_exception_fatal(&exp, ""Error reading BMP file header"");
      goto cleanup;
    }

    Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */
    Bitmap_Head.biHeight = ToS(&buffer[0x02]);  /* 14 */
    Bitmap_Head.biPlanes = ToS(&buffer[0x04]);  /* 16 */
    Bitmap_Head.biBitCnt = ToS(&buffer[0x06]);  /* 18 */
    Bitmap_Head.biCompr = 0;
    Bitmap_Head.biSizeIm = 0;
    Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;
    Bitmap_Head.biClrUsed = 0;
    Bitmap_Head.biClrImp = 0;
    Bitmap_Head.masks[0] = 0;
    Bitmap_Head.masks[1] = 0;
    Bitmap_Head.masks[2] = 0;
    Bitmap_Head.masks[3] = 0;

    memset(masks, 0, sizeof(masks));
    Maps = 3;

  } else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */
    if (!ReadOK(fd, buffer, 36))
    {
      LOG (""Error reading BMP file header\n"");
      at_exception_fatal(&exp, ""Error reading BMP file header"");
      goto cleanup;
    }
          

    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */
    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */
    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */
    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */
    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */
    Bitmap_Head.masks[0] = 0;
    Bitmap_Head.masks[1] = 0;
    Bitmap_Head.masks[2] = 0;
    Bitmap_Head.masks[3] = 0;

    Maps = 4;
    memset(masks, 0, sizeof(masks));

    if (Bitmap_Head.biCompr == BI_BITFIELDS)
      {
	if (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))
	  {
	    LOG(""Error reading BMP file header\n"");
	    at_exception_fatal(&exp, ""Error reading BMP file header"");
	    goto cleanup;
	  }

	Bitmap_Head.masks[0] = ToL(&buffer[0x00]);
	Bitmap_Head.masks[1] = ToL(&buffer[0x04]);
	Bitmap_Head.masks[2] = ToL(&buffer[0x08]);

	ReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);
      }
    else if (Bitmap_Head.biCompr == BI_RGB)
      {
	setMasksDefault(Bitmap_Head.biBitCnt, masks);
      }
    else if ((Bitmap_Head.biCompr != BI_RLE4) &&
	     (Bitmap_Head.biCompr != BI_RLE8))
      {
	/* BI_ALPHABITFIELDS, etc. */
	LOG(""Unsupported compression in BMP file\n"");
	at_exception_fatal(&exp, ""Unsupported compression in BMP file"");
	goto cleanup;
      }
  }
  else if (Bitmap_File_Head.biSize >= 56 &&
	   Bitmap_File_Head.biSize <= 64)
  {
    /* enhanced Windows format with bit masks */

    if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))
    {

      LOG(""Error reading BMP file header\n"");
      at_exception_fatal(&exp, ""Error reading BMP file header"");
      goto cleanup;
    }

    Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
    Bitmap_Head.biHeight = ToL(&buffer[0x04]);  /* 16 */
    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);  /* 1A */
    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);  /* 1C */
    Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);  /* 22 */
    Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
    Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);  /* 32 */
    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);       /* 36 */
    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);       /* 3A */
    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);       /* 3E */
    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);       /* 42 */

    Maps = 4;
    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
  }
  else if (Bitmap_File_Head.biSize == 108 ||
           Bitmap_File_Head.biSize == 124)
  {
    /* BMP Version 4 or 5 */

    if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))
    {
	    LOG(""Error reading BMP file header\n"");
	    at_exception_fatal(&exp, ""Error reading BMP file header"");
	    goto cleanup;
    }

    Bitmap_Head.biWidth = ToL(&buffer[0x00]);
    Bitmap_Head.biHeight = ToL(&buffer[0x04]);
    Bitmap_Head.biPlanes = ToS(&buffer[0x08]);
    Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);
    Bitmap_Head.biCompr = ToL(&buffer[0x0C]);
    Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);
    Bitmap_Head.biXPels = ToL(&buffer[0x14]);
    Bitmap_Head.biYPels = ToL(&buffer[0x18]);
    Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);
    Bitmap_Head.biClrImp = ToL(&buffer[0x20]);
    Bitmap_Head.masks[0] = ToL(&buffer[0x24]);
    Bitmap_Head.masks[1] = ToL(&buffer[0x28]);
    Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);
    Bitmap_Head.masks[3] = ToL(&buffer[0x30]);

    Maps = 4;

    if (Bitmap_Head.biCompr == BI_BITFIELDS)
    {
	    ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
    }
    else if (Bitmap_Head.biCompr == BI_RGB)
    {
	    setMasksDefault(Bitmap_Head.biBitCnt, masks);
    }
  } else {
    LOG(""Error reading BMP file header\n"");
    at_exception_fatal(&exp, ""Error reading BMP file header"");
    goto cleanup;
  }

  /* Valid options 1, 4, 8, 16, 24, 32 */
  /* 16 is awful, we should probably shoot whoever invented it */

  switch (Bitmap_Head.biBitCnt)
  {
  case 1:
  case 2:
  case 4:
  case 8:
  case 16:
  case 24:
  case 32:
	  break;
  default:
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  /* There should be some colors used! */

  ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;

  if ((Bitmap_Head.biClrUsed == 0) &&
      (Bitmap_Head.biBitCnt <= 8))
  {
	  ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;
  }

  if (ColormapSize > 256)
    ColormapSize = 256;

  /* Sanity checks */

  if (Bitmap_Head.biHeight == 0 ||
	  Bitmap_Head.biWidth == 0)
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  /* biHeight may be negative, but -2147483648 is dangerous because:
	 -2147483648 == -(-2147483648) */
  if (Bitmap_Head.biWidth < 0 ||
	  Bitmap_Head.biHeight == -2147483648)
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  if (Bitmap_Head.biPlanes != 1)
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  if (Bitmap_Head.biClrUsed > 256 &&
	  Bitmap_Head.biBitCnt <= 8)
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  /* protect against integer overflows caused by malicious BMPs */
  /* use divisions in comparisons to avoid type overflows */

  if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||
	  ((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)
  {
	  LOG(""%s is not a valid BMP file"", filename);
	  at_exception_fatal(&exp, ""bmp: invalid input file"");
	  goto cleanup;
  }

  /* Windows and OS/2 declare filler so that rows are a multiple of
   * word length (32 bits == 4 bytes)
   */
   
  unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;
  if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {
    LOG(""Error reading BMP file header. Width is too large\n"");
    at_exception_fatal(&exp, ""Error reading BMP file header. Width is too large"");
    goto cleanup;
  }

  rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;

#ifdef DEBUG
  printf(""\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\n"", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);
#endif


  if (Bitmap_Head.biBitCnt <= 8)
  {
#ifdef DEBUG
    printf(""Colormap read\n"");
#endif
	  /* Get the Colormap */
	  if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))
		  goto cleanup;
  }

  fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);

  /* Get the Image and return the ID or -1 on error */
  image_storage = ReadImage(fd, 
	Bitmap_Head.biWidth, Bitmap_Head.biHeight,
	ColorMap,
        Bitmap_Head.biClrUsed,
	Bitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,
        Grey,
	masks,
	&exp);

  image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);
cleanup:
  fclose(fd);
  return (image);
}",CWE-787,16
1,"*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args)
{
	u32 priv_sz = sizeof(struct vidtv_s302m_ctx);
	struct vidtv_s302m_ctx *ctx;
	struct vidtv_encoder *e;

	e = kzalloc(sizeof(*e), GFP_KERNEL);
	if (!e)
		return NULL;

	e->id = S302M;

	if (args.name)
		e->name = kstrdup(args.name, GFP_KERNEL);

	e->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ);
	e->encoder_buf_sz = VIDTV_S302M_BUF_SZ;
	e->encoder_buf_offset = 0;

	e->sample_count = 0;

	e->src_buf = (args.src_buf) ? args.src_buf : NULL;
	e->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0;
	e->src_buf_offset = 0;

	e->is_video_encoder = false;

	ctx = kzalloc(priv_sz, GFP_KERNEL);
	if (!ctx) {
		kfree(e);
		return NULL;
	}

	e->ctx = ctx;
	ctx->last_duration = 0;

	e->encode = vidtv_s302m_encode;
	e->clear = vidtv_s302m_clear;

	e->es_pid = cpu_to_be16(args.es_pid);
	e->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1);

	e->sync = args.sync;
	e->sampling_rate_hz = S302M_SAMPLING_RATE_HZ;

	e->last_sample_cb = args.last_sample_cb;

	e->destroy = vidtv_s302m_encoder_destroy;

	if (args.head) {
		while (args.head->next)
			args.head = args.head->next;

		args.head->next = e;
	}

	e->next = NULL;

	return e;
}",CWE-476,12
1,"TfLiteIntArray* TfLiteIntArrayCreate(int size) {
  int alloc_size = TfLiteIntArrayGetSizeInBytes(size);
  if (alloc_size <= 0) return NULL;
  TfLiteIntArray* ret = (TfLiteIntArray*)malloc(alloc_size);
  if (!ret) return ret;
  ret->size = size;
  return ret;
}",CWE-190,2
1,"bool st_select_lex::optimize_unflattened_subqueries(bool const_only)
{
  SELECT_LEX_UNIT *next_unit= NULL;
  for (SELECT_LEX_UNIT *un= first_inner_unit();
       un;
       un= next_unit ? next_unit : un->next_unit())
  {
    Item_subselect *subquery_predicate= un->item;
    next_unit= NULL;

    if (subquery_predicate)
    {
      if (!subquery_predicate->fixed)
      {
	/*
	 This subquery was excluded as part of some expression so it is
	 invisible from all prepared expression.
       */
	next_unit= un->next_unit();
	un->exclude_level();
	if (next_unit)
	  continue;
	break;
      }
      if (subquery_predicate->substype() == Item_subselect::IN_SUBS)
      {
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
        if (in_subs->is_jtbm_merged)
          continue;
      }

      if (const_only && !subquery_predicate->const_item())
      {
        /* Skip non-constant subqueries if the caller asked so. */
        continue;
      }

      bool empty_union_result= true;
      bool is_correlated_unit= false;
      bool first= true;
      bool union_plan_saved= false;
      /*
        If the subquery is a UNION, optimize all the subqueries in the UNION. If
        there is no UNION, then the loop will execute once for the subquery.
      */
      for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
      {
        JOIN *inner_join= sl->join;
        if (first)
          first= false;
        else
        {
          if (!union_plan_saved)
          {
            union_plan_saved= true;
            if (un->save_union_explain(un->thd->lex->explain))
              return true; /* Failure */
          }
        }
        if (!inner_join)
          continue;
        SELECT_LEX *save_select= un->thd->lex->current_select;
        ulonglong save_options;
        int res;
        /* We need only 1 row to determine existence */
        un->set_limit(un->global_parameters());
        un->thd->lex->current_select= sl;
        save_options= inner_join->select_options;
        if (options & SELECT_DESCRIBE)
        {
          /* Optimize the subquery in the context of EXPLAIN. */
          sl->set_explain_type(FALSE);
          sl->options|= SELECT_DESCRIBE;
          inner_join->select_options|= SELECT_DESCRIBE;
        }
        if ((res= inner_join->optimize()))
          return TRUE;
        if (!inner_join->cleaned)
          sl->update_used_tables();
        sl->update_correlated_cache();
        is_correlated_unit|= sl->is_correlated;
        inner_join->select_options= save_options;
        un->thd->lex->current_select= save_select;

        Explain_query *eq;
        if ((eq= inner_join->thd->lex->explain))
        {
          Explain_select *expl_sel;
          if ((expl_sel= eq->get_select(inner_join->select_lex->select_number)))
          {
            sl->set_explain_type(TRUE);
            expl_sel->select_type= sl->type;
          }
        }

        if (empty_union_result)
        {
          /*
            If at least one subquery in a union is non-empty, the UNION result
            is non-empty. If there is no UNION, the only subquery is non-empy.
          */
          empty_union_result= inner_join->empty_result();
        }
        if (res)
          return TRUE;
      }
      if (empty_union_result)
        subquery_predicate->no_rows_in_result();
      if (!is_correlated_unit)
        un->uncacheable&= ~UNCACHEABLE_DEPENDENT;
      subquery_predicate->is_correlated= is_correlated_unit;
    }
  }
  return FALSE;
}",CWE-476,12
1,"static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {
	char *p = src + src_prefix_len + 1;
	char *q = dst + dst_prefix_len + 1;
	char *r = dst + dst_prefix_len;
	struct stat s;
	bool last = false;
	*r = '\0';
	for (; !last; p++, q++) {
		if (*p == '\0') {
			last = true;
		}
		if (*p == '\0' || (*p == '/' && *(p - 1) != '/')) {
			// We found a new component of our src path.
			// Null-terminate it temporarily here so that we can work
			// with it.
			*p = '\0';
			if (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {
				// Null-terminate the dst path and undo its previous
				// termination.
				*q = '\0';
				*r = '/';
				r = q;
				mkdir_attr(dst, s.st_mode, 0, 0);
			}
			if (!last) {
				// If we're not at the final terminating null, restore
				// the slash so that we can continue our traversal.
				*p = '/';
			}
		}
	}
}",CWE-94,23
1,"rpa_read_buffer(pool_t pool, const unsigned char **data,
		const unsigned char *end, unsigned char **buffer)
{
	const unsigned char *p = *data;
	unsigned int len;

	if (p > end)
		return 0;

	len = *p++;
	if (p + len > end)
		return 0;

	*buffer = p_malloc(pool, len);
	memcpy(*buffer, p, len);

	*data += 1 + len;

	return len;
}",CWE-125,1
1,"u_undo_end(
    int		did_undo,	// just did an undo
    int		absolute)	// used "":undo N""
{
    char	*msgstr;
    u_header_T	*uhp;
    char_u	msgbuf[80];

#ifdef FEAT_FOLDING
    if ((fdo_flags & FDO_UNDO) && KeyTyped)
	foldOpenCursor();
#endif

    if (global_busy	    // no messages now, wait until global is finished
	    || !messaging())  // 'lazyredraw' set, don't do messages now
	return;

    if (curbuf->b_ml.ml_flags & ML_EMPTY)
	--u_newcount;

    u_oldcount -= u_newcount;
    if (u_oldcount == -1)
	msgstr = N_(""more line"");
    else if (u_oldcount < 0)
	msgstr = N_(""more lines"");
    else if (u_oldcount == 1)
	msgstr = N_(""line less"");
    else if (u_oldcount > 1)
	msgstr = N_(""fewer lines"");
    else
    {
	u_oldcount = u_newcount;
	if (u_newcount == 1)
	    msgstr = N_(""change"");
	else
	    msgstr = N_(""changes"");
    }

    if (curbuf->b_u_curhead != NULL)
    {
	// For "":undo N"" we prefer a ""after #N"" message.
	if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL)
	{
	    uhp = curbuf->b_u_curhead->uh_next.ptr;
	    did_undo = FALSE;
	}
	else if (did_undo)
	    uhp = curbuf->b_u_curhead;
	else
	    uhp = curbuf->b_u_curhead->uh_next.ptr;
    }
    else
	uhp = curbuf->b_u_newhead;

    if (uhp == NULL)
	*msgbuf = NUL;
    else
	add_time(msgbuf, sizeof(msgbuf), uhp->uh_time);

#ifdef FEAT_CONCEAL
    {
	win_T	*wp;

	FOR_ALL_WINDOWS(wp)
	{
	    if (wp->w_buffer == curbuf && wp->w_p_cole > 0)
		redraw_win_later(wp, NOT_VALID);
	}
    }
#endif

    smsg_attr_keep(0, _(""%ld %s; %s #%ld  %s""),
	    u_oldcount < 0 ? -u_oldcount : u_oldcount,
	    _(msgstr),
	    did_undo ? _(""before"") : _(""after""),
	    uhp == NULL ? 0L : uhp->uh_seq,
	    msgbuf);
}",CWE-787,16
1,"static void singlevar (LexState *ls, expdesc *var) {
  TString *varname = str_checkname(ls);
  FuncState *fs = ls->fs;
  singlevaraux(fs, varname, var, 1);
  if (var->k == VVOID) {  /* global name? */
    expdesc key;
    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
    lua_assert(var->k != VVOID);  /* this one must exist */
    codestring(&key, varname);  /* key is variable name */
    luaK_indexed(fs, var, &key);  /* env[varname] */
  }
}",CWE-125,1
1," */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
	st_entry 			*ent1, *ent2;
	wddx_stack 			*stack = (wddx_stack *)user_data;
	HashTable 			*target_hash;
	zend_class_entry 	**pce;
	zval				*obj;
	zval				*tmp;
	TSRMLS_FETCH();

/* OBJECTS_FIXME */
	if (stack->top == 0) {
		return;
	}

	if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
		!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
	  	!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
		!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
		!strcmp(name, EL_DATETIME)) {
		wddx_stack_top(stack, (void**)&ent1);

		if (!ent1->data) {
			if (stack->top > 1) {
				stack->top--;
			} else {
				stack->done = 1;
			}
			efree(ent1);
			return;
		}

		if (!strcmp(name, EL_BINARY)) {
			int new_len=0;
			unsigned char *new_str;

			new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
			STR_FREE(Z_STRVAL_P(ent1->data));
			Z_STRVAL_P(ent1->data) = new_str;
			Z_STRLEN_P(ent1->data) = new_len;
		}

		/* Call __wakeup() method on the object. */
		if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
			zval *fname, *retval = NULL;

			MAKE_STD_ZVAL(fname);
			ZVAL_STRING(fname, ""__wakeup"", 1);

			call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);

			zval_dtor(fname);
			FREE_ZVAL(fname);
			if (retval) {
				zval_ptr_dtor(&retval);
			}
		}

		if (stack->top > 1) {
			stack->top--;
			wddx_stack_top(stack, (void**)&ent2);

			/* if non-existent field */
			if (ent2->type == ST_FIELD && ent2->data == NULL) {
				zval_ptr_dtor(&ent1->data);
				efree(ent1);
				return;
			}

			if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
				target_hash = HASH_OF(ent2->data);

				if (ent1->varname) {
					if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
						Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
						ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
						zend_bool incomplete_class = 0;

						zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
						if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
										   Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
							incomplete_class = 1;
							pce = &PHP_IC_ENTRY;
						}

						/* Initialize target object */
						MAKE_STD_ZVAL(obj);
						object_init_ex(obj, *pce);

						/* Merge current hashtable with object's default properties */
						zend_hash_merge(Z_OBJPROP_P(obj),
										Z_ARRVAL_P(ent2->data),
										(void (*)(void *)) zval_add_ref,
										(void *) &tmp, sizeof(zval *), 0);

						if (incomplete_class) {
							php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
						}

						/* Clean up old array entry */
						zval_ptr_dtor(&ent2->data);

						/* Set stack entry to point to the newly created object */
						ent2->data = obj;

						/* Clean up class name var entry */
						zval_ptr_dtor(&ent1->data);
					} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
						zend_class_entry *old_scope = EG(scope);

						EG(scope) = Z_OBJCE_P(ent2->data);
						Z_DELREF_P(ent1->data);
						add_property_zval(ent2->data, ent1->varname, ent1->data);
						EG(scope) = old_scope;
					} else {
						zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
					}
					efree(ent1->varname);
				} else	{
					zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
				}
			}
			efree(ent1);
		} else {
			stack->done = 1;
		}
	} else if (!strcmp(name, EL_VAR) && stack->varname) {
		efree(stack->varname);
		stack->varname = NULL;
	} else if (!strcmp(name, EL_FIELD)) {
		st_entry *ent;
		wddx_stack_top(stack, (void **)&ent);
		efree(ent);
		stack->top--;
	}",CWE-476,12
1,"TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params,
                          const TfLiteTensor* indices, TfLiteTensor* output) {
  switch (params->type) {
    case kTfLiteFloat32:
      return GatherNd(params, indices, output);
    case kTfLiteUInt8:
      return GatherNd(params, indices, output);
    case kTfLiteInt8:
      return GatherNd(params, indices, output);
    case kTfLiteInt16:
      return GatherNd(params, indices, output);
    case kTfLiteInt32:
      return GatherNd(params, indices, output);
    case kTfLiteInt64:
      return GatherNd(params, indices, output);
    case kTfLiteString:
      return GatherNdString(params, indices, output);
    default:
      context->ReportError(context,
                           ""Params type '%s' are not supported by gather_nd."",
                           TfLiteTypeGetName(params->type));
      return kTfLiteError;
  }
}",CWE-125,1
1,"  void Compute(OpKernelContext *ctx) override {
    const Tensor *indices_t, *values_t, *shape_t, *reduction_axes_t;
    OP_REQUIRES_OK(ctx, ctx->input(""input_indices"", &indices_t));
    OP_REQUIRES_OK(ctx, ctx->input(""input_values"", &values_t));
    OP_REQUIRES_OK(ctx, ctx->input(""input_shape"", &shape_t));
    OP_REQUIRES_OK(ctx, ctx->input(""reduction_axes"", &reduction_axes_t));

    OP_REQUIRES_OK(ctx, ValidateInputs(shape_t, reduction_axes_t));

    // TODO(zongheng): we will call Reorder() below, which will modify
    // in-place the underlying indices and values buffers.  To avoid
    // surprises of this kernel being stateful, we work around the above by
    // making deep copies here.  Remove this if/when we change Reorder()'s
    // semantics.
    const auto shape_vec = shape_t->vec();
    SparseTensor sp;
    OP_REQUIRES_OK(ctx, SparseTensor::Create(
        tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),
                    TensorShape(shape_vec), &sp));
    ReduceDetails reduction = SparseTensorReduceHelper(
        sp, reduction_axes_t->flat(), keep_dims_);

    Tensor *out_values;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output(0, reduction.reduced_shape, &out_values));
    auto out_flat = out_values->flat();
    out_flat.setZero();

    Tensor tmp_reduced_val;
    OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,
                                           TensorShape({}), &tmp_reduced_val));
    auto reduced_val = tmp_reduced_val.scalar();

    // Compute strides, and use it to convert coords to flat index.  The
    // coordinates returned by .group() have the same ndims as group_by_dims.
    gtl::InlinedVector output_strides(reduction.group_by_dims.size());
    if (!output_strides.empty()) {  // Do this iff we don't reduce all.
      output_strides.back() = 1;
      for (int d = output_strides.size() - 2; d >= 0; --d) {
        output_strides[d] =
            output_strides[d + 1] * shape_vec(reduction.group_by_dims[d + 1]);
      }
    }

    auto CoordinatesToFlatIndex = [](ArraySlice coords,
                                     ArraySlice strides) -> int64 {
      if (strides.empty()) {  // Reduce all.
        return 0;
      }
      CHECK_EQ(coords.size(), strides.size());
      int64_t idx = 0;
      for (int i = 0; i < coords.size(); ++i) {
        idx += coords[i] * strides[i];
      }
      return idx;
    };

    // Each group maps one-on-one onto a value in the reduced tensor.
    // g.group() provides the coordinates of a particular reduced value.
    sp.Reorder(reduction.reorder_dims);
    for (const auto &g : sp.group(reduction.group_by_dims)) {
      Op::template Run(ctx, reduced_val, g.template values());
      const int64_t idx = CoordinatesToFlatIndex(g.group(), output_strides);
      out_flat(idx) = reduced_val();
      VLOG(2) << ""coords: "" << absl::StrJoin(g.group(), "","")
              << ""; idx: "" << idx << ""; group "" << Op::Name() << "": ""
              << reduced_val();
    }
  }",CWE-125,1
1,"static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream)
{
    auth_client *auth_user = stream;
    size_t bytes = size * nmemb;
    client_t *client = auth_user->client;

    if (client)
    {
        auth_t *auth = client->auth;
        auth_url *url = auth->state;
        if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0)
            client->authenticated = 1;
        if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0)
        {
            unsigned int limit = 0;
            sscanf ((char *)ptr+url->timelimit_header_len, ""%u\r\n"", &limit);
            client->con->discon_time = time(NULL) + limit;
        }
        if (strncasecmp (ptr, ""icecast-auth-message: "", 22) == 0)
        {
            char *eol;
            snprintf (url->errormsg, sizeof (url->errormsg), ""%s"", (char*)ptr+22);
            eol = strchr (url->errormsg, '\r');
            if (eol == NULL)
                eol = strchr (url->errormsg, '\n');
            if (eol)
                *eol = '\0';
        }
    }

    return bytes;
}",CWE-119,0
0,"  virtual void RemoveNetworkObserver(const std::string& service_path,
                                     NetworkObserver* observer) {}
",none,24
0,"void WifiNetwork::Clear() {
  WirelessNetwork::Clear();
  encryption_ = SECURITY_NONE;
  passphrase_.clear();
  identity_.clear();
  cert_path_.clear();
}
",none,24
1,"xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
                  const xmlChar **URI, int *tlen) {
    const xmlChar *localname;
    const xmlChar *prefix;
    const xmlChar *attname;
    const xmlChar *aprefix;
    const xmlChar *nsname;
    xmlChar *attvalue;
    const xmlChar **atts = ctxt->atts;
    int maxatts = ctxt->maxatts;
    int nratts, nbatts, nbdef;
    int i, j, nbNs, attval, oldline, oldcol, inputNr;
    const xmlChar *base;
    unsigned long cur;
    int nsNr = ctxt->nsNr;

    if (RAW != '<') return(NULL);
    NEXT1;

    /*
     * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
     *       point since the attribute values may be stored as pointers to
     *       the buffer and calling SHRINK would destroy them !
     *       The Shrinking is only possible once the full set of attribute
     *       callbacks have been done.
     */
reparse:
    SHRINK;
    base = ctxt->input->base;
    cur = ctxt->input->cur - ctxt->input->base;
    inputNr = ctxt->inputNr;
    oldline = ctxt->input->line;
    oldcol = ctxt->input->col;
    nbatts = 0;
    nratts = 0;
    nbdef = 0;
    nbNs = 0;
    attval = 0;
    /* Forget any namespaces added during an earlier parse of this element. */
    ctxt->nsNr = nsNr;

    localname = xmlParseQName(ctxt, &prefix);
    if (localname == NULL) {
	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
		       ""StartTag: invalid element name\n"");
        return(NULL);
    }
    *tlen = ctxt->input->cur - ctxt->input->base - cur;

    /*
     * Now parse the attributes, it ends up with the ending
     *
     * (S Attribute)* S?
     */
    SKIP_BLANKS;
    GROW;
    if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr))
        goto base_changed;

    while (((RAW != '>') &&
	   ((RAW != '/') || (NXT(1) != '>')) &&
	   (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
	const xmlChar *q = CUR_PTR;
	unsigned int cons = ctxt->input->consumed;
	int len = -1, alloc = 0;

	attname = xmlParseAttribute2(ctxt, prefix, localname,
	                             &aprefix, &attvalue, &len, &alloc);
	if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) {
	    if ((attvalue != NULL) && (alloc != 0))
	        xmlFree(attvalue);
	    attvalue = NULL;
	    goto base_changed;
	}
        if ((attname != NULL) && (attvalue != NULL)) {
	    if (len < 0) len = xmlStrlen(attvalue);
            if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
	        const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
		xmlURIPtr uri;

                if (URL == NULL) {
		    xmlErrMemory(ctxt, ""dictionary allocation failure"");
		    if ((attvalue != NULL) && (alloc != 0))
			xmlFree(attvalue);
		    return(NULL);
		}
                if (*URL != 0) {
		    uri = xmlParseURI((const char *) URL);
		    if (uri == NULL) {
			xmlNsErr(ctxt, XML_WAR_NS_URI,
			         ""xmlns: '%s' is not a valid URI\n"",
					   URL, NULL, NULL);
		    } else {
			if (uri->scheme == NULL) {
			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
				      ""xmlns: URI %s is not absolute\n"",
				      URL, NULL, NULL);
			}
			xmlFreeURI(uri);
		    }
		    if (URL == ctxt->str_xml_ns) {
			if (attname != ctxt->str_xml) {
			    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			 ""xml namespace URI cannot be the default namespace\n"",
				     NULL, NULL, NULL);
			}
			goto skip_default_ns;
		    }
		    if ((len == 29) &&
			(xmlStrEqual(URL,
				 BAD_CAST ""http://www.w3.org/2000/xmlns/""))) {
			xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""reuse of the xmlns namespace name is forbidden\n"",
				 NULL, NULL, NULL);
			goto skip_default_ns;
		    }
		}
		/*
		 * check that it's not a defined namespace
		 */
		for (j = 1;j <= nbNs;j++)
		    if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
			break;
		if (j <= nbNs)
		    xmlErrAttributeDup(ctxt, NULL, attname);
		else
		    if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
skip_default_ns:
		if (alloc != 0) xmlFree(attvalue);
		if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
		    break;
		if (!IS_BLANK_CH(RAW)) {
		    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
				   ""attributes construct error\n"");
		    break;
		}
		SKIP_BLANKS;
		continue;
	    }
            if (aprefix == ctxt->str_xmlns) {
	        const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
		xmlURIPtr uri;

                if (attname == ctxt->str_xml) {
		    if (URL != ctxt->str_xml_ns) {
		        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			         ""xml namespace prefix mapped to wrong URI\n"",
			         NULL, NULL, NULL);
		    }
		    /*
		     * Do not keep a namespace definition node
		     */
		    goto skip_ns;
		}
                if (URL == ctxt->str_xml_ns) {
		    if (attname != ctxt->str_xml) {
		        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			         ""xml namespace URI mapped to wrong prefix\n"",
			         NULL, NULL, NULL);
		    }
		    goto skip_ns;
		}
                if (attname == ctxt->str_xmlns) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""redefinition of the xmlns prefix is forbidden\n"",
			     NULL, NULL, NULL);
		    goto skip_ns;
		}
		if ((len == 29) &&
		    (xmlStrEqual(URL,
		                 BAD_CAST ""http://www.w3.org/2000/xmlns/""))) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""reuse of the xmlns namespace name is forbidden\n"",
			     NULL, NULL, NULL);
		    goto skip_ns;
		}
		if ((URL == NULL) || (URL[0] == 0)) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
		             ""xmlns:%s: Empty XML namespace is not allowed\n"",
			          attname, NULL, NULL);
		    goto skip_ns;
		} else {
		    uri = xmlParseURI((const char *) URL);
		    if (uri == NULL) {
			xmlNsErr(ctxt, XML_WAR_NS_URI,
			     ""xmlns:%s: '%s' is not a valid URI\n"",
					   attname, URL, NULL);
		    } else {
			if ((ctxt->pedantic) && (uri->scheme == NULL)) {
			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
				      ""xmlns:%s: URI %s is not absolute\n"",
				      attname, URL, NULL);
			}
			xmlFreeURI(uri);
		    }
		}

		/*
		 * check that it's not a defined namespace
		 */
		for (j = 1;j <= nbNs;j++)
		    if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
			break;
		if (j <= nbNs)
		    xmlErrAttributeDup(ctxt, aprefix, attname);
		else
		    if (nsPush(ctxt, attname, URL) > 0) nbNs++;
skip_ns:
		if (alloc != 0) xmlFree(attvalue);
		if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
		    break;
		if (!IS_BLANK_CH(RAW)) {
		    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
				   ""attributes construct error\n"");
		    break;
		}
		SKIP_BLANKS;
		if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr))
		    goto base_changed;
		continue;
	    }

	    /*
	     * Add the pair to atts
	     */
	    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
	        if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
		    if (attvalue[len] == 0)
			xmlFree(attvalue);
		    goto failed;
		}
	        maxatts = ctxt->maxatts;
		atts = ctxt->atts;
	    }
	    ctxt->attallocs[nratts++] = alloc;
	    atts[nbatts++] = attname;
	    atts[nbatts++] = aprefix;
	    atts[nbatts++] = NULL; /* the URI will be fetched later */
	    atts[nbatts++] = attvalue;
	    attvalue += len;
	    atts[nbatts++] = attvalue;
	    /*
	     * tag if some deallocation is needed
	     */
	    if (alloc != 0) attval = 1;
	} else {
	    if ((attvalue != NULL) && (attvalue[len] == 0))
		xmlFree(attvalue);
	}

failed:

	GROW
        if (ctxt->instate == XML_PARSER_EOF)
            break;
	if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr))
	    goto base_changed;
	if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
	    break;
	if (!IS_BLANK_CH(RAW)) {
	    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
			   ""attributes construct error\n"");
	    break;
	}
	SKIP_BLANKS;
        if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
            (attname == NULL) && (attvalue == NULL)) {
	    xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
	         ""xmlParseStartTag: problem parsing attributes\n"");
	    break;
	}
        GROW;
	if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr))
	    goto base_changed;
    }

    /*
     * The attributes defaulting
     */
    if (ctxt->attsDefault != NULL) {
        xmlDefAttrsPtr defaults;

	defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
	if (defaults != NULL) {
	    for (i = 0;i < defaults->nbAttrs;i++) {
	        attname = defaults->values[5 * i];
		aprefix = defaults->values[5 * i + 1];

                /*
		 * special work for namespaces defaulted defs
		 */
		if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, NULL);
		    if (nsname != defaults->values[5 * i + 2]) {
			if (nsPush(ctxt, NULL,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else if (aprefix == ctxt->str_xmlns) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, attname);
		    if (nsname != defaults->values[2]) {
			if (nsPush(ctxt, attname,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else {
		    /*
		     * check that it's not a defined attribute
		     */
		    for (j = 0;j < nbatts;j+=5) {
			if ((attname == atts[j]) && (aprefix == atts[j+1]))
			    break;
		    }
		    if (j < nbatts) continue;

		    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
			if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
			    return(NULL);
			}
			maxatts = ctxt->maxatts;
			atts = ctxt->atts;
		    }
		    atts[nbatts++] = attname;
		    atts[nbatts++] = aprefix;
		    if (aprefix == NULL)
			atts[nbatts++] = NULL;
		    else
		        atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
		    atts[nbatts++] = defaults->values[5 * i + 2];
		    atts[nbatts++] = defaults->values[5 * i + 3];
		    if ((ctxt->standalone == 1) &&
		        (defaults->values[5 * i + 4] != NULL)) {
			xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
	  ""standalone: attribute %s on %s defaulted from external subset\n"",
	                                 attname, localname);
		    }
		    nbdef++;
		}
	    }
	}
    }

    /*
     * The attributes checkings
     */
    for (i = 0; i < nbatts;i += 5) {
        /*
	* The default namespace does not apply to attribute names.
	*/
	if (atts[i + 1] != NULL) {
	    nsname = xmlGetNamespace(ctxt, atts[i + 1]);
	    if (nsname == NULL) {
		xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
		    ""Namespace prefix %s for %s on %s is not defined\n"",
		    atts[i + 1], atts[i], localname);
	    }
	    atts[i + 2] = nsname;
	} else
	    nsname = NULL;
	/*
	 * [ WFC: Unique Att Spec ]
	 * No attribute name may appear more than once in the same
	 * start-tag or empty-element tag.
	 * As extended by the Namespace in XML REC.
	 */
        for (j = 0; j < i;j += 5) {
	    if (atts[i] == atts[j]) {
	        if (atts[i+1] == atts[j+1]) {
		    xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
		    break;
		}
		if ((nsname != NULL) && (atts[j + 2] == nsname)) {
		    xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
			     ""Namespaced Attribute %s in '%s' redefined\n"",
			     atts[i], nsname, NULL);
		    break;
		}
	    }
	}
    }

    nsname = xmlGetNamespace(ctxt, prefix);
    if ((prefix != NULL) && (nsname == NULL)) {
	xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
	         ""Namespace prefix %s on %s is not defined\n"",
		 prefix, localname, NULL);
    }
    *pref = prefix;
    *URI = nsname;

    /*
     * SAX: Start of Element !
     */
    if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
	(!ctxt->disableSAX)) {
	if (nbNs > 0)
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
			  nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
			  nbatts / 5, nbdef, atts);
	else
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
	                  nsname, 0, NULL, nbatts / 5, nbdef, atts);
    }

    /*
     * Free up attribute allocated strings if needed
     */
    if (attval != 0) {
	for (i = 3,j = 0; j < nratts;i += 5,j++)
	    if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
	        xmlFree((xmlChar *) atts[i]);
    }

    return(localname);

base_changed:
    /*
     * the attribute strings are valid iif the base didn't changed
     */
    if (attval != 0) {
	for (i = 3,j = 0; j < nratts;i += 5,j++)
	    if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
	        xmlFree((xmlChar *) atts[i]);
    }

    /*
     * We can't switch from one entity to another in the middle
     * of a start tag
     */
    if (inputNr != ctxt->inputNr) {
        xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
		    ""Start tag doesn't start and stop in the same entity\n"");
	return(NULL);
    }

    ctxt->input->cur = ctxt->input->base + cur;
    ctxt->input->line = oldline;
    ctxt->input->col = oldcol;
    if (ctxt->wellFormed == 1) {
	goto reparse;
    }
    return(NULL);
}",CWE-119,0
1,"mp_sint32 LoaderS3M::load(XMFileBase& f, XModule* module)
{	
	module->cleanUp();

	// this will make code much easier to read
	TXMHeader*		header = &module->header;
	TXMInstrument*	instr  = module->instr;
	TXMSample*		smp	   = module->smp;
	TXMPattern*		phead  = module->phead;	

	// we're already out of memory here
	if (!phead || !instr || !smp)
		return MP_OUT_OF_MEMORY;
	
	f.read(&header->name,1,28);
	header->whythis1a = f.readByte();
	
	if (f.readByte() != 16) 
		return MP_LOADER_FAILED;	// no ST3 module
	
	f.readByte(); // skip something
	f.readByte(); // skip something
	
	header->ordnum = f.readWord(); // number of positions in order list (songlength)
	
	mp_ubyte* orders = new mp_ubyte[header->ordnum];
	if (orders == NULL) 
		return MP_OUT_OF_MEMORY;
	
	header->insnum = f.readWord(); // number of instruments
	header->patnum = f.readWord(); // number of patterns	
	
	mp_sint32 flags = f.readWord(); // st3 flags	

	mp_sint32 Cvt = f.readWord();

	header->flags = XModule::MODULE_ST3NEWINSTRUMENT | XModule::MODULE_ST3DUALCOMMANDS;

	if (Cvt == 0x1300 || (flags & 64))
		header->flags |= module->MODULE_OLDS3MVOLSLIDES;
		
	header->flags |= module->MODULE_ST3NOTECUT;
	
	/*mp_uword Ffi = */f.readWord();
	
	f.read(header->sig,1,4);
	
	header->mainvol = module->vol64to255(f.readByte()); // initial main volume
	
	header->tempo = f.readByte(); // tempo
	
	header->speed = f.readByte(); // speed
	
	f.readByte(); // global volume? skipped...
	
	f.readByte(); // ignore GUS click removal
	
	/*mp_ubyte dp = */f.readByte();
	
	f.readDword();	// skip something
	f.readDword();	// skip something
	f.readWord();	// skip some more...
	
	mp_ubyte channelSettings[32];
	f.read(channelSettings,1,32);
	
	mp_sint32 numChannels = 0;
	
	for (numChannels = 0; numChannels < 32; numChannels++)
		if (channelSettings[numChannels] == 255)
			break;
	
	header->channum = numChannels; // number of channels
	
	f.read(orders,1,header->ordnum);
	
	mp_sint32 j = 0, i = 0;
	for (i = 0; i < header->ordnum; i++)
	{
		if (orders[i] == 255) 
			break;
		
		header->ord[j++] = orders[i];		
	}
	
	header->ordnum = j; // final songlength
	
	delete[] orders;
	
	mp_uword* insParaPtrs = new mp_uword[header->insnum];
	
	if (insParaPtrs == NULL)
		return MP_OUT_OF_MEMORY;
	
	f.readWords(insParaPtrs,header->insnum);
	
	mp_uword* patParaPtrs = new mp_uword[header->patnum];
	
	if (patParaPtrs == NULL)
	{
		delete[] insParaPtrs;
		return MP_OUT_OF_MEMORY;
	}
	
	f.readWords(patParaPtrs,header->patnum);
	
	//for (i = 0; i < header->insnum; i++)
	//{
	//	printf(""%x\n"",insParaPtrs[i]*16);
	//}
		
	//////////////////////
	// read instruments //
	//////////////////////
	mp_uint32* samplePtrs = new mp_uint32[header->insnum];
	if (samplePtrs == NULL)
	{
		delete[] insParaPtrs;
		delete[] patParaPtrs;
		return MP_OUT_OF_MEMORY;
	}
	
	memset(samplePtrs,0,sizeof(mp_uint32)*header->insnum);
	
	mp_sint32 s = 0;
	for (i = 0; i < header->insnum; i++)
	{
		mp_uint32 insOffs = insParaPtrs[i]*16;

		if (insOffs)
		{
			f.seekWithBaseOffset(insOffs);
		
			// We can only read that if it's a sample
			mp_ubyte type = f.readByte();
			
			if (type == 1)
			{
				f.read(smp[s].name,1,12);	// read dos filename
		
				mp_ubyte bOffs = f.readByte();
				mp_uword wOffs = f.readWord();
				
				// stupid fileoffsets
				samplePtrs[i] = (((mp_uint32)bOffs<<16)+(mp_uint32)wOffs)*16;
				
				smp[s].flags = 1;
				smp[s].pan = 0x80;
				
				smp[s].samplen = f.readDword();
				smp[s].loopstart = f.readDword();
				mp_sint32 looplen = ((mp_sint32)f.readDword() - (mp_sint32)smp[s].loopstart);
				if (looplen < 0) 
					looplen = 0;
				smp[s].looplen = looplen;
				
				smp[s].vol = module->vol64to255(f.readByte());
				
				f.readByte(); // skip something
				
				smp[s].res = f.readByte() == 0x04 ? 0xAD : 0; // packing
				
				mp_ubyte flags = f.readByte();
				
				// looping
				if (flags & 1)
				{
					smp[s].type = 1;	
				}
				
				// 16 bit sample
				if (flags & 4)
				{
					smp[s].type |= 16;
					smp[s].samplen >>= 1;
					smp[s].loopstart >>= 1;
					smp[s].looplen >>= 1;
				}
				
				mp_uint32 c4spd = f.readDword();
				
				XModule::convertc4spd(c4spd,&smp[s].finetune,&smp[s].relnote);

#ifdef VERBOSE
				printf(""%i, %i\n"",c4spd,module->getc4spd(smp[s].relnote,smp[s].finetune));				
#endif

				f.readDword(); // skip something
				
				f.readDword(); // skip two internal words
				
				f.readDword(); // skip internal dword

				f.read(instr[i].name,1,28); // instrument name
				
				f.readDword(); // skip signature
				
				if (samplePtrs[i] && smp[s].samplen)
				{
					instr[i].samp=1;
					for (j=0;j<120;j++) 
						instr[i].snum[j] = s;
					s++;
				}
			}
			else if (type == 0)
			{
				samplePtrs[i] = 0;
			
				mp_ubyte buffer[12];
				f.read(buffer,1,12);	// read dos filename
		
				f.readByte();
				f.readWord();
				
				f.readDword();
				f.readDword();
				f.readDword();
				f.readByte();
				f.readByte(); // skip something
				f.readByte(); // skip packing
				
				f.readByte();
				
				f.readDword();
				
				f.readDword(); // skip something
				
				f.readDword(); // skip two internal words
				
				f.readDword(); // skip internal dword

				f.read(instr[i].name,1,28); // instrument name
				
				f.readDword(); // skip signature				
			}
			else 
			{
				samplePtrs[i] = 0;
			}
			
		}

	}
	
	//////////////////////
	// read patterns	//
	//////////////////////
	mp_ubyte* pattern = new mp_ubyte[64*32*5];
	if (pattern == NULL)
	{
		delete[] insParaPtrs;
		delete[] patParaPtrs;
		delete[] samplePtrs;
		return MP_OUT_OF_MEMORY;
	}
	
	mp_uint32 songMaxChannels = 1;
	
	for (i = 0; i < header->patnum; i++)
	{
		for (j = 0; j < 32*64; j++)
		{
			pattern[j*5] = 0xFF;
			pattern[j*5+1] = 0;
			pattern[j*5+2] = 0xFF;
			pattern[j*5+3] = 0xFF;
			pattern[j*5+4] = 0;
		}
		
		mp_uint32 patOffs = patParaPtrs[i]*16;
		
		mp_uint32 maxChannels = 1;			
		
		if (patOffs)
		{
			f.seekWithBaseOffset(patOffs);
			
			mp_uint32 size = f.readWord();
			
			if (size > 2)
			{
				size-=2;
				
				mp_ubyte* packed = new mp_ubyte[size+5];
				if (packed == NULL)
				{
					delete[] insParaPtrs;
					delete[] patParaPtrs;
					delete[] samplePtrs;
					delete[] pattern;
					return MP_OUT_OF_MEMORY;				
				}
				
				memset(packed, 0, size);
				f.read(packed, 1, size);
				
				mp_uint32 index = 0;
				mp_uint32 row = 0;
				
				while (index= 64)
						{
							int i = 0;
							i++;
							i--;
							break;
						}
						continue;
					}
					
					mp_uint32 chn = pi&31;
					
					if (chn>maxChannels && (pi & (32+64+128)))
					{
						maxChannels = chn;
					}
					
					mp_ubyte* slot = pattern+(row*32*5)+chn*5;
					
					if (pi & 32)
					{
						slot[0] = safeRead(packed, index, size, 0xFF);
						slot[1] = safeRead(packed, index, size);
					}
					if (pi & 64)
					{
						slot[2] = safeRead(packed, index, size, 0xFF);
					}
					if (pi & 128)
					{
						slot[3] = safeRead(packed, index, size, 0xFF);
						slot[4] = safeRead(packed, index, size);
					}
					
				}
				
				maxChannels++;
				
				if (maxChannels > header->channum)
					maxChannels = header->channum;
				
				delete[] packed;
			}
			
			if (maxChannels > songMaxChannels)
				songMaxChannels = maxChannels;
			
		}
		
		convertS3MPattern(&phead[i], pattern, maxChannels, i);
		
		
	}
	
	if (header->channum > songMaxChannels)
		header->channum = songMaxChannels;
	
	delete[] pattern;
	delete[] insParaPtrs;
	delete[] patParaPtrs;
	
	s = 0;
	for (i = 0; i < header->insnum; i++)
	{
		mp_uint32 smpOffs = samplePtrs[i];

		if (smpOffs)
		{
			f.seekWithBaseOffset(smpOffs);
			
			if (!smp[s].samplen)
				continue;

			bool adpcm = (smp[s].res == 0xAD);

			mp_sint32 result = module->loadModuleSample(f, s, 
										  adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_UNSIGNED, 
										  adpcm ? (XModule::ST_16BIT | XModule::ST_PACKING_ADPCM) : (XModule::ST_16BIT | XModule::ST_UNSIGNED));
			if (result != MP_OK)
			{
				delete[] samplePtrs;
				return result;
			}
			
			if (adpcm)
				// no longer needed
				smp[s].res = 0;			
							
			s++;
			
		}

	}
	
	delete[] samplePtrs;
	
	header->smpnum = s;
	
	strcpy(header->tracker,""Screamtracker 3"");
	
	module->setDefaultPanning();
	
	module->postProcessSamples();
	
	return MP_OK;	
}",CWE-787,16
1,"static ptrdiff_t finderrfunc(lua_State *L)
{
  cTValue *frame = L->base-1, *bot = tvref(L->stack);
  void *cf = L->cframe;
  while (frame > bot && cf) {
    while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */
      if (frame >= restorestack(L, -cframe_nres(cf)))
	break;
      if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */
	return cframe_errfunc(cf);
      cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */
      if (cf == NULL)
	return 0;
    }
    switch (frame_typep(frame)) {
    case FRAME_LUA:
    case FRAME_LUAP:
      frame = frame_prevl(frame);
      break;
    case FRAME_C:
      cf = cframe_prev(cf);
      /* fallthrough */
    case FRAME_VARG:
      frame = frame_prevd(frame);
      break;
    case FRAME_CONT:
#if LJ_HASFFI
      if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
	cf = cframe_prev(cf);
#endif
      frame = frame_prevd(frame);
      break;
    case FRAME_CP:
      if (cframe_canyield(cf)) return 0;
      if (cframe_errfunc(cf) >= 0)
	return cframe_errfunc(cf);
      frame = frame_prevd(frame);
      break;
    case FRAME_PCALL:
    case FRAME_PCALLH:
      if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue)))  /* xpcall? */
	return savestack(L, frame-1);  /* Point to xpcall's errorfunc. */
      return 0;
    default:
      lua_assert(0);
      return 0;
    }
  }
  return 0;
}",CWE-125,1
0,"void QuotaManager::DeleteOriginData(
    const GURL& origin, StorageType type, StatusCallback* callback) {
  LazyInitialize();

  if (origin.is_empty() || clients_.empty()) {
    callback->Run(kQuotaStatusOk);
    delete callback;
    return;
  }

  OriginDataDeleter* deleter =
      new OriginDataDeleter(this, origin, type, callback);
  deleter->Start();
}
",none,24
1,"static Image *ReadWPGImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
  typedef struct
  {
    size_t FileId;
    MagickOffsetType DataOffset;
    unsigned int ProductType;
    unsigned int FileType;
    unsigned char MajorVersion;
    unsigned char MinorVersion;
    unsigned int EncryptKey;
    unsigned int Reserved;
  } WPGHeader;

  typedef struct
  {
    unsigned char RecType;
    size_t RecordLength;
  } WPGRecord;

  typedef struct
  {
    unsigned char Class;
    unsigned char RecType;
    size_t Extension;
    size_t RecordLength;
  } WPG2Record;

  typedef struct
  {
    unsigned  HorizontalUnits;
    unsigned  VerticalUnits;
    unsigned char PosSizePrecision;
  } WPG2Start;

  typedef struct
  {
    unsigned int Width;
    unsigned int Height;
    unsigned int Depth;
    unsigned int HorzRes;
    unsigned int VertRes;
  } WPGBitmapType1;

  typedef struct
  {
    unsigned int Width;
    unsigned int Height;
    unsigned char Depth;
    unsigned char Compression;
  } WPG2BitmapType1;

  typedef struct
  {
    unsigned int RotAngle;
    unsigned int LowLeftX;
    unsigned int LowLeftY;
    unsigned int UpRightX;
    unsigned int UpRightY;
    unsigned int Width;
    unsigned int Height;
    unsigned int Depth;
    unsigned int HorzRes;
    unsigned int VertRes;
  } WPGBitmapType2;

  typedef struct
  {
    unsigned int StartIndex;
    unsigned int NumOfEntries;
  } WPGColorMapRec;

  /*
  typedef struct {
    size_t PS_unknown1;
    unsigned int PS_unknown2;
    unsigned int PS_unknown3;
  } WPGPSl1Record;  
  */

  Image
    *image;

  unsigned int
    status;

  WPGHeader
    Header;

  WPGRecord
    Rec;

  WPG2Record
    Rec2;

  WPG2Start StartWPG;

  WPGBitmapType1
    BitmapHeader1;

  WPG2BitmapType1
    Bitmap2Header1;

  WPGBitmapType2
    BitmapHeader2;

  WPGColorMapRec
    WPG_Palette;

  int
    i,
    bpp,
    WPG2Flags;

  ssize_t
    ldblk;

  size_t
    one;

  unsigned char
    *BImgBuff;

  tCTM CTM;         /*current transform matrix*/

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  one=1;
  image=AcquireImage(image_info,exception);
  image->depth=8;
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read WPG image.
  */
  Header.FileId=ReadBlobLSBLong(image);
  Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
  Header.ProductType=ReadBlobLSBShort(image);
  Header.FileType=ReadBlobLSBShort(image);
  Header.MajorVersion=ReadBlobByte(image);
  Header.MinorVersion=ReadBlobByte(image);
  Header.EncryptKey=ReadBlobLSBShort(image);
  Header.Reserved=ReadBlobLSBShort(image);

  if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
  if (Header.EncryptKey!=0)
    ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported"");

  image->columns = 1;
  image->rows = 1;
  image->colors = 0;
  bpp=0;
  BitmapHeader2.RotAngle=0;
  Rec2.RecordLength=0;

  switch(Header.FileType)
    {
    case 1:     /* WPG level 1 */
      while(!EOFBlob(image)) /* object parser loop */
        {
          (void) SeekBlob(image,Header.DataOffset,SEEK_SET);
          if(EOFBlob(image))
            break;

          Rec.RecType=(i=ReadBlobByte(image));
          if(i==EOF)
            break;
          Rd_WP_DWORD(image,&Rec.RecordLength);
          if (Rec.RecordLength > GetBlobSize(image))
            ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
          if(EOFBlob(image))
            break;

          Header.DataOffset=TellBlob(image)+Rec.RecordLength;

          switch(Rec.RecType)
            {
            case 0x0B: /* bitmap type 1 */
              BitmapHeader1.Width=ReadBlobLSBShort(image);
              BitmapHeader1.Height=ReadBlobLSBShort(image);
              if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
                ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
              BitmapHeader1.Depth=ReadBlobLSBShort(image);
              BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
              BitmapHeader1.VertRes=ReadBlobLSBShort(image);

              if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
                {
                  image->units=PixelsPerCentimeterResolution;
                  image->resolution.x=BitmapHeader1.HorzRes/470.0;
                  image->resolution.y=BitmapHeader1.VertRes/470.0;
                }
              image->columns=BitmapHeader1.Width;
              image->rows=BitmapHeader1.Height;
              bpp=BitmapHeader1.Depth;

              goto UnpackRaster;

            case 0x0E:  /*Color palette */
              WPG_Palette.StartIndex=ReadBlobLSBShort(image);
              WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
              if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
                  (Rec2.RecordLength-2-2) / 3)
                ThrowReaderException(CorruptImageError,""InvalidColormapIndex"");
              image->colors=WPG_Palette.NumOfEntries;
              if (!AcquireImageColormap(image,image->colors,exception))
                goto NoMemory;
              for (i=WPG_Palette.StartIndex;
                   i < (int)WPG_Palette.NumOfEntries; i++)
                {
                  image->colormap[i].red=ScaleCharToQuantum((unsigned char)
                    ReadBlobByte(image));
                  image->colormap[i].green=ScaleCharToQuantum((unsigned char)
                    ReadBlobByte(image));
                  image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
                    ReadBlobByte(image));
                }
              break;
     
            case 0x11:  /* Start PS l1 */
              if(Rec.RecordLength > 8)
                image=ExtractPostscript(image,image_info,
                  TellBlob(image)+8,   /* skip PS header in the wpg */
                  (ssize_t) Rec.RecordLength-8,exception);
              break;     

            case 0x14:  /* bitmap type 2 */
              BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
              BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
              BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
              BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
              BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
              BitmapHeader2.Width=ReadBlobLSBShort(image);
              BitmapHeader2.Height=ReadBlobLSBShort(image);
              if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
                ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
              BitmapHeader2.Depth=ReadBlobLSBShort(image);
              BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
              BitmapHeader2.VertRes=ReadBlobLSBShort(image);

              image->units=PixelsPerCentimeterResolution;
              image->page.width=(unsigned int)
                ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
              image->page.height=(unsigned int)
                ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
              image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
              image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
              if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
                {
                  image->resolution.x=BitmapHeader2.HorzRes/470.0;
                  image->resolution.y=BitmapHeader2.VertRes/470.0;
                }
              image->columns=BitmapHeader2.Width;
              image->rows=BitmapHeader2.Height;
              bpp=BitmapHeader2.Depth;

            UnpackRaster:      
              status=SetImageExtent(image,image->columns,image->rows,exception);
              if (status == MagickFalse)
                break;
              if ((image->colors == 0) && (bpp != 24))
                {
                  image->colors=one << bpp;
                  if (!AcquireImageColormap(image,image->colors,exception))
                    {
                    NoMemory:
                      ThrowReaderException(ResourceLimitError,
                        ""MemoryAllocationFailed"");
                    }
                  /* printf(""Load default colormap \n""); */
                  for (i=0; (i < (int) image->colors) && (i < 256); i++)
                    {               
                      image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
                      image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
                      image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
                    }
                }
              else
                {
                  if (bpp < 24)
                    if ( (image->colors < (one << bpp)) && (bpp != 24) )
                      image->colormap=(PixelInfo *) ResizeQuantumMemory(
                        image->colormap,(size_t) (one << bpp),
                        sizeof(*image->colormap));
                }
          
              if (bpp == 1)
                {
                  if(image->colormap[0].red==0 &&
                     image->colormap[0].green==0 &&
                     image->colormap[0].blue==0 &&
                     image->colormap[1].red==0 &&
                     image->colormap[1].green==0 &&
                     image->colormap[1].blue==0)
                    {  /* fix crippled monochrome palette */
                      image->colormap[1].red =
                        image->colormap[1].green =
                        image->colormap[1].blue = QuantumRange;
                    }
                }      

              if(UnpackWPGRaster(image,bpp,exception) < 0)
                /* The raster cannot be unpacked */
                {
                DecompressionFailed:
                  ThrowReaderException(CoderError,""UnableToDecompressImage"");
                    }

              if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
                {  
                  /* flop command */
                  if(BitmapHeader2.RotAngle & 0x8000)
                    {
                      Image
                        *flop_image;

                      flop_image = FlopImage(image, exception);
                      if (flop_image != (Image *) NULL) {
                        DuplicateBlob(flop_image,image);
                        ReplaceImageInList(&image,flop_image);
                      }
                    }
                  /* flip command */
                  if(BitmapHeader2.RotAngle & 0x2000)
                    {
                      Image
                        *flip_image;

                      flip_image = FlipImage(image, exception);
                      if (flip_image != (Image *) NULL) {
                        DuplicateBlob(flip_image,image);
                        ReplaceImageInList(&image,flip_image);
                      }
                    }
                  /* rotate command */
                  if(BitmapHeader2.RotAngle & 0x0FFF)
                    {
                      Image
                        *rotate_image;

                      rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
                        0x0FFF), exception);
                      if (rotate_image != (Image *) NULL) {
                        DuplicateBlob(rotate_image,image);
                        ReplaceImageInList(&image,rotate_image);
                      }
                    }
                }

              /* Allocate next image structure. */
              AcquireNextImage(image_info,image,exception);
              image->depth=8;
              if (image->next == (Image *) NULL)
                goto Finish;
              image=SyncNextImageInList(image);
              image->columns=image->rows=1;
              image->colors=0;
              break;

            case 0x1B:  /* Postscript l2 */
              if(Rec.RecordLength>0x3C)
                image=ExtractPostscript(image,image_info,
                  TellBlob(image)+0x3C,   /* skip PS l2 header in the wpg */
                  (ssize_t) Rec.RecordLength-0x3C,exception);
              break;
            }
        }
      break;

    case 2:  /* WPG level 2 */
      (void) memset(CTM,0,sizeof(CTM));
      StartWPG.PosSizePrecision = 0;
      while(!EOFBlob(image)) /* object parser loop */
        {
          (void) SeekBlob(image,Header.DataOffset,SEEK_SET);
          if(EOFBlob(image))
            break;

          Rec2.Class=(i=ReadBlobByte(image));
          if(i==EOF)
            break;
          Rec2.RecType=(i=ReadBlobByte(image));
          if(i==EOF)
            break;
          Rd_WP_DWORD(image,&Rec2.Extension);
          Rd_WP_DWORD(image,&Rec2.RecordLength);
          if(EOFBlob(image))
            break;

          Header.DataOffset=TellBlob(image)+Rec2.RecordLength;

          switch(Rec2.RecType)
            {
      case 1:
              StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
              StartWPG.VerticalUnits=ReadBlobLSBShort(image);
              StartWPG.PosSizePrecision=ReadBlobByte(image);
              break;
            case 0x0C:    /* Color palette */
              WPG_Palette.StartIndex=ReadBlobLSBShort(image);
              WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
              if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) >
                  (Rec2.RecordLength-2-2) / 3)
                ThrowReaderException(CorruptImageError,""InvalidColormapIndex"");
              image->colors=WPG_Palette.NumOfEntries;
              if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
                ThrowReaderException(ResourceLimitError,
                  ""MemoryAllocationFailed"");
              for (i=WPG_Palette.StartIndex;
                   i < (int)WPG_Palette.NumOfEntries; i++)
                {
                  image->colormap[i].red=ScaleCharToQuantum((char)
                    ReadBlobByte(image));
                  image->colormap[i].green=ScaleCharToQuantum((char)
                    ReadBlobByte(image));
                  image->colormap[i].blue=ScaleCharToQuantum((char)
                    ReadBlobByte(image));
                  (void) ReadBlobByte(image);   /*Opacity??*/
                }
              break;
            case 0x0E:
              Bitmap2Header1.Width=ReadBlobLSBShort(image);
              Bitmap2Header1.Height=ReadBlobLSBShort(image);
              if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
                ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
              Bitmap2Header1.Depth=ReadBlobByte(image);
              Bitmap2Header1.Compression=ReadBlobByte(image);

              if(Bitmap2Header1.Compression > 1)
                continue; /*Unknown compression method */
              switch(Bitmap2Header1.Depth)
                {
                case 1:
                  bpp=1;
                  break;
                case 2:
                  bpp=2;
                  break;
                case 3:
                  bpp=4;
                  break;
                case 4:
                  bpp=8;
                  break;
                case 8:
                  bpp=24;
                  break;
                default:
                  continue;  /*Ignore raster with unknown depth*/
                }
              image->columns=Bitmap2Header1.Width;
              image->rows=Bitmap2Header1.Height;
              status=SetImageExtent(image,image->columns,image->rows,exception);
              if (status == MagickFalse)
                break;
              if ((image->colors == 0) && (bpp != 24))
                {
                  image->colors=one << bpp;
                  if (!AcquireImageColormap(image,image->colors,exception))
                    goto NoMemory;
                }
              else
                {
                  if(bpp < 24)
                    if( image->colors<(one << bpp) && bpp!=24 )
                      image->colormap=(PixelInfo *) ResizeQuantumMemory(
                       image->colormap,(size_t) (one << bpp),
                       sizeof(*image->colormap));
                }


              switch(Bitmap2Header1.Compression)
                {
                case 0:    /*Uncompressed raster*/
                  {
                    ldblk=(ssize_t) ((bpp*image->columns+7)/8);
                    BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
                      ldblk+1,sizeof(*BImgBuff));
                    if (BImgBuff == (unsigned char *) NULL)
                      goto NoMemory;

                    for(i=0; i< (ssize_t) image->rows; i++)
                      {
                        (void) ReadBlob(image,ldblk,BImgBuff);
                        InsertRow(image,BImgBuff,i,bpp,exception);
                      }

                    if(BImgBuff)
                      BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
                    break;
                  }
                case 1:    /*RLE for WPG2 */
                  {
                    if( UnpackWPG2Raster(image,bpp,exception) < 0)
                      goto DecompressionFailed;
                    break;
                  }   
                }

              if(CTM[0][0]<0 && !image_info->ping)
                {    /*?? RotAngle=360-RotAngle;*/
                  Image
                    *flop_image;

                  flop_image = FlopImage(image, exception);
                  if (flop_image != (Image *) NULL) {
                    DuplicateBlob(flop_image,image);
                    ReplaceImageInList(&image,flop_image);
                  }
                  /* Try to change CTM according to Flip - I am not sure, must be checked.
                     Tx(0,0)=-1;      Tx(1,0)=0;   Tx(2,0)=0;
                     Tx(0,1)= 0;      Tx(1,1)=1;   Tx(2,1)=0;
                     Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
                     Tx(1,2)=0;   Tx(2,2)=1; */
                }
              if(CTM[1][1]<0 && !image_info->ping)
                {    /*?? RotAngle=360-RotAngle;*/
                  Image
                    *flip_image;

                   flip_image = FlipImage(image, exception);
                   if (flip_image != (Image *) NULL) {
                     DuplicateBlob(flip_image,image);
                     ReplaceImageInList(&image,flip_image);
                    }
                  /* Try to change CTM according to Flip - I am not sure, must be checked.
                     float_matrix Tx(3,3);
                     Tx(0,0)= 1;   Tx(1,0)= 0;   Tx(2,0)=0;
                     Tx(0,1)= 0;   Tx(1,1)=-1;   Tx(2,1)=0;
                     Tx(0,2)= 0;   Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
                     Tx(2,2)=1; */
              }


              /* Allocate next image structure. */
              AcquireNextImage(image_info,image,exception);
              image->depth=8;
              if (image->next == (Image *) NULL)
                goto Finish;
              image=SyncNextImageInList(image);
              image->columns=image->rows=1;
              image->colors=0;
              break;

            case 0x12:  /* Postscript WPG2*/
        i=ReadBlobLSBShort(image);
              if(Rec2.RecordLength > (unsigned int) i)
                image=ExtractPostscript(image,image_info,
                  TellBlob(image)+i,    /*skip PS header in the wpg2*/
                  (ssize_t) (Rec2.RecordLength-i-2),exception);
              break;

      case 0x1B:          /*bitmap rectangle*/
              WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
              (void) WPG2Flags;
              break;
            }
        }

      break;

    default:
      {
         ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported"");
      }
   }

 Finish:
  (void) CloseBlob(image);

  {
    Image
      *p;

    ssize_t
      scene=0;

    /*
      Rewind list, removing any empty images while rewinding.
    */
    p=image;
    image=NULL;
    while (p != (Image *) NULL)
      {
        Image *tmp=p;
        if ((p->rows == 0) || (p->columns == 0)) {
          p=p->previous;
          DeleteImageFromList(&tmp);
        } else {
          image=p;
          p=p->previous;
        }
      }
    /*
      Fix scene numbers.
    */
    for (p=image; p != (Image *) NULL; p=p->next)
      p->scene=(size_t) scene++;
  }
  if (image == (Image *) NULL)
    ThrowReaderException(CorruptImageError,
      ""ImageFileDoesNotContainAnyImageData"");
  return(image);
}",CWE-400,9
0,"void CountOriginType(const std::set& origins,
                     SpecialStoragePolicy* policy,
                     size_t* protected_origins,
                     size_t* unlimited_origins) {
  DCHECK(protected_origins);
  DCHECK(unlimited_origins);
  *protected_origins = 0;
  *unlimited_origins = 0;
  if (!policy)
    return;
  for (std::set::const_iterator itr = origins.begin();
       itr != origins.end();
       ++itr) {
    if (policy->IsStorageProtected(*itr))
      ++*protected_origins;
    if (policy->IsStorageUnlimited(*itr))
      ++*unlimited_origins;
  }
}
",none,24
1,"void mobi_buffer_move(MOBIBuffer *buf, const int offset, const size_t len) {
    size_t aoffset = (size_t) abs(offset);
    unsigned char *source = buf->data + buf->offset;
    if (offset >= 0) {
        if (buf->offset + aoffset + len > buf->maxlen) {
            debug_print(""%s"", ""End of buffer\n"");
            buf->error = MOBI_BUFFER_END;
            return;
        }
        source += aoffset;
    } else {
        if (buf->offset < aoffset) {
            debug_print(""%s"", ""End of buffer\n"");
            buf->error = MOBI_BUFFER_END;
            return;
        }
        source -= aoffset;
    }
    memmove(buf->data + buf->offset, source, len);
    buf->offset += len;
}",CWE-787,16
1,"static void naludmx_queue_param_set(GF_NALUDmxCtx *ctx, char *data, u32 size, u32 ps_type, s32 ps_id)
{
	GF_List *list = NULL, *alt_list = NULL;
	GF_NALUFFParam *sl;
	u32 i, count;
	u32 crc = gf_crc_32(data, size);

	if (ctx->codecid==GF_CODECID_HEVC) {
		switch (ps_type) {
		case GF_HEVC_NALU_VID_PARAM:
			if (!ctx->vps) ctx->vps = gf_list_new();
			list = ctx->vps;
			break;
		case GF_HEVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_HEVC_NALU_PIC_PARAM:
			list = ctx->pps;
			break;
		default:
			assert(0);
			return;
		}
	} else if (ctx->codecid==GF_CODECID_VVC) {
		switch (ps_type) {
		case GF_VVC_NALU_VID_PARAM:
			if (!ctx->vps) ctx->vps = gf_list_new();
			list = ctx->vps;
			break;
		case GF_VVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_VVC_NALU_PIC_PARAM:
			list = ctx->pps;
			break;
		case GF_VVC_NALU_DEC_PARAM:
			if (!ctx->vvc_dci) ctx->vvc_dci = gf_list_new();
			list = ctx->vvc_dci;
			break;
		case GF_VVC_NALU_APS_PREFIX:
			if (!ctx->vvc_aps_pre) ctx->vvc_aps_pre = gf_list_new();
			list = ctx->vvc_aps_pre;
			break;
		default:
			assert(0);
			return;
		}
	} else {
		switch (ps_type) {
		case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
		case GF_AVC_NALU_SEQ_PARAM:
			list = ctx->sps;
			break;
		case GF_AVC_NALU_PIC_PARAM:
			list = ctx->pps;
			alt_list = ctx->pps_svc;
			break;
		case GF_AVC_NALU_SEQ_PARAM_EXT:
			if (!ctx->sps_ext) ctx->sps_ext = gf_list_new();
			list = ctx->sps_ext;
			break;
		default:
			assert(0);
			return;
		}
	}
	sl = NULL;
	count = gf_list_count(list);
	for (i=0; iid != ps_id) {
			sl = NULL;
			continue;
		}
		//same ID, same CRC, we don't change our state
		if (sl->crc == crc) return;
		break;
	}
	//handle alt PPS list for SVC
	if (!sl && alt_list) {
		count = gf_list_count(alt_list);
		for (i=0; iid != ps_id) {
				sl = NULL;
				continue;
			}
			//same ID, same CRC, we don't change our state
			if (sl->crc == crc) return;
			break;
		}
	}

	if (sl) {
		//otherwise we keep this new param set
		sl->data = gf_realloc(sl->data, size);
		memcpy(sl->data, data, size);
		sl->size = size;
		sl->crc = crc;
		ctx->ps_modified = GF_TRUE;
		return;
	}
	//TODO we might want to purge the list after a while !!

	GF_SAFEALLOC(sl, GF_NALUFFParam);
	if (!sl) return;
	sl->data = gf_malloc(sizeof(char) * size);
	if (!sl->data) {
		gf_free(sl);
		return;
	}
	memcpy(sl->data, data, size);
	sl->size = size;
	sl->id = ps_id;
	sl->crc = crc;

	ctx->ps_modified = GF_TRUE;
	gf_list_add(list, sl);
}",CWE-476,12
0,"  virtual bool wifi_connecting() const { return false; }
",none,24
0,"  HostUsageCallback* NewWaitableHostUsageCallback() {
    ++waiting_callbacks_;
    return callback_factory_.NewCallback(
            &UsageAndQuotaDispatcherTask::DidGetHostUsage);
  }
",none,24
1,"static void atusb_disconnect(struct usb_interface *interface)
{
	struct atusb *atusb = usb_get_intfdata(interface);

	dev_dbg(&atusb->usb_dev->dev, ""%s\n"", __func__);

	atusb->shutdown = 1;
	cancel_delayed_work_sync(&atusb->work);

	usb_kill_anchored_urbs(&atusb->rx_urbs);
	atusb_free_urbs(atusb);
	usb_kill_urb(atusb->tx_urb);
	usb_free_urb(atusb->tx_urb);

	ieee802154_unregister_hw(atusb->hw);

	ieee802154_free_hw(atusb->hw);

	usb_set_intfdata(interface, NULL);
	usb_put_dev(atusb->usb_dev);

	pr_debug(""%s done\n"", __func__);
}",CWE-416,10
1,"  Status SetUnknownShape(const NodeDef* node, int output_port) {
    shape_inference::ShapeHandle shape =
        GetUnknownOutputShape(node, output_port);
    InferenceContext* ctx = GetContext(node);
    if (ctx == nullptr) {
      return errors::InvalidArgument(""Missing context"");
    }
    ctx->set_output(output_port, shape);
    return Status::OK();
  }",CWE-787,16
1,"  void Compute(OpKernelContext* context) override {
    const Tensor& indices = context->input(0);
    const Tensor& values = context->input(1);
    const Tensor& shape = context->input(2);
    const Tensor& weights = context->input(3);
    bool use_weights = weights.NumElements() > 0;

    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),
                errors::InvalidArgument(
                    ""Input indices must be a 2-dimensional tensor. Got: "",
                    indices.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(values.shape()),
                errors::InvalidArgument(""Input values must be a vector. Got: "",
                                        values.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(shape.shape()),
                errors::InvalidArgument(""Input shape must be a vector. Got: "",
                                        shape.shape().DebugString()));
    OP_REQUIRES(context,
                values.shape().dim_size(0) == indices.shape().dim_size(0),
                errors::InvalidArgument(
                    ""Number of values must match first dimension of indices."",
                    ""Got "", values.shape().dim_size(0),
                    "" values, indices shape: "", indices.shape().DebugString()));
    OP_REQUIRES(
        context, shape.shape().dim_size(0) == indices.shape().dim_size(1),
        errors::InvalidArgument(
            ""Number of dimensions must match second dimension of indices."",
            ""Got "", shape.shape().dim_size(0),
            "" dimensions, indices shape: "", indices.shape().DebugString()));
    OP_REQUIRES(context, shape.NumElements() > 0,
                errors::InvalidArgument(
                    ""The shape argument requires at least one element.""));

    if (use_weights) {
      OP_REQUIRES(
          context, weights.shape() == values.shape(),
          errors::InvalidArgument(
              ""Weights and values must have the same shape. Weight shape: "",
              weights.shape().DebugString(),
              ""; values shape: "", values.shape().DebugString()));
    }

    bool is_1d = shape.NumElements() == 1;
    auto shape_vector = shape.flat();
    int num_batches = is_1d ? 1 : shape_vector(0);
    int num_values = values.NumElements();

    const auto indices_values = indices.matrix();
    const auto values_values = values.flat();
    const auto weight_values = weights.flat();

    auto per_batch_counts = BatchedMap(num_batches);

    T max_value = 0;

    for (int idx = 0; idx < num_values; ++idx) {
      int batch = is_1d ? 0 : indices_values(idx, 0);
      if (batch >= num_batches) {
        OP_REQUIRES(context, batch < num_batches,
                    errors::InvalidArgument(
                        ""Indices value along the first dimension must be "",
                        ""lower than the first index of the shape."", ""Got "",
                        batch, "" as batch and "", num_batches,
                        "" as the first dimension of the shape.""));
      }
      const auto& value = values_values(idx);
      if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {
        if (binary_output_) {
          per_batch_counts[batch][value] = 1;
        } else if (use_weights) {
          per_batch_counts[batch][value] += weight_values(idx);
        } else {
          per_batch_counts[batch][value]++;
        }
        if (value > max_value) {
          max_value = value;
        }
      }
    }

    int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);
    OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,
                                            is_1d, context));
  }",CWE-787,16
0,"  virtual void AddNetworkObserver(const std::string& service_path,
                                  NetworkObserver* observer) {
    DCHECK(observer);
    if (!EnsureCrosLoaded())
      return;
    NetworkObserverMap::iterator iter = network_observers_.find(service_path);
    NetworkObserverList* oblist;
    if (iter != network_observers_.end()) {
      oblist = iter->second;
    } else {
      std::pair inserted =
        network_observers_.insert(
            std::make_pair(
                service_path,
                new NetworkObserverList(this, service_path)));
      oblist = inserted.first->second;
    }
    if (!oblist->HasObserver(observer))
      oblist->AddObserver(observer);
  }
",none,24
0,"  void UpdateSystemInfo() {
    if (EnsureCrosLoaded()) {
      UpdateNetworkManagerStatus();
    }
  }
",none,24
0,"static NetworkRoamingState ParseRoamingState(
    const std::string& roaming_state) {
    if (roaming_state == kRoamingStateHome)
    return ROAMING_STATE_HOME;
  if (roaming_state == kRoamingStateRoaming)
    return ROAMING_STATE_ROAMING;
  if (roaming_state == kRoamingStateUnknown)
    return ROAMING_STATE_UNKNOWN;
  return ROAMING_STATE_UNKNOWN;
}
",none,24
1,"RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {
	RList *entries = r_list_newf (free);
	if (!entries) {
		return NULL;
	}
	RList *segments = r_bin_ne_get_segments (bin);
	if (!segments) {
		r_list_free (entries);
		return NULL;
	}
	if (bin->ne_header->csEntryPoint) {
		RBinAddr *entry = R_NEW0 (RBinAddr);
		if (!entry) {
			r_list_free (entries);
			return NULL;
		}
		entry->bits = 16;
		ut32 entry_cs = bin->ne_header->csEntryPoint;
		RBinSection *s = r_list_get_n (segments, entry_cs - 1);
		entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);

		r_list_append (entries, entry);
	}
	int off = 0;
	size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;
	while (off < bin->ne_header->EntryTableLength) {
		if (tableat + off >= r_buf_size (bin->buf)) {
			break;
		}
		ut8 bundle_length = *(ut8 *)(bin->entry_table + off);
		if (!bundle_length) {
			break;
		}
		off++;
		ut8 bundle_type = *(ut8 *)(bin->entry_table + off);
		off++;
		int i;
		for (i = 0; i < bundle_length; i++) {
			if (tableat + off + 4 >= r_buf_size (bin->buf)) {
				break;
			}
			RBinAddr *entry = R_NEW0 (RBinAddr);
			if (!entry) {
				r_list_free (entries);
				return NULL;
			}
			off++;
			if (!bundle_type) { // Skip
				off--;
				free (entry);
				break;
			} else if (bundle_type == 0xff) { // moveable
				off += 2;
				ut8 segnum = *(bin->entry_table + off);
				off++;
				ut16 segoff = *(ut16 *)(bin->entry_table + off);
				if (segnum > 0) {
					entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;
				}
			} else { // Fixed
				if (bundle_type < bin->ne_header->SegCount) {
					entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset
						* bin->alignment + *(ut16 *)(bin->entry_table + off);
				}
			}
			off += 2;
			r_list_append (entries, entry);
		}
	}
	r_list_free (segments);
	bin->entries = entries;
	return entries;
}",CWE-476,12
1,"find_pattern_in_path(
    char_u	*ptr,		// pointer to search pattern
    int		dir UNUSED,	// direction of expansion
    int		len,		// length of search pattern
    int		whole,		// match whole words only
    int		skip_comments,	// don't match inside comments
    int		type,		// Type of search; are we looking for a type?
				// a macro?
    long	count,
    int		action,		// What to do when we find it
    linenr_T	start_lnum,	// first line to start searching
    linenr_T	end_lnum)	// last line for searching
{
    SearchedFile *files;		// Stack of included files
    SearchedFile *bigger;		// When we need more space
    int		max_path_depth = 50;
    long	match_count = 1;

    char_u	*pat;
    char_u	*new_fname;
    char_u	*curr_fname = curbuf->b_fname;
    char_u	*prev_fname = NULL;
    linenr_T	lnum;
    int		depth;
    int		depth_displayed;	// For type==CHECK_PATH
    int		old_files;
    int		already_searched;
    char_u	*file_line;
    char_u	*line;
    char_u	*p;
    char_u	save_char;
    int		define_matched;
    regmatch_T	regmatch;
    regmatch_T	incl_regmatch;
    regmatch_T	def_regmatch;
    int		matched = FALSE;
    int		did_show = FALSE;
    int		found = FALSE;
    int		i;
    char_u	*already = NULL;
    char_u	*startp = NULL;
    char_u	*inc_opt = NULL;
#if defined(FEAT_QUICKFIX)
    win_T	*curwin_save = NULL;
#endif

    regmatch.regprog = NULL;
    incl_regmatch.regprog = NULL;
    def_regmatch.regprog = NULL;

    file_line = alloc(LSIZE);
    if (file_line == NULL)
	return;

    if (type != CHECK_PATH && type != FIND_DEFINE
	    // when CONT_SOL is set compare ""ptr"" with the beginning of the
	    // line is faster than quote_meta/regcomp/regexec ""ptr"" -- Acevedo
	    && !compl_status_sol())
    {
	pat = alloc(len + 5);
	if (pat == NULL)
	    goto fpip_end;
	sprintf((char *)pat, whole ? ""\\<%.*s\\>"" : ""%.*s"", len, ptr);
	// ignore case according to p_ic, p_scs and pat
	regmatch.rm_ic = ignorecase(pat);
	regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
	vim_free(pat);
	if (regmatch.regprog == NULL)
	    goto fpip_end;
    }
    inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;
    if (*inc_opt != NUL)
    {
	incl_regmatch.regprog = vim_regcomp(inc_opt,
						 magic_isset() ? RE_MAGIC : 0);
	if (incl_regmatch.regprog == NULL)
	    goto fpip_end;
	incl_regmatch.rm_ic = FALSE;	// don't ignore case in incl. pat.
    }
    if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL))
    {
	def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL
			   ? p_def : curbuf->b_p_def,
						 magic_isset() ? RE_MAGIC : 0);
	if (def_regmatch.regprog == NULL)
	    goto fpip_end;
	def_regmatch.rm_ic = FALSE;	// don't ignore case in define pat.
    }
    files = lalloc_clear(max_path_depth * sizeof(SearchedFile), TRUE);
    if (files == NULL)
	goto fpip_end;
    old_files = max_path_depth;
    depth = depth_displayed = -1;

    lnum = start_lnum;
    if (end_lnum > curbuf->b_ml.ml_line_count)
	end_lnum = curbuf->b_ml.ml_line_count;
    if (lnum > end_lnum)		// do at least one line
	lnum = end_lnum;
    line = ml_get(lnum);

    for (;;)
    {
	if (incl_regmatch.regprog != NULL
		&& vim_regexec(&incl_regmatch, line, (colnr_T)0))
	{
	    char_u *p_fname = (curr_fname == curbuf->b_fname)
					      ? curbuf->b_ffname : curr_fname;

	    if (inc_opt != NULL && strstr((char *)inc_opt, ""\\zs"") != NULL)
		// Use text from '\zs' to '\ze' (or end) of 'include'.
		new_fname = find_file_name_in_path(incl_regmatch.startp[0],
		       (int)(incl_regmatch.endp[0] - incl_regmatch.startp[0]),
				 FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname);
	    else
		// Use text after match with 'include'.
		new_fname = file_name_in_line(incl_regmatch.endp[0], 0,
			     FNAME_EXP|FNAME_INCL|FNAME_REL, 1L, p_fname, NULL);
	    already_searched = FALSE;
	    if (new_fname != NULL)
	    {
		// Check whether we have already searched in this file
		for (i = 0;; i++)
		{
		    if (i == depth + 1)
			i = old_files;
		    if (i == max_path_depth)
			break;
		    if (fullpathcmp(new_fname, files[i].name, TRUE, TRUE)
								    & FPC_SAME)
		    {
			if (type != CHECK_PATH
				&& action == ACTION_SHOW_ALL
				&& files[i].matched)
			{
			    msg_putchar('\n');	    // cursor below last one
			    if (!got_int)	    // don't display if 'q'
						    // typed at ""--more--""
						    // message
			    {
				msg_home_replace_hl(new_fname);
				msg_puts(_("" (includes previously listed match)""));
				prev_fname = NULL;
			    }
			}
			VIM_CLEAR(new_fname);
			already_searched = TRUE;
			break;
		    }
		}
	    }

	    if (type == CHECK_PATH && (action == ACTION_SHOW_ALL
				 || (new_fname == NULL && !already_searched)))
	    {
		if (did_show)
		    msg_putchar('\n');	    // cursor below last one
		else
		{
		    gotocmdline(TRUE);	    // cursor at status line
		    msg_puts_title(_(""--- Included files ""));
		    if (action != ACTION_SHOW_ALL)
			msg_puts_title(_(""not found ""));
		    msg_puts_title(_(""in path ---\n""));
		}
		did_show = TRUE;
		while (depth_displayed < depth && !got_int)
		{
		    ++depth_displayed;
		    for (i = 0; i < depth_displayed; i++)
			msg_puts(""  "");
		    msg_home_replace(files[depth_displayed].name);
		    msg_puts("" -->\n"");
		}
		if (!got_int)		    // don't display if 'q' typed
					    // for ""--more--"" message
		{
		    for (i = 0; i <= depth_displayed; i++)
			msg_puts(""  "");
		    if (new_fname != NULL)
		    {
			// using ""new_fname"" is more reliable, e.g., when
			// 'includeexpr' is set.
			msg_outtrans_attr(new_fname, HL_ATTR(HLF_D));
		    }
		    else
		    {
			/*
			 * Isolate the file name.
			 * Include the surrounding """" or <> if present.
			 */
			if (inc_opt != NULL
				   && strstr((char *)inc_opt, ""\\zs"") != NULL)
			{
			    // pattern contains \zs, use the match
			    p = incl_regmatch.startp[0];
			    i = (int)(incl_regmatch.endp[0]
						   - incl_regmatch.startp[0]);
			}
			else
			{
			    // find the file name after the end of the match
			    for (p = incl_regmatch.endp[0];
						  *p && !vim_isfilec(*p); p++)
				;
			    for (i = 0; vim_isfilec(p[i]); i++)
				;
			}

			if (i == 0)
			{
			    // Nothing found, use the rest of the line.
			    p = incl_regmatch.endp[0];
			    i = (int)STRLEN(p);
			}
			// Avoid checking before the start of the line, can
			// happen if \zs appears in the regexp.
			else if (p > line)
			{
			    if (p[-1] == '""' || p[-1] == '<')
			    {
				--p;
				++i;
			    }
			    if (p[i] == '""' || p[i] == '>')
				++i;
			}
			save_char = p[i];
			p[i] = NUL;
			msg_outtrans_attr(p, HL_ATTR(HLF_D));
			p[i] = save_char;
		    }

		    if (new_fname == NULL && action == ACTION_SHOW_ALL)
		    {
			if (already_searched)
			    msg_puts(_(""  (Already listed)""));
			else
			    msg_puts(_(""  NOT FOUND""));
		    }
		}
		out_flush();	    // output each line directly
	    }

	    if (new_fname != NULL)
	    {
		// Push the new file onto the file stack
		if (depth + 1 == old_files)
		{
		    bigger = ALLOC_MULT(SearchedFile, max_path_depth * 2);
		    if (bigger != NULL)
		    {
			for (i = 0; i <= depth; i++)
			    bigger[i] = files[i];
			for (i = depth + 1; i < old_files + max_path_depth; i++)
			{
			    bigger[i].fp = NULL;
			    bigger[i].name = NULL;
			    bigger[i].lnum = 0;
			    bigger[i].matched = FALSE;
			}
			for (i = old_files; i < max_path_depth; i++)
			    bigger[i + max_path_depth] = files[i];
			old_files += max_path_depth;
			max_path_depth *= 2;
			vim_free(files);
			files = bigger;
		    }
		}
		if ((files[depth + 1].fp = mch_fopen((char *)new_fname, ""r""))
								    == NULL)
		    vim_free(new_fname);
		else
		{
		    if (++depth == old_files)
		    {
			/*
			 * lalloc() for 'bigger' must have failed above.  We
			 * will forget one of our already visited files now.
			 */
			vim_free(files[old_files].name);
			++old_files;
		    }
		    files[depth].name = curr_fname = new_fname;
		    files[depth].lnum = 0;
		    files[depth].matched = FALSE;
		    if (action == ACTION_EXPAND)
		    {
			msg_hist_off = TRUE;	// reset in msg_trunc_attr()
			vim_snprintf((char*)IObuff, IOSIZE,
				_(""Scanning included file: %s""),
				(char *)new_fname);
			msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
		    }
		    else if (p_verbose >= 5)
		    {
			verbose_enter();
			smsg(_(""Searching included file %s""),
							   (char *)new_fname);
			verbose_leave();
		    }

		}
	    }
	}
	else
	{
	    /*
	     * Check if the line is a define (type == FIND_DEFINE)
	     */
	    p = line;
search_line:
	    define_matched = FALSE;
	    if (def_regmatch.regprog != NULL
			      && vim_regexec(&def_regmatch, line, (colnr_T)0))
	    {
		/*
		 * Pattern must be first identifier after 'define', so skip
		 * to that position before checking for match of pattern.  Also
		 * don't let it match beyond the end of this identifier.
		 */
		p = def_regmatch.endp[0];
		while (*p && !vim_iswordc(*p))
		    p++;
		define_matched = TRUE;
	    }

	    /*
	     * Look for a match.  Don't do this if we are looking for a
	     * define and this line didn't match define_prog above.
	     */
	    if (def_regmatch.regprog == NULL || define_matched)
	    {
		if (define_matched || compl_status_sol())
		{
		    // compare the first ""len"" chars from ""ptr""
		    startp = skipwhite(p);
		    if (p_ic)
			matched = !MB_STRNICMP(startp, ptr, len);
		    else
			matched = !STRNCMP(startp, ptr, len);
		    if (matched && define_matched && whole
						  && vim_iswordc(startp[len]))
			matched = FALSE;
		}
		else if (regmatch.regprog != NULL
			 && vim_regexec(®match, line, (colnr_T)(p - line)))
		{
		    matched = TRUE;
		    startp = regmatch.startp[0];
		    /*
		     * Check if the line is not a comment line (unless we are
		     * looking for a define).  A line starting with ""# define""
		     * is not considered to be a comment line.
		     */
		    if (!define_matched && skip_comments)
		    {
			if ((*line != '#' ||
				STRNCMP(skipwhite(line + 1), ""define"", 6) != 0)
				&& get_leader_len(line, NULL, FALSE, TRUE))
			    matched = FALSE;

			/*
			 * Also check for a ""/ *"" or ""/ /"" before the match.
			 * Skips lines like ""int backwards;  / * normal index
			 * * /"" when looking for ""normal"".
			 * Note: Doesn't skip ""/ *"" in comments.
			 */
			p = skipwhite(line);
			if (matched
				|| (p[0] == '/' && p[1] == '*') || p[0] == '*')
			    for (p = line; *p && p < startp; ++p)
			    {
				if (matched
					&& p[0] == '/'
					&& (p[1] == '*' || p[1] == '/'))
				{
				    matched = FALSE;
				    // After ""//"" all text is comment
				    if (p[1] == '/')
					break;
				    ++p;
				}
				else if (!matched && p[0] == '*' && p[1] == '/')
				{
				    // Can find match after ""* /"".
				    matched = TRUE;
				    ++p;
				}
			    }
		    }
		}
	    }
	}
	if (matched)
	{
	    if (action == ACTION_EXPAND)
	    {
		int	cont_s_ipos = FALSE;
		int	add_r;
		char_u	*aux;

		if (depth == -1 && lnum == curwin->w_cursor.lnum)
		    break;
		found = TRUE;
		aux = p = startp;
		if (compl_status_adding())
		{
		    p += ins_compl_len();
		    if (vim_iswordp(p))
			goto exit_matched;
		    p = find_word_start(p);
		}
		p = find_word_end(p);
		i = (int)(p - aux);

		if (compl_status_adding() && i == ins_compl_len())
		{
		    // IOSIZE > compl_length, so the STRNCPY works
		    STRNCPY(IObuff, aux, i);

		    // Get the next line: when ""depth"" < 0  from the current
		    // buffer, otherwise from the included file.  Jump to
		    // exit_matched when past the last line.
		    if (depth < 0)
		    {
			if (lnum >= end_lnum)
			    goto exit_matched;
			line = ml_get(++lnum);
		    }
		    else if (vim_fgets(line = file_line,
						      LSIZE, files[depth].fp))
			goto exit_matched;

		    // we read a line, set ""already"" to check this ""line"" later
		    // if depth >= 0 we'll increase files[depth].lnum far
		    // below  -- Acevedo
		    already = aux = p = skipwhite(line);
		    p = find_word_start(p);
		    p = find_word_end(p);
		    if (p > aux)
		    {
			if (*aux != ')' && IObuff[i-1] != TAB)
			{
			    if (IObuff[i-1] != ' ')
				IObuff[i++] = ' ';
			    // IObuf =~ ""\(\k\|\i\).* "", thus i >= 2
			    if (p_js
				&& (IObuff[i-2] == '.'
				    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL
					&& (IObuff[i-2] == '?'
					    || IObuff[i-2] == '!'))))
				IObuff[i++] = ' ';
			}
			// copy as much as possible of the new word
			if (p - aux >= IOSIZE - i)
			    p = aux + IOSIZE - i - 1;
			STRNCPY(IObuff + i, aux, p - aux);
			i += (int)(p - aux);
			cont_s_ipos = TRUE;
		    }
		    IObuff[i] = NUL;
		    aux = IObuff;

		    if (i == ins_compl_len())
			goto exit_matched;
		}

		add_r = ins_compl_add_infercase(aux, i, p_ic,
			curr_fname == curbuf->b_fname ? NULL : curr_fname,
			dir, cont_s_ipos);
		if (add_r == OK)
		    // if dir was BACKWARD then honor it just once
		    dir = FORWARD;
		else if (add_r == FAIL)
		    break;
	    }
	    else if (action == ACTION_SHOW_ALL)
	    {
		found = TRUE;
		if (!did_show)
		    gotocmdline(TRUE);		// cursor at status line
		if (curr_fname != prev_fname)
		{
		    if (did_show)
			msg_putchar('\n');	// cursor below last one
		    if (!got_int)		// don't display if 'q' typed
						// at ""--more--"" message
			msg_home_replace_hl(curr_fname);
		    prev_fname = curr_fname;
		}
		did_show = TRUE;
		if (!got_int)
		    show_pat_in_path(line, type, TRUE, action,
			    (depth == -1) ? NULL : files[depth].fp,
			    (depth == -1) ? &lnum : &files[depth].lnum,
			    match_count++);

		// Set matched flag for this file and all the ones that
		// include it
		for (i = 0; i <= depth; ++i)
		    files[i].matched = TRUE;
	    }
	    else if (--count <= 0)
	    {
		found = TRUE;
		if (depth == -1 && lnum == curwin->w_cursor.lnum
#if defined(FEAT_QUICKFIX)
						      && g_do_tagpreview == 0
#endif
						      )
		    emsg(_(e_match_is_on_current_line));
		else if (action == ACTION_SHOW)
		{
		    show_pat_in_path(line, type, did_show, action,
			(depth == -1) ? NULL : files[depth].fp,
			(depth == -1) ? &lnum : &files[depth].lnum, 1L);
		    did_show = TRUE;
		}
		else
		{
#ifdef FEAT_GUI
		    need_mouse_correct = TRUE;
#endif
#if defined(FEAT_QUICKFIX)
		    // "":psearch"" uses the preview window
		    if (g_do_tagpreview != 0)
		    {
			curwin_save = curwin;
			prepare_tagpreview(TRUE, TRUE, FALSE);
		    }
#endif
		    if (action == ACTION_SPLIT)
		    {
			if (win_split(0, 0) == FAIL)
			    break;
			RESET_BINDING(curwin);
		    }
		    if (depth == -1)
		    {
			// match in current file
#if defined(FEAT_QUICKFIX)
			if (g_do_tagpreview != 0)
			{
			    if (!win_valid(curwin_save))
				break;
			    if (!GETFILE_SUCCESS(getfile(
					   curwin_save->w_buffer->b_fnum, NULL,
						     NULL, TRUE, lnum, FALSE)))
				break;	// failed to jump to file
			}
			else
#endif
			    setpcmark();
			curwin->w_cursor.lnum = lnum;
			check_cursor();
		    }
		    else
		    {
			if (!GETFILE_SUCCESS(getfile(
					0, files[depth].name, NULL, TRUE,
						    files[depth].lnum, FALSE)))
			    break;	// failed to jump to file
			// autocommands may have changed the lnum, we don't
			// want that here
			curwin->w_cursor.lnum = files[depth].lnum;
		    }
		}
		if (action != ACTION_SHOW)
		{
		    curwin->w_cursor.col = (colnr_T)(startp - line);
		    curwin->w_set_curswant = TRUE;
		}

#if defined(FEAT_QUICKFIX)
		if (g_do_tagpreview != 0
			   && curwin != curwin_save && win_valid(curwin_save))
		{
		    // Return cursor to where we were
		    validate_cursor();
		    redraw_later(VALID);
		    win_enter(curwin_save, TRUE);
		}
# ifdef FEAT_PROP_POPUP
		else if (WIN_IS_POPUP(curwin))
		    // can't keep focus in popup window
		    win_enter(firstwin, TRUE);
# endif
#endif
		break;
	    }
exit_matched:
	    matched = FALSE;
	    // look for other matches in the rest of the line if we
	    // are not at the end of it already
	    if (def_regmatch.regprog == NULL
		    && action == ACTION_EXPAND
		    && !compl_status_sol()
		    && *startp != NUL
		    && *(p = startp + mb_ptr2len(startp)) != NUL)
		goto search_line;
	}
	line_breakcheck();
	if (action == ACTION_EXPAND)
	    ins_compl_check_keys(30, FALSE);
	if (got_int || ins_compl_interrupted())
	    break;

	/*
	 * Read the next line.  When reading an included file and encountering
	 * end-of-file, close the file and continue in the file that included
	 * it.
	 */
	while (depth >= 0 && !already
		&& vim_fgets(line = file_line, LSIZE, files[depth].fp))
	{
	    fclose(files[depth].fp);
	    --old_files;
	    files[old_files].name = files[depth].name;
	    files[old_files].matched = files[depth].matched;
	    --depth;
	    curr_fname = (depth == -1) ? curbuf->b_fname
				       : files[depth].name;
	    if (depth < depth_displayed)
		depth_displayed = depth;
	}
	if (depth >= 0)		// we could read the line
	{
	    files[depth].lnum++;
	    // Remove any CR and LF from the line.
	    i = (int)STRLEN(line);
	    if (i > 0 && line[i - 1] == '\n')
		line[--i] = NUL;
	    if (i > 0 && line[i - 1] == '\r')
		line[--i] = NUL;
	}
	else if (!already)
	{
	    if (++lnum > end_lnum)
		break;
	    line = ml_get(lnum);
	}
	already = NULL;
    }
    // End of big for (;;) loop.

    // Close any files that are still open.
    for (i = 0; i <= depth; i++)
    {
	fclose(files[i].fp);
	vim_free(files[i].name);
    }
    for (i = old_files; i < max_path_depth; i++)
	vim_free(files[i].name);
    vim_free(files);

    if (type == CHECK_PATH)
    {
	if (!did_show)
	{
	    if (action != ACTION_SHOW_ALL)
		msg(_(""All included files were found""));
	    else
		msg(_(""No included files""));
	}
    }
    else if (!found && action != ACTION_EXPAND)
    {
	if (got_int || ins_compl_interrupted())
	    emsg(_(e_interrupted));
	else if (type == FIND_DEFINE)
	    emsg(_(e_couldnt_find_definition));
	else
	    emsg(_(e_couldnt_find_pattern));
    }
    if (action == ACTION_SHOW || action == ACTION_SHOW_ALL)
	msg_end();

fpip_end:
    vim_free(file_line);
    vim_regfree(regmatch.regprog);
    vim_regfree(incl_regmatch.regprog);
    vim_regfree(def_regmatch.regprog);
}",CWE-416,10
1,"R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
	RBinJavaClassesAttribute *icattr;
	RBinJavaAttrInfo *attr = NULL;
	RBinJavaCPTypeObj *obj;
	ut32 i = 0;
	ut64 offset = 0, curpos;
	attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
	offset += 6;
	if (attr == NULL) {
		// TODO eprintf
		return attr;
	}
	attr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR;
	attr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset);
	offset += 2;
	attr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free);
	for (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) {
		curpos = buf_offset + offset;
		if (offset + 8 > sz) {
			eprintf (""Invalid amount of inner classes\n"");
			break;
		}
		icattr = R_NEW0 (RBinJavaClassesAttribute);
		if (!icattr) {
			break;
		}
		icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
		offset += 2;
		icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
		offset += 2;
		icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
		offset += 2;
		icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);
		offset += 2;
		icattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags);
		icattr->file_offset = curpos;
		icattr->size = 8;

		obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx);
		if (obj == NULL) {
			eprintf (""BINCPLIS IS HULL %d\n"", icattr->inner_name_idx);
		}
		icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);
		if (!icattr->name) {
			obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx);
			if (!obj) {
				eprintf (""BINCPLIST IS NULL %d\n"", icattr->inner_class_info_idx);
			}
			icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);
			if (!icattr->name) {
				icattr->name = r_str_dup (NULL, ""NULL"");
				eprintf (""r_bin_java_inner_classes_attr: Unable to find the name for %d index.\n"", icattr->inner_name_idx);
				free (icattr);
				break;
			}
		}

		IFDBG eprintf(""r_bin_java_inner_classes_attr: Inner class name %d is %s.\n"", icattr->inner_name_idx, icattr->name);
		r_list_append (attr->info.inner_classes_attr.classes, (void *) icattr);
	}
	attr->size = offset;
	// IFDBG r_bin_java_print_inner_classes_attr_summary(attr);
	return attr;
}",CWE-787,16
1,"void update_process_times(int user_tick)
{
	struct task_struct *p = current;

	/* Note: this timer irq context must be accounted for as well. */
	account_process_tick(p, user_tick);
	run_local_timers();
	rcu_sched_clock_irq(user_tick);
#ifdef CONFIG_IRQ_WORK
	if (in_irq())
		irq_work_tick();
#endif
	scheduler_tick();
	if (IS_ENABLED(CONFIG_POSIX_TIMERS))
		run_posix_cpu_timers();
}",CWE-200,4
1,"setup_seccomp (FlatpakBwrap   *bwrap,
               const char     *arch,
               gulong          allowed_personality,
               FlatpakRunFlags run_flags,
               GError        **error)
{
  gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0;
  gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0;

  __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL;

  /**** BEGIN NOTE ON CODE SHARING
   *
   * There are today a number of different Linux container
   * implementations.  That will likely continue for long into the
   * future.  But we can still try to share code, and it's important
   * to do so because it affects what library and application writers
   * can do, and we should support code portability between different
   * container tools.
   *
   * This syscall blocklist is copied from linux-user-chroot, which was in turn
   * clearly influenced by the Sandstorm.io blocklist.
   *
   * If you make any changes here, I suggest sending the changes along
   * to other sandbox maintainers.  Using the libseccomp list is also
   * an appropriate venue:
   * https://groups.google.com/forum/#!forum/libseccomp
   *
   * A non-exhaustive list of links to container tooling that might
   * want to share this blocklist:
   *
   *  https://github.com/sandstorm-io/sandstorm
   *    in src/sandstorm/supervisor.c++
   *  https://github.com/flatpak/flatpak.git
   *    in common/flatpak-run.c
   *  https://git.gnome.org/browse/linux-user-chroot
   *    in src/setup-seccomp.c
   *
   **** END NOTE ON CODE SHARING
   */
  struct
  {
    int                  scall;
    struct scmp_arg_cmp *arg;
  } syscall_blocklist[] = {
    /* Block dmesg */
    {SCMP_SYS (syslog)},
    /* Useless old syscall */
    {SCMP_SYS (uselib)},
    /* Don't allow disabling accounting */
    {SCMP_SYS (acct)},
    /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a
       historic source of interesting information leaks. */
    {SCMP_SYS (modify_ldt)},
    /* Don't allow reading current quota use */
    {SCMP_SYS (quotactl)},

    /* Don't allow access to the kernel keyring */
    {SCMP_SYS (add_key)},
    {SCMP_SYS (keyctl)},
    {SCMP_SYS (request_key)},

    /* Scary VM/NUMA ops */
    {SCMP_SYS (move_pages)},
    {SCMP_SYS (mbind)},
    {SCMP_SYS (get_mempolicy)},
    {SCMP_SYS (set_mempolicy)},
    {SCMP_SYS (migrate_pages)},

    /* Don't allow subnamespace setups: */
    {SCMP_SYS (unshare)},
    {SCMP_SYS (mount)},
    {SCMP_SYS (pivot_root)},
#if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)
    /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack
     * and flags arguments are reversed so the flags come second */
    {SCMP_SYS (clone), &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#else
    /* Normally the flags come first */
    {SCMP_SYS (clone), &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)},
#endif

    /* Don't allow faking input to the controlling tty (CVE-2017-5226) */
    {SCMP_SYS (ioctl), &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)},
  };

  struct
  {
    int                  scall;
    struct scmp_arg_cmp *arg;
  } syscall_nondevel_blocklist[] = {
    /* Profiling operations; we expect these to be done by tools from outside
     * the sandbox.  In particular perf has been the source of many CVEs.
     */
    {SCMP_SYS (perf_event_open)},
    /* Don't allow you to switch to bsd emulation or whatnot */
    {SCMP_SYS (personality), &SCMP_A0 (SCMP_CMP_NE, allowed_personality)},
    {SCMP_SYS (ptrace)}
  };
  /* Blocklist all but unix, inet, inet6 and netlink */
  struct
  {
    int             family;
    FlatpakRunFlags flags_mask;
  } socket_family_allowlist[] = {
    /* NOTE: Keep in numerical order */
    { AF_UNSPEC, 0 },
    { AF_LOCAL, 0 },
    { AF_INET, 0 },
    { AF_INET6, 0 },
    { AF_NETLINK, 0 },
    { AF_CAN, FLATPAK_RUN_FLAG_CANBUS },
    { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH },
  };
  int last_allowed_family;
  int i, r;
  g_auto(GLnxTmpfile) seccomp_tmpf  = { 0, };

  seccomp = seccomp_init (SCMP_ACT_ALLOW);
  if (!seccomp)
    return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed""));

  if (arch != NULL)
    {
      uint32_t arch_id = 0;
      const uint32_t *extra_arches = NULL;

      if (strcmp (arch, ""i386"") == 0)
        {
          arch_id = SCMP_ARCH_X86;
        }
      else if (strcmp (arch, ""x86_64"") == 0)
        {
          arch_id = SCMP_ARCH_X86_64;
          extra_arches = seccomp_x86_64_extra_arches;
        }
      else if (strcmp (arch, ""arm"") == 0)
        {
          arch_id = SCMP_ARCH_ARM;
        }
#ifdef SCMP_ARCH_AARCH64
      else if (strcmp (arch, ""aarch64"") == 0)
        {
          arch_id = SCMP_ARCH_AARCH64;
          extra_arches = seccomp_aarch64_extra_arches;
        }
#endif

      /* We only really need to handle arches on multiarch systems.
       * If only one arch is supported the default is fine */
      if (arch_id != 0)
        {
          /* This *adds* the target arch, instead of replacing the
             native one. This is not ideal, because we'd like to only
             allow the target arch, but we can't really disallow the
             native arch at this point, because then bubblewrap
             couldn't continue running. */
          r = seccomp_arch_add (seccomp, arch_id);
          if (r < 0 && r != -EEXIST)
            return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter""));

          if (multiarch && extra_arches != NULL)
            {
              for (i = 0; extra_arches[i] != 0; i++)
                {
                  r = seccomp_arch_add (seccomp, extra_arches[i]);
                  if (r < 0 && r != -EEXIST)
                    return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter""));
                }
            }
        }
    }

  /* TODO: Should we filter the kernel keyring syscalls in some way?
   * We do want them to be used by desktop apps, but they could also perhaps
   * leak system stuff or secrets from other apps.
   */

  for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++)
    {
      int scall = syscall_blocklist[i].scall;
      if (syscall_blocklist[i].arg)
        r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_blocklist[i].arg);
      else
        r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);
      if (r < 0 && r == -EFAULT /* unknown syscall */)
        return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall);
    }

  if (!devel)
    {
      for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++)
        {
          int scall = syscall_nondevel_blocklist[i].scall;
          if (syscall_nondevel_blocklist[i].arg)
            r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 1, *syscall_nondevel_blocklist[i].arg);
          else
            r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (EPERM), scall, 0);

          if (r < 0 && r == -EFAULT /* unknown syscall */)
            return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall);
        }
    }

  /* Socket filtering doesn't work on e.g. i386, so ignore failures here
   * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
   * something else: https://github.com/seccomp/libseccomp/issues/8 */
  last_allowed_family = -1;
  for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++)
    {
      int family = socket_family_allowlist[i].family;
      int disallowed;

      if (socket_family_allowlist[i].flags_mask != 0 &&
          (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask)
        continue;

      for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++)
        {
          /* Blocklist the in-between valid families */
          seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed));
        }
      last_allowed_family = family;
    }
  /* Blocklist the rest */
  seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1));

  if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error))
    return FALSE;

  if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0)
    return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf""));

  lseek (seccomp_tmpf.fd, 0, SEEK_SET);

  flatpak_bwrap_add_args_data_fd (bwrap,
                                  ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL);

  return TRUE;
}",CWE-20,3
1,"static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
{
	unsigned long cons_pos, prod_pos, new_prod_pos, flags;
	u32 len, pg_off;
	struct bpf_ringbuf_hdr *hdr;

	if (unlikely(size > RINGBUF_MAX_RECORD_SZ))
		return NULL;

	len = round_up(size + BPF_RINGBUF_HDR_SZ, 8);
	cons_pos = smp_load_acquire(&rb->consumer_pos);

	if (in_nmi()) {
		if (!spin_trylock_irqsave(&rb->spinlock, flags))
			return NULL;
	} else {
		spin_lock_irqsave(&rb->spinlock, flags);
	}

	prod_pos = rb->producer_pos;
	new_prod_pos = prod_pos + len;

	/* check for out of ringbuf space by ensuring producer position
	 * doesn't advance more than (ringbuf_size - 1) ahead
	 */
	if (new_prod_pos - cons_pos > rb->mask) {
		spin_unlock_irqrestore(&rb->spinlock, flags);
		return NULL;
	}

	hdr = (void *)rb->data + (prod_pos & rb->mask);
	pg_off = bpf_ringbuf_rec_pg_off(rb, hdr);
	hdr->len = size | BPF_RINGBUF_BUSY_BIT;
	hdr->pg_off = pg_off;

	/* pairs with consumer's smp_load_acquire() */
	smp_store_release(&rb->producer_pos, new_prod_pos);

	spin_unlock_irqrestore(&rb->spinlock, flags);

	return (void *)hdr + BPF_RINGBUF_HDR_SZ;
}",CWE-787,16
0,"  bool Connecting() const {
    return ethernet_connecting() || wifi_connecting() || cellular_connecting();
  }
",none,24
1,"std::string controller::bookmark(
		const std::string& url,
		const std::string& title,
		const std::string& description,
		const std::string& feed_title)
{
	std::string bookmark_cmd = cfg.get_configvalue(""bookmark-cmd"");
	bool is_interactive = cfg.get_configvalue_as_bool(""bookmark-interactive"");
	if (bookmark_cmd.length() > 0) {
		std::string cmdline = strprintf::fmt(""%s '%s' %s %s %s"",
		                                       bookmark_cmd,
		                                       utils::replace_all(url,""'"", ""%27""),
		                                       quote_empty(stfl::quote(title)),
		                                       quote_empty(stfl::quote(description)),
		                                       quote_empty(stfl::quote(feed_title)));

		LOG(level::DEBUG, ""controller::bookmark: cmd = %s"", cmdline);

		if (is_interactive) {
			v->push_empty_formaction();
			stfl::reset();
			utils::run_interactively(cmdline, ""controller::bookmark"");
			v->pop_current_formaction();
			return """";
		} else {
			char * my_argv[4];
			my_argv[0] = const_cast(""/bin/sh"");
			my_argv[1] = const_cast(""-c"");
			my_argv[2] = const_cast(cmdline.c_str());
			my_argv[3] = nullptr;
			return utils::run_program(my_argv, """");
		}
	} else {
		return _(""bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."");
	}
}",CWE-787,16
1,"PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_rpsi(
					const void *buf,
					pj_size_t length,
					pjmedia_rtcp_fb_rpsi *rpsi)
{
    pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;
    pj_uint8_t *p;
    pj_uint8_t padlen;
    pj_size_t rpsi_len;

    PJ_ASSERT_RETURN(buf && rpsi, PJ_EINVAL);
    PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);

    /* RPSI uses pt==RTCP_PSFB and FMT==3 */
    if (hdr->pt != RTCP_PSFB || hdr->count != 3)
	return PJ_ENOTFOUND;

    rpsi_len = (pj_ntohs((pj_uint16_t)hdr->length)-2) * 4;
    if (length < rpsi_len + 12)
	return PJ_ETOOSMALL;

    p = (pj_uint8_t*)hdr + sizeof(*hdr);
    padlen = *p++;
    rpsi->pt = (*p++ & 0x7F);
    rpsi->rpsi_bit_len = rpsi_len*8 - 16 - padlen;
    pj_strset(&rpsi->rpsi, (char*)p, (rpsi->rpsi_bit_len + 7)/8);

    return PJ_SUCCESS;
}",CWE-200,4
0,"void CellularNetwork::Clear() {
  WirelessNetwork::Clear();
  activation_state_ = ACTIVATION_STATE_UNKNOWN;
  roaming_state_ = ROAMING_STATE_UNKNOWN;
  network_technology_ = NETWORK_TECHNOLOGY_UNKNOWN;
  restricted_pool_ = false;
  service_name_.clear();
  operator_name_.clear();
  operator_code_.clear();
  payment_url_.clear();
  meid_.clear();
  imei_.clear();
  imsi_.clear();
  esn_.clear();
  mdn_.clear();
  min_.clear();
  model_id_.clear();
  manufacturer_.clear();
  firmware_revision_.clear();
  hardware_revision_.clear();
  last_update_.clear();
  prl_version_ = 0;
}
",none,24
1,"int callback_glewlwyd_user_auth (const struct _u_request * request, struct _u_response * response, void * user_data) {
  struct config_elements * config = (struct config_elements *)user_data;
  json_t * j_param = ulfius_get_json_body_request(request, NULL), * j_result = NULL;
  const char * ip_source = get_ip_source(request);
  char * issued_for = get_client_hostname(request);
  char * session_uid, expires[129];
  time_t now;
  struct tm ts;
  
  time(&now);
  now += GLEWLWYD_DEFAULT_SESSION_EXPIRATION_COOKIE;
  gmtime_r(&now, &ts);
  strftime(expires, 128, ""%a, %d %b %Y %T %Z"", &ts);
  if (j_param != NULL) {
    if (json_string_length(json_object_get(j_param, ""username""))) {
      if (json_object_get(j_param, ""scheme_type"") == NULL || 0 == o_strcmp(json_string_value(json_object_get(j_param, ""scheme_type"")), ""password"")) {
        if (json_string_length(json_object_get(j_param, ""password""))) {
          j_result = auth_check_user_credentials(config, json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""password"")));
          if (check_result_value(j_result, G_OK)) {
            if ((session_uid = get_session_id(config, request)) == NULL) {
              session_uid = generate_session_id();
            }
            if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 1) != G_OK) {
              y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (1)"");
              response->status = 500;
            } else {
              ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0);
              y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with password"", json_string_value(json_object_get(j_param, ""username"")));
            }
            o_free(session_uid);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, ""scheme_type"", ""password"", NULL);
          } else {
            if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {
              y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username %s at IP Address %s"", json_string_value(json_object_get(j_param, ""username"")), ip_source);
            }
            if ((session_uid = get_session_id(config, request)) != NULL && user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 1) != G_OK) {
              y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (2)"");
            }
            o_free(session_uid);
            response->status = 401;
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, ""scheme_type"", ""password"", NULL);
          }
          json_decref(j_result);
        } else if (json_object_get(j_param, ""password"") != NULL && !json_is_string(json_object_get(j_param, ""password""))) {
          ulfius_set_string_body_response(response, 400, ""password must be a string"");
        } else {
          session_uid = get_session_id(config, request);
          j_result = get_users_for_session(config, session_uid);
          if (check_result_value(j_result, G_OK)) {
            // Refresh username to set as default
            if (user_session_update(config, u_map_get(request->map_cookie, config->session_key), u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), NULL, 0) != G_OK) {
              y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (3)"");
              response->status = 500;
            } else {
              ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0);
            }
          } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {
            response->status = 401;
          } else {
            y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error get_users_for_session"");
            response->status = 500;
          }
          o_free(session_uid);
          json_decref(j_result);
        }
      } else {
        if (json_string_length(json_object_get(j_param, ""scheme_type"")) && json_string_length(json_object_get(j_param, ""scheme_name"")) && json_is_object(json_object_get(j_param, ""value""))) {
          j_result = auth_check_user_scheme(config, json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")), json_string_value(json_object_get(j_param, ""username"")), json_object_get(j_param, ""value""), request);
          if (check_result_value(j_result, G_ERROR_PARAM)) {
            ulfius_set_string_body_response(response, 400, ""bad scheme response"");
          } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {
            y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username %s at IP Address %s"", json_string_value(json_object_get(j_param, ""username"")), ip_source);
            response->status = 401;
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID, 1, NULL);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_INVALID_SCHEME, 1, ""scheme_type"", json_string_value(json_object_get(j_param, ""scheme_type"")), ""scheme_name"", json_string_value(json_object_get(j_param, ""scheme_name"")), NULL);
          } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {
            response->status = 404;
          } else if (check_result_value(j_result, G_OK)) {
            if ((session_uid = get_session_id(config, request)) == NULL) {
              session_uid = generate_session_id();
            }
            if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""scheme_name"")), 1) != G_OK) {
              y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (4)"");
              response->status = 500;
            } else {
              ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0);
              y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with scheme '%s/%s'"", json_string_value(json_object_get(j_param, ""username"")), json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")));
            }
            o_free(session_uid);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID, 1, NULL);
            glewlwyd_metrics_increment_counter_va(config, GLWD_METRICS_AUTH_USER_VALID_SCHEME, 1, ""scheme_type"", json_string_value(json_object_get(j_param, ""scheme_type"")), ""scheme_name"", json_string_value(json_object_get(j_param, ""scheme_name"")), NULL);
          } else {
            y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error auth_check_user_scheme"");
            response->status = 500;
          }
          json_decref(j_result);
        } else {
          ulfius_set_string_body_response(response, 400, ""scheme_type, scheme_name and value are mandatory"");
        }
      }
    } else {
      if (json_string_length(json_object_get(j_param, ""scheme_type"")) && json_string_length(json_object_get(j_param, ""scheme_name"")) && json_is_object(json_object_get(j_param, ""value""))) {
        j_result = auth_check_identify_scheme(config, json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")), json_object_get(j_param, ""value""), request);
        if (check_result_value(j_result, G_ERROR_PARAM)) {
          ulfius_set_string_body_response(response, 400, ""bad scheme response"");
        } else if (check_result_value(j_result, G_ERROR_UNAUTHORIZED)) {
          y_log_message(Y_LOG_LEVEL_WARNING, ""Security - Authorization invalid for username  at IP Address %s"", ip_source);
          response->status = 401;
        } else if (check_result_value(j_result, G_ERROR_NOT_FOUND)) {
          response->status = 404;
        } else if (check_result_value(j_result, G_OK)) {
          if ((session_uid = get_session_id(config, request)) == NULL) {
            session_uid = generate_session_id();
          }
          if (user_session_update(config, session_uid, u_map_get_case(request->map_header, ""user-agent""), issued_for, json_string_value(json_object_get(j_result, ""username"")), json_string_value(json_object_get(j_param, ""scheme_name"")), 1) != G_OK) {
            y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error user_session_update (4)"");
            response->status = 500;
          } else {
            ulfius_add_cookie_to_response(response, config->session_key, session_uid, expires, 0, config->cookie_domain, ""/"", config->cookie_secure, 0);
            y_log_message(Y_LOG_LEVEL_INFO, ""Event - User '%s' authenticated with scheme '%s/%s'"", json_string_value(json_object_get(j_result, ""username"")), json_string_value(json_object_get(j_param, ""scheme_type"")), json_string_value(json_object_get(j_param, ""scheme_name"")));
          }
          o_free(session_uid);
        } else {
          y_log_message(Y_LOG_LEVEL_ERROR, ""callback_glewlwyd_user_auth - Error auth_check_user_scheme"");
          response->status = 500;
        }
        json_decref(j_result);
      } else {
        ulfius_set_string_body_response(response, 400, ""username is mandatory"");
      }
    }
  } else {
    ulfius_set_string_body_response(response, 400, ""Input parameters must be in JSON format"");
  }
  json_decref(j_param);
  o_free(issued_for);

  return U_CALLBACK_CONTINUE;
}",CWE-287,7
0,"  virtual CellularNetwork* cellular_network() { return cellular_; }
",none,24
1,"s32 gf_avc_parse_nalu(GF_BitStream *bs, AVCState *avc)
{
	u8 idr_flag;
	s32 slice, ret;
	u32 nal_hdr;
	AVCSliceInfo n_state;

	gf_bs_enable_emulation_byte_removal(bs, GF_TRUE);

	nal_hdr = gf_bs_read_u8(bs);

	slice = 0;
	memcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));
	avc->last_nal_type_parsed = n_state.nal_unit_type = nal_hdr & 0x1F;
	n_state.nal_ref_idc = (nal_hdr >> 5) & 0x3;

	idr_flag = 0;

	switch (n_state.nal_unit_type) {
	case GF_AVC_NALU_ACCESS_UNIT:
	case GF_AVC_NALU_END_OF_SEQ:
	case GF_AVC_NALU_END_OF_STREAM:
		ret = 1;
		break;

	case GF_AVC_NALU_SVC_SLICE:
		SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
		// slice buffer - read the info and compare.
		/*ret = */svc_parse_slice(bs, avc, &n_state);
		if (avc->s_info.nal_ref_idc) {
			n_state.poc_lsb_prev = avc->s_info.poc_lsb;
			n_state.poc_msb_prev = avc->s_info.poc_msb;
		}
		avc_compute_poc(&n_state);

		if (avc->s_info.poc != n_state.poc) {
			memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
			return 1;
		}
		memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
		return 0;

	case GF_AVC_NALU_SVC_PREFIX_NALU:
		SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
		return 0;

	case GF_AVC_NALU_IDR_SLICE:
	case GF_AVC_NALU_NON_IDR_SLICE:
	case GF_AVC_NALU_DP_A_SLICE:
	case GF_AVC_NALU_DP_B_SLICE:
	case GF_AVC_NALU_DP_C_SLICE:
		slice = 1;
		/* slice buffer - read the info and compare.*/
		ret = avc_parse_slice(bs, avc, idr_flag, &n_state);
		if (ret < 0) return ret;
		ret = 0;
		if (
			((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))
			&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)
			) {
			break;
		}
		if (avc->s_info.frame_num != n_state.frame_num) {
			ret = 1;
			break;
		}

		if (avc->s_info.field_pic_flag != n_state.field_pic_flag) {
			ret = 1;
			break;
		}
		if ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&
			(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {
			ret = 1;
			break;
		}
		assert(avc->s_info.sps);

		if (avc->s_info.sps->poc_type == n_state.sps->poc_type) {
			if (!avc->s_info.sps->poc_type) {
				if (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {
					ret = 1;
					break;
				}
				if (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {
					ret = 1;
					break;
				}
			}
			else if (avc->s_info.sps->poc_type == 1) {
				if (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {
					ret = 1;
					break;
				}
				if (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {
					ret = 1;
					break;
				}
			}
		}

		if (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
			if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/
				ret = 1;
				break;
			}
			else if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/
				ret = 1;
				break;
			}
		}
		break;
	case GF_AVC_NALU_SEQ_PARAM:
		avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 0, NULL, nal_hdr);
		if (avc->last_ps_idx < 0) return -1;
		return 0;

	case GF_AVC_NALU_PIC_PARAM:
		avc->last_ps_idx = gf_avc_read_pps_bs_internal(bs, avc, nal_hdr);
		if (avc->last_ps_idx < 0) return -1;
		return 0;
	case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
		avc->last_ps_idx = gf_avc_read_sps_bs_internal(bs, avc, 1, NULL, nal_hdr);
		if (avc->last_ps_idx < 0) return -1;
		return 0;
	case GF_AVC_NALU_SEQ_PARAM_EXT:
		avc->last_ps_idx = (s32) gf_bs_read_ue(bs);
		if (avc->last_ps_idx < 0) return -1;
		return 0;

	case GF_AVC_NALU_SEI:
	case GF_AVC_NALU_FILLER_DATA:
		return 0;

	default:
		if (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;
		//To detect change of AU when multiple sps and pps in stream
		else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)
			ret = 1;
		else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc->s_info.nal_unit_type == GF_AVC_NALU_SVC_SLICE)
			ret = 1;
		else
			ret = 0;
		break;
	}

	/* save _prev values */
	if (ret && avc->s_info.sps) {
		n_state.frame_num_offset_prev = avc->s_info.frame_num_offset;
		if ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))
			n_state.frame_num_prev = avc->s_info.frame_num;
		if (avc->s_info.nal_ref_idc) {
			n_state.poc_lsb_prev = avc->s_info.poc_lsb;
			n_state.poc_msb_prev = avc->s_info.poc_msb;
		}
	}
	if (slice)
		avc_compute_poc(&n_state);
	memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
	return ret;
}",CWE-476,12
0,"QuotaManager::QuotaManager(bool is_incognito,
                           const FilePath& profile_path,
                           base::MessageLoopProxy* io_thread,
                           base::MessageLoopProxy* db_thread,
                           SpecialStoragePolicy* special_storage_policy)
  : is_incognito_(is_incognito),
    profile_path_(profile_path),
    proxy_(new QuotaManagerProxy(
        ALLOW_THIS_IN_INITIALIZER_LIST(this), io_thread)),
    db_disabled_(false),
    eviction_disabled_(false),
    io_thread_(io_thread),
    db_thread_(db_thread),
    need_initialize_origins_(false),
    temporary_global_quota_(-1),
    special_storage_policy_(special_storage_policy),
    callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
",none,24
1,"int parse(char *elf) {
    int fd;
    struct stat st;
    uint8_t *elf_map;
    int count;
    char *tmp;
    char *name;
    char flag[4];

    MODE = get_elf_class(elf);

    fd = open(elf, O_RDONLY);
    if (fd < 0) {
        perror(""open"");
        return -1;
    }

    if (fstat(fd, &st) < 0) {
        perror(""fstat"");
        return -1;
    }

    elf_map = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (elf_map == MAP_FAILED) {
        perror(""mmap"");
        return -1;
    }

    /* 32bit */
    if (MODE == ELFCLASS32) {
        /* ELF Header Information */
        Elf32_Ehdr *ehdr;
        ehdr = (Elf32_Ehdr *)elf_map;

        INFO(""ELF Header\n"");        
        switch (ehdr->e_type) {
            case ET_NONE:
                tmp = ""An unknown type"";
                break;

            case ET_REL:
                tmp = ""A relocatable file"";
                break;

            case ET_EXEC:
                tmp = ""An executable file"";
                break;

            case ET_DYN:
                tmp = ""A shared object"";
                break;

            case ET_CORE:
                tmp = ""A core file"";
                break;
            
            default:
                tmp = ""An unknown type"";
                break;
        }
        PRINT_HEADER_EXP(""e_type:"", ehdr->e_type, tmp);

        switch (ehdr->e_type) {
            case EM_NONE:
                tmp = ""An unknown machine"";
                break;

            case EM_M32:
                tmp = ""AT&T WE 32100"";
                break;

            case EM_SPARC:
                tmp = ""Sun Microsystems SPARC"";
                break;

            case EM_386:
                tmp = ""Intel 80386"";
                break;

            case EM_68K:
                tmp = ""Motorola 68000"";
                break;
            
            case EM_88K:
                tmp = ""Motorola 88000"";
                break;

            case EM_860:
                tmp = ""Intel 80860"";
                break;

            case EM_MIPS:
                tmp = ""MIPS RS3000 (big-endian only)"";
                break;

            case EM_PARISC:
                tmp = ""HP/PA"";
                break;

            case EM_SPARC32PLUS:
                tmp = ""SPARC with enhanced instruction set"";
                break;
            
            case EM_PPC:
                tmp = ""PowerPC"";
                break;

            case EM_PPC64:
                tmp = ""PowerPC 64-bit"";
                break;

            case EM_S390:
                tmp = ""IBM S/390"";
                break;

            case EM_ARM:
                tmp = ""Advanced RISC Machines"";
                break;

            case EM_SH:
                tmp = ""Renesas SuperH"";
                break;
            
            case EM_SPARCV9:
                tmp = ""SPARC v9 64-bit"";
                break;

            case EM_IA_64:
                tmp = ""Intel Itanium"";
                break;

            case EM_X86_64:
                tmp = ""AMD x86-64"";
                break;

            case EM_VAX:
                tmp = ""DEC Vax"";
                break;
            
            default:
                tmp = ""An unknown machine"";
                break;
        }
        PRINT_HEADER_EXP(""e_machine:"", ehdr->e_machine, tmp);

        switch (ehdr->e_version) {
            case EV_NONE:
                tmp = ""Invalid version"";
                break;

            case EV_CURRENT:
                tmp = ""Current version"";
                break;

            default:
                tmp = ""Known version"";
                break;
        }
        PRINT_HEADER_EXP(""e_version:"", ehdr->e_version, tmp);
        PRINT_HEADER(""e_entry:"", ehdr->e_entry);
        PRINT_HEADER(""e_phoff:"", ehdr->e_phoff);
        PRINT_HEADER(""e_shoff:"", ehdr->e_shoff);
        PRINT_HEADER(""e_flags:"", ehdr->e_flags);
        PRINT_HEADER(""e_ehsize:"", ehdr->e_ehsize);
        PRINT_HEADER(""e_phentsize:"", ehdr->e_phentsize);
        PRINT_HEADER(""e_phnum:"", ehdr->e_phnum);
        PRINT_HEADER(""e_shentsize:"", ehdr->e_shentsize);
        PRINT_HEADER(""e_shentsize:"", ehdr->e_shentsize);
        PRINT_HEADER(""e_shstrndx:"", ehdr->e_shstrndx);

        /* Section Information */
        Elf32_Shdr *shdr;
        Elf32_Phdr *phdr;
        Elf32_Shdr shstrtab;

        shdr = (Elf32_Shdr *)&elf_map[ehdr->e_shoff];
        phdr = (Elf32_Phdr *)&elf_map[ehdr->e_phoff];
        shstrtab = shdr[ehdr->e_shstrndx];

        INFO(""Section Header Table\n"");
        PRINT_SECTION_TITLE(""Nr"", ""Name"", ""Type"", ""Addr"", ""Off"", ""Size"", ""Es"", ""Flg"", ""Lk"", ""Inf"", ""Al"");
        for (int i = 0; i < ehdr->e_shnum; i++) {
            name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;

            switch (shdr[i].sh_type) {
                case SHT_NULL:
                    tmp = ""SHT_NULL"";
                    break;
                
                case SHT_PROGBITS:
                    tmp = ""SHT_PROGBITS"";
                    break;

                case SHT_SYMTAB:
                    tmp = ""SHT_SYMTAB"";
                    break;

                case SHT_STRTAB:
                    tmp = ""SHT_STRTAB"";
                    break;

                case SHT_RELA:
                    tmp = ""SHT_RELA"";
                    break;

                case SHT_HASH:
                    tmp = ""SHT_HASH"";
                    break;

                case SHT_DYNAMIC:
                    tmp = ""SHT_DYNAMIC"";
                    break;

                case SHT_NOTE:
                    tmp = ""SHT_NOTE"";
                    break;

                case SHT_NOBITS:
                    tmp = ""SHT_NOBITS"";
                    break;

                case SHT_REL:
                    tmp = ""SHT_REL"";
                    break;

                case SHT_SHLIB:
                    tmp = ""SHT_SHLIB"";
                    break;

                case SHT_DYNSYM:
                    tmp = ""SHT_DYNSYM"";
                    break;

                case SHT_LOPROC:
                    tmp = ""SHT_LOPROC"";
                    break;

                case SHT_HIPROC:
                    tmp = ""SHT_HIPROC"";
                    break;

                case SHT_LOUSER:
                    tmp = ""SHT_LOUSER"";
                    break;

                case SHT_HIUSER:
                    tmp = ""SHT_HIUSER"";
                    break;
                
                default:
                    break;
            }

            if (strlen(name) > 15) {
                strcpy(&name[15 - 6], ""[...]"");
            }
            strcpy(flag, ""   "");
            flag2str_sh(shdr[i].sh_flags, flag);
            PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \
                            flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);
        }

        INFO(""Program Header Table\n"");
        PRINT_PROGRAM_TITLE(""Nr"", ""Type"", ""Offset"", ""Virtaddr"", ""Physaddr"", ""Filesiz"", ""Memsiz"", ""Flg"", ""Align"");
        for (int i = 0; i < ehdr->e_phnum; i++) {
            switch (phdr[i].p_type) {
                case PT_NULL:
                    tmp = ""PT_NULL"";
                    break;
                
                case PT_LOAD:
                    tmp = ""PT_LOAD"";
                    break;

                case PT_DYNAMIC:
                    tmp = ""PT_DYNAMIC"";
                    break;

                case PT_INTERP:
                    tmp = ""PT_INTERP"";
                    break;

                case PT_NOTE:
                    tmp = ""PT_NOTE"";
                    break;

                case PT_SHLIB:
                    tmp = ""PT_SHLIB"";
                    break;

                case PT_PHDR:
                    tmp = ""PT_PHDR"";
                    break;

                case PT_LOPROC:
                    tmp = ""PT_LOPROC"";
                    break;

                case PT_HIPROC:
                    tmp = ""PT_HIPROC"";
                    break;

                case PT_GNU_STACK:
                    tmp = ""PT_GNU_STACK"";
                    break;
                
                default:
                    break;
            }
            strcpy(flag, ""   "");
            flag2str(phdr[i].p_flags, flag);
            PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); 
        }

        INFO(""Section to segment mapping\n"");
        for (int i = 0; i < ehdr->e_phnum; i++) {
            printf(""     [%2d]"", i);
            for (int j = 0; j < ehdr->e_shnum; j++) {
                name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;
                if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {
                    if (shdr[j].sh_flags >> 1 & 0x1) {
                        printf("" %s"", name);
                    }
                }    
            }
            printf(""\n"");
        }

        INFO(""Dynamic link information\n"");
        int dynstr;
        int dynamic;
        Elf32_Dyn *dyn;
        for (int i = 0; i < ehdr->e_shnum; i++) {
            name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;
            if (!strcmp(name, "".dynstr"")) {
                dynstr = i;
            }
            if (!strcmp(name, "".dynamic"")) {
                dynamic = i;
            }
        }

        char value[50];
        name = """";
        dyn = (Elf32_Dyn *)&elf_map[shdr[dynamic].sh_offset];
        count = shdr[dynamic].sh_size / sizeof(Elf32_Dyn);
        INFO(""Dynamic section at offset 0x%x contains %d entries\n"", shdr[dynamic].sh_offset, count);
        PRINT_DYN_TITLE(""Tag"", ""Type"", ""Name/Value"");
        
        for(int i = 0; i < count; i++) {
            tmp = """";
            memset(value, 0, 50);
            snprintf(value, 50, ""0x%x"", dyn[i].d_un.d_val);
            switch (dyn[i].d_tag) {
                /* Legal values for d_tag (dynamic entry type).  */
                case DT_NULL:
                    tmp = ""DT_NULL"";
                    break;

                case DT_NEEDED:
                    tmp = ""DT_NEEDED"";
                    name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;
                    snprintf(value, 50, ""Shared library: [%s]"", name);
                    break;
                
                case DT_PLTRELSZ:
                    tmp = ""DT_PLTRELSZ"";
                    break;

                case DT_PLTGOT:
                    tmp = ""DT_PLTGOT"";
                    break;

                case DT_HASH:
                    tmp = ""DT_HASH"";
                    break;

                case DT_STRTAB:
                    tmp = ""DT_STRTAB"";
                    break;

                case DT_SYMTAB:
                    tmp = ""DT_SYMTAB"";
                    break;

                case DT_RELA:
                    tmp = ""DT_RELA"";
                    break;

                case DT_RELASZ:
                    tmp = ""DT_RELASZ"";
                    break;

                case DT_RELAENT:
                    tmp = ""DT_RELAENT"";
                    break;

                case DT_STRSZ:
                    tmp = ""DT_STRSZ"";
                    break;

                case DT_SYMENT:
                    tmp = ""DT_SYMENT"";
                    break;

                case DT_INIT:
                    tmp = ""DT_INIT"";
                    break;

                case DT_FINI:
                    tmp = ""DT_FINI"";
                    break;

                case DT_SONAME:
                    tmp = ""DT_SONAME"";
                    break;

                case DT_RPATH:
                    tmp = ""DT_RPATH"";
                    break;

                case DT_SYMBOLIC:
                    tmp = ""DT_SYMBOLIC"";
                    break;

                case DT_REL:
                    tmp = ""DT_REL"";
                    break;

                case DT_RELSZ:
                    tmp = ""DT_RELSZ"";
                    break;

                case DT_RELENT:
                    tmp = ""DT_RELENT"";
                    break;
                    
                case DT_PLTREL:
                    tmp = ""DT_PLTREL"";
                    break;

                case DT_DEBUG:
                    tmp = ""DT_DEBUG"";
                    break;

                case DT_TEXTREL:
                    tmp = ""DT_TEXTREL"";
                    break;

                case DT_JMPREL:
                    tmp = ""DT_JMPREL"";
                    break;

                case DT_BIND_NOW:
                    tmp = ""DT_BIND_NOW"";
                    break;

                case DT_INIT_ARRAY:
                    tmp = ""DT_INIT_ARRAY"";
                    break;

                case DT_FINI_ARRAY:
                    tmp = ""DT_FINI_ARRAY"";
                    break;

                case DT_INIT_ARRAYSZ:
                    tmp = ""DT_INIT_ARRAYSZ"";
                    break;
                
                case DT_FINI_ARRAYSZ:
                    tmp = ""DT_FINI_ARRAYSZ"";
                    break;

                case DT_RUNPATH:
                    tmp = ""DT_RUNPATH"";
                    break;

                case DT_FLAGS:
                    tmp = ""DT_FLAGS"";
                    snprintf(value, 50, ""Flags: %d"", dyn[i].d_un.d_val);
                    break;
                
                case DT_ENCODING:
                    tmp = ""DT_ENCODING"";
                    break;

                case DT_PREINIT_ARRAYSZ:
                    tmp = ""DT_PREINIT_ARRAYSZ"";
                    break;

                case DT_SYMTAB_SHNDX:
                    tmp = ""DT_SYMTAB_SHNDX"";
                    break;
                
                case DT_NUM:
                    tmp = ""DT_NUM"";
                    break;

                case DT_LOOS:
                    tmp = ""DT_LOOS"";
                    break;

                case DT_HIOS:
                    tmp = ""DT_HIOS"";
                    break;

                case DT_LOPROC:
                    tmp = ""DT_LOPROC"";
                    break;

                case DT_HIPROC:
                    tmp = ""DT_HIPROC"";
                    break;

                case DT_PROCNUM:
                    tmp = ""DT_LOPROC"";
                    break;

                /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
                 * Dyn.d_un.d_val field of the Elf*_Dyn structure.  This follows Sun's
                 * approach. */

                case DT_VALRNGLO:
                    tmp = ""DT_VALRNGLO"";
                    break;

                case DT_GNU_PRELINKED:
                    tmp = ""DT_GNU_PRELINKED"";
                    break;
                
                case DT_GNU_CONFLICTSZ:
                    tmp = ""DT_GNU_CONFLICTSZ"";
                    break;

                case DT_GNU_LIBLISTSZ:
                    tmp = ""DT_GNU_LIBLISTSZ"";
                    break;

                case DT_CHECKSUM:
                    tmp = ""DT_CHECKSUM"";
                    break;

                case DT_PLTPADSZ:
                    tmp = ""DT_PLTPADSZ"";
                    break;

                case DT_MOVEENT:
                    tmp = ""DT_MOVEENT"";
                    break;

                case DT_MOVESZ:
                    tmp = ""DT_MOVESZ"";
                    break;

                case DT_FEATURE_1:
                    tmp = ""DT_FEATURE_1"";
                    break;

                case DT_POSFLAG_1:
                    tmp = ""DT_POSFLAG_1"";
                    break;

                case DT_SYMINSZ:
                    tmp = ""DT_SYMINSZ"";
                    break;

                case DT_SYMINENT:
                    tmp = ""DT_SYMINENT"";
                    break;

                /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
                 * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
                 * If any adjustment is made to the ELF object after it has been
                 * built these entries will need to be adjusted.  */
                case DT_ADDRRNGLO:
                    tmp = ""DT_ADDRRNGLO"";
                    break;

                case DT_GNU_HASH:
                    tmp = ""DT_GNU_HASH"";
                    break;

                case DT_TLSDESC_PLT:
                    tmp = ""DT_TLSDESC_PLT"";
                    break;

                case DT_TLSDESC_GOT:
                    tmp = ""DT_TLSDESC_GOT"";
                    break;

                case DT_GNU_CONFLICT:
                    tmp = ""DT_GNU_CONFLICT"";
                    break;

                case DT_GNU_LIBLIST:
                    tmp = ""DT_GNU_LIBLIST"";
                    break;

                case DT_CONFIG:
                    tmp = ""DT_CONFIG"";
                    break;

                case DT_DEPAUDIT:
                    tmp = ""DT_DEPAUDIT"";
                    break;

                case DT_AUDIT:
                    tmp = ""DT_AUDIT"";
                    break;

                case DT_PLTPAD:
                    tmp = ""DT_PLTPAD"";
                    break;

                case DT_MOVETAB:
                    tmp = ""DT_MOVETAB"";
                    break;

                case DT_SYMINFO:
                    tmp = ""DT_SYMINFO"";
                    break;
                    
                /* The versioning entry types.  The next are defined as part of the
                 * GNU extension.  */
                case DT_VERSYM:
                    tmp = ""DT_VERSYM"";
                    break;

                case DT_RELACOUNT:
                    tmp = ""DT_RELACOUNT"";
                    break;

                case DT_RELCOUNT:
                    tmp = ""DT_RELCOUNT"";
                    break;
                
                /* These were chosen by Sun.  */
                case DT_FLAGS_1:
                    tmp = ""DT_FLAGS_1"";
                    switch (dyn[i].d_un.d_val) {
                        case DF_1_PIE:
                            snprintf(value, 50, ""Flags: %s"", ""PIE"");
                            break;
                        
                        default:
                            snprintf(value, 50, ""Flags: %d"", dyn[i].d_un.d_val);
                            break;
                    }
                    
                    break;

                case DT_VERDEF:
                    tmp = ""DT_VERDEF"";
                    break;

                case DT_VERDEFNUM:
                    tmp = ""DT_VERDEFNUM"";
                    break;

                case DT_VERNEED:
                    tmp = ""DT_VERNEED"";
                    break;

                case DT_VERNEEDNUM:
                    tmp = ""DT_VERNEEDNUM"";
                    break;
                
                default:
                    break;
            }
            PRINT_DYN(dyn[i].d_tag, tmp, value);
        }        
    }

    /* 64bit */
    if (MODE == ELFCLASS64) {
        /* ELF Header Information */
        Elf64_Ehdr *ehdr;
        ehdr = (Elf64_Ehdr *)elf_map;

        INFO(""ELF Header\n"");        
        switch (ehdr->e_type) {
            case ET_NONE:
                tmp = ""An unknown type"";
                break;

            case ET_REL:
                tmp = ""A relocatable file"";
                break;

            case ET_EXEC:
                tmp = ""An executable file"";
                break;

            case ET_DYN:
                tmp = ""A shared object"";
                break;

            case ET_CORE:
                tmp = ""A core file"";
                break;
            
            default:
                tmp = ""An unknown type"";
                break;
        }
        PRINT_HEADER_EXP(""e_type:"", ehdr->e_type, tmp);

        switch (ehdr->e_type) {
            case EM_NONE:
                tmp = ""An unknown machine"";
                break;

            case EM_M32:
                tmp = ""AT&T WE 32100"";
                break;

            case EM_SPARC:
                tmp = ""Sun Microsystems SPARC"";
                break;

            case EM_386:
                tmp = ""Intel 80386"";
                break;

            case EM_68K:
                tmp = ""Motorola 68000"";
                break;
            
            case EM_88K:
                tmp = ""Motorola 88000"";
                break;

            case EM_860:
                tmp = ""Intel 80860"";
                break;

            case EM_MIPS:
                tmp = ""MIPS RS3000 (big-endian only)"";
                break;

            case EM_PARISC:
                tmp = ""HP/PA"";
                break;

            case EM_SPARC32PLUS:
                tmp = ""SPARC with enhanced instruction set"";
                break;
            
            case EM_PPC:
                tmp = ""PowerPC"";
                break;

            case EM_PPC64:
                tmp = ""PowerPC 64-bit"";
                break;

            case EM_S390:
                tmp = ""IBM S/390"";
                break;

            case EM_ARM:
                tmp = ""Advanced RISC Machines"";
                break;

            case EM_SH:
                tmp = ""Renesas SuperH"";
                break;
            
            case EM_SPARCV9:
                tmp = ""SPARC v9 64-bit"";
                break;

            case EM_IA_64:
                tmp = ""Intel Itanium"";
                break;

            case EM_X86_64:
                tmp = ""AMD x86-64"";
                break;

            case EM_VAX:
                tmp = ""DEC Vax"";
                break;
            
            default:
                tmp = ""An unknown machine"";
                break;
        }
        PRINT_HEADER_EXP(""e_machine:"", ehdr->e_machine, tmp);

        switch (ehdr->e_version) {
            case EV_NONE:
                tmp = ""Invalid version"";
                break;

            case EV_CURRENT:
                tmp = ""Current version"";
                break;

            default:
                tmp = ""Known version"";
                break;
        }
        PRINT_HEADER_EXP(""e_version:"", ehdr->e_version, tmp);
        PRINT_HEADER(""e_entry:"", ehdr->e_entry);
        PRINT_HEADER(""e_phoff:"", ehdr->e_phoff);
        PRINT_HEADER(""e_shoff:"", ehdr->e_shoff);
        PRINT_HEADER(""e_flags:"", ehdr->e_flags);
        PRINT_HEADER(""e_ehsize:"", ehdr->e_ehsize);
        PRINT_HEADER(""e_phentsize:"", ehdr->e_phentsize);
        PRINT_HEADER(""e_phnum:"", ehdr->e_phnum);
        PRINT_HEADER(""e_shentsize:"", ehdr->e_shentsize);
        PRINT_HEADER(""e_shentsize:"", ehdr->e_shentsize);
        PRINT_HEADER(""e_shstrndx:"", ehdr->e_shstrndx);

        /* Section Information */
        Elf64_Shdr *shdr;
        Elf64_Phdr *phdr;
        Elf64_Shdr shstrtab;

        shdr = (Elf64_Shdr *)&elf_map[ehdr->e_shoff];
        phdr = (Elf64_Phdr *)&elf_map[ehdr->e_phoff];
        shstrtab = shdr[ehdr->e_shstrndx];

        INFO(""Section Header Table\n"");
        PRINT_SECTION_TITLE(""Nr"", ""Name"", ""Type"", ""Addr"", ""Off"", ""Size"", ""Es"", ""Flg"", ""Lk"", ""Inf"", ""Al"");
        for (int i = 0; i < ehdr->e_shnum; i++) {
            name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;

            switch (shdr[i].sh_type) {
                case SHT_NULL:
                    tmp = ""SHT_NULL"";
                    break;
                
                case SHT_PROGBITS:
                    tmp = ""SHT_PROGBITS"";
                    break;

                case SHT_SYMTAB:
                    tmp = ""SHT_SYMTAB"";
                    break;

                case SHT_STRTAB:
                    tmp = ""SHT_STRTAB"";
                    break;

                case SHT_RELA:
                    tmp = ""SHT_RELA"";
                    break;

                case SHT_HASH:
                    tmp = ""SHT_HASH"";
                    break;

                case SHT_DYNAMIC:
                    tmp = ""SHT_DYNAMIC"";
                    break;

                case SHT_NOTE:
                    tmp = ""SHT_NOTE"";
                    break;

                case SHT_NOBITS:
                    tmp = ""SHT_NOBITS"";
                    break;

                case SHT_REL:
                    tmp = ""SHT_REL"";
                    break;

                case SHT_SHLIB:
                    tmp = ""SHT_SHLIB"";
                    break;

                case SHT_DYNSYM:
                    tmp = ""SHT_DYNSYM"";
                    break;

                case SHT_LOPROC:
                    tmp = ""SHT_LOPROC"";
                    break;

                case SHT_HIPROC:
                    tmp = ""SHT_HIPROC"";
                    break;

                case SHT_LOUSER:
                    tmp = ""SHT_LOUSER"";
                    break;

                case SHT_HIUSER:
                    tmp = ""SHT_HIUSER"";
                    break;
                
                default:
                    break;
            }

            if (strlen(name) > 15) {
                strcpy(&name[15 - 6], ""[...]"");
            }
            strcpy(flag, ""   "");
            flag2str_sh(shdr[i].sh_flags, flag);
            PRINT_SECTION(i, name, tmp, shdr[i].sh_addr, shdr[i].sh_offset, shdr[i].sh_size, shdr[i].sh_entsize, \
                            flag, shdr[i].sh_link, shdr[i].sh_info, shdr[i].sh_addralign);
        }

        INFO(""Program Header Table\n"");
        PRINT_PROGRAM_TITLE(""Nr"", ""Type"", ""Offset"", ""Virtaddr"", ""Physaddr"", ""Filesiz"", ""Memsiz"", ""Flg"", ""Align"");
        for (int i = 0; i < ehdr->e_phnum; i++) {
            switch (phdr[i].p_type) {
                case PT_NULL:
                    tmp = ""PT_NULL"";
                    break;
                
                case PT_LOAD:
                    tmp = ""PT_LOAD"";
                    break;

                case PT_DYNAMIC:
                    tmp = ""PT_DYNAMIC"";
                    break;

                case PT_INTERP:
                    tmp = ""PT_INTERP"";
                    break;

                case PT_NOTE:
                    tmp = ""PT_NOTE"";
                    break;

                case PT_SHLIB:
                    tmp = ""PT_SHLIB"";
                    break;

                case PT_PHDR:
                    tmp = ""PT_PHDR"";
                    break;

                case PT_LOPROC:
                    tmp = ""PT_LOPROC"";
                    break;

                case PT_HIPROC:
                    tmp = ""PT_HIPROC"";
                    break;

                case PT_GNU_STACK:
                    tmp = ""PT_GNU_STACK"";
                    break;
                
                default:
                    break;
            }
            strcpy(flag, ""   "");
            flag2str(phdr[i].p_flags, flag);
            PRINT_PROGRAM(i, tmp, phdr[i].p_offset, phdr[i].p_vaddr, phdr[i].p_paddr, phdr[i].p_filesz, phdr[i].p_memsz, flag, phdr[i].p_align); 
        }

        INFO(""Section to segment mapping\n"");
        for (int i = 0; i < ehdr->e_phnum; i++) {
            printf(""     [%2d]"", i);
            for (int j = 0; j < ehdr->e_shnum; j++) {
                name = elf_map + shstrtab.sh_offset + shdr[j].sh_name;
                if (shdr[j].sh_addr >= phdr[i].p_vaddr && shdr[j].sh_addr + shdr[j].sh_size <= phdr[i].p_vaddr + phdr[i].p_memsz && shdr[j].sh_type != SHT_NULL) {
                    if (shdr[j].sh_flags >> 1 & 0x1) {
                        printf("" %s"", name);
                    }
                }    
            }
            printf(""\n"");
        }

        INFO(""Dynamic link information\n"");
        int dynstr;
        int dynamic;
        Elf64_Dyn *dyn;
        for (int i = 0; i < ehdr->e_shnum; i++) {
            name = elf_map + shstrtab.sh_offset + shdr[i].sh_name;
            if (!strcmp(name, "".dynstr"")) {
                dynstr = i;
            }
            if (!strcmp(name, "".dynamic"")) {
                dynamic = i;
            }
        }

        char value[50];
        name = """";
        dyn = (Elf64_Dyn *)&elf_map[shdr[dynamic].sh_offset];
        count = shdr[dynamic].sh_size / sizeof(Elf64_Dyn);
        INFO(""Dynamic section at offset 0x%x contains %d entries\n"", shdr[dynamic].sh_offset, count);
        PRINT_DYN_TITLE(""Tag"", ""Type"", ""Name/Value"");
        
        for(int i = 0; i < count; i++) {
            tmp = """";
            memset(value, 0, 50);
            snprintf(value, 50, ""0x%x"", dyn[i].d_un.d_val);
            switch (dyn[i].d_tag) {
                /* Legal values for d_tag (dynamic entry type).  */
                case DT_NULL:
                    tmp = ""DT_NULL"";
                    break;

                case DT_NEEDED:
                    tmp = ""DT_NEEDED"";
                    name = elf_map + shdr[dynstr].sh_offset + dyn[i].d_un.d_val;
                    snprintf(value, 50, ""Shared library: [%s]"", name);
                    break;
                
                case DT_PLTRELSZ:
                    tmp = ""DT_PLTRELSZ"";
                    break;

                case DT_PLTGOT:
                    tmp = ""DT_PLTGOT"";
                    break;

                case DT_HASH:
                    tmp = ""DT_HASH"";
                    break;

                case DT_STRTAB:
                    tmp = ""DT_STRTAB"";
                    break;

                case DT_SYMTAB:
                    tmp = ""DT_SYMTAB"";
                    break;

                case DT_RELA:
                    tmp = ""DT_RELA"";
                    break;

                case DT_RELASZ:
                    tmp = ""DT_RELASZ"";
                    break;

                case DT_RELAENT:
                    tmp = ""DT_RELAENT"";
                    break;

                case DT_STRSZ:
                    tmp = ""DT_STRSZ"";
                    break;

                case DT_SYMENT:
                    tmp = ""DT_SYMENT"";
                    break;

                case DT_INIT:
                    tmp = ""DT_INIT"";
                    break;

                case DT_FINI:
                    tmp = ""DT_FINI"";
                    break;

                case DT_SONAME:
                    tmp = ""DT_SONAME"";
                    break;

                case DT_RPATH:
                    tmp = ""DT_RPATH"";
                    break;

                case DT_SYMBOLIC:
                    tmp = ""DT_SYMBOLIC"";
                    break;

                case DT_REL:
                    tmp = ""DT_REL"";
                    break;

                case DT_RELSZ:
                    tmp = ""DT_RELSZ"";
                    break;

                case DT_RELENT:
                    tmp = ""DT_RELENT"";
                    break;
                    
                case DT_PLTREL:
                    tmp = ""DT_PLTREL"";
                    break;

                case DT_DEBUG:
                    tmp = ""DT_DEBUG"";
                    break;

                case DT_TEXTREL:
                    tmp = ""DT_TEXTREL"";
                    break;

                case DT_JMPREL:
                    tmp = ""DT_JMPREL"";
                    break;

                case DT_BIND_NOW:
                    tmp = ""DT_BIND_NOW"";
                    break;

                case DT_INIT_ARRAY:
                    tmp = ""DT_INIT_ARRAY"";
                    break;

                case DT_FINI_ARRAY:
                    tmp = ""DT_FINI_ARRAY"";
                    break;

                case DT_INIT_ARRAYSZ:
                    tmp = ""DT_INIT_ARRAYSZ"";
                    break;
                
                case DT_FINI_ARRAYSZ:
                    tmp = ""DT_FINI_ARRAYSZ"";
                    break;

                case DT_RUNPATH:
                    tmp = ""DT_RUNPATH"";
                    break;

                case DT_FLAGS:
                    tmp = ""DT_FLAGS"";
                    snprintf(value, 50, ""Flags: %d"", dyn[i].d_un.d_val);
                    break;
                
                case DT_ENCODING:
                    tmp = ""DT_ENCODING"";
                    break;

                case DT_PREINIT_ARRAYSZ:
                    tmp = ""DT_PREINIT_ARRAYSZ"";
                    break;

                case DT_SYMTAB_SHNDX:
                    tmp = ""DT_SYMTAB_SHNDX"";
                    break;
                
                case DT_NUM:
                    tmp = ""DT_NUM"";
                    break;

                case DT_LOOS:
                    tmp = ""DT_LOOS"";
                    break;

                case DT_HIOS:
                    tmp = ""DT_HIOS"";
                    break;

                case DT_LOPROC:
                    tmp = ""DT_LOPROC"";
                    break;

                case DT_HIPROC:
                    tmp = ""DT_HIPROC"";
                    break;

                case DT_PROCNUM:
                    tmp = ""DT_LOPROC"";
                    break;

                /* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
                 * Dyn.d_un.d_val field of the Elf*_Dyn structure.  This follows Sun's
                 * approach. */

                case DT_VALRNGLO:
                    tmp = ""DT_VALRNGLO"";
                    break;

                case DT_GNU_PRELINKED:
                    tmp = ""DT_GNU_PRELINKED"";
                    break;
                
                case DT_GNU_CONFLICTSZ:
                    tmp = ""DT_GNU_CONFLICTSZ"";
                    break;

                case DT_GNU_LIBLISTSZ:
                    tmp = ""DT_GNU_LIBLISTSZ"";
                    break;

                case DT_CHECKSUM:
                    tmp = ""DT_CHECKSUM"";
                    break;

                case DT_PLTPADSZ:
                    tmp = ""DT_PLTPADSZ"";
                    break;

                case DT_MOVEENT:
                    tmp = ""DT_MOVEENT"";
                    break;

                case DT_MOVESZ:
                    tmp = ""DT_MOVESZ"";
                    break;

                case DT_FEATURE_1:
                    tmp = ""DT_FEATURE_1"";
                    break;

                case DT_POSFLAG_1:
                    tmp = ""DT_POSFLAG_1"";
                    break;

                case DT_SYMINSZ:
                    tmp = ""DT_SYMINSZ"";
                    break;

                case DT_SYMINENT:
                    tmp = ""DT_SYMINENT"";
                    break;

                /* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
                 * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
                 * If any adjustment is made to the ELF object after it has been
                 * built these entries will need to be adjusted.  */
                case DT_ADDRRNGLO:
                    tmp = ""DT_ADDRRNGLO"";
                    break;

                case DT_GNU_HASH:
                    tmp = ""DT_GNU_HASH"";
                    break;

                case DT_TLSDESC_PLT:
                    tmp = ""DT_TLSDESC_PLT"";
                    break;

                case DT_TLSDESC_GOT:
                    tmp = ""DT_TLSDESC_GOT"";
                    break;

                case DT_GNU_CONFLICT:
                    tmp = ""DT_GNU_CONFLICT"";
                    break;

                case DT_GNU_LIBLIST:
                    tmp = ""DT_GNU_LIBLIST"";
                    break;

                case DT_CONFIG:
                    tmp = ""DT_CONFIG"";
                    break;

                case DT_DEPAUDIT:
                    tmp = ""DT_DEPAUDIT"";
                    break;

                case DT_AUDIT:
                    tmp = ""DT_AUDIT"";
                    break;

                case DT_PLTPAD:
                    tmp = ""DT_PLTPAD"";
                    break;

                case DT_MOVETAB:
                    tmp = ""DT_MOVETAB"";
                    break;

                case DT_SYMINFO:
                    tmp = ""DT_SYMINFO"";
                    break;
                    
                /* The versioning entry types.  The next are defined as part of the
                 * GNU extension.  */
                case DT_VERSYM:
                    tmp = ""DT_VERSYM"";
                    break;

                case DT_RELACOUNT:
                    tmp = ""DT_RELACOUNT"";
                    break;

                case DT_RELCOUNT:
                    tmp = ""DT_RELCOUNT"";
                    break;
                
                /* These were chosen by Sun.  */
                case DT_FLAGS_1:
                    tmp = ""DT_FLAGS_1"";
                    switch (dyn[i].d_un.d_val) {
                        case DF_1_PIE:
                            snprintf(value, 50, ""Flags: %s"", ""PIE"");
                            break;
                        
                        default:
                            snprintf(value, 50, ""Flags: %d"", dyn[i].d_un.d_val);
                            break;
                    }
                    
                    break;

                case DT_VERDEF:
                    tmp = ""DT_VERDEF"";
                    break;

                case DT_VERDEFNUM:
                    tmp = ""DT_VERDEFNUM"";
                    break;

                case DT_VERNEED:
                    tmp = ""DT_VERNEED"";
                    break;

                case DT_VERNEEDNUM:
                    tmp = ""DT_VERNEEDNUM"";
                    break;
                
                default:
                    break;
            }
            PRINT_DYN(dyn[i].d_tag, tmp, value);
        }        
    }

    return 0;
}",CWE-125,1
0,"void QuotaManager::NotifyOriginNoLongerInUse(const GURL& origin) {
  DCHECK(io_thread_->BelongsToCurrentThread());
  DCHECK(IsOriginInUse(origin));
  int& count = origins_in_use_[origin];
  if (--count == 0)
    origins_in_use_.erase(origin);
}
",none,24
1,"qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid)
{
    linenr_T	lnum;
    qfline_T	*qfp;
    int		old_KeyTyped = KeyTyped;
    list_T	*qftf_list = NULL;
    listitem_T	*qftf_li = NULL;

    if (old_last == NULL)
    {
	if (buf != curbuf)
	{
	    internal_error(""qf_fill_buffer()"");
	    return;
	}

	// delete all existing lines
	while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0)
	    (void)ml_delete((linenr_T)1);
    }

    // Check if there is anything to display
    if (qfl != NULL)
    {
	char_u		dirname[MAXPATHL];
	int		invalid_val = FALSE;
	int		prev_bufnr = -1;

	*dirname = NUL;

	// Add one line for each error
	if (old_last == NULL)
	{
	    qfp = qfl->qf_start;
	    lnum = 0;
	}
	else
	{
	    if (old_last->qf_next != NULL)
		qfp = old_last->qf_next;
	    else
		qfp = old_last;
	    lnum = buf->b_ml.ml_line_count;
	}

	qftf_list = call_qftf_func(qfl, qf_winid, (long)(lnum + 1),
							(long)qfl->qf_count);
	if (qftf_list != NULL)
	    qftf_li = qftf_list->lv_first;

	while (lnum < qfl->qf_count)
	{
	    char_u	*qftf_str = NULL;

	    // Use the text supplied by the user defined function (if any).
	    // If the returned value is not string, then ignore the rest
	    // of the returned values and use the default.
	    if (qftf_li != NULL && !invalid_val)
	    {
		qftf_str = tv_get_string_chk(&qftf_li->li_tv);
		if (qftf_str == NULL)
		    invalid_val = TRUE;
	    }

	    if (qf_buf_add_line(buf, lnum, qfp, dirname,
			prev_bufnr != qfp->qf_fnum, qftf_str) == FAIL)
		break;

	    prev_bufnr = qfp->qf_fnum;
	    ++lnum;
	    qfp = qfp->qf_next;
	    if (qfp == NULL)
		break;

	    if (qftf_li != NULL)
		qftf_li = qftf_li->li_next;
	}

	if (old_last == NULL)
	    // Delete the empty line which is now at the end
	    (void)ml_delete(lnum + 1);
    }

    // correct cursor position
    check_lnums(TRUE);

    if (old_last == NULL)
    {
	// Set the 'filetype' to ""qf"" each time after filling the buffer.
	// This resembles reading a file into a buffer, it's more logical when
	// using autocommands.
	++curbuf_lock;
	set_option_value_give_err((char_u *)""ft"",
						0L, (char_u *)""qf"", OPT_LOCAL);
	curbuf->b_p_ma = FALSE;

	keep_filetype = TRUE;		// don't detect 'filetype'
	apply_autocmds(EVENT_BUFREADPOST, (char_u *)""quickfix"", NULL,
							       FALSE, curbuf);
	apply_autocmds(EVENT_BUFWINENTER, (char_u *)""quickfix"", NULL,
							       FALSE, curbuf);
	keep_filetype = FALSE;
	--curbuf_lock;

	// make sure it will be redrawn
	redraw_curbuf_later(UPD_NOT_VALID);
    }

    // Restore KeyTyped, setting 'filetype' may reset it.
    KeyTyped = old_KeyTyped;
}",CWE-416,10
0,"  virtual void SaveCellularNetwork(const CellularNetwork* network) {}
",none,24
0,"  virtual WifiNetwork* FindWifiNetworkByPath(
      const std::string& path) { return NULL; }
",none,24
0,"  virtual void RefreshCellularDataPlans(const CellularNetwork* network) {
    DCHECK(network);
    if (!EnsureCrosLoaded() || !network)
      return;
    RequestCellularDataPlanUpdate(network->service_path().c_str());
  }
",none,24
1,"  void Compute(OpKernelContext* ctx) override {
    const Tensor& val = ctx->input(0);
    int64 id = ctx->session_state()->GetNewId();
    TensorStore::TensorAndKey tk{val, id, requested_device()};
    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));

    Tensor* handle = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
      ResourceHandle resource_handle = MakeResourceHandle(
          ctx, SessionState::kTensorHandleResourceTypeName,
          tk.GetHandle(name()));
      resource_handle.set_maybe_type_name(
          SessionState::kTensorHandleResourceTypeName);
      handle->scalar()() = resource_handle;
    } else {
      // Legacy behavior in V1.
      handle->flat().setConstant(tk.GetHandle(name()));
    }
  }",CWE-476,12
1,"static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)
{
    char *p = buf;
    char *end = buf+len;
    unsigned i;
    int printed;

    /* check length for the ""m="" line. */
    if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {
	return -1;
    }
    *p++ = 'm';	    /* m= */
    *p++ = '=';
    pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);
    p += m->desc.media.slen;
    *p++ = ' ';
    printed = pj_utoa(m->desc.port, p);
    p += printed;
    if (m->desc.port_count > 1) {
	*p++ = '/';
	printed = pj_utoa(m->desc.port_count, p);
	p += printed;
    }
    *p++ = ' ';
    pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);
    p += m->desc.transport.slen;
    for (i=0; idesc.fmt_count; ++i) {
	*p++ = ' ';
	pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);
	p += m->desc.fmt[i].slen;
    }
    *p++ = '\r';
    *p++ = '\n';

    /* print connection info, if present. */
    if (m->conn) {
	printed = print_connection_info(m->conn, p, (int)(end-p));
	if (printed < 0) {
	    return -1;
	}
	p += printed;
    }
    
    /* print optional bandwidth info. */
    for (i=0; ibandw_count; ++i) {
	printed = (int)print_bandw(m->bandw[i], p, end-p);
	if (printed < 0) {
	    return -1;
	}
	p += printed;
    }

    /* print attributes. */
    for (i=0; iattr_count; ++i) {
	printed = (int)print_attr(m->attr[i], p, end-p);
	if (printed < 0) {
	    return -1;
	}
	p += printed;
    }

    return (int)(p-buf);
}",CWE-787,16
1,"int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
{
	u8 *tail;
	int nfrags;
	int esph_offset;
	struct page *page;
	struct sk_buff *trailer;
	int tailen = esp->tailen;

	/* this is non-NULL only with TCP/UDP Encapsulation */
	if (x->encap) {
		int err = esp_output_encap(x, skb, esp);

		if (err < 0)
			return err;
	}

	if (!skb_cloned(skb)) {
		if (tailen <= skb_tailroom(skb)) {
			nfrags = 1;
			trailer = skb;
			tail = skb_tail_pointer(trailer);

			goto skip_cow;
		} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)
			   && !skb_has_frag_list(skb)) {
			int allocsize;
			struct sock *sk = skb->sk;
			struct page_frag *pfrag = &x->xfrag;

			esp->inplace = false;

			allocsize = ALIGN(tailen, L1_CACHE_BYTES);

			spin_lock_bh(&x->lock);

			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
				spin_unlock_bh(&x->lock);
				goto cow;
			}

			page = pfrag->page;
			get_page(page);

			tail = page_address(page) + pfrag->offset;

			esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);

			nfrags = skb_shinfo(skb)->nr_frags;

			__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,
					     tailen);
			skb_shinfo(skb)->nr_frags = ++nfrags;

			pfrag->offset = pfrag->offset + allocsize;

			spin_unlock_bh(&x->lock);

			nfrags++;

			skb->len += tailen;
			skb->data_len += tailen;
			skb->truesize += tailen;
			if (sk && sk_fullsock(sk))
				refcount_add(tailen, &sk->sk_wmem_alloc);

			goto out;
		}
	}

cow:
	esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);

	nfrags = skb_cow_data(skb, tailen, &trailer);
	if (nfrags < 0)
		goto out;
	tail = skb_tail_pointer(trailer);
	esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);

skip_cow:
	esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
	pskb_put(skb, trailer, tailen);

out:
	return nfrags;
}",CWE-787,16
1,"static sctp_disposition_t sctp_sf_violation_paramlen(
				     const struct sctp_endpoint *ep,
				     const struct sctp_association *asoc,
				     const sctp_subtype_t type,
				     void *arg,
				     sctp_cmd_seq_t *commands) {
	static const char err_str[] = ""The following parameter had invalid length:"";

	return sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,
					sizeof(err_str));
}",CWE-20,3
1,"bmexec_trans (kwset_t kwset, char const *text, size_t size)
{
  unsigned char const *d1;
  char const *ep, *sp, *tp;
  int d;
  int len = kwset->mind;
  char const *trans = kwset->trans;

  if (len == 0)
    return 0;
  if (len > size)
    return -1;
  if (len == 1)
    {
      tp = memchr_kwset (text, size, kwset);
      return tp ? tp - text : -1;
    }

  d1 = kwset->delta;
  sp = kwset->target + len;
  tp = text + len;
  char gc1 = kwset->gc1;
  char gc2 = kwset->gc2;

  /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
  if (size > 12 * len)
    /* 11 is not a bug, the initial offset happens only once. */
    for (ep = text + size - 11 * len; tp <= ep; )
      {
        char const *tp0 = tp;
        d = d1[U(tp[-1])], tp += d;
        d = d1[U(tp[-1])], tp += d;
        if (d != 0)
          {
            d = d1[U(tp[-1])], tp += d;
            d = d1[U(tp[-1])], tp += d;
            d = d1[U(tp[-1])], tp += d;
            if (d != 0)
              {
                d = d1[U(tp[-1])], tp += d;
                d = d1[U(tp[-1])], tp += d;
                d = d1[U(tp[-1])], tp += d;
                if (d != 0)
                  {
                    d = d1[U(tp[-1])], tp += d;
                    d = d1[U(tp[-1])], tp += d;

                    /* As a heuristic, prefer memchr to seeking by
                       delta1 when the latter doesn't advance much.  */
                    int advance_heuristic = 16 * sizeof (long);
                    if (advance_heuristic <= tp - tp0)
                      goto big_advance;
                    tp--;
                    tp = memchr_kwset (tp, text + size - tp, kwset);
                    if (! tp)
                      return -1;
                    tp++;
                  }
              }
          }
        if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, d1, kwset))
          return tp - text;
      big_advance:;
      }

  /* Now we have only a few characters left to search.  We
     carefully avoid ever producing an out-of-bounds pointer. */
  ep = text + size;
  d = d1[U(tp[-1])];
  while (d <= ep - tp)
    {
      d = d1[U((tp += d)[-1])];
      if (d != 0)
        continue;
      if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset))
        return tp - text;
    }

  return -1;
}",CWE-119,0
1,"    void publish(Topic *iterator, size_t start, size_t stop, std::string_view topic, std::pair message) {
        /* If we already have 64 triggered topics make sure to drain it here */
        if (numTriggeredTopics == 64) {
            drain();
        }

        /* Iterate over all segments in given topic */
        for (; stop != std::string::npos; start = stop + 1) {
            stop = topic.find('/', start);
            std::string_view segment = topic.substr(start, stop - start);

            /* It is very important to disallow wildcards when publishing.
             * We will not catch EVERY misuse this lazy way, but enough to hinder
             * explosive recursion.
             * Terminating wildcards MAY still get triggered along the way, if for
             * instace the error is found late while iterating the topic segments. */
            if (segment.length() == 1) {
                if (segment[0] == '+' || segment[0] == '#') {
                    return;
                }
            }

            /* Do we have a terminating wildcard child? */
            if (iterator->terminatingWildcardChild) {
                iterator->terminatingWildcardChild->messages[messageId] = message;

                /* Add this topic to triggered */
                if (!iterator->terminatingWildcardChild->triggered) {
                    triggeredTopics[numTriggeredTopics++] = iterator->terminatingWildcardChild;
                    iterator->terminatingWildcardChild->triggered = true;
                }
            }

            /* Do we have a wildcard child? */
            if (iterator->wildcardChild) {
                publish(iterator->wildcardChild, stop + 1, stop, topic, message);
            }

            std::map::iterator it = iterator->children.find(segment);
            if (it == iterator->children.end()) {
                /* Stop trying to match by exact string */
                return;
            }

            iterator = it->second;
        }

        /* If we went all the way we matched exactly */
        iterator->messages[messageId] = message;

        /* Add this topic to triggered */
        if (!iterator->triggered) {
            triggeredTopics[numTriggeredTopics++] = iterator;
            iterator->triggered = true;
        }
    }",CWE-787,16
1,"do_cmdline(
    char_u	*cmdline,
    char_u	*(*fgetline)(int, void *, int, getline_opt_T),
    void	*cookie,		// argument for fgetline()
    int		flags)
{
    char_u	*next_cmdline;		// next cmd to execute
    char_u	*cmdline_copy = NULL;	// copy of cmd line
    int		used_getline = FALSE;	// used ""fgetline"" to obtain command
    static int	recursive = 0;		// recursive depth
    int		msg_didout_before_start = 0;
    int		count = 0;		// line number count
    int		did_inc = FALSE;	// incremented RedrawingDisabled
    int		retval = OK;
#ifdef FEAT_EVAL
    cstack_T	cstack;			// conditional stack
    garray_T	lines_ga;		// keep lines for "":while""/"":for""
    int		current_line = 0;	// active line in lines_ga
    int		current_line_before = 0;
    char_u	*fname = NULL;		// function or script name
    linenr_T	*breakpoint = NULL;	// ptr to breakpoint field in cookie
    int		*dbg_tick = NULL;	// ptr to dbg_tick field in cookie
    struct dbg_stuff debug_saved;	// saved things for debug mode
    int		initial_trylevel;
    msglist_T	**saved_msg_list = NULL;
    msglist_T	*private_msg_list = NULL;

    // ""fgetline"" and ""cookie"" passed to do_one_cmd()
    char_u	*(*cmd_getline)(int, void *, int, getline_opt_T);
    void	*cmd_cookie;
    struct loop_cookie cmd_loop_cookie;
    void	*real_cookie;
    int		getline_is_func;
#else
# define cmd_getline fgetline
# define cmd_cookie cookie
#endif
    static int	call_depth = 0;		// recursiveness
#ifdef FEAT_EVAL
    // For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory
    // location for storing error messages to be converted to an exception.
    // This ensures that the do_errthrow() call in do_one_cmd() does not
    // combine the messages stored by an earlier invocation of do_one_cmd()
    // with the command name of the later one.  This would happen when
    // BufWritePost autocommands are executed after a write error.
    saved_msg_list = msg_list;
    msg_list = &private_msg_list;
#endif

    // It's possible to create an endless loop with "":execute"", catch that
    // here.  The value of 200 allows nested function calls, "":source"", etc.
    // Allow 200 or 'maxfuncdepth', whatever is larger.
    if (call_depth >= 200
#ifdef FEAT_EVAL
	    && call_depth >= p_mfd
#endif
	    )
    {
	emsg(_(e_command_too_recursive));
#ifdef FEAT_EVAL
	// When converting to an exception, we do not include the command name
	// since this is not an error of the specific command.
	do_errthrow((cstack_T *)NULL, (char_u *)NULL);
	msg_list = saved_msg_list;
#endif
	return FAIL;
    }
    ++call_depth;

#ifdef FEAT_EVAL
    CLEAR_FIELD(cstack);
    cstack.cs_idx = -1;
    ga_init2(&lines_ga, sizeof(wcmd_T), 10);

    real_cookie = getline_cookie(fgetline, cookie);

    // Inside a function use a higher nesting level.
    getline_is_func = getline_equal(fgetline, cookie, get_func_line);
    if (getline_is_func && ex_nesting_level == func_level(real_cookie))
	++ex_nesting_level;

    // Get the function or script name and the address where the next breakpoint
    // line and the debug tick for a function or script are stored.
    if (getline_is_func)
    {
	fname = func_name(real_cookie);
	breakpoint = func_breakpoint(real_cookie);
	dbg_tick = func_dbg_tick(real_cookie);
    }
    else if (getline_equal(fgetline, cookie, getsourceline))
    {
	fname = SOURCING_NAME;
	breakpoint = source_breakpoint(real_cookie);
	dbg_tick = source_dbg_tick(real_cookie);
    }

    /*
     * Initialize ""force_abort""  and ""suppress_errthrow"" at the top level.
     */
    if (!recursive)
    {
	force_abort = FALSE;
	suppress_errthrow = FALSE;
    }

    /*
     * If requested, store and reset the global values controlling the
     * exception handling (used when debugging).  Otherwise clear it to avoid
     * a bogus compiler warning when the optimizer uses inline functions...
     */
    if (flags & DOCMD_EXCRESET)
	save_dbg_stuff(&debug_saved);
    else
	CLEAR_FIELD(debug_saved);

    initial_trylevel = trylevel;

    /*
     * ""did_throw"" will be set to TRUE when an exception is being thrown.
     */
    did_throw = FALSE;
#endif
    /*
     * ""did_emsg"" will be set to TRUE when emsg() is used, in which case we
     * cancel the whole command line, and any if/endif or loop.
     * If force_abort is set, we cancel everything.
     */
#ifdef FEAT_EVAL
    did_emsg_cumul += did_emsg;
#endif
    did_emsg = FALSE;

    /*
     * KeyTyped is only set when calling vgetc().  Reset it here when not
     * calling vgetc() (sourced command lines).
     */
    if (!(flags & DOCMD_KEYTYPED)
			       && !getline_equal(fgetline, cookie, getexline))
	KeyTyped = FALSE;

    /*
     * Continue executing command lines:
     * - when inside an "":if"", "":while"" or "":for""
     * - for multiple commands on one line, separated with '|'
     * - when repeating until there are no more lines (for "":source"")
     */
    next_cmdline = cmdline;
    do
    {
#ifdef FEAT_EVAL
	getline_is_func = getline_equal(fgetline, cookie, get_func_line);
#endif

	// stop skipping cmds for an error msg after all endif/while/for
	if (next_cmdline == NULL
#ifdef FEAT_EVAL
		&& !force_abort
		&& cstack.cs_idx < 0
		&& !(getline_is_func && func_has_abort(real_cookie))
#endif
							)
	{
#ifdef FEAT_EVAL
	    did_emsg_cumul += did_emsg;
#endif
	    did_emsg = FALSE;
	}

	/*
	 * 1. If repeating a line in a loop, get a line from lines_ga.
	 * 2. If no line given: Get an allocated line with fgetline().
	 * 3. If a line is given: Make a copy, so we can mess with it.
	 */

#ifdef FEAT_EVAL
	// 1. If repeating, get a previous line from lines_ga.
	if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len)
	{
	    // Each '|' separated command is stored separately in lines_ga, to
	    // be able to jump to it.  Don't use next_cmdline now.
	    VIM_CLEAR(cmdline_copy);

	    // Check if a function has returned or, unless it has an unclosed
	    // try conditional, aborted.
	    if (getline_is_func)
	    {
# ifdef FEAT_PROFILE
		if (do_profiling == PROF_YES)
		    func_line_end(real_cookie);
# endif
		if (func_has_ended(real_cookie))
		{
		    retval = FAIL;
		    break;
		}
	    }
#ifdef FEAT_PROFILE
	    else if (do_profiling == PROF_YES
			    && getline_equal(fgetline, cookie, getsourceline))
		script_line_end();
#endif

	    // Check if a sourced file hit a "":finish"" command.
	    if (source_finished(fgetline, cookie))
	    {
		retval = FAIL;
		break;
	    }

	    // If breakpoints have been added/deleted need to check for it.
	    if (breakpoint != NULL && dbg_tick != NULL
						   && *dbg_tick != debug_tick)
	    {
		*breakpoint = dbg_find_breakpoint(
				getline_equal(fgetline, cookie, getsourceline),
							fname, SOURCING_LNUM);
		*dbg_tick = debug_tick;
	    }

	    next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line;
	    SOURCING_LNUM = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum;

	    // Did we encounter a breakpoint?
	    if (breakpoint != NULL && *breakpoint != 0
					      && *breakpoint <= SOURCING_LNUM)
	    {
		dbg_breakpoint(fname, SOURCING_LNUM);
		// Find next breakpoint.
		*breakpoint = dbg_find_breakpoint(
			       getline_equal(fgetline, cookie, getsourceline),
							fname, SOURCING_LNUM);
		*dbg_tick = debug_tick;
	    }
# ifdef FEAT_PROFILE
	    if (do_profiling == PROF_YES)
	    {
		if (getline_is_func)
		    func_line_start(real_cookie, SOURCING_LNUM);
		else if (getline_equal(fgetline, cookie, getsourceline))
		    script_line_start();
	    }
# endif
	}
#endif

	// 2. If no line given, get an allocated line with fgetline().
	if (next_cmdline == NULL)
	{
	    /*
	     * Need to set msg_didout for the first line after an "":if"",
	     * otherwise the "":if"" will be overwritten.
	     */
	    if (count == 1 && getline_equal(fgetline, cookie, getexline))
		msg_didout = TRUE;
	    if (fgetline == NULL || (next_cmdline = fgetline(':', cookie,
#ifdef FEAT_EVAL
		    cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2
#else
		    0
#endif
		    , in_vim9script() ? GETLINE_CONCAT_CONTBAR
					       : GETLINE_CONCAT_CONT)) == NULL)
	    {
		// Don't call wait_return() for aborted command line.  The NULL
		// returned for the end of a sourced file or executed function
		// doesn't do this.
		if (KeyTyped && !(flags & DOCMD_REPEAT))
		    need_wait_return = FALSE;
		retval = FAIL;
		break;
	    }
	    used_getline = TRUE;

	    /*
	     * Keep the first typed line.  Clear it when more lines are typed.
	     */
	    if (flags & DOCMD_KEEPLINE)
	    {
		vim_free(repeat_cmdline);
		if (count == 0)
		    repeat_cmdline = vim_strsave(next_cmdline);
		else
		    repeat_cmdline = NULL;
	    }
	}

	// 3. Make a copy of the command so we can mess with it.
	else if (cmdline_copy == NULL)
	{
	    next_cmdline = vim_strsave(next_cmdline);
	    if (next_cmdline == NULL)
	    {
		emsg(_(e_out_of_memory));
		retval = FAIL;
		break;
	    }
	}
	cmdline_copy = next_cmdline;

#ifdef FEAT_EVAL
	/*
	 * Inside a while/for loop, and when the command looks like a "":while""
	 * or "":for"", the line is stored, because we may need it later when
	 * looping.
	 *
	 * When there is a '|' and another command, it is stored separately,
	 * because we need to be able to jump back to it from an
	 * :endwhile/:endfor.
	 *
	 * Pass a different ""fgetline"" function to do_one_cmd() below,
	 * that it stores lines in or reads them from ""lines_ga"".  Makes it
	 * possible to define a function inside a while/for loop and handles
	 * line continuation.
	 */
	if ((cstack.cs_looplevel > 0 || has_loop_cmd(next_cmdline)))
	{
	    cmd_getline = get_loop_line;
	    cmd_cookie = (void *)&cmd_loop_cookie;
	    cmd_loop_cookie.lines_gap = &lines_ga;
	    cmd_loop_cookie.current_line = current_line;
	    cmd_loop_cookie.getline = fgetline;
	    cmd_loop_cookie.cookie = cookie;
	    cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len);

	    // Save the current line when encountering it the first time.
	    if (current_line == lines_ga.ga_len
		    && store_loop_line(&lines_ga, next_cmdline) == FAIL)
	    {
		retval = FAIL;
		break;
	    }
	    current_line_before = current_line;
	}
	else
	{
	    cmd_getline = fgetline;
	    cmd_cookie = cookie;
	}

	did_endif = FALSE;
#endif

	if (count++ == 0)
	{
	    /*
	     * All output from the commands is put below each other, without
	     * waiting for a return. Don't do this when executing commands
	     * from a script or when being called recursive (e.g. for "":e
	     * +command file"").
	     */
	    if (!(flags & DOCMD_NOWAIT) && !recursive)
	    {
		msg_didout_before_start = msg_didout;
		msg_didany = FALSE; // no output yet
		msg_start();
		msg_scroll = TRUE;  // put messages below each other
		++no_wait_return;   // don't wait for return until finished
		++RedrawingDisabled;
		did_inc = TRUE;
	    }
	}

	if ((p_verbose >= 15 && SOURCING_NAME != NULL) || p_verbose >= 16)
	    msg_verbose_cmd(SOURCING_LNUM, cmdline_copy);

	/*
	 * 2. Execute one '|' separated command.
	 *    do_one_cmd() will return NULL if there is no trailing '|'.
	 *    ""cmdline_copy"" can change, e.g. for '%' and '#' expansion.
	 */
	++recursive;
	next_cmdline = do_one_cmd(&cmdline_copy, flags,
#ifdef FEAT_EVAL
				&cstack,
#endif
				cmd_getline, cmd_cookie);
	--recursive;

#ifdef FEAT_EVAL
	if (cmd_cookie == (void *)&cmd_loop_cookie)
	    // Use ""current_line"" from ""cmd_loop_cookie"", it may have been
	    // incremented when defining a function.
	    current_line = cmd_loop_cookie.current_line;
#endif

	if (next_cmdline == NULL)
	{
	    VIM_CLEAR(cmdline_copy);

	    /*
	     * If the command was typed, remember it for the ':' register.
	     * Do this AFTER executing the command to make :@: work.
	     */
	    if (getline_equal(fgetline, cookie, getexline)
						  && new_last_cmdline != NULL)
	    {
		vim_free(last_cmdline);
		last_cmdline = new_last_cmdline;
		new_last_cmdline = NULL;
	    }
	}
	else
	{
	    // need to copy the command after the '|' to cmdline_copy, for the
	    // next do_one_cmd()
	    STRMOVE(cmdline_copy, next_cmdline);
	    next_cmdline = cmdline_copy;
	}


#ifdef FEAT_EVAL
	// reset did_emsg for a function that is not aborted by an error
	if (did_emsg && !force_abort
		&& getline_equal(fgetline, cookie, get_func_line)
					      && !func_has_abort(real_cookie))
	{
	    // did_emsg_cumul is not set here
	    did_emsg = FALSE;
	}

	if (cstack.cs_looplevel > 0)
	{
	    ++current_line;

	    /*
	     * An "":endwhile"", "":endfor"" and "":continue"" is handled here.
	     * If we were executing commands, jump back to the "":while"" or
	     * "":for"".
	     * If we were not executing commands, decrement cs_looplevel.
	     */
	    if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP))
	    {
		cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP);

		// Jump back to the matching "":while"" or "":for"".  Be careful
		// not to use a cs_line[] from an entry that isn't a "":while""
		// or "":for"": It would make ""current_line"" invalid and can
		// cause a crash.
		if (!did_emsg && !got_int && !did_throw
			&& cstack.cs_idx >= 0
			&& (cstack.cs_flags[cstack.cs_idx]
						      & (CSF_WHILE | CSF_FOR))
			&& cstack.cs_line[cstack.cs_idx] >= 0
			&& (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE))
		{
		    current_line = cstack.cs_line[cstack.cs_idx];
						// remember we jumped there
		    cstack.cs_lflags |= CSL_HAD_LOOP;
		    line_breakcheck();		// check if CTRL-C typed

		    // Check for the next breakpoint at or after the "":while""
		    // or "":for"".
		    if (breakpoint != NULL)
		    {
			*breakpoint = dbg_find_breakpoint(
			       getline_equal(fgetline, cookie, getsourceline),
									fname,
			   ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1);
			*dbg_tick = debug_tick;
		    }
		}
		else
		{
		    // can only get here with "":endwhile"" or "":endfor""
		    if (cstack.cs_idx >= 0)
			rewind_conditionals(&cstack, cstack.cs_idx - 1,
				   CSF_WHILE | CSF_FOR, &cstack.cs_looplevel);
		}
	    }

	    /*
	     * For a "":while"" or "":for"" we need to remember the line number.
	     */
	    else if (cstack.cs_lflags & CSL_HAD_LOOP)
	    {
		cstack.cs_lflags &= ~CSL_HAD_LOOP;
		cstack.cs_line[cstack.cs_idx] = current_line_before;
	    }
	}

	// Check for the next breakpoint after a watchexpression
	if (breakpoint != NULL && has_watchexpr())
	{
	    *breakpoint = dbg_find_breakpoint(FALSE, fname, SOURCING_LNUM);
	    *dbg_tick = debug_tick;
	}

	/*
	 * When not inside any "":while"" loop, clear remembered lines.
	 */
	if (cstack.cs_looplevel == 0)
	{
	    if (lines_ga.ga_len > 0)
	    {
		SOURCING_LNUM =
		       ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum;
		free_cmdlines(&lines_ga);
	    }
	    current_line = 0;
	}

	/*
	 * A "":finally"" makes did_emsg, got_int, and did_throw pending for
	 * being restored at the "":endtry"".  Reset them here and set the
	 * ACTIVE and FINALLY flags, so that the finally clause gets executed.
	 * This includes the case where a missing "":endif"", "":endwhile"" or
	 * "":endfor"" was detected by the "":finally"" itself.
	 */
	if (cstack.cs_lflags & CSL_HAD_FINA)
	{
	    cstack.cs_lflags &= ~CSL_HAD_FINA;
	    report_make_pending(cstack.cs_pending[cstack.cs_idx]
		    & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW),
		    did_throw ? (void *)current_exception : NULL);
	    did_emsg = got_int = did_throw = FALSE;
	    cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY;
	}

	// Update global ""trylevel"" for recursive calls to do_cmdline() from
	// within this loop.
	trylevel = initial_trylevel + cstack.cs_trylevel;

	/*
	 * If the outermost try conditional (across function calls and sourced
	 * files) is aborted because of an error, an interrupt, or an uncaught
	 * exception, cancel everything.  If it is left normally, reset
	 * force_abort to get the non-EH compatible abortion behavior for
	 * the rest of the script.
	 */
	if (trylevel == 0 && !did_emsg && !got_int && !did_throw)
	    force_abort = FALSE;

	// Convert an interrupt to an exception if appropriate.
	(void)do_intthrow(&cstack);
#endif // FEAT_EVAL

    }
    /*
     * Continue executing command lines when:
     * - no CTRL-C typed, no aborting error, no exception thrown or try
     *   conditionals need to be checked for executing finally clauses or
     *   catching an interrupt exception
     * - didn't get an error message or lines are not typed
     * - there is a command after '|', inside a :if, :while, :for or :try, or
     *   looping for "":source"" command or function call.
     */
    while (!((got_int
#ifdef FEAT_EVAL
		    || (did_emsg && (force_abort || in_vim9script()))
		    || did_throw
#endif
	     )
#ifdef FEAT_EVAL
		&& cstack.cs_trylevel == 0
#endif
	    )
	    && !(did_emsg
#ifdef FEAT_EVAL
		// Keep going when inside try/catch, so that the error can be
		// deal with, except when it is a syntax error, it may cause
		// the :endtry to be missed.
		&& (cstack.cs_trylevel == 0 || did_emsg_syntax)
#endif
		&& used_getline
			    && (getline_equal(fgetline, cookie, getexmodeline)
			       || getline_equal(fgetline, cookie, getexline)))
	    && (next_cmdline != NULL
#ifdef FEAT_EVAL
			|| cstack.cs_idx >= 0
#endif
			|| (flags & DOCMD_REPEAT)));

    vim_free(cmdline_copy);
    did_emsg_syntax = FALSE;
#ifdef FEAT_EVAL
    free_cmdlines(&lines_ga);
    ga_clear(&lines_ga);

    if (cstack.cs_idx >= 0)
    {
	/*
	 * If a sourced file or executed function ran to its end, report the
	 * unclosed conditional.
	 * In Vim9 script do not give a second error, executing aborts after
	 * the first one.
	 */
	if (!got_int && !did_throw && !aborting()
		&& !(did_emsg && in_vim9script())
		&& ((getline_equal(fgetline, cookie, getsourceline)
			&& !source_finished(fgetline, cookie))
		    || (getline_equal(fgetline, cookie, get_func_line)
					    && !func_has_ended(real_cookie))))
	{
	    if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY)
		emsg(_(e_missing_endtry));
	    else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE)
		emsg(_(e_missing_endwhile));
	    else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR)
		emsg(_(e_missing_endfor));
	    else
		emsg(_(e_missing_endif));
	}

	/*
	 * Reset ""trylevel"" in case of a "":finish"" or "":return"" or a missing
	 * "":endtry"" in a sourced file or executed function.  If the try
	 * conditional is in its finally clause, ignore anything pending.
	 * If it is in a catch clause, finish the caught exception.
	 * Also cleanup any ""cs_forinfo"" structures.
	 */
	do
	{
	    int idx = cleanup_conditionals(&cstack, 0, TRUE);

	    if (idx >= 0)
		--idx;	    // remove try block not in its finally clause
	    rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR,
							&cstack.cs_looplevel);
	}
	while (cstack.cs_idx >= 0);
	trylevel = initial_trylevel;
    }

    // If a missing "":endtry"", "":endwhile"", "":endfor"", or "":endif"" or a memory
    // lack was reported above and the error message is to be converted to an
    // exception, do this now after rewinding the cstack.
    do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line)
				  ? (char_u *)""endfunction"" : (char_u *)NULL);

    if (trylevel == 0)
    {
	// Just in case did_throw got set but current_exception wasn't.
	if (current_exception == NULL)
	    did_throw = FALSE;

	/*
	 * When an exception is being thrown out of the outermost try
	 * conditional, discard the uncaught exception, disable the conversion
	 * of interrupts or errors to exceptions, and ensure that no more
	 * commands are executed.
	 */
	if (did_throw)
	    handle_did_throw();

	/*
	 * On an interrupt or an aborting error not converted to an exception,
	 * disable the conversion of errors to exceptions.  (Interrupts are not
	 * converted anymore, here.) This enables also the interrupt message
	 * when force_abort is set and did_emsg unset in case of an interrupt
	 * from a finally clause after an error.
	 */
	else if (got_int || (did_emsg && force_abort))
	    suppress_errthrow = TRUE;
    }

    /*
     * The current cstack will be freed when do_cmdline() returns.  An uncaught
     * exception will have to be rethrown in the previous cstack.  If a function
     * has just returned or a script file was just finished and the previous
     * cstack belongs to the same function or, respectively, script file, it
     * will have to be checked for finally clauses to be executed due to the
     * "":return"" or "":finish"".  This is done in do_one_cmd().
     */
    if (did_throw)
	need_rethrow = TRUE;
    if ((getline_equal(fgetline, cookie, getsourceline)
		&& ex_nesting_level > source_level(real_cookie))
	    || (getline_equal(fgetline, cookie, get_func_line)
		&& ex_nesting_level > func_level(real_cookie) + 1))
    {
	if (!did_throw)
	    check_cstack = TRUE;
    }
    else
    {
	// When leaving a function, reduce nesting level.
	if (getline_equal(fgetline, cookie, get_func_line))
	    --ex_nesting_level;
	/*
	 * Go to debug mode when returning from a function in which we are
	 * single-stepping.
	 */
	if ((getline_equal(fgetline, cookie, getsourceline)
		    || getline_equal(fgetline, cookie, get_func_line))
		&& ex_nesting_level + 1 <= debug_break_level)
	    do_debug(getline_equal(fgetline, cookie, getsourceline)
		    ? (char_u *)_(""End of sourced file"")
		    : (char_u *)_(""End of function""));
    }

    /*
     * Restore the exception environment (done after returning from the
     * debugger).
     */
    if (flags & DOCMD_EXCRESET)
	restore_dbg_stuff(&debug_saved);

    msg_list = saved_msg_list;

    // Cleanup if ""cs_emsg_silent_list"" remains.
    if (cstack.cs_emsg_silent_list != NULL)
    {
	eslist_T *elem, *temp;

	for (elem = cstack.cs_emsg_silent_list; elem != NULL; elem = temp)
	{
	    temp = elem->next;
	    vim_free(elem);
	}
    }
#endif // FEAT_EVAL

    /*
     * If there was too much output to fit on the command line, ask the user to
     * hit return before redrawing the screen. With the "":global"" command we do
     * this only once after the command is finished.
     */
    if (did_inc)
    {
	--RedrawingDisabled;
	--no_wait_return;
	msg_scroll = FALSE;

	/*
	 * When just finished an "":if""-"":else"" which was typed, no need to
	 * wait for hit-return.  Also for an error situation.
	 */
	if (retval == FAIL
#ifdef FEAT_EVAL
		|| (did_endif && KeyTyped && !did_emsg)
#endif
					    )
	{
	    need_wait_return = FALSE;
	    msg_didany = FALSE;		// don't wait when restarting edit
	}
	else if (need_wait_return)
	{
	    /*
	     * The msg_start() above clears msg_didout. The wait_return() we do
	     * here should not overwrite the command that may be shown before
	     * doing that.
	     */
	    msg_didout |= msg_didout_before_start;
	    wait_return(FALSE);
	}
    }

#ifdef FEAT_EVAL
    did_endif = FALSE;  // in case do_cmdline used recursively
#else
    /*
     * Reset if_level, in case a sourced script file contains more "":if"" than
     * "":endif"" (could be "":if x | foo | endif"").
     */
    if_level = 0;
#endif

    --call_depth;
    return retval;
}",CWE-416,10
0,"  DeleteOriginInfo(
      QuotaManager* manager,
      const GURL& origin,
      StorageType type)
      : DatabaseTaskBase(manager),
        origin_(origin),
        type_(type) {}
",none,24
1,"FindEmptyObjectSlot(
		    TPMI_DH_OBJECT  *handle         // OUT: (optional)
		    )
{
    UINT32               i;
    OBJECT              *object;
    for(i = 0; i < MAX_LOADED_OBJECTS; i++)
	{
	    object = &s_objects[i];
	    if(object->attributes.occupied == CLEAR)
		{
		    if(handle)
			*handle = i + TRANSIENT_FIRST;
		    // Initialize the object attributes
		    MemorySet(&object->attributes, 0, sizeof(OBJECT_ATTRIBUTES));
		    return object;
		}
	}
    return NULL;
}",CWE-119,0
1,"static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image)
{
	jpc_enc_cp_t *cp;
	jas_tvparser_t *tvp;
	int ret;
	int numilyrrates;
	double *ilyrrates;
	int i;
	int tagid;
	jpc_enc_tcp_t *tcp;
	jpc_enc_tccp_t *tccp;
	jpc_enc_ccp_t *ccp;
	uint_fast16_t rlvlno;
	uint_fast16_t prcwidthexpn;
	uint_fast16_t prcheightexpn;
	bool enablemct;
	uint_fast32_t jp2overhead;
	uint_fast16_t lyrno;
	uint_fast32_t hsteplcm;
	uint_fast32_t vsteplcm;
	bool mctvalid;

	tvp = 0;
	cp = 0;
	ilyrrates = 0;
	numilyrrates = 0;

	if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
		goto error;
	}

	prcwidthexpn = 15;
	prcheightexpn = 15;
	enablemct = true;
	jp2overhead = 0;

	cp->ccps = 0;
	cp->debug = 0;
	cp->imgareatlx = UINT_FAST32_MAX;
	cp->imgareatly = UINT_FAST32_MAX;
	cp->refgrdwidth = 0;
	cp->refgrdheight = 0;
	cp->tilegrdoffx = UINT_FAST32_MAX;
	cp->tilegrdoffy = UINT_FAST32_MAX;
	cp->tilewidth = 0;
	cp->tileheight = 0;
	cp->numcmpts = jas_image_numcmpts(image);

	hsteplcm = 1;
	vsteplcm = 1;
	for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
		if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
		  jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
		  jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
			jas_eprintf(""unsupported image type\n"");
			goto error;
		}
		/* Note: We ought to be calculating the LCMs here.  Fix some day. */
		hsteplcm *= jas_image_cmpthstep(image, cmptno);
		vsteplcm *= jas_image_cmptvstep(image, cmptno);
	}

	if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {
		goto error;
	}
	unsigned cmptno;
	for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno,
	  ++ccp) {
		ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
		ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
		/* XXX - this isn't quite correct for more general image */
		ccp->sampgrdsubstepx = 0;
		ccp->sampgrdsubstepx = 0;
		ccp->prec = jas_image_cmptprec(image, cmptno);
		ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
		ccp->numstepsizes = 0;
		memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
	}

	cp->rawsize = jas_image_rawsize(image);
	if (cp->rawsize == 0) {
		/* prevent division by zero in cp_create() */
		goto error;
	}
	cp->totalsize = UINT_FAST32_MAX;

	tcp = &cp->tcp;
	tcp->csty = 0;
	tcp->intmode = true;
	tcp->prg = JPC_COD_LRCPPRG;
	tcp->numlyrs = 1;
	tcp->ilyrrates = 0;

	tccp = &cp->tccp;
	tccp->csty = 0;
	tccp->maxrlvls = 6;
	tccp->cblkwidthexpn = 6;
	tccp->cblkheightexpn = 6;
	tccp->cblksty = 0;
	tccp->numgbits = 2;

	if (!(tvp = jas_tvparser_create(optstr ? optstr : """"))) {
		goto error;
	}

	while (!(ret = jas_tvparser_next(tvp))) {
		switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
		  jas_tvparser_gettag(tvp)))->id) {
		case OPT_DEBUG:
			cp->debug = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_IMGAREAOFFX:
			cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_IMGAREAOFFY:
			cp->imgareatly = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_TILEGRDOFFX:
			cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_TILEGRDOFFY:
			cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_TILEWIDTH:
			cp->tilewidth = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_TILEHEIGHT:
			cp->tileheight = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_PRCWIDTH:
			prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
			break;
		case OPT_PRCHEIGHT:
			prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
			break;
		case OPT_CBLKWIDTH:
			tccp->cblkwidthexpn =
			  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
			break;
		case OPT_CBLKHEIGHT:
			tccp->cblkheightexpn =
			  jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
			break;
		case OPT_MODE:
			if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
			  jas_tvparser_getval(tvp)))->id) < 0) {
				jas_eprintf(""ignoring invalid mode %s\n"",
				  jas_tvparser_getval(tvp));
			} else {
				tcp->intmode = (tagid == MODE_INT);
			}
			break;
		case OPT_PRG:
			if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
			  jas_tvparser_getval(tvp)))->id) < 0) {
				jas_eprintf(""ignoring invalid progression order %s\n"",
				  jas_tvparser_getval(tvp));
			} else {
				tcp->prg = tagid;
			}
			break;
		case OPT_NOMCT:
			enablemct = false;
			break;
		case OPT_MAXRLVLS:
			tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_SOP:
			cp->tcp.csty |= JPC_COD_SOP;
			break;
		case OPT_EPH:
			cp->tcp.csty |= JPC_COD_EPH;
			break;
		case OPT_LAZY:
			tccp->cblksty |= JPC_COX_LAZY;
			break;
		case OPT_TERMALL:
			tccp->cblksty |= JPC_COX_TERMALL;
			break;
		case OPT_SEGSYM:
			tccp->cblksty |= JPC_COX_SEGSYM;
			break;
		case OPT_VCAUSAL:
			tccp->cblksty |= JPC_COX_VSC;
			break;
		case OPT_RESET:
			tccp->cblksty |= JPC_COX_RESET;
			break;
		case OPT_PTERM:
			tccp->cblksty |= JPC_COX_PTERM;
			break;
		case OPT_NUMGBITS:
			cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
			break;
		case OPT_RATE:
			if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
			  &cp->totalsize)) {
				jas_eprintf(""ignoring bad rate specifier %s\n"",
				  jas_tvparser_getval(tvp));
			}
			break;
		case OPT_ILYRRATES:
			if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
			  &ilyrrates)) {
				jas_eprintf(""warning: invalid intermediate layer rates specifier ignored (%s)\n"",
				  jas_tvparser_getval(tvp));
			}
			break;

		case OPT_JP2OVERHEAD:
			jp2overhead = atoi(jas_tvparser_getval(tvp));
			break;
		default:
			jas_eprintf(""warning: ignoring invalid option %s\n"",
			 jas_tvparser_gettag(tvp));
			break;
		}
	}

	jas_tvparser_destroy(tvp);
	tvp = 0;

	if (cp->totalsize != UINT_FAST32_MAX) {
		cp->totalsize = (cp->totalsize > jp2overhead) ?
		  (cp->totalsize - jp2overhead) : 0;
	}

	if (cp->imgareatlx == UINT_FAST32_MAX) {
		cp->imgareatlx = 0;
	} else {
		if (hsteplcm != 1) {
			jas_eprintf(""warning: overriding imgareatlx value\n"");
		}
		cp->imgareatlx *= hsteplcm;
	}
	if (cp->imgareatly == UINT_FAST32_MAX) {
		cp->imgareatly = 0;
	} else {
		if (vsteplcm != 1) {
			jas_eprintf(""warning: overriding imgareatly value\n"");
		}
		cp->imgareatly *= vsteplcm;
	}
	cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
	cp->refgrdheight = cp->imgareatly + jas_image_height(image);
	if (cp->tilegrdoffx == UINT_FAST32_MAX) {
		cp->tilegrdoffx = cp->imgareatlx;
	}
	if (cp->tilegrdoffy == UINT_FAST32_MAX) {
		cp->tilegrdoffy = cp->imgareatly;
	}
	if (!cp->tilewidth) {
		cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
	}
	if (!cp->tileheight) {
		cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
	}

	if (cp->numcmpts == 3) {
		mctvalid = true;
		for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
			if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
			  jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
			  jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
			  jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
				mctvalid = false;
			}
		}
	} else {
		mctvalid = false;
	}
	if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
		jas_eprintf(""warning: color space apparently not RGB\n"");
	}
	if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
		tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
	} else {
		tcp->mctid = JPC_MCT_NONE;
	}
	tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);

	for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
		tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
		tccp->prcheightexpns[rlvlno] = prcheightexpn;
	}
	if (prcwidthexpn != 15 || prcheightexpn != 15) {
		tccp->csty |= JPC_COX_PRT;
	}

	/* Ensure that the tile width and height is valid. */
	if (!cp->tilewidth) {
		jas_eprintf(""invalid tile width %lu\n"", (unsigned long)
		  cp->tilewidth);
		goto error;
	}
	if (!cp->tileheight) {
		jas_eprintf(""invalid tile height %lu\n"", (unsigned long)
		  cp->tileheight);
		goto error;
	}

	/* Ensure that the tile grid offset is valid. */
	if (cp->tilegrdoffx > cp->imgareatlx ||
	  cp->tilegrdoffy > cp->imgareatly ||
	  cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
	  cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
		jas_eprintf(""invalid tile grid offset (%lu, %lu)\n"",
		  (unsigned long) cp->tilegrdoffx, (unsigned long)
		  cp->tilegrdoffy);
		goto error;
	}

	cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
	  cp->tilewidth);
	cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
	  cp->tileheight);
	cp->numtiles = cp->numhtiles * cp->numvtiles;

	if (ilyrrates && numilyrrates > 0) {
		tcp->numlyrs = numilyrrates + 1;
		if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),
		  sizeof(jpc_fix_t)))) {
			goto error;
		}
		for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
			tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
		}
	}

	/* Ensure that the integer mode is used in the case of lossless
	  coding. */
	if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
		jas_eprintf(""cannot use real mode for lossless coding\n"");
		goto error;
	}

	/* Ensure that the precinct width is valid. */
	if (prcwidthexpn > 15) {
		jas_eprintf(""invalid precinct width\n"");
		goto error;
	}

	/* Ensure that the precinct height is valid. */
	if (prcheightexpn > 15) {
		jas_eprintf(""invalid precinct height\n"");
		goto error;
	}

	/* Ensure that the code block width is valid. */
	if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
		jas_eprintf(""invalid code block width %d\n"",
		  JPC_POW2(cp->tccp.cblkwidthexpn));
		goto error;
	}

	/* Ensure that the code block height is valid. */
	if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
		jas_eprintf(""invalid code block height %d\n"",
		  JPC_POW2(cp->tccp.cblkheightexpn));
		goto error;
	}

	/* Ensure that the code block size is not too large. */
	if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
		jas_eprintf(""code block size too large\n"");
		goto error;
	}

	/* Ensure that the number of layers is valid. */
	if (cp->tcp.numlyrs > 16384) {
		jas_eprintf(""too many layers\n"");
		goto error;
	}

	/* There must be at least one resolution level. */
	if (cp->tccp.maxrlvls < 1) {
		jas_eprintf(""must be at least one resolution level\n"");
		goto error;
	}

	/* Ensure that the number of guard bits is valid. */
	if (cp->tccp.numgbits > 8) {
		jas_eprintf(""invalid number of guard bits\n"");
		goto error;
	}

	/* Ensure that the rate is within the legal range. */
	if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
		jas_eprintf(""warning: specified rate is unreasonably large (%lu > %lu)\n"", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
	}

	/* Ensure that the intermediate layer rates are valid. */
	if (tcp->numlyrs > 1) {
		/* The intermediate layers rates must increase monotonically. */
		for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
			if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
				jas_eprintf(""intermediate layer rates must increase monotonically\n"");
				goto error;
			}
		}
		/* The intermediate layer rates must be less than the overall rate. */
		if (cp->totalsize != UINT_FAST32_MAX) {
			for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
				if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
				  / cp->rawsize) {
					jas_eprintf(""warning: intermediate layer rates must be less than overall rate\n"");
					goto error;
				}
			}
		}
	}

	if (ilyrrates) {
		jas_free(ilyrrates);
	}

	return cp;

error:

	if (ilyrrates) {
		jas_free(ilyrrates);
	}
	if (tvp) {
		jas_tvparser_destroy(tvp);
	}
	if (cp) {
		jpc_enc_cp_destroy(cp);
	}
	return 0;
}",CWE-20,3
0,"void QuotaManager::NotifyStorageAccessed(
    QuotaClient::ID client_id,
    const GURL& origin, StorageType type) {
  NotifyStorageAccessedInternal(client_id, origin, type, base::Time::Now());
}
",none,24
1,"win_redr_status(win_T *wp, int ignore_pum UNUSED)
{
    int		row;
    char_u	*p;
    int		len;
    int		fillchar;
    int		attr;
    int		this_ru_col;
    static int  busy = FALSE;

    // It's possible to get here recursively when 'statusline' (indirectly)
    // invokes "":redrawstatus"".  Simply ignore the call then.
    if (busy)
	return;
    busy = TRUE;

    row = statusline_row(wp);

    wp->w_redr_status = FALSE;
    if (wp->w_status_height == 0)
    {
	// no status line, can only be last window
	redraw_cmdline = TRUE;
    }
    else if (!redrawing()
	    // don't update status line when popup menu is visible and may be
	    // drawn over it, unless it will be redrawn later
	    || (!ignore_pum && pum_visible()))
    {
	// Don't redraw right now, do it later.
	wp->w_redr_status = TRUE;
    }
#ifdef FEAT_STL_OPT
    else if (*p_stl != NUL || *wp->w_p_stl != NUL)
    {
	// redraw custom status line
	redraw_custom_statusline(wp);
    }
#endif
    else
    {
	fillchar = fillchar_status(&attr, wp);

	get_trans_bufname(wp->w_buffer);
	p = NameBuff;
	len = (int)STRLEN(p);

	if (bt_help(wp->w_buffer)
#ifdef FEAT_QUICKFIX
		|| wp->w_p_pvw
#endif
		|| bufIsChanged(wp->w_buffer)
		|| wp->w_buffer->b_p_ro)
	    *(p + len++) = ' ';
	if (bt_help(wp->w_buffer))
	{
	    vim_snprintf((char *)p + len, MAXPATHL - len, ""%s"", _(""[Help]""));
	    len += (int)STRLEN(p + len);
	}
#ifdef FEAT_QUICKFIX
	if (wp->w_p_pvw)
	{
	    vim_snprintf((char *)p + len, MAXPATHL - len, ""%s"", _(""[Preview]""));
	    len += (int)STRLEN(p + len);
	}
#endif
	if (bufIsChanged(wp->w_buffer)
#ifdef FEAT_TERMINAL
		&& !bt_terminal(wp->w_buffer)
#endif
		)
	{
	    vim_snprintf((char *)p + len, MAXPATHL - len, ""%s"", ""[+]"");
	    len += (int)STRLEN(p + len);
	}
	if (wp->w_buffer->b_p_ro)
	{
	    vim_snprintf((char *)p + len, MAXPATHL - len, ""%s"", _(""[RO]""));
	    len += (int)STRLEN(p + len);
	}

	this_ru_col = ru_col - (Columns - wp->w_width);
	if (this_ru_col < (wp->w_width + 1) / 2)
	    this_ru_col = (wp->w_width + 1) / 2;
	if (this_ru_col <= 1)
	{
	    p = (char_u *)""<"";		// No room for file name!
	    len = 1;
	}
	else if (has_mbyte)
	{
	    int	clen = 0, i;

	    // Count total number of display cells.
	    clen = mb_string2cells(p, -1);

	    // Find first character that will fit.
	    // Going from start to end is much faster for DBCS.
	    for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;
		    i += (*mb_ptr2len)(p + i))
		clen -= (*mb_ptr2cells)(p + i);
	    len = clen;
	    if (i > 0)
	    {
		p = p + i - 1;
		*p = '<';
		++len;
	    }

	}
	else if (len > this_ru_col - 1)
	{
	    p += len - (this_ru_col - 1);
	    *p = '<';
	    len = this_ru_col - 1;
	}

	screen_puts(p, row, wp->w_wincol, attr);
	screen_fill(row, row + 1, len + wp->w_wincol,
			this_ru_col + wp->w_wincol, fillchar, fillchar, attr);

	if (get_keymap_str(wp, (char_u *)""<%s>"", NameBuff, MAXPATHL)
		&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))
	    screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)
						   - 1 + wp->w_wincol), attr);

#ifdef FEAT_CMDL_INFO
	win_redr_ruler(wp, TRUE, ignore_pum);
#endif
    }

    /*
     * May need to draw the character below the vertical separator.
     */
    if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())
    {
	if (stl_connected(wp))
	    fillchar = fillchar_status(&attr, wp);
	else
	    fillchar = fillchar_vsep(&attr);
	screen_putchar(fillchar, row, W_ENDCOL(wp), attr);
    }
    busy = FALSE;
}",CWE-200,4
0,"  virtual bool ethernet_available() const { return true; }
",none,24
1,"void qemu_ram_free(struct uc_struct *uc, RAMBlock *block)
{
    if (!block) {
        return;
    }

    //if (block->host) {
    //    ram_block_notify_remove(block->host, block->max_length);
    //}

    QLIST_REMOVE(block, next);
    uc->ram_list.mru_block = NULL;
    /* Write list before version */
    //smp_wmb();
    // call_rcu(block, reclaim_ramblock, rcu);
    reclaim_ramblock(uc, block);
}",CWE-476,12
0,"static std::string WrapWithTH(std::string text) {
  return """" + text + """";
}
",none,24
1,"fname_match(
    regmatch_T	*rmp,
    char_u	*name,
    int		ignore_case)  // when TRUE ignore case, when FALSE use 'fic'
{
    char_u	*match = NULL;
    char_u	*p;

    if (name != NULL)
    {
	// Ignore case when 'fileignorecase' or the argument is set.
	rmp->rm_ic = p_fic || ignore_case;
	if (vim_regexec(rmp, name, (colnr_T)0))
	    match = name;
	else
	{
	    // Replace $(HOME) with '~' and try matching again.
	    p = home_replace_save(NULL, name);
	    if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))
		match = name;
	    vim_free(p);
	}
    }

    return match;
}",CWE-476,12
0,"  int64 global_usage() const { return global_usage_; }
",none,24
1,"static void compile_xclass_matchingpath(compiler_common *common, PCRE2_SPTR cc, jump_list **backtracks)
{
DEFINE_COMPILER;
jump_list *found = NULL;
jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks;
sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX;
struct sljit_jump *jump = NULL;
PCRE2_SPTR ccbegin;
int compares, invertcmp, numberofcmps;
#if defined SUPPORT_UNICODE && (PCRE2_CODE_UNIT_WIDTH == 8 || PCRE2_CODE_UNIT_WIDTH == 16)
BOOL utf = common->utf;
#endif /* SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH == [8|16] */

#ifdef SUPPORT_UNICODE
sljit_u32 unicode_status = 0;
int typereg = TMP1;
const sljit_u32 *other_cases;
sljit_uw typeoffset;
#endif /* SUPPORT_UNICODE */

/* Scanning the necessary info. */
cc++;
ccbegin = cc;
compares = 0;

if (cc[-1] & XCL_MAP)
  {
  min = 0;
  cc += 32 / sizeof(PCRE2_UCHAR);
  }

while (*cc != XCL_END)
  {
  compares++;
  if (*cc == XCL_SINGLE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    if (c > max) max = c;
    if (c < min) min = c;
#ifdef SUPPORT_UNICODE
    unicode_status |= XCLASS_SAVE_CHAR;
#endif /* SUPPORT_UNICODE */
    }
  else if (*cc == XCL_RANGE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    if (c < min) min = c;
    GETCHARINCTEST(c, cc);
    if (c > max) max = c;
#ifdef SUPPORT_UNICODE
    unicode_status |= XCLASS_SAVE_CHAR;
#endif /* SUPPORT_UNICODE */
    }
#ifdef SUPPORT_UNICODE
  else
    {
    SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
    cc++;
    if (*cc == PT_CLIST)
      {
      other_cases = PRIV(ucd_caseless_sets) + cc[1];
      while (*other_cases != NOTACHAR)
        {
        if (*other_cases > max) max = *other_cases;
        if (*other_cases < min) min = *other_cases;
        other_cases++;
        }
      }
    else
      {
      max = READ_CHAR_MAX;
      min = 0;
      }

    switch(*cc)
      {
      case PT_ANY:
      /* Any either accepts everything or ignored. */
      if (cc[-1] == XCL_PROP)
        {
        compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE);
        if (list == backtracks)
          add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));
        return;
        }
      break;

      case PT_LAMP:
      case PT_GC:
      case PT_PC:
      case PT_ALNUM:
      unicode_status |= XCLASS_HAS_TYPE;
      break;

      case PT_SCX:
      unicode_status |= XCLASS_HAS_SCRIPT_EXTENSION;
      if (cc[-1] == XCL_NOTPROP)
        {
        unicode_status |= XCLASS_SCRIPT_EXTENSION_NOTPROP;
        break;
        }
      compares++;
      /* Fall through */ 

      case PT_SC:
      unicode_status |= XCLASS_HAS_SCRIPT;
      break;

      case PT_SPACE:
      case PT_PXSPACE:
      case PT_WORD:
      case PT_PXGRAPH:
      case PT_PXPRINT:
      case PT_PXPUNCT:
      unicode_status |= XCLASS_SAVE_CHAR | XCLASS_HAS_TYPE;
      break;

      case PT_CLIST:
      case PT_UCNC:
      unicode_status |= XCLASS_SAVE_CHAR;
      break;

      case PT_BOOL:
      unicode_status |= XCLASS_HAS_BOOL;
      break;

      case PT_BIDICL:
      unicode_status |= XCLASS_HAS_BIDICL;
      break;

      default:
      SLJIT_UNREACHABLE();
      break;
      }
    cc += 2;
    }
#endif /* SUPPORT_UNICODE */
  }
SLJIT_ASSERT(compares > 0);

/* We are not necessary in utf mode even in 8 bit mode. */
cc = ccbegin;
if ((cc[-1] & XCL_NOT) != 0)
  read_char(common, min, max, backtracks, READ_CHAR_UPDATE_STR_PTR);
else
  {
#ifdef SUPPORT_UNICODE
  read_char(common, min, max, (unicode_status & XCLASS_NEEDS_UCD) ? backtracks : NULL, 0);
#else /* !SUPPORT_UNICODE */
  read_char(common, min, max, NULL, 0);
#endif /* SUPPORT_UNICODE */
  }

if ((cc[-1] & XCL_HASPROP) == 0)
  {
  if ((cc[-1] & XCL_MAP) != 0)
    {
    jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);
    if (!optimize_class(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found))
      {
      OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);
      OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);
      OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);
      OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);
      OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);
      add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO));
      }

    add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));
    JUMPHERE(jump);

    cc += 32 / sizeof(PCRE2_UCHAR);
    }
  else
    {
    OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min);
    add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min));
    }
  }
else if ((cc[-1] & XCL_MAP) != 0)
  {
  OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);
#ifdef SUPPORT_UNICODE
  unicode_status |= XCLASS_CHAR_SAVED;
#endif /* SUPPORT_UNICODE */
  if (!optimize_class(common, (const sljit_u8 *)cc, FALSE, TRUE, list))
    {
#if PCRE2_CODE_UNIT_WIDTH == 8
    jump = NULL;
    if (common->utf)
#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */
      jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);

    OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);
    OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);
    OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);
    OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);
    OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);
    add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO));

#if PCRE2_CODE_UNIT_WIDTH == 8
    if (common->utf)
#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */
      JUMPHERE(jump);
    }

  OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);
  cc += 32 / sizeof(PCRE2_UCHAR);
  }

#ifdef SUPPORT_UNICODE
if (unicode_status & XCLASS_NEEDS_UCD)
  {
  if ((unicode_status & (XCLASS_SAVE_CHAR | XCLASS_CHAR_SAVED)) == XCLASS_SAVE_CHAR)
    OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);

#if PCRE2_CODE_UNIT_WIDTH == 32
  if (!common->utf)
    {
    jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, MAX_UTF_CODE_POINT + 1);
    OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, UNASSIGNED_UTF_CHAR);
    JUMPHERE(jump);
    }
#endif /* PCRE2_CODE_UNIT_WIDTH == 32 */

  OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 1);
  OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1));
  OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);
  OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0);
  OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2));
  OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1);
  OP2(SLJIT_SHL, TMP1, 0, TMP2, 0, SLJIT_IMM, 3);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 2);
  OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0);

  ccbegin = cc;

  if (unicode_status & XCLASS_HAS_BIDICL)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));
    OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BIDICLASS_SHIFT);

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_BIDICL)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;
          jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]);
          add_jump(compiler, compares > 0 ? list : backtracks, jump);
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_BOOL)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, bprops));
    OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BPROPS_MASK);
    OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_BOOL)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;

          OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_boolprop_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));
          add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_SCRIPT)
    {
    OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        switch (*cc)
          {
          case PT_SCX:
          if (cc[-1] == XCL_NOTPROP)
            break;
          /* Fall through */ 

          case PT_SC:
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;

          add_jump(compiler, compares > 0 ? list : backtracks, CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]));
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_SCRIPT_EXTENSION)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));
    OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_SCRIPTX_MASK);
    OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);

    if (unicode_status & XCLASS_SCRIPT_EXTENSION_NOTPROP)
      {
      if (unicode_status & XCLASS_HAS_TYPE)
        {
        if (unicode_status & XCLASS_SAVE_CHAR)
          {
          OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP2, 0);
          unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0;
          }
        else
          {
          OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0);
          unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR;
          }
        }
      OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));
      }

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_SCX)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);

          jump = NULL;
          if (cc[-1] == XCL_NOTPROP)
            {
            jump = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, (int)cc[1]);
            if (invertcmp)
              {
              add_jump(compiler, backtracks, jump);
              jump = NULL;
              }
            invertcmp ^= 0x1;
            }

          OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_script_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));
          add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));

          if (jump != NULL)
            JUMPHERE(jump);
          }
        cc += 2;
        }
      }

    if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0)
      OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0);
    else if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR)
      OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0);
    cc = ccbegin;
    }

  if (unicode_status & XCLASS_SAVE_CHAR)
    OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);

  if (unicode_status & XCLASS_HAS_TYPE)
    {
    if (unicode_status & XCLASS_SAVE_CHAR)
      typereg = RETURN_ADDR;

    OP1(SLJIT_MOV_U8, typereg, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype));
    }
  }
#endif /* SUPPORT_UNICODE */

/* Generating code. */
charoffset = 0;
numberofcmps = 0;
#ifdef SUPPORT_UNICODE
typeoffset = 0;
#endif /* SUPPORT_UNICODE */

while (*cc != XCL_END)
  {
  compares--;
  invertcmp = (compares == 0 && list != backtracks);
  jump = NULL;

  if (*cc == XCL_SINGLE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);

    if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))
      {
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      numberofcmps++;
      }
    else if (numberofcmps > 0)
      {
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      numberofcmps = 0;
      }
    else
      {
      jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      numberofcmps = 0;
      }
    }
  else if (*cc == XCL_RANGE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    SET_CHAR_OFFSET(c);
    GETCHARINCTEST(c, cc);

    if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))
      {
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      numberofcmps++;
      }
    else if (numberofcmps > 0)
      {
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      numberofcmps = 0;
      }
    else
      {
      jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      numberofcmps = 0;
      }
    }
#ifdef SUPPORT_UNICODE
  else
    {
    SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
    if (*cc == XCL_NOTPROP)
      invertcmp ^= 0x1;
    cc++;
    switch(*cc)
      {
      case PT_ANY:
      if (!invertcmp)
        jump = JUMP(SLJIT_JUMP);
      break;

      case PT_LAMP:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_GC:
      c = PRIV(ucp_typerange)[(int)cc[1] * 2];
      SET_TYPE_OFFSET(c);
      jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c);
      break;

      case PT_PC:
      jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset);
      break;

      case PT_SC:
      case PT_SCX:
      case PT_BOOL:
      case PT_BIDICL:
      compares++;
      /* Do nothing. */
      break;

      case PT_SPACE:
      case PT_PXSPACE:
      SET_CHAR_OFFSET(9);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0xd - 0x9);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x85 - 0x9);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x9);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      SET_TYPE_OFFSET(ucp_Zl);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_WORD:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset));
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      /* Fall through. */

      case PT_ALNUM:
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll);
      OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      SET_TYPE_OFFSET(ucp_Nd);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_CLIST:
      other_cases = PRIV(ucd_caseless_sets) + cc[1];

      /* At least three characters are required.
         Otherwise this case would be handled by the normal code path. */
      SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR);
      SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]);

      /* Optimizing character pairs, if their difference is power of 2. */
      if (is_powerof2(other_cases[1] ^ other_cases[0]))
        {
        if (charoffset == 0)
          OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
        else
          {
          OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);
          OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
          }
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[1]);
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
        other_cases += 2;
        }
      else if (is_powerof2(other_cases[2] ^ other_cases[1]))
        {
        if (charoffset == 0)
          OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]);
        else
          {
          OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);
          OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
          }
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[2]);
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);

        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset));
        OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);

        other_cases += 3;
        }
      else
        {
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
        }

      while (*other_cases != NOTACHAR)
        {
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));
        OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);
        }
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_UCNC:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset));
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      SET_CHAR_OFFSET(0xa0);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      SET_CHAR_OFFSET(0);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_PXGRAPH:
      /* C and Z groups are the farthest two groups. */
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);

      jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);

      /* In case of ucp_Cf, we overwrite the result. */
      SET_CHAR_OFFSET(0x2066);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      JUMPHERE(jump);
      jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);
      break;

      case PT_PXPRINT:
      /* C and Z groups are the farthest two groups. */
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll);
      OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL);

      jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);

      /* In case of ucp_Cf, we overwrite the result. */
      SET_CHAR_OFFSET(0x2066);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      JUMPHERE(jump);
      jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);
      break;

      case PT_PXPUNCT:
      SET_TYPE_OFFSET(ucp_Sc);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      SET_CHAR_OFFSET(0);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x7f);
      OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL);

      SET_TYPE_OFFSET(ucp_Pc);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      default:
      SLJIT_UNREACHABLE();
      break;
      }
    cc += 2;
    }
#endif /* SUPPORT_UNICODE */

  if (jump != NULL)
    add_jump(compiler, compares > 0 ? list : backtracks, jump);
  }

if (found != NULL)
  set_jumps(found, LABEL());
}",CWE-125,1
1,"lzw_result lzw_decode(struct lzw_ctx *ctx,
		const uint8_t ** const stack_pos_out)
{
	lzw_result res;
	uint32_t code_new;
	uint32_t code_out;
	uint8_t last_value;
	uint8_t *stack_pos = ctx->stack_base;
	uint32_t clear_code = ctx->clear_code;
	uint32_t current_entry = ctx->current_entry;
	struct lzw_dictionary_entry * const table = ctx->table;

	/* Get a new code from the input */
	res = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new);
	if (res != LZW_OK) {
		return res;
	}

	/* Handle the new code */
	if (code_new == clear_code) {
		/* Got Clear code */
		return lzw__clear_codes(ctx, stack_pos_out);

	} else if (code_new == ctx->eoi_code) {
		/* Got End of Information code */
		return LZW_EOI_CODE;

	} else if (code_new > current_entry) {
		/* Code is invalid */
		return LZW_BAD_CODE;

	} else if (code_new < current_entry) {
		/* Code is in table */
		code_out = code_new;
		last_value = table[code_new].first_value;
	} else {
		/* Code not in table */
		*stack_pos++ = ctx->previous_code_first;
		code_out = ctx->previous_code;
		last_value = ctx->previous_code_first;
	}

	/* Add to the dictionary, only if there's space */
	if (current_entry < (1 << LZW_CODE_MAX)) {
		struct lzw_dictionary_entry *entry = table + current_entry;
		entry->last_value     = last_value;
		entry->first_value    = ctx->previous_code_first;
		entry->previous_entry = ctx->previous_code;
		ctx->current_entry++;
	}

	/* Ensure code size is increased, if needed. */
	if (current_entry == ctx->current_code_size_max) {
		if (ctx->current_code_size < LZW_CODE_MAX) {
			ctx->current_code_size++;
			ctx->current_code_size_max =
					(1 << ctx->current_code_size) - 1;
		}
	}

	/* Store details of this code as ""previous code"" to the context. */
	ctx->previous_code_first = table[code_new].first_value;
	ctx->previous_code = code_new;

	/* Put rest of data for this code on output stack.
	 * Note, in the case of ""code not in table"", the last entry of the
	 * current code has already been placed on the stack above. */
	while (code_out > clear_code) {
		struct lzw_dictionary_entry *entry = table + code_out;
		*stack_pos++ = entry->last_value;
		code_out = entry->previous_entry;
	}
	*stack_pos++ = table[code_out].last_value;

	*stack_pos_out = stack_pos;
	return LZW_OK;
}",CWE-125,1
1,"static void compile_xclass_matchingpath(compiler_common *common, PCRE2_SPTR cc, jump_list **backtracks)
{
DEFINE_COMPILER;
jump_list *found = NULL;
jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks;
sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX;
struct sljit_jump *jump = NULL;
PCRE2_SPTR ccbegin;
int compares, invertcmp, numberofcmps;
#if defined SUPPORT_UNICODE && (PCRE2_CODE_UNIT_WIDTH == 8 || PCRE2_CODE_UNIT_WIDTH == 16)
BOOL utf = common->utf;
#endif /* SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH == [8|16] */

#ifdef SUPPORT_UNICODE
sljit_u32 unicode_status = 0;
int typereg = TMP1;
const sljit_u32 *other_cases;
sljit_uw typeoffset;
#endif /* SUPPORT_UNICODE */

/* Scanning the necessary info. */
cc++;
ccbegin = cc;
compares = 0;

if (cc[-1] & XCL_MAP)
  {
  min = 0;
  cc += 32 / sizeof(PCRE2_UCHAR);
  }

while (*cc != XCL_END)
  {
  compares++;
  if (*cc == XCL_SINGLE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    if (c > max) max = c;
    if (c < min) min = c;
#ifdef SUPPORT_UNICODE
    unicode_status |= XCLASS_SAVE_CHAR;
#endif /* SUPPORT_UNICODE */
    }
  else if (*cc == XCL_RANGE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    if (c < min) min = c;
    GETCHARINCTEST(c, cc);
    if (c > max) max = c;
#ifdef SUPPORT_UNICODE
    unicode_status |= XCLASS_SAVE_CHAR;
#endif /* SUPPORT_UNICODE */
    }
#ifdef SUPPORT_UNICODE
  else
    {
    SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
    cc++;
    if (*cc == PT_CLIST && *cc == XCL_PROP)
      {
      other_cases = PRIV(ucd_caseless_sets) + cc[1];
      while (*other_cases != NOTACHAR)
        {
        if (*other_cases > max) max = *other_cases;
        if (*other_cases < min) min = *other_cases;
        other_cases++;
        }
      }
    else
      {
      max = READ_CHAR_MAX;
      min = 0;
      }

    switch(*cc)
      {
      case PT_ANY:
      /* Any either accepts everything or ignored. */
      if (cc[-1] == XCL_PROP)
        {
        compile_char1_matchingpath(common, OP_ALLANY, cc, backtracks, FALSE);
        if (list == backtracks)
          add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));
        return;
        }
      break;

      case PT_LAMP:
      case PT_GC:
      case PT_PC:
      case PT_ALNUM:
      unicode_status |= XCLASS_HAS_TYPE;
      break;

      case PT_SCX:
      unicode_status |= XCLASS_HAS_SCRIPT_EXTENSION;
      if (cc[-1] == XCL_NOTPROP)
        {
        unicode_status |= XCLASS_SCRIPT_EXTENSION_NOTPROP;
        break;
        }
      compares++;
      /* Fall through */ 

      case PT_SC:
      unicode_status |= XCLASS_HAS_SCRIPT;
      break;

      case PT_SPACE:
      case PT_PXSPACE:
      case PT_WORD:
      case PT_PXGRAPH:
      case PT_PXPRINT:
      case PT_PXPUNCT:
      unicode_status |= XCLASS_SAVE_CHAR | XCLASS_HAS_TYPE;
      break;

      case PT_CLIST:
      case PT_UCNC:
      unicode_status |= XCLASS_SAVE_CHAR;
      break;

      case PT_BOOL:
      unicode_status |= XCLASS_HAS_BOOL;
      break;

      case PT_BIDICL:
      unicode_status |= XCLASS_HAS_BIDICL;
      break;

      default:
      SLJIT_UNREACHABLE();
      break;
      }
    cc += 2;
    }
#endif /* SUPPORT_UNICODE */
  }
SLJIT_ASSERT(compares > 0);

/* We are not necessary in utf mode even in 8 bit mode. */
cc = ccbegin;
if ((cc[-1] & XCL_NOT) != 0)
  read_char(common, min, max, backtracks, READ_CHAR_UPDATE_STR_PTR);
else
  {
#ifdef SUPPORT_UNICODE
  read_char(common, min, max, (unicode_status & XCLASS_NEEDS_UCD) ? backtracks : NULL, 0);
#else /* !SUPPORT_UNICODE */
  read_char(common, min, max, NULL, 0);
#endif /* SUPPORT_UNICODE */
  }

if ((cc[-1] & XCL_HASPROP) == 0)
  {
  if ((cc[-1] & XCL_MAP) != 0)
    {
    jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);
    if (!optimize_class(common, (const sljit_u8 *)cc, (((const sljit_u8 *)cc)[31] & 0x80) != 0, TRUE, &found))
      {
      OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);
      OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);
      OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);
      OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);
      OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);
      add_jump(compiler, &found, JUMP(SLJIT_NOT_ZERO));
      }

    add_jump(compiler, backtracks, JUMP(SLJIT_JUMP));
    JUMPHERE(jump);

    cc += 32 / sizeof(PCRE2_UCHAR);
    }
  else
    {
    OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min);
    add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_GREATER, TMP2, 0, SLJIT_IMM, max - min));
    }
  }
else if ((cc[-1] & XCL_MAP) != 0)
  {
  OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);
#ifdef SUPPORT_UNICODE
  unicode_status |= XCLASS_CHAR_SAVED;
#endif /* SUPPORT_UNICODE */
  if (!optimize_class(common, (const sljit_u8 *)cc, FALSE, TRUE, list))
    {
#if PCRE2_CODE_UNIT_WIDTH == 8
    jump = NULL;
    if (common->utf)
#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */
      jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);

    OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);
    OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);
    OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc);
    OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0);
    OP2U(SLJIT_AND | SLJIT_SET_Z, TMP1, 0, TMP2, 0);
    add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO));

#if PCRE2_CODE_UNIT_WIDTH == 8
    if (common->utf)
#endif /* PCRE2_CODE_UNIT_WIDTH == 8 */
      JUMPHERE(jump);
    }

  OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);
  cc += 32 / sizeof(PCRE2_UCHAR);
  }

#ifdef SUPPORT_UNICODE
if (unicode_status & XCLASS_NEEDS_UCD)
  {
  if ((unicode_status & (XCLASS_SAVE_CHAR | XCLASS_CHAR_SAVED)) == XCLASS_SAVE_CHAR)
    OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0);

#if PCRE2_CODE_UNIT_WIDTH == 32
  if (!common->utf)
    {
    jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, MAX_UTF_CODE_POINT + 1);
    OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, UNASSIGNED_UTF_CHAR);
    JUMPHERE(jump);
    }
#endif /* PCRE2_CODE_UNIT_WIDTH == 32 */

  OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 1);
  OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1));
  OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT);
  OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0);
  OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2));
  OP1(SLJIT_MOV_U16, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1);
  OP2(SLJIT_SHL, TMP1, 0, TMP2, 0, SLJIT_IMM, 3);
  OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 2);
  OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP1, 0);

  ccbegin = cc;

  if (unicode_status & XCLASS_HAS_BIDICL)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));
    OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BIDICLASS_SHIFT);

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_BIDICL)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;
          jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]);
          add_jump(compiler, compares > 0 ? list : backtracks, jump);
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_BOOL)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, bprops));
    OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BPROPS_MASK);
    OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_BOOL)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;

          OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_boolprop_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));
          add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_SCRIPT)
    {
    OP1(SLJIT_MOV_U8, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        switch (*cc)
          {
          case PT_SCX:
          if (cc[-1] == XCL_NOTPROP)
            break;
          /* Fall through */ 

          case PT_SC:
          compares--;
          invertcmp = (compares == 0 && list != backtracks);
          if (cc[-1] == XCL_NOTPROP)
            invertcmp ^= 0x1;

          add_jump(compiler, compares > 0 ? list : backtracks, CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (int)cc[1]));
          }
        cc += 2;
        }
      }

    cc = ccbegin;
    }

  if (unicode_status & XCLASS_HAS_SCRIPT_EXTENSION)
    {
    OP1(SLJIT_MOV_U16, TMP1, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, scriptx_bidiclass));
    OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_SCRIPTX_MASK);
    OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 2);

    if (unicode_status & XCLASS_SCRIPT_EXTENSION_NOTPROP)
      {
      if (unicode_status & XCLASS_HAS_TYPE)
        {
        if (unicode_status & XCLASS_SAVE_CHAR)
          {
          OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP2, 0);
          unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0;
          }
        else
          {
          OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP2, 0);
          unicode_status |= XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR;
          }
        }
      OP1(SLJIT_MOV_U8, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script));
      }

    while (*cc != XCL_END)
      {
      if (*cc == XCL_SINGLE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        }
      else if (*cc == XCL_RANGE)
        {
        cc ++;
        GETCHARINCTEST(c, cc);
        GETCHARINCTEST(c, cc);
        }
      else
        {
        SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
        cc++;
        if (*cc == PT_SCX)
          {
          compares--;
          invertcmp = (compares == 0 && list != backtracks);

          jump = NULL;
          if (cc[-1] == XCL_NOTPROP)
            {
            jump = CMP(SLJIT_EQUAL, TMP2, 0, SLJIT_IMM, (int)cc[1]);
            if (invertcmp)
              {
              add_jump(compiler, backtracks, jump);
              jump = NULL;
              }
            invertcmp ^= 0x1;
            }

          OP2U(SLJIT_AND32 | SLJIT_SET_Z, SLJIT_MEM1(TMP1), (sljit_sw)(PRIV(ucd_script_sets) + (cc[1] >> 5)), SLJIT_IMM, (sljit_sw)1 << (cc[1] & 0x1f));
          add_jump(compiler, compares > 0 ? list : backtracks, JUMP(SLJIT_NOT_ZERO ^ invertcmp));

          if (jump != NULL)
            JUMPHERE(jump);
          }
        cc += 2;
        }
      }

    if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_LOCALS0)
      OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0);
    else if (unicode_status & XCLASS_SCRIPT_EXTENSION_RESTORE_RETURN_ADDR)
      OP1(SLJIT_MOV, TMP2, 0, RETURN_ADDR, 0);
    cc = ccbegin;
    }

  if (unicode_status & XCLASS_SAVE_CHAR)
    OP1(SLJIT_MOV, TMP1, 0, RETURN_ADDR, 0);

  if (unicode_status & XCLASS_HAS_TYPE)
    {
    if (unicode_status & XCLASS_SAVE_CHAR)
      typereg = RETURN_ADDR;

    OP1(SLJIT_MOV_U8, typereg, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype));
    }
  }
#endif /* SUPPORT_UNICODE */

/* Generating code. */
charoffset = 0;
numberofcmps = 0;
#ifdef SUPPORT_UNICODE
typeoffset = 0;
#endif /* SUPPORT_UNICODE */

while (*cc != XCL_END)
  {
  compares--;
  invertcmp = (compares == 0 && list != backtracks);
  jump = NULL;

  if (*cc == XCL_SINGLE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);

    if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))
      {
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      numberofcmps++;
      }
    else if (numberofcmps > 0)
      {
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      numberofcmps = 0;
      }
    else
      {
      jump = CMP(SLJIT_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      numberofcmps = 0;
      }
    }
  else if (*cc == XCL_RANGE)
    {
    cc ++;
    GETCHARINCTEST(c, cc);
    SET_CHAR_OFFSET(c);
    GETCHARINCTEST(c, cc);

    if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE))
      {
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      numberofcmps++;
      }
    else if (numberofcmps > 0)
      {
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      numberofcmps = 0;
      }
    else
      {
      jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset));
      numberofcmps = 0;
      }
    }
#ifdef SUPPORT_UNICODE
  else
    {
    SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP);
    if (*cc == XCL_NOTPROP)
      invertcmp ^= 0x1;
    cc++;
    switch(*cc)
      {
      case PT_ANY:
      if (!invertcmp)
        jump = JUMP(SLJIT_JUMP);
      break;

      case PT_LAMP:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_GC:
      c = PRIV(ucp_typerange)[(int)cc[1] * 2];
      SET_TYPE_OFFSET(c);
      jump = CMP(SLJIT_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c);
      break;

      case PT_PC:
      jump = CMP(SLJIT_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset);
      break;

      case PT_SC:
      case PT_SCX:
      case PT_BOOL:
      case PT_BIDICL:
      compares++;
      /* Do nothing. */
      break;

      case PT_SPACE:
      case PT_PXSPACE:
      SET_CHAR_OFFSET(9);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0xd - 0x9);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x85 - 0x9);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x9);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      SET_TYPE_OFFSET(ucp_Zl);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_WORD:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset));
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      /* Fall through. */

      case PT_ALNUM:
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll);
      OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      SET_TYPE_OFFSET(ucp_Nd);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_CLIST:
      other_cases = PRIV(ucd_caseless_sets) + cc[1];

      /* At least three characters are required.
         Otherwise this case would be handled by the normal code path. */
      SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR);
      SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]);

      /* Optimizing character pairs, if their difference is power of 2. */
      if (is_powerof2(other_cases[1] ^ other_cases[0]))
        {
        if (charoffset == 0)
          OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
        else
          {
          OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);
          OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
          }
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[1]);
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
        other_cases += 2;
        }
      else if (is_powerof2(other_cases[2] ^ other_cases[1]))
        {
        if (charoffset == 0)
          OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]);
        else
          {
          OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset);
          OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]);
          }
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP2, 0, SLJIT_IMM, other_cases[2]);
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);

        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset));
        OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);

        other_cases += 3;
        }
      else
        {
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));
        OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
        }

      while (*other_cases != NOTACHAR)
        {
        OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset));
        OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_Z : 0), TMP2, 0, SLJIT_EQUAL);
        }
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_UCNC:
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset));
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);
      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      SET_CHAR_OFFSET(0xa0);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset));
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_LESS_EQUAL);
      SET_CHAR_OFFSET(0);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_GREATER_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      case PT_PXGRAPH:
      /* C and Z groups are the farthest two groups. */
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);

      jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);

      /* In case of ucp_Cf, we overwrite the result. */
      SET_CHAR_OFFSET(0x2066);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      JUMPHERE(jump);
      jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);
      break;

      case PT_PXPRINT:
      /* C and Z groups are the farthest two groups. */
      SET_TYPE_OFFSET(ucp_Ll);
      OP2U(SLJIT_SUB | SLJIT_SET_GREATER, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_GREATER);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll);
      OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_NOT_EQUAL);

      jump = CMP(SLJIT_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll);

      /* In case of ucp_Cf, we overwrite the result. */
      SET_CHAR_OFFSET(0x2066);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066);
      OP_FLAGS(SLJIT_OR, TMP2, 0, SLJIT_EQUAL);

      JUMPHERE(jump);
      jump = CMP(SLJIT_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0);
      break;

      case PT_PXPUNCT:
      SET_TYPE_OFFSET(ucp_Sc);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc);
      OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_LESS_EQUAL);

      SET_CHAR_OFFSET(0);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, TMP1, 0, SLJIT_IMM, 0x7f);
      OP_FLAGS(SLJIT_AND, TMP2, 0, SLJIT_LESS_EQUAL);

      SET_TYPE_OFFSET(ucp_Pc);
      OP2U(SLJIT_SUB | SLJIT_SET_LESS_EQUAL, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc);
      OP_FLAGS(SLJIT_OR | SLJIT_SET_Z, TMP2, 0, SLJIT_LESS_EQUAL);
      jump = JUMP(SLJIT_NOT_ZERO ^ invertcmp);
      break;

      default:
      SLJIT_UNREACHABLE();
      break;
      }
    cc += 2;
    }
#endif /* SUPPORT_UNICODE */

  if (jump != NULL)
    add_jump(compiler, compares > 0 ? list : backtracks, jump);
  }

if (found != NULL)
  set_jumps(found, LABEL());
}",CWE-125,1
1,"static int ax25_release(struct socket *sock)
{
	struct sock *sk = sock->sk;
	ax25_cb *ax25;
	ax25_dev *ax25_dev;

	if (sk == NULL)
		return 0;

	sock_hold(sk);
	lock_sock(sk);
	sock_orphan(sk);
	ax25 = sk_to_ax25(sk);
	ax25_dev = ax25->ax25_dev;

	if (sk->sk_type == SOCK_SEQPACKET) {
		switch (ax25->state) {
		case AX25_STATE_0:
			release_sock(sk);
			ax25_disconnect(ax25, 0);
			lock_sock(sk);
			ax25_destroy_socket(ax25);
			break;

		case AX25_STATE_1:
		case AX25_STATE_2:
			ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
			release_sock(sk);
			ax25_disconnect(ax25, 0);
			lock_sock(sk);
			if (!sock_flag(ax25->sk, SOCK_DESTROY))
				ax25_destroy_socket(ax25);
			break;

		case AX25_STATE_3:
		case AX25_STATE_4:
			ax25_clear_queues(ax25);
			ax25->n2count = 0;

			switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
			case AX25_PROTO_STD_SIMPLEX:
			case AX25_PROTO_STD_DUPLEX:
				ax25_send_control(ax25,
						  AX25_DISC,
						  AX25_POLLON,
						  AX25_COMMAND);
				ax25_stop_t2timer(ax25);
				ax25_stop_t3timer(ax25);
				ax25_stop_idletimer(ax25);
				break;
#ifdef CONFIG_AX25_DAMA_SLAVE
			case AX25_PROTO_DAMA_SLAVE:
				ax25_stop_t3timer(ax25);
				ax25_stop_idletimer(ax25);
				break;
#endif
			}
			ax25_calculate_t1(ax25);
			ax25_start_t1timer(ax25);
			ax25->state = AX25_STATE_2;
			sk->sk_state                = TCP_CLOSE;
			sk->sk_shutdown            |= SEND_SHUTDOWN;
			sk->sk_state_change(sk);
			sock_set_flag(sk, SOCK_DESTROY);
			break;

		default:
			break;
		}
	} else {
		sk->sk_state     = TCP_CLOSE;
		sk->sk_shutdown |= SEND_SHUTDOWN;
		sk->sk_state_change(sk);
		ax25_destroy_socket(ax25);
	}
	if (ax25_dev) {
		dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);
		ax25_dev_put(ax25_dev);
	}

	sock->sk   = NULL;
	release_sock(sk);
	sock_put(sk);

	return 0;
}",CWE-476,12
1,"getcmdline_int(
    int		firstc,
    long	count UNUSED,	// only used for incremental search
    int		indent,		// indent for inside conditionals
    int		clear_ccline)	// clear ccline first
{
    static int	depth = 0;	    // call depth
    int		c;
    int		i;
    int		j;
    int		gotesc = FALSE;		// TRUE when  just typed
    int		do_abbr;		// when TRUE check for abbr.
    char_u	*lookfor = NULL;	// string to match
    int		hiscnt;			// current history line in use
    int		histype;		// history type to be used
#ifdef FEAT_SEARCH_EXTRA
    incsearch_state_T	is_state;
#endif
    int		did_wild_list = FALSE;	// did wild_list() recently
    int		wim_index = 0;		// index in wim_flags[]
    int		res;
    int		save_msg_scroll = msg_scroll;
    int		save_State = State;	// remember State when called
    int		some_key_typed = FALSE;	// one of the keys was typed
    // mouse drag and release events are ignored, unless they are
    // preceded with a mouse down event
    int		ignore_drag_release = TRUE;
#ifdef FEAT_EVAL
    int		break_ctrl_c = FALSE;
#endif
    expand_T	xpc;
    long	*b_im_ptr = NULL;
    cmdline_info_T save_ccline;
    int		did_save_ccline = FALSE;
    int		cmdline_type;
    int		wild_type;

    // one recursion level deeper
    ++depth;

    if (ccline.cmdbuff != NULL)
    {
	// Being called recursively.  Since ccline is global, we need to save
	// the current buffer and restore it when returning.
	save_cmdline(&save_ccline);
	did_save_ccline = TRUE;
    }
    if (clear_ccline)
	CLEAR_FIELD(ccline);

#ifdef FEAT_EVAL
    if (firstc == -1)
    {
	firstc = NUL;
	break_ctrl_c = TRUE;
    }
#endif
#ifdef FEAT_RIGHTLEFT
    // start without Hebrew mapping for a command line
    if (firstc == ':' || firstc == '=' || firstc == '>')
	cmd_hkmap = 0;
#endif

#ifdef FEAT_SEARCH_EXTRA
    init_incsearch_state(&is_state);
#endif

    if (init_ccline(firstc, indent) != OK)
	goto theend;	// out of memory

    if (depth == 50)
    {
	// Somehow got into a loop recursively calling getcmdline(), bail out.
	emsg(_(e_command_too_recursive));
	goto theend;
    }

    ExpandInit(&xpc);
    ccline.xpc = &xpc;

#ifdef FEAT_RIGHTLEFT
    if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
					  && (firstc == '/' || firstc == '?'))
	cmdmsg_rl = TRUE;
    else
	cmdmsg_rl = FALSE;
#endif

    redir_off = TRUE;		// don't redirect the typed command
    if (!cmd_silent)
    {
	i = msg_scrolled;
	msg_scrolled = 0;		// avoid wait_return() message
	gotocmdline(TRUE);
	msg_scrolled += i;
	redrawcmdprompt();		// draw prompt or indent
	set_cmdspos();
    }
    xpc.xp_context = EXPAND_NOTHING;
    xpc.xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
    xpc.xp_shell = FALSE;
#endif

#if defined(FEAT_EVAL)
    if (ccline.input_fn)
    {
	xpc.xp_context = ccline.xp_context;
	xpc.xp_pattern = ccline.cmdbuff;
	xpc.xp_arg = ccline.xp_arg;
    }
#endif

    /*
     * Avoid scrolling when called by a recursive do_cmdline(), e.g. when
     * doing "":@0"" when register 0 doesn't contain a CR.
     */
    msg_scroll = FALSE;

    State = MODE_CMDLINE;

    if (firstc == '/' || firstc == '?' || firstc == '@')
    {
	// Use "":lmap"" mappings for search pattern and input().
	if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
	    b_im_ptr = &curbuf->b_p_iminsert;
	else
	    b_im_ptr = &curbuf->b_p_imsearch;
	if (*b_im_ptr == B_IMODE_LMAP)
	    State |= MODE_LANGMAP;
#ifdef HAVE_INPUT_METHOD
	im_set_active(*b_im_ptr == B_IMODE_IM);
#endif
    }
#ifdef HAVE_INPUT_METHOD
    else if (p_imcmdline)
	im_set_active(TRUE);
#endif

    setmouse();
#ifdef CURSOR_SHAPE
    ui_cursor_shape();		// may show different cursor shape
#endif

    // When inside an autocommand for writing ""exiting"" may be set and
    // terminal mode set to cooked.  Need to set raw mode here then.
    settmode(TMODE_RAW);

    // Trigger CmdlineEnter autocommands.
    cmdline_type = firstc == NUL ? '-' : firstc;
    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);
#ifdef FEAT_EVAL
    if (!debug_mode)
	may_trigger_modechanged();
#endif

    init_history();
    hiscnt = get_hislen();	// set hiscnt to impossible history value
    histype = hist_char2type(firstc);

#ifdef FEAT_DIGRAPHS
    do_digraph(-1);		// init digraph typeahead
#endif

    // If something above caused an error, reset the flags, we do want to type
    // and execute commands. Display may be messed up a bit.
    if (did_emsg)
	redrawcmd();

#ifdef FEAT_STL_OPT
    // Redraw the statusline in case it uses the current mode using the mode()
    // function.
    if (!cmd_silent && msg_scrolled == 0)
    {
	int	found_one = FALSE;
	win_T	*wp;

	FOR_ALL_WINDOWS(wp)
	    if (*p_stl != NUL || *wp->w_p_stl != NUL)
	    {
		wp->w_redr_status = TRUE;
		found_one = TRUE;
	    }

	if (*p_tal != NUL)
	{
	    redraw_tabline = TRUE;
	    found_one = TRUE;
	}

	if (found_one)
	    redraw_statuslines();
    }
#endif

    did_emsg = FALSE;
    got_int = FALSE;

    /*
     * Collect the command string, handling editing keys.
     */
    for (;;)
    {
	int trigger_cmdlinechanged = TRUE;
	int end_wildmenu;

	redir_off = TRUE;	// Don't redirect the typed command.
				// Repeated, because a "":redir"" inside
				// completion may switch it on.
#ifdef USE_ON_FLY_SCROLL
	dont_scroll = FALSE;	// allow scrolling here
#endif
	quit_more = FALSE;	// reset after CTRL-D which had a more-prompt

	did_emsg = FALSE;	// There can't really be a reason why an error
				// that occurs while typing a command should
				// cause the command not to be executed.

	// Trigger SafeState if nothing is pending.
	may_trigger_safestate(xpc.xp_numfiles <= 0);

	// Get a character.  Ignore K_IGNORE and K_NOP, they should not do
	// anything, such as stop completion.
	do
	{
	    cursorcmd();		// set the cursor on the right spot
	    c = safe_vgetc();
	} while (c == K_IGNORE || c == K_NOP);

	if (c == K_COMMAND || c == K_SCRIPT_COMMAND)
	{
	    int	    clen = ccline.cmdlen;

	    if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)
	    {
		if (clen == ccline.cmdlen)
		    trigger_cmdlinechanged = FALSE;
		goto cmdline_changed;
	    }
	}

	if (KeyTyped)
	{
	    some_key_typed = TRUE;
#ifdef FEAT_RIGHTLEFT
	    if (cmd_hkmap)
		c = hkmap(c);
	    if (cmdmsg_rl && !KeyStuffed)
	    {
		// Invert horizontal movements and operations.  Only when
		// typed by the user directly, not when the result of a
		// mapping.
		switch (c)
		{
		    case K_RIGHT:   c = K_LEFT; break;
		    case K_S_RIGHT: c = K_S_LEFT; break;
		    case K_C_RIGHT: c = K_C_LEFT; break;
		    case K_LEFT:    c = K_RIGHT; break;
		    case K_S_LEFT:  c = K_S_RIGHT; break;
		    case K_C_LEFT:  c = K_C_RIGHT; break;
		}
	    }
#endif
	}

	/*
	 * Ignore got_int when CTRL-C was typed here.
	 * Don't ignore it in :global, we really need to break then, e.g., for
	 * "":g/pat/normal /pat"" (without the ).
	 * Don't ignore it for the input() function.
	 */
	if ((c == Ctrl_C
#ifdef UNIX
		|| c == intr_char
#endif
				)
#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
		&& firstc != '@'
#endif
#ifdef FEAT_EVAL
		// do clear got_int in Ex mode to avoid infinite Ctrl-C loop
		&& (!break_ctrl_c || exmode_active)
#endif
		&& !global_busy)
	    got_int = FALSE;

	// free old command line when finished moving around in the history
	// list
	if (lookfor != NULL
		&& c != K_S_DOWN && c != K_S_UP
		&& c != K_DOWN && c != K_UP
		&& c != K_PAGEDOWN && c != K_PAGEUP
		&& c != K_KPAGEDOWN && c != K_KPAGEUP
		&& c != K_LEFT && c != K_RIGHT
		&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
	    VIM_CLEAR(lookfor);

	/*
	 * When there are matching completions to select  works like
	 * CTRL-P (unless 'wc' is ).
	 */
	if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
	    c = Ctrl_P;

	if (p_wmnu)
	    c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);

	if (cmdline_pum_active())
	{
	    // Ctrl-Y: Accept the current selection and close the popup menu.
	    // Ctrl-E: cancel the cmdline popup menu and return the original
	    // text.
	    if (c == Ctrl_E || c == Ctrl_Y)
	    {
		wild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;
		if (nextwild(&xpc, wild_type, WILD_NO_BEEP,
							firstc != '@') == FAIL)
		    break;
		c = Ctrl_E;
	    }
	}

	// The wildmenu is cleared if the pressed key is not used for
	// navigating the wild menu (i.e. the key is not 'wildchar' or
	// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).
	// If the popup menu is displayed, then PageDown and PageUp keys are
	// also used to navigate the menu.
	end_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm
		&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);
	end_wildmenu = end_wildmenu && (!cmdline_pum_active() ||
			    (c != K_PAGEDOWN && c != K_PAGEUP
			     && c != K_KPAGEDOWN && c != K_KPAGEUP));

	// free expanded names when finished walking through matches
	if (end_wildmenu)
	{
	    if (cmdline_pum_active())
		cmdline_pum_remove();
	    if (xpc.xp_numfiles != -1)
		(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
	    did_wild_list = FALSE;
	    if (!p_wmnu || (c != K_UP && c != K_DOWN))
		xpc.xp_context = EXPAND_NOTHING;
	    wim_index = 0;
	    wildmenu_cleanup(&ccline);
	}

	if (p_wmnu)
	    c = wildmenu_process_key(&ccline, c, &xpc);

	// CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
	// mode when 'insertmode' is set, CTRL-\ e prompts for an expression.
	if (c == Ctrl_BSL)
	{
	    res = cmdline_handle_backslash_key(c, &gotesc);
	    if (res == CMDLINE_CHANGED)
		goto cmdline_changed;
	    else if (res == CMDLINE_NOT_CHANGED)
		goto cmdline_not_changed;
	    else if (res == GOTO_NORMAL_MODE)
		goto returncmd;		// back to cmd mode
	    c = Ctrl_BSL;		// backslash key not processed by
					// cmdline_handle_backslash_key()
	}

#ifdef FEAT_CMDWIN
	if (c == cedit_key || c == K_CMDWIN)
	{
	    // TODO: why is ex_normal_busy checked here?
	    if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)
	    {
		/*
		 * Open a window to edit the command line (and history).
		 */
		c = open_cmdwin();
		some_key_typed = TRUE;
	    }
	}
# ifdef FEAT_DIGRAPHS
	else
# endif
#endif
#ifdef FEAT_DIGRAPHS
	    c = do_digraph(c);
#endif

	if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
			&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
	{
	    // In Ex mode a backslash escapes a newline.
	    if (exmode_active
		    && c != ESC
		    && ccline.cmdpos == ccline.cmdlen
		    && ccline.cmdpos > 0
		    && ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
	    {
		if (c == K_KENTER)
		    c = '\n';
	    }
	    else
	    {
		gotesc = FALSE;	// Might have typed ESC previously, don't
				// truncate the cmdline now.
		if (ccheck_abbr(c + ABBR_OFF))
		    goto cmdline_changed;
		if (!cmd_silent)
		{
		    windgoto(msg_row, 0);
		    out_flush();
		}
		break;
	    }
	}

	// Completion for 'wildchar' or 'wildcharm' key.
	if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
	{
	    res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,
		    &wim_index, &xpc, &gotesc);
	    if (res == CMDLINE_CHANGED)
		goto cmdline_changed;
	}

	gotesc = FALSE;

	//  goes to last match, in a clumsy way
	if (c == K_S_TAB && KeyTyped)
	{
	    if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)
	    {
		if (xpc.xp_numfiles > 1
		    && ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))
			    || p_wmnu))
		{
		    // Trigger the popup menu when wildoptions=pum
		    showmatches(&xpc, p_wmnu
			    && ((wim_flags[wim_index] & WIM_LIST) == 0));
		}
		if (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK
			&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)
		    goto cmdline_changed;
	    }
	}

	if (c == NUL || c == K_ZERO)	    // NUL is stored as NL
	    c = NL;

	do_abbr = TRUE;		// default: check for abbreviation

	/*
	 * Big switch for a typed command line character.
	 */
	switch (c)
	{
	case K_BS:
	case Ctrl_H:
	case K_DEL:
	case K_KDEL:
	case Ctrl_W:
	    res = cmdline_erase_chars(c, indent
#ifdef FEAT_SEARCH_EXTRA
		    , &is_state
#endif
		    );
	    if (res == CMDLINE_NOT_CHANGED)
		goto cmdline_not_changed;
	    else if (res == GOTO_NORMAL_MODE)
		goto returncmd;		// back to cmd mode
	    goto cmdline_changed;

	case K_INS:
	case K_KINS:
		ccline.overstrike = !ccline.overstrike;
#ifdef CURSOR_SHAPE
		ui_cursor_shape();	// may show different cursor shape
#endif
		goto cmdline_not_changed;

	case Ctrl_HAT:
		cmdline_toggle_langmap(b_im_ptr);
		goto cmdline_not_changed;

//	case '@':   only in very old vi
	case Ctrl_U:
		// delete all characters left of the cursor
		j = ccline.cmdpos;
		ccline.cmdlen -= j;
		i = ccline.cmdpos = 0;
		while (i < ccline.cmdlen)
		    ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
		// Truncate at the end, required for multi-byte chars.
		ccline.cmdbuff[ccline.cmdlen] = NUL;
#ifdef FEAT_SEARCH_EXTRA
		if (ccline.cmdlen == 0)
		    is_state.search_start = is_state.save_cursor;
#endif
		redrawcmd();
		goto cmdline_changed;

#ifdef FEAT_CLIPBOARD
	case Ctrl_Y:
		// Copy the modeless selection, if there is one.
		if (clip_star.state != SELECT_CLEARED)
		{
		    if (clip_star.state == SELECT_DONE)
			clip_copy_modeless_selection(TRUE);
		    goto cmdline_not_changed;
		}
		break;
#endif

	case ESC:	// get here if p_wc != ESC or when ESC typed twice
	case Ctrl_C:
		// In exmode it doesn't make sense to return.  Except when
		// "":normal"" runs out of characters.
		if (exmode_active
			       && (ex_normal_busy == 0 || typebuf.tb_len > 0))
		    goto cmdline_not_changed;

		gotesc = TRUE;		// will free ccline.cmdbuff after
					// putting it in history
		goto returncmd;		// back to cmd mode

	case Ctrl_R:			// insert register
		res = cmdline_insert_reg(&gotesc);
		if (res == CMDLINE_NOT_CHANGED)
		    goto cmdline_not_changed;
		else if (res == GOTO_NORMAL_MODE)
		    goto returncmd;
		goto cmdline_changed;

	case Ctrl_D:
		if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
		    break;	// Use ^D as normal char instead

		redrawcmd();
		continue;	// don't do incremental search now

	case K_RIGHT:
	case K_S_RIGHT:
	case K_C_RIGHT:
		do
		{
		    if (ccline.cmdpos >= ccline.cmdlen)
			break;
		    i = cmdline_charsize(ccline.cmdpos);
		    if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
			break;
		    ccline.cmdspos += i;
		    if (has_mbyte)
			ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
							     + ccline.cmdpos);
		    else
			++ccline.cmdpos;
		}
		while ((c == K_S_RIGHT || c == K_C_RIGHT
			       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
			&& ccline.cmdbuff[ccline.cmdpos] != ' ');
		if (has_mbyte)
		    set_cmdspos_cursor();
		goto cmdline_not_changed;

	case K_LEFT:
	case K_S_LEFT:
	case K_C_LEFT:
		if (ccline.cmdpos == 0)
		    goto cmdline_not_changed;
		do
		{
		    --ccline.cmdpos;
		    if (has_mbyte)	// move to first byte of char
			ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
					      ccline.cmdbuff + ccline.cmdpos);
		    ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
		}
		while (ccline.cmdpos > 0
			&& (c == K_S_LEFT || c == K_C_LEFT
			       || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
			&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
		if (has_mbyte)
		    set_cmdspos_cursor();
		goto cmdline_not_changed;

	case K_IGNORE:
		// Ignore mouse event or open_cmdwin() result.
		goto cmdline_not_changed;

#ifdef FEAT_GUI_MSWIN
	    // On MS-Windows ignore , we get it when closing the window
	    // was cancelled.
	case K_F4:
	    if (mod_mask == MOD_MASK_ALT)
	    {
		redrawcmd();	    // somehow the cmdline is cleared
		goto cmdline_not_changed;
	    }
	    break;
#endif

	case K_MIDDLEDRAG:
	case K_MIDDLERELEASE:
		goto cmdline_not_changed;	// Ignore mouse

	case K_MIDDLEMOUSE:
# ifdef FEAT_GUI
		// When GUI is active, also paste when 'mouse' is empty
		if (!gui.in_use)
# endif
		    if (!mouse_has(MOUSE_COMMAND))
			goto cmdline_not_changed;   // Ignore mouse
# ifdef FEAT_CLIPBOARD
		if (clip_star.available)
		    cmdline_paste('*', TRUE, TRUE);
		else
# endif
		    cmdline_paste(0, TRUE, TRUE);
		redrawcmd();
		goto cmdline_changed;

# ifdef FEAT_DND
	case K_DROP:
		cmdline_paste('~', TRUE, FALSE);
		redrawcmd();
		goto cmdline_changed;
# endif

	case K_LEFTDRAG:
	case K_LEFTRELEASE:
	case K_RIGHTDRAG:
	case K_RIGHTRELEASE:
		// Ignore drag and release events when the button-down wasn't
		// seen before.
		if (ignore_drag_release)
		    goto cmdline_not_changed;
		// FALLTHROUGH
	case K_LEFTMOUSE:
	case K_RIGHTMOUSE:
		cmdline_left_right_mouse(c, &ignore_drag_release);
		goto cmdline_not_changed;

	// Mouse scroll wheel: ignored here
	case K_MOUSEDOWN:
	case K_MOUSEUP:
	case K_MOUSELEFT:
	case K_MOUSERIGHT:
	// Alternate buttons ignored here
	case K_X1MOUSE:
	case K_X1DRAG:
	case K_X1RELEASE:
	case K_X2MOUSE:
	case K_X2DRAG:
	case K_X2RELEASE:
	case K_MOUSEMOVE:
		goto cmdline_not_changed;

#ifdef FEAT_GUI
	case K_LEFTMOUSE_NM:	// mousefocus click, ignored
	case K_LEFTRELEASE_NM:
		goto cmdline_not_changed;

	case K_VER_SCROLLBAR:
		if (msg_scrolled == 0)
		{
		    gui_do_scroll();
		    redrawcmd();
		}
		goto cmdline_not_changed;

	case K_HOR_SCROLLBAR:
		if (msg_scrolled == 0)
		{
		    gui_do_horiz_scroll(scrollbar_value, FALSE);
		    redrawcmd();
		}
		goto cmdline_not_changed;
#endif
#ifdef FEAT_GUI_TABLINE
	case K_TABLINE:
	case K_TABMENU:
		// Don't want to change any tabs here.  Make sure the same tab
		// is still selected.
		if (gui_use_tabline())
		    gui_mch_set_curtab(tabpage_index(curtab));
		goto cmdline_not_changed;
#endif

	case K_SELECT:	    // end of Select mode mapping - ignore
		goto cmdline_not_changed;

	case Ctrl_B:	    // begin of command line
	case K_HOME:
	case K_KHOME:
	case K_S_HOME:
	case K_C_HOME:
		ccline.cmdpos = 0;
		set_cmdspos();
		goto cmdline_not_changed;

	case Ctrl_E:	    // end of command line
	case K_END:
	case K_KEND:
	case K_S_END:
	case K_C_END:
		ccline.cmdpos = ccline.cmdlen;
		set_cmdspos_cursor();
		goto cmdline_not_changed;

	case Ctrl_A:	    // all matches
		if (cmdline_pum_active())
		    // As Ctrl-A completes all the matches, close the popup
		    // menu (if present)
		    cmdline_pum_cleanup(&ccline);

		if (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)
		    break;
		xpc.xp_context = EXPAND_NOTHING;
		did_wild_list = FALSE;
		goto cmdline_changed;

	case Ctrl_L:
#ifdef FEAT_SEARCH_EXTRA
		if (may_add_char_to_search(firstc, &c, &is_state) == OK)
		    goto cmdline_not_changed;
#endif

		// completion: longest common part
		if (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)
		    break;
		goto cmdline_changed;

	case Ctrl_N:	    // next match
	case Ctrl_P:	    // previous match
		if (xpc.xp_numfiles > 0)
		{
		    wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;
		    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
			break;
		    goto cmdline_not_changed;
		}
		// FALLTHROUGH
	case K_UP:
	case K_DOWN:
	case K_S_UP:
	case K_S_DOWN:
	case K_PAGEUP:
	case K_KPAGEUP:
	case K_PAGEDOWN:
	case K_KPAGEDOWN:
		if (cmdline_pum_active()
			&& (c == K_PAGEUP || c == K_PAGEDOWN ||
			    c == K_KPAGEUP || c == K_KPAGEDOWN))
		{
		    // If the popup menu is displayed, then PageUp and PageDown
		    // are used to scroll the menu.
		    wild_type = WILD_PAGEUP;
		    if (c == K_PAGEDOWN || c == K_KPAGEDOWN)
			wild_type = WILD_PAGEDOWN;
		    if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
			break;
		    goto cmdline_not_changed;
		}
		else
		{
		    res = cmdline_browse_history(c, firstc, &lookfor, histype,
			    &hiscnt, &xpc);
		    if (res == CMDLINE_CHANGED)
			goto cmdline_changed;
		    else if (res == GOTO_NORMAL_MODE)
			goto returncmd;
		}
		goto cmdline_not_changed;

#ifdef FEAT_SEARCH_EXTRA
	case Ctrl_G:	    // next match
	case Ctrl_T:	    // previous match
		if (may_adjust_incsearch_highlighting(
					  firstc, count, &is_state, c) == FAIL)
		    goto cmdline_not_changed;
		break;
#endif

	case Ctrl_V:
	case Ctrl_Q:
		{
		    ignore_drag_release = TRUE;
		    putcmdline('^', TRUE);

		    // Get next (two) character(s).  Do not change any
		    // modifyOtherKeys ESC sequence to a normal key for
		    // CTRL-SHIFT-V.
		    c = get_literal(mod_mask & MOD_MASK_SHIFT);

		    do_abbr = FALSE;	    // don't do abbreviation now
		    extra_char = NUL;
		    // may need to remove ^ when composing char was typed
		    if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
		    {
			draw_cmdline(ccline.cmdpos,
						ccline.cmdlen - ccline.cmdpos);
			msg_putchar(' ');
			cursorcmd();
		    }
		}

		break;

#ifdef FEAT_DIGRAPHS
	case Ctrl_K:
		ignore_drag_release = TRUE;
		putcmdline('?', TRUE);
# ifdef USE_ON_FLY_SCROLL
		dont_scroll = TRUE;	    // disallow scrolling here
# endif
		c = get_digraph(TRUE);
		extra_char = NUL;
		if (c != NUL)
		    break;

		redrawcmd();
		goto cmdline_not_changed;
#endif // FEAT_DIGRAPHS

#ifdef FEAT_RIGHTLEFT
	case Ctrl__:	    // CTRL-_: switch language mode
		if (!p_ari)
		    break;
		cmd_hkmap = !cmd_hkmap;
		goto cmdline_not_changed;
#endif

	case K_PS:
		bracketed_paste(PASTE_CMDLINE, FALSE, NULL);
		goto cmdline_changed;

	default:
#ifdef UNIX
		if (c == intr_char)
		{
		    gotesc = TRUE;	// will free ccline.cmdbuff after
					// putting it in history
		    goto returncmd;	// back to Normal mode
		}
#endif
		/*
		 * Normal character with no special meaning.  Just set mod_mask
		 * to 0x0 so that typing Shift-Space in the GUI doesn't enter
		 * the string .  This should only happen after ^V.
		 */
		if (!IS_SPECIAL(c))
		    mod_mask = 0x0;
		break;
	}
	/*
	 * End of switch on command line character.
	 * We come here if we have a normal character.
	 */

	if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))
		&& (ccheck_abbr(
			// Add ABBR_OFF for characters above 0x100, this is
			// what check_abbr() expects.
				(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)
		    || c == Ctrl_RSB))
	    goto cmdline_changed;

	/*
	 * put the character in the command line
	 */
	if (IS_SPECIAL(c) || mod_mask != 0)
	    put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
	else
	{
	    if (has_mbyte)
	    {
		j = (*mb_char2bytes)(c, IObuff);
		IObuff[j] = NUL;	// exclude composing chars
		put_on_cmdline(IObuff, j, TRUE);
	    }
	    else
	    {
		IObuff[0] = c;
		put_on_cmdline(IObuff, 1, TRUE);
	    }
	}
	goto cmdline_changed;

/*
 * This part implements incremental searches for ""/"" and ""?""
 * Jump to cmdline_not_changed when a character has been read but the command
 * line did not change. Then we only search and redraw if something changed in
 * the past.
 * Jump to cmdline_changed when the command line did change.
 * (Sorry for the goto's, I know it is ugly).
 */
cmdline_not_changed:
#ifdef FEAT_SEARCH_EXTRA
	if (!is_state.incsearch_postponed)
	    continue;
#endif

cmdline_changed:
#ifdef FEAT_SEARCH_EXTRA
	// If the window changed incremental search state is not valid.
	if (is_state.winid != curwin->w_id)
	    init_incsearch_state(&is_state);
#endif
	if (trigger_cmdlinechanged)
	    // Trigger CmdlineChanged autocommands.
	    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);

#ifdef FEAT_SEARCH_EXTRA
	if (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))
	    may_do_incsearch_highlighting(firstc, count, &is_state);
#endif

#ifdef FEAT_RIGHTLEFT
	if (cmdmsg_rl
# ifdef FEAT_ARABIC
		|| (p_arshape && !p_tbidi
				       && cmdline_has_arabic(0, ccline.cmdlen))
# endif
		)
	    // Always redraw the whole command line to fix shaping and
	    // right-left typing.  Not efficient, but it works.
	    // Do it only when there are no characters left to read
	    // to avoid useless intermediate redraws.
	    if (vpeekc() == NUL)
		redrawcmd();
#endif
    }

returncmd:

#ifdef FEAT_RIGHTLEFT
    cmdmsg_rl = FALSE;
#endif

    ExpandCleanup(&xpc);
    ccline.xpc = NULL;

#ifdef FEAT_SEARCH_EXTRA
    finish_incsearch_highlighting(gotesc, &is_state, FALSE);
#endif

    if (ccline.cmdbuff != NULL)
    {
	/*
	 * Put line in history buffer ("":"" and ""="" only when it was typed).
	 */
	if (ccline.cmdlen && firstc != NUL
		&& (some_key_typed || histype == HIST_SEARCH))
	{
	    add_to_history(histype, ccline.cmdbuff, TRUE,
				       histype == HIST_SEARCH ? firstc : NUL);
	    if (firstc == ':')
	    {
		vim_free(new_last_cmdline);
		new_last_cmdline = vim_strsave(ccline.cmdbuff);
	    }
	}

	if (gotesc)
	    abandon_cmdline();
    }

    /*
     * If the screen was shifted up, redraw the whole screen (later).
     * If the line is too long, clear it, so ruler and shown command do
     * not get printed in the middle of it.
     */
    msg_check();
    msg_scroll = save_msg_scroll;
    redir_off = FALSE;

    // When the command line was typed, no need for a wait-return prompt.
    if (some_key_typed)
	need_wait_return = FALSE;

    // Trigger CmdlineLeave autocommands.
    trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);

    State = save_State;

#ifdef FEAT_EVAL
    if (!debug_mode)
	may_trigger_modechanged();
#endif

#ifdef HAVE_INPUT_METHOD
    if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
	im_save_status(b_im_ptr);
    im_set_active(FALSE);
#endif
    setmouse();
#ifdef CURSOR_SHAPE
    ui_cursor_shape();		// may show different cursor shape
#endif
    sb_text_end_cmdline();

theend:
    {
	char_u *p = ccline.cmdbuff;

	--depth;
	if (did_save_ccline)
	    restore_cmdline(&save_ccline);
	else
	    ccline.cmdbuff = NULL;
	return p;
    }
}",CWE-416,10
1,"static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) {
	D eprintf (""Dragons at 0x%x\n"", off);
	ut64 size = r_buf_size (buf);
	if (off >= size) {
		return NULL;
	}
	size -= off;
	if (!size) {
		return NULL;
	}
	ut8 *b = malloc (size);
	if (!b) {
		return NULL;
	}
	int available = r_buf_read_at (buf, off, b, size);
	if (available != size) {
		eprintf (""Warning: r_buf_read_at failed\n"");
		return NULL;
	}
#if 0
	// after the list of sections, there's a bunch of unknown
	// data, brobably dwords, and then the same section list again
	// this function aims to parse it.
	0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U..
                         n_segments ----.          .--- how many sections ?
	0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U..........
	             .---- how many symbols? 0xc7
	0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................
	0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U..
	0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F..
	0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............
	0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................
	0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT..
	0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................
	0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA..
	0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................
	0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM..
	0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................
	0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED
	0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i..
#endif
	// eprintf (""Dragon's magic:\n"");
	int magicCombo = 0;
	if (!memcmp (""\x1a\x2b\xb2\xa1"", b, 4)) { // 0x130  ?
		magicCombo++;
	}
	if (!memcmp (""\x1a\x2b\xb2\xa1"", b + 8, 4)) {
		magicCombo++;
	}
	if (magicCombo != 2) {
		// hack for C22F7494
		available = r_buf_read_at (buf, off - 8, b, size);
		if (available != size) {
			eprintf (""Warning: r_buf_read_at failed\n"");
			return NULL;
		}
		if (!memcmp (""\x1a\x2b\xb2\xa1"", b, 4)) { // 0x130  ?
			off -= 8;
		} else {
			eprintf (""0x%08x  parsing error: invalid magic retry\n"", off);
		}
	}
	D eprintf (""0x%08x  magic  OK\n"", off);
	D {
		const int e0ss = r_read_le32 (b + 12);
		eprintf (""0x%08x  eoss   0x%x\n"", off + 12, e0ss);
	}
	free (b);
	return r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name);
}",CWE-787,16
1,"  void DoCompute(OpKernelContext* c) {
    core::RefCountPtr v;
    OP_REQUIRES_OK(c, LookupResource(c, HandleFromInput(c, 0), &v));
    Tensor* params = v->tensor();
    const Tensor& indices = c->input(1);
    const Tensor& updates = c->input(2);

    // Check that rank(updates.shape) = rank(indices.shape + params.shape[1:])
    OP_REQUIRES(c,
                updates.dims() == 0 ||
                    updates.dims() == indices.dims() + params->dims() - 1,
                errors::InvalidArgument(
                    ""Must have updates.shape = indices.shape + ""
                    ""params.shape[1:] or updates.shape = [], got "",
                    ""updates.shape "", updates.shape().DebugString(),
                    "", indices.shape "", indices.shape().DebugString(),
                    "", params.shape "", params->shape().DebugString()));

    // Check that we have enough index space
    const int64_t N_big = indices.NumElements();
    OP_REQUIRES(
        c, N_big <= std::numeric_limits::max(),
        errors::InvalidArgument(""indices has too many elements for "",
                                DataTypeString(DataTypeToEnum::v()),
                                "" indexing: "", N_big, "" > "",
                                std::numeric_limits::max()));
    const Index N = static_cast(N_big);
    OP_REQUIRES(
        c, params->dim_size(0) <= std::numeric_limits::max(),
        errors::InvalidArgument(""params.shape[0] too large for "",
                                DataTypeString(DataTypeToEnum::v()),
                                "" indexing: "", params->dim_size(0), "" > "",
                                std::numeric_limits::max()));

    if (N > 0) {
      auto indices_flat = indices.flat();
      auto params_flat = params->flat_outer_dims();
      if (TensorShapeUtils::IsScalar(updates.shape())) {
        const auto update = updates.scalar();

        functor::ScatterScalarFunctor functor;
        const Index bad_i = functor(c, c->template eigen_device(),
                                    params_flat, update, indices_flat);
        OP_REQUIRES(c, bad_i < 0,
                    errors::InvalidArgument(
                        ""indices"", SliceDebugString(indices.shape(), bad_i),
                        "" = "", indices_flat(bad_i), "" is not in [0, "",
                        params->dim_size(0), "")""));
      } else {
        int64_t num_updates = updates.NumElements();
        OP_REQUIRES(c, num_updates % N == 0,
                    errors::InvalidArgument(
                        ""shape of indices ("", indices.shape().DebugString(),
                        "") is not compatible with the shape of updates ("",
                        updates.shape().DebugString(), "")""));
        auto updates_flat = updates.shaped({N, num_updates / N});

        functor::ScatterFunctor functor;
        const Index bad_i = functor(c, c->template eigen_device(),
                                    params_flat, updates_flat, indices_flat);
        OP_REQUIRES(c, bad_i < 0,
                    errors::InvalidArgument(
                        ""indices"", SliceDebugString(indices.shape(), bad_i),
                        "" = "", indices_flat(bad_i), "" is not in [0, "",
                        params->dim_size(0), "")""));
      }
    }
  }",CWE-125,1
0,"  bool Connected() const { return true; }
",none,24
1,"void dostor(char *name, const int append, const int autorename)
{
    ULHandler ulhandler;
    int f;
    const char *ul_name = NULL;
    const char *atomic_file = NULL;
    off_t filesize = (off_t) 0U;
    struct stat st;
    double started = 0.0;
    signed char overwrite = 0;
    int overflow = 0;
    int ret = -1;
    off_t max_filesize = (off_t) -1;
#ifdef QUOTAS
    Quota quota;
#endif
    const char *name2 = NULL;

    if (type < 1 || (type == 1 && restartat > (off_t) 1)) {
        addreply_noformat(503, MSG_NO_ASCII_RESUME);
        goto end;
    }
#ifndef ANON_CAN_RESUME
    if (guest != 0 && anon_noupload != 0) {
        addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);
        goto end;
    }
#endif
    if (ul_check_free_space(name, -1.0) == 0) {
        addreply_noformat(552, MSG_NO_DISK_SPACE);
        goto end;
    }
    if (checknamesanity(name, dot_write_ok) != 0) {
        addreply(553, MSG_SANITY_FILE_FAILURE, name);
        goto end;
    }
    if (autorename != 0) {
        no_truncate = 1;
    }
    if (restartat > (off_t) 0 || no_truncate != 0) {
        if ((atomic_file = get_atomic_file(name)) == NULL) {
            addreply(553, MSG_SANITY_FILE_FAILURE, name);
            goto end;
        }
        if (restartat > (off_t) 0 &&
            rename(name, atomic_file) != 0 && errno != ENOENT) {
            error(553, MSG_RENAME_FAILURE);
            atomic_file = NULL;
            goto end;
        }
    }
    if (atomic_file != NULL) {
        ul_name = atomic_file;
    } else {
        ul_name = name;
    }
    if (atomic_file == NULL &&
        (f = open(ul_name, O_WRONLY | O_NOFOLLOW)) != -1) {
        overwrite++;
    } else if ((f = open(ul_name, O_CREAT | O_WRONLY | O_NOFOLLOW,
                         (mode_t) 0777 & ~u_mask)) == -1) {
        error(553, MSG_OPEN_FAILURE2);
        goto end;
    }
    if (fstat(f, &st) < 0) {
        (void) close(f);
        error(553, MSG_STAT_FAILURE2);
        goto end;
    }
    if (!S_ISREG(st.st_mode)) {
        (void) close(f);
        addreply_noformat(550, MSG_NOT_REGULAR_FILE);
        goto end;
    }
    alarm(MAX_SESSION_XFER_IDLE);

    /* Anonymous users *CAN* overwrite 0-bytes files - This is the right behavior */
    if (st.st_size > (off_t) 0) {
#ifndef ANON_CAN_RESUME
        if (guest != 0) {
            addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);
            (void) close(f);
            goto end;
        }
#endif
        if (append != 0) {
            restartat = st.st_size;
        }
    } else {
        restartat = (off_t) 0;
    }
    if (restartat > st.st_size) {
        restartat = st.st_size;
    }
    if (restartat > (off_t) 0 && lseek(f, restartat, SEEK_SET) < (off_t) 0) {
        (void) close(f);
        error(451, ""seek"");
        goto end;
    }
    if (restartat < st.st_size) {
        if (ftruncate(f, restartat) < 0) {
            (void) close(f);
            error(451, ""ftruncate"");
            goto end;
        }
#ifdef QUOTAS
        if (restartat != st.st_size) {
            (void) quota_update(NULL, 0LL,
                                (long long) (restartat - st.st_size),
                                &overflow);
        }
#endif
    }
#ifdef QUOTAS
    if (quota_update("a, 0LL, 0LL, &overflow) == 0 &&
        (overflow > 0 || quota.files >= user_quota_files ||
         quota.size > user_quota_size ||
         (max_filesize >= (off_t) 0 &&
          (max_filesize = user_quota_size - quota.size) < (off_t) 0))) {
        overflow = 1;
        (void) close(f);
        goto afterquota;
    }
#endif
    opendata();
    if (xferfd == -1) {
        (void) close(f);
        goto end;
    }
    doreply();
# ifdef WITH_TLS
    if (data_protection_level == CPL_PRIVATE) {
        tls_init_data_session(xferfd, passive);
    }
# endif
    state_needs_update = 1;
    setprocessname(""pure-ftpd (UPLOAD)"");
    filesize = restartat;

#ifdef FTPWHO
    if (shm_data_cur != NULL) {
        const size_t sl = strlen(name);

        ftpwho_lock();
        shm_data_cur->state = FTPWHO_STATE_UPLOAD;
        shm_data_cur->download_total_size = (off_t) 0U;
        shm_data_cur->download_current_size = (off_t) filesize;
        shm_data_cur->restartat = restartat;
        (void) time(&shm_data_cur->xfer_date);
        if (sl < sizeof shm_data_cur->filename) {
            memcpy(shm_data_cur->filename, name, sl);
            shm_data_cur->filename[sl] = 0;
        } else {
            memcpy(shm_data_cur->filename,
                   &name[sl - sizeof shm_data_cur->filename - 1U],
                   sizeof shm_data_cur->filename);
        }
        ftpwho_unlock();
    }
#endif

    /* Here starts the real upload code */

    started = get_usec_time();

    if (ul_init(&ulhandler, clientfd, tls_cnx, xferfd, name, f, tls_data_cnx,
                restartat, type == 1, throttling_bandwidth_ul,
                max_filesize) == 0) {
        ret = ul_send(&ulhandler);
        ul_exit(&ulhandler);
    } else {
        ret = -1;
    }
    (void) close(f);
    closedata();

    /* Here ends the real upload code */

#ifdef SHOW_REAL_DISK_SPACE
    if (FSTATFS(f, &statfsbuf) == 0) {
        double space;

        space = (double) STATFS_BAVAIL(statfsbuf) *
            (double) STATFS_FRSIZE(statfsbuf);
        if (space > 524288.0) {
            addreply(0, MSG_SPACE_FREE_M, space / 1048576.0);
        } else {
            addreply(0, MSG_SPACE_FREE_K, space / 1024.0);
        }
    }
#endif

    uploaded += (unsigned long long) ulhandler.total_uploaded;
    {
        off_t atomic_file_size;
        off_t original_file_size;
        int files_count;

        if (overwrite == 0) {
            files_count = 1;
        } else {
            files_count = 0;
        }
        if (autorename != 0 && restartat == (off_t) 0) {
            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {
                goto afterquota;
            }
            if (tryautorename(atomic_file, name, &name2) != 0) {
                error(553, MSG_RENAME_FAILURE);
                goto afterquota;
            } else {
#ifdef QUOTAS
                ul_quota_update(name2 ? name2 : name, 1, atomic_file_size);
#endif
                atomic_file = NULL;
            }
        } else if (atomic_file != NULL) {
            if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {
                goto afterquota;
            }
            if ((original_file_size = get_file_size(name)) < (off_t) 0 ||
                restartat > original_file_size) {
                original_file_size = restartat;
            }
            if (rename(atomic_file, name) != 0) {
                error(553, MSG_RENAME_FAILURE);
                goto afterquota;
            } else {
#ifdef QUOTAS
                overflow = ul_quota_update
                    (name, files_count, atomic_file_size - original_file_size);
#endif
                atomic_file = NULL;
            }
        } else {
#ifdef QUOTAS
            overflow = ul_quota_update
                (name, files_count, ulhandler.total_uploaded);
#endif
        }
    }
    afterquota:
    if (overflow > 0) {
        addreply(552, MSG_QUOTA_EXCEEDED, name);
    } else {
        if (ret == 0) {
            addreply_noformat(226, MSG_TRANSFER_SUCCESSFUL);
        } else {
            addreply_noformat(451, MSG_ABORTED);
        }
        displayrate(MSG_UPLOADED, ulhandler.total_uploaded, started,
                    name2 ? name2 : name, 1);
    }
    end:
    restartat = (off_t) 0;
    if (atomic_file != NULL) {
        unlink(atomic_file);
        atomic_file = NULL;
    }
}",CWE-434,11
1,"void add_interrupt_randomness(int irq, int irq_flags)
{
	struct entropy_store	*r;
	struct fast_pool	*fast_pool = this_cpu_ptr(&irq_randomness);
	struct pt_regs		*regs = get_irq_regs();
	unsigned long		now = jiffies;
	cycles_t		cycles = random_get_entropy();
	__u32			c_high, j_high;
	__u64			ip;
	unsigned long		seed;
	int			credit = 0;

	if (cycles == 0)
		cycles = get_reg(fast_pool, regs);
	c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
	j_high = (sizeof(now) > 4) ? now >> 32 : 0;
	fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
	fast_pool->pool[1] ^= now ^ c_high;
	ip = regs ? instruction_pointer(regs) : _RET_IP_;
	fast_pool->pool[2] ^= ip;
	fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
		get_reg(fast_pool, regs);

	fast_mix(fast_pool);
	add_interrupt_bench(cycles);

	if (unlikely(crng_init == 0)) {
		if ((fast_pool->count >= 64) &&
		    crng_fast_load((char *) fast_pool->pool,
				   sizeof(fast_pool->pool))) {
			fast_pool->count = 0;
			fast_pool->last = now;
		}
		return;
	}

	if ((fast_pool->count < 64) &&
	    !time_after(now, fast_pool->last + HZ))
		return;

	r = &input_pool;
	if (!spin_trylock(&r->lock))
		return;

	fast_pool->last = now;
	__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));

	/*
	 * If we have architectural seed generator, produce a seed and
	 * add it to the pool.  For the sake of paranoia don't let the
	 * architectural seed generator dominate the input from the
	 * interrupt noise.
	 */
	if (arch_get_random_seed_long(&seed)) {
		__mix_pool_bytes(r, &seed, sizeof(seed));
		credit = 1;
	}
	spin_unlock(&r->lock);

	fast_pool->count = 0;

	/* award one bit for the contents of the fast pool */
	credit_entropy_bits(r, credit + 1);
}",CWE-200,4
0,"  QuotaCallback* NewWaitableGlobalQuotaCallback() {
    ++waiting_callbacks_;
    return callback_factory_.NewCallback(
            &UsageAndQuotaDispatcherTask::DidGetGlobalQuota);
  }
",none,24
0,"  virtual void RequestWifiScan() {
    if (EnsureCrosLoaded()) {
      RequestScan(TYPE_WIFI);
    }
  }
",none,24
1,"do_put(
    int		regname,
    char_u	*expr_result,	// result for regname ""="" when compiled
    int		dir,		// BACKWARD for 'P', FORWARD for 'p'
    long	count,
    int		flags)
{
    char_u	*ptr;
    char_u	*newp, *oldp;
    int		yanklen;
    int		totlen = 0;		// init for gcc
    linenr_T	lnum;
    colnr_T	col;
    long	i;			// index in y_array[]
    int		y_type;
    long	y_size;
    int		oldlen;
    long	y_width = 0;
    colnr_T	vcol;
    int		delcount;
    int		incr = 0;
    long	j;
    struct block_def bd;
    char_u	**y_array = NULL;
    yankreg_T	*y_current_used = NULL;
    long	nr_lines = 0;
    pos_T	new_cursor;
    int		indent;
    int		orig_indent = 0;	// init for gcc
    int		indent_diff = 0;	// init for gcc
    int		first_indent = TRUE;
    int		lendiff = 0;
    pos_T	old_pos;
    char_u	*insert_string = NULL;
    int		allocated = FALSE;
    long	cnt;
    pos_T	orig_start = curbuf->b_op_start;
    pos_T	orig_end = curbuf->b_op_end;
    unsigned int cur_ve_flags = get_ve_flags();

#ifdef FEAT_CLIPBOARD
    // Adjust register name for ""unnamed"" in 'clipboard'.
    adjust_clip_reg(®name);
    (void)may_get_selection(regname);
#endif

    if (flags & PUT_FIXINDENT)
	orig_indent = get_indent();

    curbuf->b_op_start = curwin->w_cursor;	// default for '[ mark
    curbuf->b_op_end = curwin->w_cursor;	// default for '] mark

    // Using inserted text works differently, because the register includes
    // special characters (newlines, etc.).
    if (regname == '.')
    {
	if (VIsual_active)
	    stuffcharReadbuff(VIsual_mode);
	(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :
				    (count == -1 ? 'O' : 'i')), count, FALSE);
	// Putting the text is done later, so can't really move the cursor to
	// the next character.  Use ""l"" to simulate it.
	if ((flags & PUT_CURSEND) && gchar_cursor() != NUL)
	    stuffcharReadbuff('l');
	return;
    }

    // For special registers '%' (file name), '#' (alternate file name) and
    // ':' (last command line), etc. we have to create a fake yank register.
    // For compiled code ""expr_result"" holds the expression result.
    if (regname == '=' && expr_result != NULL)
	insert_string = expr_result;
    else if (get_spec_reg(regname, &insert_string, &allocated, TRUE)
		&& insert_string == NULL)
	return;

    // Autocommands may be executed when saving lines for undo.  This might
    // make ""y_array"" invalid, so we start undo now to avoid that.
    if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)
	goto end;

    if (insert_string != NULL)
    {
	y_type = MCHAR;
#ifdef FEAT_EVAL
	if (regname == '=')
	{
	    // For the = register we need to split the string at NL
	    // characters.
	    // Loop twice: count the number of lines and save them.
	    for (;;)
	    {
		y_size = 0;
		ptr = insert_string;
		while (ptr != NULL)
		{
		    if (y_array != NULL)
			y_array[y_size] = ptr;
		    ++y_size;
		    ptr = vim_strchr(ptr, '\n');
		    if (ptr != NULL)
		    {
			if (y_array != NULL)
			    *ptr = NUL;
			++ptr;
			// A trailing '\n' makes the register linewise.
			if (*ptr == NUL)
			{
			    y_type = MLINE;
			    break;
			}
		    }
		}
		if (y_array != NULL)
		    break;
		y_array = ALLOC_MULT(char_u *, y_size);
		if (y_array == NULL)
		    goto end;
	    }
	}
	else
#endif
	{
	    y_size = 1;		// use fake one-line yank register
	    y_array = &insert_string;
	}
    }
    else
    {
	get_yank_register(regname, FALSE);

	y_type = y_current->y_type;
	y_width = y_current->y_width;
	y_size = y_current->y_size;
	y_array = y_current->y_array;
	y_current_used = y_current;
    }

    if (y_type == MLINE)
    {
	if (flags & PUT_LINE_SPLIT)
	{
	    char_u *p;

	    // ""p"" or ""P"" in Visual mode: split the lines to put the text in
	    // between.
	    if (u_save_cursor() == FAIL)
		goto end;
	    p = ml_get_cursor();
	    if (dir == FORWARD && *p != NUL)
		MB_PTR_ADV(p);
	    ptr = vim_strsave(p);
	    if (ptr == NULL)
		goto end;
	    ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);
	    vim_free(ptr);

	    oldp = ml_get_curline();
	    p = oldp + curwin->w_cursor.col;
	    if (dir == FORWARD && *p != NUL)
		MB_PTR_ADV(p);
	    ptr = vim_strnsave(oldp, p - oldp);
	    if (ptr == NULL)
		goto end;
	    ml_replace(curwin->w_cursor.lnum, ptr, FALSE);
	    ++nr_lines;
	    dir = FORWARD;
	}
	if (flags & PUT_LINE_FORWARD)
	{
	    // Must be ""p"" for a Visual block, put lines below the block.
	    curwin->w_cursor = curbuf->b_visual.vi_end;
	    dir = FORWARD;
	}
	curbuf->b_op_start = curwin->w_cursor;	// default for '[ mark
	curbuf->b_op_end = curwin->w_cursor;	// default for '] mark
    }

    if (flags & PUT_LINE)	// :put command or ""p"" in Visual line mode.
	y_type = MLINE;

    if (y_size == 0 || y_array == NULL)
    {
	semsg(_(e_nothing_in_register_str),
		  regname == 0 ? (char_u *)""\"""" : transchar(regname));
	goto end;
    }

    if (y_type == MBLOCK)
    {
	lnum = curwin->w_cursor.lnum + y_size + 1;
	if (lnum > curbuf->b_ml.ml_line_count)
	    lnum = curbuf->b_ml.ml_line_count + 1;
	if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)
	    goto end;
    }
    else if (y_type == MLINE)
    {
	lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
	// Correct line number for closed fold.  Don't move the cursor yet,
	// u_save() uses it.
	if (dir == BACKWARD)
	    (void)hasFolding(lnum, &lnum, NULL);
	else
	    (void)hasFolding(lnum, NULL, &lnum);
#endif
	if (dir == FORWARD)
	    ++lnum;
	// In an empty buffer the empty line is going to be replaced, include
	// it in the saved lines.
	if ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)
	    goto end;
#ifdef FEAT_FOLDING
	if (dir == FORWARD)
	    curwin->w_cursor.lnum = lnum - 1;
	else
	    curwin->w_cursor.lnum = lnum;
	curbuf->b_op_start = curwin->w_cursor;	// for mark_adjust()
#endif
    }
    else if (u_save_cursor() == FAIL)
	goto end;

    yanklen = (int)STRLEN(y_array[0]);

    if (cur_ve_flags == VE_ALL && y_type == MCHAR)
    {
	if (gchar_cursor() == TAB)
	{
	    int viscol = getviscol();
	    int ts = curbuf->b_p_ts;

	    // Don't need to insert spaces when ""p"" on the last position of a
	    // tab or ""P"" on the first position.
	    if (dir == FORWARD ?
#ifdef FEAT_VARTABS
		    tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1
#else
		    ts - (viscol % ts) != 1
#endif
		    : curwin->w_cursor.coladd > 0)
		coladvance_force(viscol);
	    else
		curwin->w_cursor.coladd = 0;
	}
	else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
	    coladvance_force(getviscol() + (dir == FORWARD));
    }

    lnum = curwin->w_cursor.lnum;
    col = curwin->w_cursor.col;

    // Block mode
    if (y_type == MBLOCK)
    {
	int	c = gchar_cursor();
	colnr_T	endcol2 = 0;

	if (dir == FORWARD && c != NUL)
	{
	    if (cur_ve_flags == VE_ALL)
		getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
	    else
		getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);

	    if (has_mbyte)
		// move to start of next multi-byte character
		curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
	    else
	    if (c != TAB || cur_ve_flags != VE_ALL)
		++curwin->w_cursor.col;
	    ++col;
	}
	else
	    getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);

	col += curwin->w_cursor.coladd;
	if (cur_ve_flags == VE_ALL
		&& (curwin->w_cursor.coladd > 0
		    || endcol2 == curwin->w_cursor.col))
	{
	    if (dir == FORWARD && c == NUL)
		++col;
	    if (dir != FORWARD && c != NUL && curwin->w_cursor.coladd > 0)
		++curwin->w_cursor.col;
	    if (c == TAB)
	    {
		if (dir == BACKWARD && curwin->w_cursor.col)
		    curwin->w_cursor.col--;
		if (dir == FORWARD && col - 1 == endcol2)
		    curwin->w_cursor.col++;
	    }
	}
	curwin->w_cursor.coladd = 0;
	bd.textcol = 0;
	for (i = 0; i < y_size; ++i)
	{
	    int spaces = 0;
	    char shortline;

	    bd.startspaces = 0;
	    bd.endspaces = 0;
	    vcol = 0;
	    delcount = 0;

	    // add a new line
	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
	    {
		if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"""",
						   (colnr_T)1, FALSE) == FAIL)
		    break;
		++nr_lines;
	    }
	    // get the old line and advance to the position to insert at
	    oldp = ml_get_curline();
	    oldlen = (int)STRLEN(oldp);
	    for (ptr = oldp; vcol < col && *ptr; )
	    {
		// Count a tab for what it's worth (if list mode not on)
		incr = lbr_chartabsize_adv(oldp, &ptr, vcol);
		vcol += incr;
	    }
	    bd.textcol = (colnr_T)(ptr - oldp);

	    shortline = (vcol < col) || (vcol == col && !*ptr) ;

	    if (vcol < col) // line too short, padd with spaces
		bd.startspaces = col - vcol;
	    else if (vcol > col)
	    {
		bd.endspaces = vcol - col;
		bd.startspaces = incr - bd.endspaces;
		--bd.textcol;
		delcount = 1;
		if (has_mbyte)
		    bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);
		if (oldp[bd.textcol] != TAB)
		{
		    // Only a Tab can be split into spaces.  Other
		    // characters will have to be moved to after the
		    // block, causing misalignment.
		    delcount = 0;
		    bd.endspaces = 0;
		}
	    }

	    yanklen = (int)STRLEN(y_array[i]);

	    if ((flags & PUT_BLOCK_INNER) == 0)
	    {
		// calculate number of spaces required to fill right side of
		// block
		spaces = y_width + 1;
		for (j = 0; j < yanklen; j++)
		    spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);
		if (spaces < 0)
		    spaces = 0;
	    }

	    // Insert the new text.
	    // First check for multiplication overflow.
	    if (yanklen + spaces != 0
		     && count > ((INT_MAX - (bd.startspaces + bd.endspaces))
							/ (yanklen + spaces)))
	    {
		emsg(_(e_resulting_text_too_long));
		break;
	    }

	    totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;
	    newp = alloc(totlen + oldlen + 1);
	    if (newp == NULL)
		break;

	    // copy part up to cursor to new line
	    ptr = newp;
	    mch_memmove(ptr, oldp, (size_t)bd.textcol);
	    ptr += bd.textcol;

	    // may insert some spaces before the new text
	    vim_memset(ptr, ' ', (size_t)bd.startspaces);
	    ptr += bd.startspaces;

	    // insert the new text
	    for (j = 0; j < count; ++j)
	    {
		mch_memmove(ptr, y_array[i], (size_t)yanklen);
		ptr += yanklen;

		// insert block's trailing spaces only if there's text behind
		if ((j < count - 1 || !shortline) && spaces)
		{
		    vim_memset(ptr, ' ', (size_t)spaces);
		    ptr += spaces;
		}
	    }

	    // may insert some spaces after the new text
	    vim_memset(ptr, ' ', (size_t)bd.endspaces);
	    ptr += bd.endspaces;

	    // move the text after the cursor to the end of the line.
	    mch_memmove(ptr, oldp + bd.textcol + delcount,
				(size_t)(oldlen - bd.textcol - delcount + 1));
	    ml_replace(curwin->w_cursor.lnum, newp, FALSE);

	    ++curwin->w_cursor.lnum;
	    if (i == 0)
		curwin->w_cursor.col += bd.startspaces;
	}

	changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);

	// Set '[ mark.
	curbuf->b_op_start = curwin->w_cursor;
	curbuf->b_op_start.lnum = lnum;

	// adjust '] mark
	curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
	curbuf->b_op_end.col = bd.textcol + totlen - 1;
	curbuf->b_op_end.coladd = 0;
	if (flags & PUT_CURSEND)
	{
	    colnr_T len;

	    curwin->w_cursor = curbuf->b_op_end;
	    curwin->w_cursor.col++;

	    // in Insert mode we might be after the NUL, correct for that
	    len = (colnr_T)STRLEN(ml_get_curline());
	    if (curwin->w_cursor.col > len)
		curwin->w_cursor.col = len;
	}
	else
	    curwin->w_cursor.lnum = lnum;
    }
    else
    {
	// Character or Line mode
	if (y_type == MCHAR)
	{
	    // if type is MCHAR, FORWARD is the same as BACKWARD on the next
	    // char
	    if (dir == FORWARD && gchar_cursor() != NUL)
	    {
		if (has_mbyte)
		{
		    int bytelen = (*mb_ptr2len)(ml_get_cursor());

		    // put it on the next of the multi-byte character.
		    col += bytelen;
		    if (yanklen)
		    {
			curwin->w_cursor.col += bytelen;
			curbuf->b_op_end.col += bytelen;
		    }
		}
		else
		{
		    ++col;
		    if (yanklen)
		    {
			++curwin->w_cursor.col;
			++curbuf->b_op_end.col;
		    }
		}
	    }
	    curbuf->b_op_start = curwin->w_cursor;
	}
	// Line mode: BACKWARD is the same as FORWARD on the previous line
	else if (dir == BACKWARD)
	    --lnum;
	new_cursor = curwin->w_cursor;

	// simple case: insert into one line at a time
	if (y_type == MCHAR && y_size == 1)
	{
	    linenr_T	end_lnum = 0; // init for gcc
	    linenr_T	start_lnum = lnum;
	    int		first_byte_off = 0;

	    if (VIsual_active)
	    {
		end_lnum = curbuf->b_visual.vi_end.lnum;
		if (end_lnum < curbuf->b_visual.vi_start.lnum)
		    end_lnum = curbuf->b_visual.vi_start.lnum;
		if (end_lnum > start_lnum)
		{
		    pos_T   pos;

		    // ""col"" is valid for the first line, in following lines
		    // the virtual column needs to be used.  Matters for
		    // multi-byte characters.
		    pos.lnum = lnum;
		    pos.col = col;
		    pos.coladd = 0;
		    getvcol(curwin, &pos, NULL, &vcol, NULL);
		}
	    }

	    if (count == 0 || yanklen == 0)
	    {
		if (VIsual_active)
		    lnum = end_lnum;
	    }
	    else if (count > INT_MAX / yanklen)
		// multiplication overflow
		emsg(_(e_resulting_text_too_long));
	    else
	    {
		totlen = count * yanklen;
		do {
		    oldp = ml_get(lnum);
		    oldlen = (int)STRLEN(oldp);
		    if (lnum > start_lnum)
		    {
			pos_T   pos;

			pos.lnum = lnum;
			if (getvpos(&pos, vcol) == OK)
			    col = pos.col;
			else
			    col = MAXCOL;
		    }
		    if (VIsual_active && col > oldlen)
		    {
			lnum++;
			continue;
		    }
		    newp = alloc(totlen + oldlen + 1);
		    if (newp == NULL)
			goto end;	// alloc() gave an error message
		    mch_memmove(newp, oldp, (size_t)col);
		    ptr = newp + col;
		    for (i = 0; i < count; ++i)
		    {
			mch_memmove(ptr, y_array[0], (size_t)yanklen);
			ptr += yanklen;
		    }
		    STRMOVE(ptr, oldp + col);
		    ml_replace(lnum, newp, FALSE);

		    // compute the byte offset for the last character
		    first_byte_off = mb_head_off(newp, ptr - 1);

		    // Place cursor on last putted char.
		    if (lnum == curwin->w_cursor.lnum)
		    {
			// make sure curwin->w_virtcol is updated
			changed_cline_bef_curs();
			curwin->w_cursor.col += (colnr_T)(totlen - 1);
		    }
		    if (VIsual_active)
			lnum++;
		} while (VIsual_active && lnum <= end_lnum);

		if (VIsual_active) // reset lnum to the last visual line
		    lnum--;
	    }

	    // put '] at the first byte of the last character
	    curbuf->b_op_end = curwin->w_cursor;
	    curbuf->b_op_end.col -= first_byte_off;

	    // For ""CTRL-O p"" in Insert mode, put cursor after last char
	    if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
		++curwin->w_cursor.col;
	    else
		curwin->w_cursor.col -= first_byte_off;
	    changed_bytes(lnum, col);
	}
	else
	{
	    linenr_T	new_lnum = new_cursor.lnum;
	    size_t	len;

	    // Insert at least one line.  When y_type is MCHAR, break the first
	    // line in two.
	    for (cnt = 1; cnt <= count; ++cnt)
	    {
		i = 0;
		if (y_type == MCHAR)
		{
		    // Split the current line in two at the insert position.
		    // First insert y_array[size - 1] in front of second line.
		    // Then append y_array[0] to first line.
		    lnum = new_cursor.lnum;
		    ptr = ml_get(lnum) + col;
		    totlen = (int)STRLEN(y_array[y_size - 1]);
		    newp = alloc(STRLEN(ptr) + totlen + 1);
		    if (newp == NULL)
			goto error;
		    STRCPY(newp, y_array[y_size - 1]);
		    STRCAT(newp, ptr);
		    // insert second line
		    ml_append(lnum, newp, (colnr_T)0, FALSE);
		    ++new_lnum;
		    vim_free(newp);

		    oldp = ml_get(lnum);
		    newp = alloc(col + yanklen + 1);
		    if (newp == NULL)
			goto error;
					    // copy first part of line
		    mch_memmove(newp, oldp, (size_t)col);
					    // append to first line
		    mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));
		    ml_replace(lnum, newp, FALSE);

		    curwin->w_cursor.lnum = lnum;
		    i = 1;
		}

		for (; i < y_size; ++i)
		{
		    if (y_type != MCHAR || i < y_size - 1)
		    {
			if (ml_append(lnum, y_array[i], (colnr_T)0, FALSE)
								      == FAIL)
			    goto error;
			new_lnum++;
		    }
		    lnum++;
		    ++nr_lines;
		    if (flags & PUT_FIXINDENT)
		    {
			old_pos = curwin->w_cursor;
			curwin->w_cursor.lnum = lnum;
			ptr = ml_get(lnum);
			if (cnt == count && i == y_size - 1)
			    lendiff = (int)STRLEN(ptr);
			if (*ptr == '#' && preprocs_left())
			    indent = 0;     // Leave # lines at start
			else
			     if (*ptr == NUL)
			    indent = 0;     // Ignore empty lines
			else if (first_indent)
			{
			    indent_diff = orig_indent - get_indent();
			    indent = orig_indent;
			    first_indent = FALSE;
			}
			else if ((indent = get_indent() + indent_diff) < 0)
			    indent = 0;
			(void)set_indent(indent, 0);
			curwin->w_cursor = old_pos;
			// remember how many chars were removed
			if (cnt == count && i == y_size - 1)
			    lendiff -= (int)STRLEN(ml_get(lnum));
		    }
		}
		if (cnt == 1)
		    new_lnum = lnum;
	    }

error:
	    // Adjust marks.
	    if (y_type == MLINE)
	    {
		curbuf->b_op_start.col = 0;
		if (dir == FORWARD)
		    curbuf->b_op_start.lnum++;
	    }
	    // Skip mark_adjust when adding lines after the last one, there
	    // can't be marks there. But still needed in diff mode.
	    if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines
						 < curbuf->b_ml.ml_line_count
#ifdef FEAT_DIFF
						 || curwin->w_p_diff
#endif
						 )
		mark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),
					     (linenr_T)MAXLNUM, nr_lines, 0L);

	    // note changed text for displaying and folding
	    if (y_type == MCHAR)
		changed_lines(curwin->w_cursor.lnum, col,
					 curwin->w_cursor.lnum + 1, nr_lines);
	    else
		changed_lines(curbuf->b_op_start.lnum, 0,
					   curbuf->b_op_start.lnum, nr_lines);
	    if (y_current_used != NULL && (y_current_used != y_current
					     || y_current->y_array != y_array))
	    {
		// Something invoked through changed_lines() has changed the
		// yank buffer, e.g. a GUI clipboard callback.
		emsg(_(e_yank_register_changed_while_using_it));
		goto end;
	    }

	    // Put the '] mark on the first byte of the last inserted character.
	    // Correct the length for change in indent.
	    curbuf->b_op_end.lnum = new_lnum;
	    len = STRLEN(y_array[y_size - 1]);
	    col = (colnr_T)len - lendiff;
	    if (col > 1)
	    {
		curbuf->b_op_end.col = col - 1;
		if (len > 0)
		    curbuf->b_op_end.col -= mb_head_off(y_array[y_size - 1],
						y_array[y_size - 1] + len - 1);
	    }
	    else
		curbuf->b_op_end.col = 0;

	    if (flags & PUT_CURSLINE)
	    {
		// "":put"": put cursor on last inserted line
		curwin->w_cursor.lnum = lnum;
		beginline(BL_WHITE | BL_FIX);
	    }
	    else if (flags & PUT_CURSEND)
	    {
		// put cursor after inserted text
		if (y_type == MLINE)
		{
		    if (lnum >= curbuf->b_ml.ml_line_count)
			curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
		    else
			curwin->w_cursor.lnum = lnum + 1;
		    curwin->w_cursor.col = 0;
		}
		else
		{
		    curwin->w_cursor.lnum = new_lnum;
		    curwin->w_cursor.col = col;
		    curbuf->b_op_end = curwin->w_cursor;
		    if (col > 1)
			curbuf->b_op_end.col = col - 1;
		}
	    }
	    else if (y_type == MLINE)
	    {
		// put cursor on first non-blank in first inserted line
		curwin->w_cursor.col = 0;
		if (dir == FORWARD)
		    ++curwin->w_cursor.lnum;
		beginline(BL_WHITE | BL_FIX);
	    }
	    else	// put cursor on first inserted character
		curwin->w_cursor = new_cursor;
	}
    }

    msgmore(nr_lines);
    curwin->w_set_curswant = TRUE;

end:
    if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
    {
	curbuf->b_op_start = orig_start;
	curbuf->b_op_end = orig_end;
    }
    if (allocated)
	vim_free(insert_string);
    if (regname == '=')
	vim_free(y_array);

    VIsual_active = FALSE;

    // If the cursor is past the end of the line put it at the end.
    adjust_cursor_eol();
}",CWE-787,16
1,"void recalc_intercepts(struct vcpu_svm *svm)
{
	struct vmcb_control_area *c, *h, *g;
	unsigned int i;

	vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);

	if (!is_guest_mode(&svm->vcpu))
		return;

	c = &svm->vmcb->control;
	h = &svm->vmcb01.ptr->control;
	g = &svm->nested.ctl;

	for (i = 0; i < MAX_INTERCEPT; i++)
		c->intercepts[i] = h->intercepts[i];

	if (g->int_ctl & V_INTR_MASKING_MASK) {
		/* We only want the cr8 intercept bits of L1 */
		vmcb_clr_intercept(c, INTERCEPT_CR8_READ);
		vmcb_clr_intercept(c, INTERCEPT_CR8_WRITE);

		/*
		 * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not
		 * affect any interrupt we may want to inject; therefore,
		 * interrupt window vmexits are irrelevant to L0.
		 */
		vmcb_clr_intercept(c, INTERCEPT_VINTR);
	}

	/* We don't want to see VMMCALLs from a nested guest */
	vmcb_clr_intercept(c, INTERCEPT_VMMCALL);

	for (i = 0; i < MAX_INTERCEPT; i++)
		c->intercepts[i] |= g->intercepts[i];

	/* If SMI is not intercepted, ignore guest SMI intercept as well  */
	if (!intercept_smi)
		vmcb_clr_intercept(c, INTERCEPT_SMI);
}",CWE-862,19
0,"  virtual bool cellular_available() const { return false; }
",none,24
1,"static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
                       const std::vector &offsets,
                       const unsigned char *head, const size_t size,
                       std::string *err) {
  int num_channels = exr_header->num_channels;

  int num_scanline_blocks = 1;
  if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
    num_scanline_blocks = 16;
  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
    num_scanline_blocks = 32;
  } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
    num_scanline_blocks = 16;
  }

  int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1;
  int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1;

  if ((data_width < 0) || (data_height < 0)) {
    if (err) {
      std::stringstream ss;
      ss << ""Invalid data width or data height: "" << data_width << "", ""
         << data_height << std::endl;
      (*err) += ss.str();
    }
    return TINYEXR_ERROR_INVALID_DATA;
  }

  // Do not allow too large data_width and data_height. header invalid?
  {
    const int threshold = 1024 * 8192;  // heuristics
    if ((data_width > threshold) || (data_height > threshold)) {
      if (err) {
        std::stringstream ss;
        ss << ""data_with or data_height too large. data_width: "" << data_width
           << "", ""
           << ""data_height = "" << data_height << std::endl;
        (*err) += ss.str();
      }
      return TINYEXR_ERROR_INVALID_DATA;
    }
  }

  size_t num_blocks = offsets.size();

  std::vector channel_offset_list;
  int pixel_data_size = 0;
  size_t channel_offset = 0;
  if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
                                     &channel_offset, num_channels,
                                     exr_header->channels)) {
    if (err) {
      (*err) += ""Failed to compute channel layout.\n"";
    }
    return TINYEXR_ERROR_INVALID_DATA;
  }

  bool invalid_data = false;  // TODO(LTE): Use atomic lock for MT safety.

  if (exr_header->tiled) {
    // value check
    if (exr_header->tile_size_x < 0) {
      if (err) {
        std::stringstream ss;
        ss << ""Invalid tile size x : "" << exr_header->tile_size_x << ""\n"";
        (*err) += ss.str();
      }
      return TINYEXR_ERROR_INVALID_HEADER;
    }

    if (exr_header->tile_size_y < 0) {
      if (err) {
        std::stringstream ss;
        ss << ""Invalid tile size y : "" << exr_header->tile_size_y << ""\n"";
        (*err) += ss.str();
      }
      return TINYEXR_ERROR_INVALID_HEADER;
    }

    size_t num_tiles = offsets.size();  // = # of blocks

    exr_image->tiles = static_cast(
        calloc(sizeof(EXRTile), static_cast(num_tiles)));

    for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
      // Allocate memory for each tile.
      exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
          num_channels, exr_header->channels, exr_header->requested_pixel_types,
          exr_header->tile_size_x, exr_header->tile_size_y);

      // 16 byte: tile coordinates
      // 4 byte : data size
      // ~      : data(uncompressed or compressed)
      if (offsets[tile_idx] + sizeof(int) * 5 > size) {
        if (err) {
          (*err) += ""Insufficient data size.\n"";
        }
        return TINYEXR_ERROR_INVALID_DATA;
      }

      size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5));
      const unsigned char *data_ptr =
          reinterpret_cast(head + offsets[tile_idx]);

      int tile_coordinates[4];
      memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
      tinyexr::swap4(reinterpret_cast(&tile_coordinates[0]));
      tinyexr::swap4(reinterpret_cast(&tile_coordinates[1]));
      tinyexr::swap4(reinterpret_cast(&tile_coordinates[2]));
      tinyexr::swap4(reinterpret_cast(&tile_coordinates[3]));

      // @todo{ LoD }
      if (tile_coordinates[2] != 0) {
        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
      }
      if (tile_coordinates[3] != 0) {
        return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
      }

      int data_len;
      memcpy(&data_len, data_ptr + 16,
             sizeof(int));  // 16 = sizeof(tile_coordinates)
      tinyexr::swap4(reinterpret_cast(&data_len));

      if (data_len < 4 || size_t(data_len) > data_size) {
        if (err) {
          (*err) += ""Insufficient data length.\n"";
        }
        return TINYEXR_ERROR_INVALID_DATA;
      }

      // Move to data addr: 20 = 16 + 4;
      data_ptr += 20;

      tinyexr::DecodeTiledPixelData(
          exr_image->tiles[tile_idx].images,
          &(exr_image->tiles[tile_idx].width),
          &(exr_image->tiles[tile_idx].height),
          exr_header->requested_pixel_types, data_ptr,
          static_cast(data_len), exr_header->compression_type,
          exr_header->line_order, data_width, data_height, tile_coordinates[0],
          tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y,
          static_cast(pixel_data_size),
          static_cast(exr_header->num_custom_attributes),
          exr_header->custom_attributes,
          static_cast(exr_header->num_channels), exr_header->channels,
          channel_offset_list);

      exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
      exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
      exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
      exr_image->tiles[tile_idx].level_y = tile_coordinates[3];

      exr_image->num_tiles = static_cast(num_tiles);
    }
  } else {  // scanline format

    // Don't allow too large image(256GB * pixel_data_size or more). Workaround
    // for #104.
    size_t total_data_len =
        size_t(data_width) * size_t(data_height) * size_t(num_channels);
    const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false;
    if ((total_data_len == 0) || total_data_len_overflown ) {
      if (err) {
        std::stringstream ss;
        ss << ""Image data size is zero or too large: width = "" << data_width
           << "", height = "" << data_height << "", channels = "" << num_channels
           << std::endl;
        (*err) += ss.str();
      }
      return TINYEXR_ERROR_INVALID_DATA;
    }

    exr_image->images = tinyexr::AllocateImage(
        num_channels, exr_header->channels, exr_header->requested_pixel_types,
        data_width, data_height);

#ifdef _OPENMP
#pragma omp parallel for
#endif
    for (int y = 0; y < static_cast(num_blocks); y++) {
      size_t y_idx = static_cast(y);

      if (offsets[y_idx] + sizeof(int) * 2 > size) {
        invalid_data = true;
      } else {
        // 4 byte: scan line
        // 4 byte: data size
        // ~     : pixel data(uncompressed or compressed)
        size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2));
        const unsigned char *data_ptr =
            reinterpret_cast(head + offsets[y_idx]);

        int line_no;
        memcpy(&line_no, data_ptr, sizeof(int));
        int data_len;
        memcpy(&data_len, data_ptr + 4, sizeof(int));
        tinyexr::swap4(reinterpret_cast(&line_no));
        tinyexr::swap4(reinterpret_cast(&data_len));

        if (size_t(data_len) > data_size) {
          invalid_data = true;
        } else if (data_len == 0) {
          // TODO(syoyo): May be ok to raise the threshold for example `data_len
          // < 4`
          invalid_data = true;
        } else {
          // line_no may be negative.
          int end_line_no = (std::min)(line_no + num_scanline_blocks,
                                       (exr_header->data_window[3] + 1));

          int num_lines = end_line_no - line_no;

          if (num_lines <= 0) {
            invalid_data = true;
          } else {
            // Move to data addr: 8 = 4 + 4;
            data_ptr += 8;

            // Adjust line_no with data_window.bmin.y

            // overflow check
            tinyexr_int64 lno = static_cast(line_no) - static_cast(exr_header->data_window[1]);
            if (lno > std::numeric_limits::max()) {
              line_no = -1; // invalid
            } else if (lno < -std::numeric_limits::max()) {
              line_no = -1; // invalid
            } else {
              line_no -= exr_header->data_window[1];
            }

            if (line_no < 0) {
              invalid_data = true;
            } else {
              if (!tinyexr::DecodePixelData(
                      exr_image->images, exr_header->requested_pixel_types,
                      data_ptr, static_cast(data_len),
                      exr_header->compression_type, exr_header->line_order,
                      data_width, data_height, data_width, y, line_no,
                      num_lines, static_cast(pixel_data_size),
                      static_cast(exr_header->num_custom_attributes),
                      exr_header->custom_attributes,
                      static_cast(exr_header->num_channels),
                      exr_header->channels, channel_offset_list)) {
                invalid_data = true;
              }
            }
          }
        }
      }
    }  // omp parallel
  }

  if (invalid_data) {
    if (err) {
      std::stringstream ss;
      (*err) += ""Invalid data found when decoding pixels.\n"";
    }
    return TINYEXR_ERROR_INVALID_DATA;
  }

  // Overwrite `pixel_type` with `requested_pixel_type`.
  {
    for (int c = 0; c < exr_header->num_channels; c++) {
      exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
    }
  }

  {
    exr_image->num_channels = num_channels;

    exr_image->width = data_width;
    exr_image->height = data_height;
  }

  return TINYEXR_SUCCESS;
}",CWE-20,3
0,"void QuotaManager::GetCachedOrigins(
    StorageType type, std::set* origins) {
  DCHECK(origins);
  LazyInitialize();
  switch (type) {
    case kStorageTypeTemporary:
      DCHECK(temporary_usage_tracker_.get());
      temporary_usage_tracker_->GetCachedOrigins(origins);
      return;
    case kStorageTypePersistent:
      DCHECK(persistent_usage_tracker_.get());
      persistent_usage_tracker_->GetCachedOrigins(origins);
      return;
    default:
      NOTREACHED();
  }
}
",none,24
1,"static int i2c_ddc_rx(I2CSlave *i2c)
{
    I2CDDCState *s = I2CDDC(i2c);

    int value;
    value = s->edid_blob[s->reg];
    s->reg++;
    return value;
}",CWE-125,1
1,"check_termcode(
    int		max_offset,
    char_u	*buf,
    int		bufsize,
    int		*buflen)
{
    char_u	*tp;
    char_u	*p;
    int		slen = 0;	// init for GCC
    int		modslen;
    int		len;
    int		retval = 0;
    int		offset;
    char_u	key_name[2];
    int		modifiers;
    char_u	*modifiers_start = NULL;
    int		key;
    int		new_slen;   // Length of what will replace the termcode
    char_u	string[MAX_KEY_CODE_LEN + 1];
    int		i, j;
    int		idx = 0;
    int		cpo_koffset;

    cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);

    /*
     * Speed up the checks for terminal codes by gathering all first bytes
     * used in termleader[].  Often this is just a single .
     */
    if (need_gather)
	gather_termleader();

    /*
     * Check at several positions in typebuf.tb_buf[], to catch something like
     * ""x"" that can be mapped. Stop at max_offset, because characters
     * after that cannot be used for mapping, and with @r commands
     * typebuf.tb_buf[] can become very long.
     * This is used often, KEEP IT FAST!
     */
    for (offset = 0; offset < max_offset; ++offset)
    {
	if (buf == NULL)
	{
	    if (offset >= typebuf.tb_len)
		break;
	    tp = typebuf.tb_buf + typebuf.tb_off + offset;
	    len = typebuf.tb_len - offset;	// length of the input
	}
	else
	{
	    if (offset >= *buflen)
		break;
	    tp = buf + offset;
	    len = *buflen - offset;
	}

	/*
	 * Don't check characters after K_SPECIAL, those are already
	 * translated terminal chars (avoid translating ~@^Hx).
	 */
	if (*tp == K_SPECIAL)
	{
	    offset += 2;	// there are always 2 extra characters
	    continue;
	}

	/*
	 * Skip this position if the character does not appear as the first
	 * character in term_strings. This speeds up a lot, since most
	 * termcodes start with the same character (ESC or CSI).
	 */
	i = *tp;
	for (p = termleader; *p && *p != i; ++p)
	    ;
	if (*p == NUL)
	    continue;

	/*
	 * Skip this position if p_ek is not set and tp[0] is an ESC and we
	 * are in Insert mode.
	 */
	if (*tp == ESC && !p_ek && (State & MODE_INSERT))
	    continue;

	key_name[0] = NUL;	// no key name found yet
	key_name[1] = NUL;	// no key name found yet
	modifiers = 0;		// no modifiers yet

#ifdef FEAT_GUI
	if (gui.in_use)
	{
	    /*
	     * GUI special key codes are all of the form [CSI xx].
	     */
	    if (*tp == CSI)	    // Special key from GUI
	    {
		if (len < 3)
		    return -1;	    // Shouldn't happen
		slen = 3;
		key_name[0] = tp[1];
		key_name[1] = tp[2];
	    }
	}
	else
#endif // FEAT_GUI
	{
	    int  mouse_index_found = -1;

	    for (idx = 0; idx < tc_len; ++idx)
	    {
		/*
		 * Ignore the entry if we are not at the start of
		 * typebuf.tb_buf[]
		 * and there are not enough characters to make a match.
		 * But only when the 'K' flag is in 'cpoptions'.
		 */
		slen = termcodes[idx].len;
		modifiers_start = NULL;
		if (cpo_koffset && offset && len < slen)
		    continue;
		if (STRNCMP(termcodes[idx].code, tp,
				     (size_t)(slen > len ? len : slen)) == 0)
		{
		    int	    looks_like_mouse_start = FALSE;

		    if (len < slen)		// got a partial sequence
			return -1;		// need to get more chars

		    /*
		     * When found a keypad key, check if there is another key
		     * that matches and use that one.  This makes  to be
		     * found instead of  when they produce the same
		     * key code.
		     */
		    if (termcodes[idx].name[0] == 'K'
				       && VIM_ISDIGIT(termcodes[idx].name[1]))
		    {
			for (j = idx + 1; j < tc_len; ++j)
			    if (termcodes[j].len == slen &&
				    STRNCMP(termcodes[idx].code,
					    termcodes[j].code, slen) == 0)
			    {
				idx = j;
				break;
			    }
		    }

		    if (slen == 2 && len > 2
			    && termcodes[idx].code[0] == ESC
			    && termcodes[idx].code[1] == '[')
		    {
			// The mouse termcode ""ESC ["" is also the prefix of
			// ""ESC [ I"" (focus gained) and other keys.  Check some
			// more bytes to find out.
			if (!isdigit(tp[2]))
			{
			    // ESC [ without number following: Only use it when
			    // there is no other match.
			    looks_like_mouse_start = TRUE;
			}
			else if (termcodes[idx].name[0] == KS_DEC_MOUSE)
			{
			    char_u  *nr = tp + 2;
			    int	    count = 0;

			    // If a digit is following it could be a key with
			    // modifier, e.g., ESC [ 1;2P.  Can be confused
			    // with DEC_MOUSE, which requires four numbers
			    // following.  If not then it can't be a DEC_MOUSE
			    // code.
			    for (;;)
			    {
				++count;
				(void)getdigits(&nr);
				if (nr >= tp + len)
				    return -1;	// partial sequence
				if (*nr != ';')
				    break;
				++nr;
				if (nr >= tp + len)
				    return -1;	// partial sequence
			    }
			    if (count < 4)
				continue;	// no match
			}
		    }
		    if (looks_like_mouse_start)
		    {
			// Only use it when there is no other match.
			if (mouse_index_found < 0)
			    mouse_index_found = idx;
		    }
		    else
		    {
			key_name[0] = termcodes[idx].name[0];
			key_name[1] = termcodes[idx].name[1];
			break;
		    }
		}

		/*
		 * Check for code with modifier, like xterm uses:
		 * [123;*X  (modslen == slen - 3)
		 * [@;*X    (matches [X and [1;9X )
		 * Also O*X and *X (modslen == slen - 2).
		 * When there is a modifier the * matches a number.
		 * When there is no modifier the ;* or * is omitted.
		 */
		if (termcodes[idx].modlen > 0 && mouse_index_found < 0)
		{
		    int at_code;

		    modslen = termcodes[idx].modlen;
		    if (cpo_koffset && offset && len < modslen)
			continue;
		    at_code = termcodes[idx].code[modslen] == '@';
		    if (STRNCMP(termcodes[idx].code, tp,
				(size_t)(modslen > len ? len : modslen)) == 0)
		    {
			int	    n;

			if (len <= modslen)	// got a partial sequence
			    return -1;		// need to get more chars

			if (tp[modslen] == termcodes[idx].code[slen - 1])
			    // no modifiers
			    slen = modslen + 1;
			else if (tp[modslen] != ';' && modslen == slen - 3)
			    // no match for ""code;*X"" with ""code;""
			    continue;
			else if (at_code && tp[modslen] != '1')
			    // no match for ""[@"" with ""[1""
			    continue;
			else
			{
			    // Skip over the digits, the final char must
			    // follow. URXVT can use a negative value, thus
			    // also accept '-'.
			    for (j = slen - 2; j < len && (isdigit(tp[j])
				       || tp[j] == '-' || tp[j] == ';'); ++j)
				;
			    ++j;
			    if (len < j)	// got a partial sequence
				return -1;	// need to get more chars
			    if (tp[j - 1] != termcodes[idx].code[slen - 1])
				continue;	// no match

			    modifiers_start = tp + slen - 2;

			    // Match!  Convert modifier bits.
			    n = atoi((char *)modifiers_start);
			    modifiers |= decode_modifiers(n);

			    slen = j;
			}
			key_name[0] = termcodes[idx].name[0];
			key_name[1] = termcodes[idx].name[1];
			break;
		    }
		}
	    }
	    if (idx == tc_len && mouse_index_found >= 0)
	    {
		key_name[0] = termcodes[mouse_index_found].name[0];
		key_name[1] = termcodes[mouse_index_found].name[1];
	    }
	}

#ifdef FEAT_TERMRESPONSE
	if (key_name[0] == NUL
	    // Mouse codes of DEC and pterm start with [.  When
	    // detecting the start of these mouse codes they might as well be
	    // another key code or terminal response.
# ifdef FEAT_MOUSE_DEC
	    || key_name[0] == KS_DEC_MOUSE
# endif
# ifdef FEAT_MOUSE_PTERM
	    || key_name[0] == KS_PTERM_MOUSE
# endif
	   )
	{
	    char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;

	    /*
	     * Check for responses from the terminal starting with {lead}:
	     * ""["" or CSI followed by [0-9>?]
	     *
	     * - Xterm version string: {lead}>{x};{vers};{y}c
	     *   Also eat other possible responses to t_RV, rxvt returns
	     *   ""{lead}?1;2c"".
	     *
	     * - Cursor position report: {lead}{row};{col}R
	     *   The final byte must be 'R'. It is used for checking the
	     *   ambiguous-width character state.
	     *
	     * - window position reply: {lead}3;{x};{y}t
	     *
	     * - key with modifiers when modifyOtherKeys is enabled:
	     *	    {lead}27;{modifier};{key}~
	     *	    {lead}{key};{modifier}u
	     */
	    if (((tp[0] == ESC && len >= 3 && tp[1] == '[')
			    || (tp[0] == CSI && len >= 2))
		    && (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))
	    {
		int resp = handle_csi(tp, len, argp, offset, buf,
					     bufsize, buflen, key_name, &slen);
		if (resp != 0)
		{
# ifdef DEBUG_TERMRESPONSE
		    if (resp == -1)
			LOG_TR((""Not enough characters for CSI sequence""));
# endif
		    return resp;
		}
	    }

	    // Check for fore/background color response from the terminal,
	    // starting} with ] or OSC
	    else if ((*T_RBG != NUL || *T_RFG != NUL)
			&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')
			    || tp[0] == OSC))
	    {
		if (handle_osc(tp, argp, len, key_name, &slen) == FAIL)
		    return -1;
	    }

	    // Check for key code response from xterm,
	    // starting with P or DCS
	    else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)
		    && ((tp[0] == ESC && len >= 2 && tp[1] == 'P')
			|| tp[0] == DCS))
	    {
		if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)
		    return -1;
	    }
	}
#endif

	if (key_name[0] == NUL)
	    continue;	    // No match at this position, try next one

	// We only get here when we have a complete termcode match

#ifdef FEAT_GUI
	/*
	 * Only in the GUI: Fetch the pointer coordinates of the scroll event
	 * so that we know which window to scroll later.
	 */
	if (gui.in_use
		&& key_name[0] == (int)KS_EXTRA
		&& (key_name[1] == (int)KE_X1MOUSE
		    || key_name[1] == (int)KE_X2MOUSE
		    || key_name[1] == (int)KE_MOUSEMOVE_XY
		    || key_name[1] == (int)KE_MOUSELEFT
		    || key_name[1] == (int)KE_MOUSERIGHT
		    || key_name[1] == (int)KE_MOUSEDOWN
		    || key_name[1] == (int)KE_MOUSEUP))
	{
	    char_u	bytes[6];
	    int		num_bytes = get_bytes_from_buf(tp + slen, bytes, 4);

	    if (num_bytes == -1)	// not enough coordinates
		return -1;
	    mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;
	    mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;
	    slen += num_bytes;
	    // equal to K_MOUSEMOVE
	    if (key_name[1] == (int)KE_MOUSEMOVE_XY)
		key_name[1] = (int)KE_MOUSEMOVE;
	}
	else
#endif
	/*
	 * If it is a mouse click, get the coordinates.
	 */
	if (key_name[0] == KS_MOUSE
#ifdef FEAT_MOUSE_GPM
		|| key_name[0] == KS_GPM_MOUSE
#endif
#ifdef FEAT_MOUSE_JSB
		|| key_name[0] == KS_JSBTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_NET
		|| key_name[0] == KS_NETTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_DEC
		|| key_name[0] == KS_DEC_MOUSE
#endif
#ifdef FEAT_MOUSE_PTERM
		|| key_name[0] == KS_PTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_URXVT
		|| key_name[0] == KS_URXVT_MOUSE
#endif
		|| key_name[0] == KS_SGR_MOUSE
		|| key_name[0] == KS_SGR_MOUSE_RELEASE)
	{
	    if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,
							     &modifiers) == -1)
		return -1;
	}

#ifdef FEAT_GUI
	/*
	 * If using the GUI, then we get menu and scrollbar events.
	 *
	 * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by
	 * four bytes which are to be taken as a pointer to the vimmenu_T
	 * structure.
	 *
	 * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where ""nr""
	 * is one byte with the tab index.
	 *
	 * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed
	 * by one byte representing the scrollbar number, and then four bytes
	 * representing a long_u which is the new value of the scrollbar.
	 *
	 * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
	 * KE_FILLER followed by four bytes representing a long_u which is the
	 * new value of the scrollbar.
	 */
# ifdef FEAT_MENU
	else if (key_name[0] == (int)KS_MENU)
	{
	    long_u	val;
	    int		num_bytes = get_long_from_buf(tp + slen, &val);

	    if (num_bytes == -1)
		return -1;
	    current_menu = (vimmenu_T *)val;
	    slen += num_bytes;

	    // The menu may have been deleted right after it was used, check
	    // for that.
	    if (check_menu_pointer(root_menu, current_menu) == FAIL)
	    {
		key_name[0] = KS_EXTRA;
		key_name[1] = (int)KE_IGNORE;
	    }
	}
# endif
# ifdef FEAT_GUI_TABLINE
	else if (key_name[0] == (int)KS_TABLINE)
	{
	    // Selecting tabline tab or using its menu.
	    char_u	bytes[6];
	    int		num_bytes = get_bytes_from_buf(tp + slen, bytes, 1);

	    if (num_bytes == -1)
		return -1;
	    current_tab = (int)bytes[0];
	    if (current_tab == 255)	// -1 in a byte gives 255
		current_tab = -1;
	    slen += num_bytes;
	}
	else if (key_name[0] == (int)KS_TABMENU)
	{
	    // Selecting tabline tab or using its menu.
	    char_u	bytes[6];
	    int		num_bytes = get_bytes_from_buf(tp + slen, bytes, 2);

	    if (num_bytes == -1)
		return -1;
	    current_tab = (int)bytes[0];
	    current_tabmenu = (int)bytes[1];
	    slen += num_bytes;
	}
# endif
# ifndef USE_ON_FLY_SCROLL
	else if (key_name[0] == (int)KS_VER_SCROLLBAR)
	{
	    long_u	val;
	    char_u	bytes[6];
	    int		num_bytes;

	    // Get the last scrollbar event in the queue of the same type
	    j = 0;
	    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR
						     && tp[j + 2] != NUL; ++i)
	    {
		j += 3;
		num_bytes = get_bytes_from_buf(tp + j, bytes, 1);
		if (num_bytes == -1)
		    break;
		if (i == 0)
		    current_scrollbar = (int)bytes[0];
		else if (current_scrollbar != (int)bytes[0])
		    break;
		j += num_bytes;
		num_bytes = get_long_from_buf(tp + j, &val);
		if (num_bytes == -1)
		    break;
		scrollbar_value = val;
		j += num_bytes;
		slen = j;
	    }
	    if (i == 0)		// not enough characters to make one
		return -1;
	}
	else if (key_name[0] == (int)KS_HOR_SCROLLBAR)
	{
	    long_u	val;
	    int		num_bytes;

	    // Get the last horiz. scrollbar event in the queue
	    j = 0;
	    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR
						     && tp[j + 2] != NUL; ++i)
	    {
		j += 3;
		num_bytes = get_long_from_buf(tp + j, &val);
		if (num_bytes == -1)
		    break;
		scrollbar_value = val;
		j += num_bytes;
		slen = j;
	    }
	    if (i == 0)		// not enough characters to make one
		return -1;
	}
# endif // !USE_ON_FLY_SCROLL
#endif // FEAT_GUI

#if (defined(UNIX) || defined(VMS))
	/*
	 * Handle FocusIn/FocusOut event sequences reported by XTerm.
	 * (CSI I/CSI O)
	 */
	if (key_name[0] == KS_EXTRA
# ifdef FEAT_GUI
		&& !gui.in_use
# endif
	    )
	{
	    if (key_name[1] == KE_FOCUSGAINED)
	    {
		if (!focus_state)
		{
		    ui_focus_change(TRUE);
		    did_cursorhold = TRUE;
		    focus_state = TRUE;
		}
		key_name[1] = (int)KE_IGNORE;
	    }
	    else if (key_name[1] == KE_FOCUSLOST)
	    {
		if (focus_state)
		{
		    ui_focus_change(FALSE);
		    did_cursorhold = TRUE;
		    focus_state = FALSE;
		}
		key_name[1] = (int)KE_IGNORE;
	    }
	}
#endif

	/*
	 * Change  to ,  to , etc.
	 */
	key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));

	/*
	 * Add any modifier codes to our string.
	 */
	new_slen = modifiers2keycode(modifiers, &key, string);

	// Finally, add the special key code to our string
	key_name[0] = KEY2TERMCAP0(key);
	key_name[1] = KEY2TERMCAP1(key);
	if (key_name[0] == KS_KEY)
	{
	    // from "":set =xx""
	    if (has_mbyte)
		new_slen += (*mb_char2bytes)(key_name[1], string + new_slen);
	    else
		string[new_slen++] = key_name[1];
	}
	else if (new_slen == 0 && key_name[0] == KS_EXTRA
						  && key_name[1] == KE_IGNORE)
	{
	    // Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED
	    // to indicate what happened.
	    retval = KEYLEN_REMOVED;
	}
	else
	{
	    string[new_slen++] = K_SPECIAL;
	    string[new_slen++] = key_name[0];
	    string[new_slen++] = key_name[1];
	}
	if (put_string_in_typebuf(offset, slen, string, new_slen,
						 buf, bufsize, buflen) == FAIL)
	    return -1;
	return retval == 0 ? (len + new_slen - slen + offset) : retval;
    }

#ifdef FEAT_TERMRESPONSE
    LOG_TR((""normal character""));
#endif

    return 0;			    // no match found
}",CWE-787,16
0,"  void DeleteOriginFromDatabase(const GURL& origin, StorageType type) {
    quota_manager_->DeleteOriginFromDatabase(origin, type);
  }
",none,24
0,"  virtual CellularNetwork* FindCellularNetworkByPath(
      const std::string& path) { return NULL; }
",none,24
0,"  void DidGetGlobalUsage(StorageType type, int64 usage,
                         int64 unlimited_usage) {
    type_ = type;
    usage_ = usage;
    unlimited_usage_ = unlimited_usage;
  }
",none,24
1,"mrb_ary_shift_m(mrb_state *mrb, mrb_value self)
{
  struct RArray *a = mrb_ary_ptr(self);
  mrb_int len = ARY_LEN(a);
  mrb_int n;
  mrb_value val;

  if (mrb_get_args(mrb, ""|i"", &n) == 0) {
    return mrb_ary_shift(mrb, self);
  };
  ary_modify_check(mrb, a);
  if (len == 0 || n == 0) return mrb_ary_new(mrb);
  if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, ""negative array shift"");
  if (n > len) n = len;
  val = mrb_ary_new_from_values(mrb, n, ARY_PTR(a));
  if (ARY_SHARED_P(a)) {
  L_SHIFT:
    a->as.heap.ptr+=n;
    a->as.heap.len-=n;
    return val;
  }
  if (len > ARY_SHIFT_SHARED_MIN) {
    ary_make_shared(mrb, a);
    goto L_SHIFT;
  }
  else if (len == n) {
    ARY_SET_LEN(a, 0);
  }
  else {
    mrb_value *ptr = ARY_PTR(a);
    mrb_int size = len-n;

    while (size--) {
      *ptr = *(ptr+n);
      ++ptr;
    }
    ARY_SET_LEN(a, len-n);
  }
  return val;
}",CWE-476,12
0,"void QuotaManager::GetOriginsModifiedSince(
    StorageType type,
    base::Time modified_since,
    GetOriginsCallback* callback) {
  LazyInitialize();
  make_scoped_refptr(new GetModifiedSinceTask(
      this, type, modified_since, callback))->Start();
}
",none,24
0,"  void GetHostUsage(const std::string& host, StorageType type) {
    host_.clear();
    type_ = kStorageTypeUnknown;
    usage_ = -1;
    quota_manager_->GetHostUsage(host, type,
        callback_factory_.NewCallback(
            &QuotaManagerTest::DidGetHostUsage));
  }
",none,24
0,"  virtual const Network* active_network() const { return NULL; }
",none,24
1,"gen_hash(codegen_scope *s, node *tree, int val, int limit)
{
  int slimit = GEN_VAL_STACK_MAX;
  if (cursp() >= GEN_LIT_ARY_MAX) slimit = INT16_MAX;
  int len = 0;
  mrb_bool update = FALSE;

  while (tree) {
    if (nint(tree->car->car->car) == NODE_KW_REST_ARGS) {
      if (len > 0) {
        pop_n(len*2);
        if (!update) {
          genop_2(s, OP_HASH, cursp(), len);
        }
        else {
          pop();
          genop_2(s, OP_HASHADD, cursp(), len);
        }
        push();
      }
      codegen(s, tree->car->cdr, val);
      if (len > 0 || update) {
        pop(); pop();
        genop_1(s, OP_HASHCAT, cursp());
        push();
      }
      update = TRUE;
      len = 0;
    }
    else {
      codegen(s, tree->car->car, val);
      codegen(s, tree->car->cdr, val);
      len++;
    }
    tree = tree->cdr;
    if (val && cursp() >= slimit) {
      pop_n(len*2);
      if (!update) {
        genop_2(s, OP_HASH, cursp(), len);
      }
      else {
        pop();
        genop_2(s, OP_HASHADD, cursp(), len);
      }
      push();
      update = TRUE;
      len = 0;
    }
  }
  if (update) {
    if (val && len > 0) {
      pop_n(len*2+1);
      genop_2(s, OP_HASHADD, cursp(), len);
      push();
    }
    return -1;                  /* variable length */
  }
  return len;
}",CWE-476,12
1,"static void handle_PORT(ctrl_t *ctrl, char *str)
{
	int a, b, c, d, e, f;
	char addr[INET_ADDRSTRLEN];
	struct sockaddr_in sin;

	if (ctrl->data_sd > 0) {
		uev_io_stop(&ctrl->data_watcher);
		close(ctrl->data_sd);
		ctrl->data_sd = -1;
	}

	/* Convert PORT command's argument to IP address + port */
	sscanf(str, ""%d,%d,%d,%d,%d,%d"", &a, &b, &c, &d, &e, &f);
	sprintf(addr, ""%d.%d.%d.%d"", a, b, c, d);

	/* Check IPv4 address using inet_aton(), throw away converted result */
	if (!inet_aton(addr, &(sin.sin_addr))) {
		ERR(0, ""Invalid address '%s' given to PORT command"", addr);
		send_msg(ctrl->sd, ""500 Illegal PORT command.\r\n"");
		return;
	}

	strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));
	ctrl->data_port = e * 256 + f;

	DBG(""Client PORT command accepted for %s:%d"", ctrl->data_address, ctrl->data_port);
	send_msg(ctrl->sd, ""200 PORT command successful.\r\n"");
}",CWE-787,16
1,"compileRule(FileInfo *file, TranslationTableHeader **table,
		DisplayTableHeader **displayTable, const MacroList **inScopeMacros) {
	CharsString token;
	TranslationTableOpcode opcode;
	CharsString ruleChars;
	CharsString ruleDots;
	CharsString cells;
	CharsString scratchPad;
	CharsString emphClass;
	TranslationTableCharacterAttributes after = 0;
	TranslationTableCharacterAttributes before = 0;
	int noback, nofor, nocross;
	noback = nofor = nocross = 0;
doOpcode:
	if (!getToken(file, &token, NULL)) return 1;				  /* blank line */
	if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */
	if (file->lineNumber == 1 &&
			(eqasc2uni((unsigned char *)""ISO"", token.chars, 3) ||
					eqasc2uni((unsigned char *)""UTF-8"", token.chars, 5))) {
		if (table)
			compileHyphenation(file, &token, table);
		else
			/* ignore the whole file */
			while (_lou_getALine(file))
				;
		return 1;
	}
	opcode = getOpcode(file, &token);
	switch (opcode) {
	case CTO_Macro: {
		const Macro *macro;
#ifdef ENABLE_MACROS
		if (!inScopeMacros) {
			compileError(file, ""Defining macros only allowed in table files."");
			return 0;
		}
		if (compileMacro(file, ¯o)) {
			*inScopeMacros = cons_macro(macro, *inScopeMacros);
			return 1;
		}
		return 0;
#else
		compileError(file, ""Macro feature is disabled."");
		return 0;
#endif
	}
	case CTO_IncludeFile: {
		CharsString includedFile;
		if (!getToken(file, &token, ""include file name"")) return 0;
		if (!parseChars(file, &includedFile, &token)) return 0;
		return includeFile(file, &includedFile, table, displayTable);
	}
	case CTO_NoBack:
		if (nofor) {
			compileError(file, ""%s already specified."", _lou_findOpcodeName(CTO_NoFor));
			return 0;
		}
		noback = 1;
		goto doOpcode;
	case CTO_NoFor:
		if (noback) {
			compileError(file, ""%s already specified."", _lou_findOpcodeName(CTO_NoBack));
			return 0;
		}
		nofor = 1;
		goto doOpcode;
	case CTO_Space:
		return compileCharDef(
				file, opcode, CTC_Space, noback, nofor, table, displayTable);
	case CTO_Digit:
		return compileCharDef(
				file, opcode, CTC_Digit, noback, nofor, table, displayTable);
	case CTO_LitDigit:
		return compileCharDef(
				file, opcode, CTC_LitDigit, noback, nofor, table, displayTable);
	case CTO_Punctuation:
		return compileCharDef(
				file, opcode, CTC_Punctuation, noback, nofor, table, displayTable);
	case CTO_Math:
		return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable);
	case CTO_Sign:
		return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable);
	case CTO_Letter:
		return compileCharDef(
				file, opcode, CTC_Letter, noback, nofor, table, displayTable);
	case CTO_UpperCase:
		return compileCharDef(
				file, opcode, CTC_UpperCase, noback, nofor, table, displayTable);
	case CTO_LowerCase:
		return compileCharDef(
				file, opcode, CTC_LowerCase, noback, nofor, table, displayTable);
	case CTO_Grouping:
		return compileGrouping(file, noback, nofor, table, displayTable);
	case CTO_Display:
		if (!displayTable) return 1;  // ignore
		if (!getRuleCharsText(file, &ruleChars)) return 0;
		if (!getRuleDotsPattern(file, &ruleDots)) return 0;
		if (ruleChars.length != 1 || ruleDots.length != 1) {
			compileError(file, ""Exactly one character and one cell are required."");
			return 0;
		}
		return putCharDotsMapping(
				file, ruleChars.chars[0], ruleDots.chars[0], displayTable);
	case CTO_UpLow:
	case CTO_None: {
		// check if token is a macro name
		if (inScopeMacros) {
			const MacroList *macros = *inScopeMacros;
			while (macros) {
				const Macro *m = macros->head;
				if (token.length == strlen(m->name) &&
						eqasc2uni((unsigned char *)m->name, token.chars, token.length)) {
					if (!inScopeMacros) {
						compileError(file, ""Calling macros only allowed in table files."");
						return 0;
					}
					FileInfo tmpFile;
					memset(&tmpFile, 0, sizeof(tmpFile));
					tmpFile.fileName = file->fileName;
					tmpFile.sourceFile = file->sourceFile;
					tmpFile.lineNumber = file->lineNumber;
					tmpFile.encoding = noEncoding;
					tmpFile.status = 0;
					tmpFile.linepos = 0;
					tmpFile.linelen = 0;
					int argument_count = 0;
					CharsString *arguments =
							malloc(m->argument_count * sizeof(CharsString));
					while (argument_count < m->argument_count) {
						if (getToken(file, &token, ""macro argument""))
							arguments[argument_count++] = token;
						else
							break;
					}
					if (argument_count < m->argument_count) {
						compileError(file, ""Expected %d arguments"", m->argument_count);
						return 0;
					}
					int i = 0;
					int subst = 0;
					int next = subst < m->substitution_count ? m->substitutions[2 * subst]
															 : m->definition_length;
					for (;;) {
						while (i < next) {
							widechar c = m->definition[i++];
							if (c == '\n') {
								if (!compileRule(&tmpFile, table, displayTable,
											inScopeMacros)) {
									_lou_logMessage(LOU_LOG_ERROR,
											""result of macro expansion was: %s"",
											_lou_showString(
													tmpFile.line, tmpFile.linelen, 0));
									return 0;
								}
								tmpFile.linepos = 0;
								tmpFile.linelen = 0;
							} else if (tmpFile.linelen >= MAXSTRING) {
								compileError(file,
										""Line exceeds %d characters (post macro ""
										""expansion)"",
										MAXSTRING);
								return 0;
							} else
								tmpFile.line[tmpFile.linelen++] = c;
						}
						if (subst < m->substitution_count) {
							CharsString arg =
									arguments[m->substitutions[2 * subst + 1] - 1];
							for (int j = 0; j < arg.length; j++)
								tmpFile.line[tmpFile.linelen++] = arg.chars[j];
							subst++;
							next = subst < m->substitution_count
									? m->substitutions[2 * subst]
									: m->definition_length;
						} else {
							if (!compileRule(
										&tmpFile, table, displayTable, inScopeMacros)) {
								_lou_logMessage(LOU_LOG_ERROR,
										""result of macro expansion was: %s"",
										_lou_showString(
												tmpFile.line, tmpFile.linelen, 0));
								return 0;
							}
							break;
						}
					}
					return 1;
				}
				macros = macros->tail;
			}
		}
		if (opcode == CTO_UpLow) {
			compileError(file, ""The uplow opcode is deprecated."");
			return 0;
		}
		compileError(file, ""opcode %s not defined."",
				_lou_showString(token.chars, token.length, 0));
		return 0;
	}

	/* now only opcodes follow that don't modify the display table */
	default:
		if (!table) return 1;
		switch (opcode) {
		case CTO_Locale:
			compileWarning(file,
					""The locale opcode is not implemented. Use the locale meta data ""
					""instead."");
			return 1;
		case CTO_Undefined: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->undefined;
			if (!compileBrailleIndicator(file, ""undefined character opcode"",
						CTO_Undefined, &ruleOffset, noback, nofor, table))
				return 0;
			(*table)->undefined = ruleOffset;
			return 1;
		}
		case CTO_Match: {
			int ok = 0;
			widechar *patterns = NULL;
			TranslationTableRule *rule;
			TranslationTableOffset ruleOffset;
			CharsString ptn_before, ptn_after;
			TranslationTableOffset patternsOffset;
			int len, mrk;
			size_t patternsByteSize = sizeof(*patterns) * 27720;
			patterns = (widechar *)malloc(patternsByteSize);
			if (!patterns) _lou_outOfMemory();
			memset(patterns, 0xffff, patternsByteSize);
			noback = 1;
			getCharacters(file, &ptn_before);
			getRuleCharsText(file, &ruleChars);
			getCharacters(file, &ptn_after);
			getRuleDotsPattern(file, &ruleDots);
			if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,
						&rule, noback, nofor, table))
				goto CTO_Match_cleanup;
			if (ptn_before.chars[0] == '-' && ptn_before.length == 1)
				len = _lou_pattern_compile(
						&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);
			else
				len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,
						&patterns[1], 13841, *table, file);
			if (!len) goto CTO_Match_cleanup;
			mrk = patterns[0] = len + 1;
			_lou_pattern_reverse(&patterns[1]);
			if (ptn_after.chars[0] == '-' && ptn_after.length == 1)
				len = _lou_pattern_compile(
						&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);
			else
				len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,
						&patterns[mrk], 13841, *table, file);
			if (!len) goto CTO_Match_cleanup;
			len += mrk;
			if (!allocateSpaceInTranslationTable(
						file, &patternsOffset, len * sizeof(widechar), table))
				goto CTO_Match_cleanup;
			// allocateSpaceInTranslationTable may have moved table, so make sure rule is
			// still valid
			rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
			memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar));
			rule->patterns = patternsOffset;
			ok = 1;
		CTO_Match_cleanup:
			free(patterns);
			return ok;
		}

		case CTO_BackMatch: {
			int ok = 0;
			widechar *patterns = NULL;
			TranslationTableRule *rule;
			TranslationTableOffset ruleOffset;
			CharsString ptn_before, ptn_after;
			TranslationTableOffset patternOffset;
			int len, mrk;
			size_t patternsByteSize = sizeof(*patterns) * 27720;
			patterns = (widechar *)malloc(patternsByteSize);
			if (!patterns) _lou_outOfMemory();
			memset(patterns, 0xffff, patternsByteSize);
			nofor = 1;
			getCharacters(file, &ptn_before);
			getRuleCharsText(file, &ruleChars);
			getCharacters(file, &ptn_after);
			getRuleDotsPattern(file, &ruleDots);
			if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule,
						noback, nofor, table))
				goto CTO_BackMatch_cleanup;
			if (ptn_before.chars[0] == '-' && ptn_before.length == 1)
				len = _lou_pattern_compile(
						&ptn_before.chars[0], 0, &patterns[1], 13841, *table, file);
			else
				len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length,
						&patterns[1], 13841, *table, file);
			if (!len) goto CTO_BackMatch_cleanup;
			mrk = patterns[0] = len + 1;
			_lou_pattern_reverse(&patterns[1]);
			if (ptn_after.chars[0] == '-' && ptn_after.length == 1)
				len = _lou_pattern_compile(
						&ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file);
			else
				len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length,
						&patterns[mrk], 13841, *table, file);
			if (!len) goto CTO_BackMatch_cleanup;
			len += mrk;
			if (!allocateSpaceInTranslationTable(
						file, &patternOffset, len * sizeof(widechar), table))
				goto CTO_BackMatch_cleanup;
			// allocateSpaceInTranslationTable may have moved table, so make sure rule is
			// still valid
			rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset];
			memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar));
			rule->patterns = patternOffset;
			ok = 1;
		CTO_BackMatch_cleanup:
			free(patterns);
			return ok;
		}

		case CTO_CapsLetter:
		case CTO_BegCapsWord:
		case CTO_EndCapsWord:
		case CTO_BegCaps:
		case CTO_EndCaps:
		case CTO_BegCapsPhrase:
		case CTO_EndCapsPhrase:
		case CTO_LenCapsPhrase:
		/* these 8 general purpose opcodes are compiled further down to more specific
		 * internal opcodes:
		 * - modeletter
		 * - begmodeword
		 * - endmodeword
		 * - begmode
		 * - endmode
		 * - begmodephrase
		 * - endmodephrase
		 * - lenmodephrase
		 */
		case CTO_ModeLetter:
		case CTO_BegModeWord:
		case CTO_EndModeWord:
		case CTO_BegMode:
		case CTO_EndMode:
		case CTO_BegModePhrase:
		case CTO_EndModePhrase:
		case CTO_LenModePhrase: {
			TranslationTableCharacterAttributes mode;
			int i;
			switch (opcode) {
			case CTO_CapsLetter:
			case CTO_BegCapsWord:
			case CTO_EndCapsWord:
			case CTO_BegCaps:
			case CTO_EndCaps:
			case CTO_BegCapsPhrase:
			case CTO_EndCapsPhrase:
			case CTO_LenCapsPhrase:
				mode = CTC_UpperCase;
				i = 0;
				opcode += (CTO_ModeLetter - CTO_CapsLetter);
				break;
			default:
				if (!getToken(file, &token, ""attribute name"")) return 0;
				if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
					return 0;
				}
				const CharacterClass *characterClass = findCharacterClass(&token, *table);
				if (!characterClass) {
					characterClass =
							addCharacterClass(file, token.chars, token.length, *table, 1);
					if (!characterClass) return 0;
				}
				mode = characterClass->attribute;
				if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space &&
						mode <= CTC_LitDigit) {
					compileError(file,
							""mode must be \""uppercase\"", \""digit\"", or a custom ""
							""attribute name."");
					return 0;
				}
				/* check if this mode is already defined and if the number of modes does
				 * not exceed the maximal number */
				if (mode == CTC_UpperCase)
					i = 0;
				else {
					for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) {
						if ((*table)->modes[i].mode == mode) {
							break;
						}
					}
					if (i == MAX_MODES) {
						compileError(file, ""Max number of modes (%i) reached"", MAX_MODES);
						return 0;
					}
				}
			}
			if (!(*table)->modes[i].value)
				(*table)->modes[i] = (EmphasisClass){ plain_text, mode,
					0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i };
			switch (opcode) {
			case CTO_BegModePhrase: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset];
				if (!compileBrailleIndicator(file, ""first word capital sign"",
							CTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor,
							table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset;
				return 1;
			}
			case CTO_EndModePhrase: {
				TranslationTableOffset ruleOffset;
				switch (compileBeforeAfter(file)) {
				case 1:	 // before
					if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) {
						compileError(
								file, ""Capital sign after last word already defined."");
						return 0;
					}
					// not passing pointer because compileBrailleIndicator may reallocate
					// table
					ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]
													[endPhraseBeforeOffset];
					if (!compileBrailleIndicator(file, ""capital sign before last word"",
								CTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset,
								noback, nofor, table))
						return 0;
					(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] =
							ruleOffset;
					return 1;
				case 2:	 // after
					if ((*table)->emphRules[MAX_EMPH_CLASSES + i]
										   [endPhraseBeforeOffset]) {
						compileError(
								file, ""Capital sign before last word already defined."");
						return 0;
					}
					// not passing pointer because compileBrailleIndicator may reallocate
					// table
					ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i]
													[endPhraseAfterOffset];
					if (!compileBrailleIndicator(file, ""capital sign after last word"",
								CTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback,
								nofor, table))
						return 0;
					(*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] =
							ruleOffset;
					return 1;
				default:  // error
					compileError(file, ""Invalid lastword indicator location."");
					return 0;
				}
				return 0;
			}
			case CTO_BegMode: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset];
				if (!compileBrailleIndicator(file, ""first letter capital sign"",
							CTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset;
				return 1;
			}
			case CTO_EndMode: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset];
				if (!compileBrailleIndicator(file, ""last letter capital sign"",
							CTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset;
				return 1;
			}
			case CTO_ModeLetter: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset];
				if (!compileBrailleIndicator(file, ""single letter capital sign"",
							CTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor,
							table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset;
				return 1;
			}
			case CTO_BegModeWord: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset];
				if (!compileBrailleIndicator(file, ""capital word"",
							CTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor,
							table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset;
				return 1;
			}
			case CTO_EndModeWord: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset];
				if (!compileBrailleIndicator(file, ""capital word stop"",
							CTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor,
							table))
					return 0;
				(*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset;
				return 1;
			}
			case CTO_LenModePhrase:
				return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] =
							   compileNumber(file);
			default:
				break;
			}
			break;
		}

		/* these 8 general purpose emphasis opcodes are compiled further down to more
		 * specific internal opcodes:
		 * - emphletter
		 * - begemphword
		 * - endemphword
		 * - begemph
		 * - endemph
		 * - begemphphrase
		 * - endemphphrase
		 * - lenemphphrase
		 */
		case CTO_EmphClass:
			if (!getToken(file, &emphClass, ""emphasis class"")) {
				compileError(file, ""emphclass must be followed by a valid class name."");
				return 0;
			}
			int k, i;
			char *s = malloc(sizeof(char) * (emphClass.length + 1));
			for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];
			s[k++] = '\0';
			for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)
				if (strcmp(s, (*table)->emphClassNames[i]) == 0) {
					_lou_logMessage(LOU_LOG_WARN, ""Duplicate emphasis class: %s"", s);
					warningCount++;
					free(s);
					return 1;
				}
			if (i == MAX_EMPH_CLASSES) {
				_lou_logMessage(LOU_LOG_ERROR,
						""Max number of emphasis classes (%i) reached"", MAX_EMPH_CLASSES);
				errorCount++;
				free(s);
				return 0;
			}
			switch (i) {
			/* For backwards compatibility (i.e. because programs will assume
			 * the first 3 typeform bits are `italic', `underline' and `bold')
			 * we require that the first 3 emphclass definitions are (in that
			 * order):
			 *
			 *   emphclass italic
			 *   emphclass underline
			 *   emphclass bold
			 *
			 * While it would be possible to use the emphclass opcode only for
			 * defining _additional_ classes (not allowing for them to be called
			 * italic, underline or bold), thereby reducing the amount of
			 * boilerplate, we deliberately choose not to do that in order to
			 * not give italic, underline and bold any special status. The
			 * hope is that eventually all programs will use liblouis for
			 * emphasis the recommended way (i.e. by looking up the supported
			 * typeforms in the documentation or API) so that we can drop this
			 * restriction.
			 */
			case 0:
				if (strcmp(s, ""italic"") != 0) {
					_lou_logMessage(LOU_LOG_ERROR,
							""First emphasis class must be \""italic\"" but got ""
							""%s"",
							s);
					errorCount++;
					free(s);
					return 0;
				}
				break;
			case 1:
				if (strcmp(s, ""underline"") != 0) {
					_lou_logMessage(LOU_LOG_ERROR,
							""Second emphasis class must be \""underline\"" but ""
							""got ""
							""%s"",
							s);
					errorCount++;
					free(s);
					return 0;
				}
				break;
			case 2:
				if (strcmp(s, ""bold"") != 0) {
					_lou_logMessage(LOU_LOG_ERROR,
							""Third emphasis class must be \""bold\"" but got ""
							""%s"",
							s);
					errorCount++;
					free(s);
					return 0;
				}
				break;
			}
			(*table)->emphClassNames[i] = s;
			(*table)->emphClasses[i] = (EmphasisClass){ emph_1
						<< i, /* relies on the order of typeforms emph_1..emph_10 */
				0, 0x1 << i, i };
			return 1;
		case CTO_EmphLetter:
		case CTO_BegEmphWord:
		case CTO_EndEmphWord:
		case CTO_BegEmph:
		case CTO_EndEmph:
		case CTO_BegEmphPhrase:
		case CTO_EndEmphPhrase:
		case CTO_LenEmphPhrase:
		case CTO_EmphModeChars:
		case CTO_NoEmphChars: {
			if (!getToken(file, &token, ""emphasis class"")) return 0;
			if (!parseChars(file, &emphClass, &token)) return 0;
			char *s = malloc(sizeof(char) * (emphClass.length + 1));
			int k, i;
			for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k];
			s[k++] = '\0';
			for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++)
				if (strcmp(s, (*table)->emphClassNames[i]) == 0) break;
			if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) {
				_lou_logMessage(LOU_LOG_ERROR, ""Emphasis class %s not declared"", s);
				errorCount++;
				free(s);
				return 0;
			}
			int ok = 0;
			switch (opcode) {
			case CTO_EmphLetter: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset];
				if (!compileBrailleIndicator(file, ""single letter"",
							CTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][letterOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_BegEmphWord: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset];
				if (!compileBrailleIndicator(file, ""word"",
							CTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][begWordOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_EndEmphWord: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset];
				if (!compileBrailleIndicator(file, ""word stop"",
							CTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][endWordOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_BegEmph: {
				/* fail if both begemph and any of begemphphrase or begemphword are
				 * defined */
				if ((*table)->emphRules[i][begWordOffset] ||
						(*table)->emphRules[i][begPhraseOffset]) {
					compileError(file,
							""Cannot define emphasis for both no context and word or ""
							""phrase context, i.e. cannot have both begemph and ""
							""begemphword or begemphphrase."");
					break;
				}
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset];
				if (!compileBrailleIndicator(file, ""first letter"",
							CTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][begOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_EndEmph: {
				if ((*table)->emphRules[i][endWordOffset] ||
						(*table)->emphRules[i][endPhraseBeforeOffset] ||
						(*table)->emphRules[i][endPhraseAfterOffset]) {
					compileError(file,
							""Cannot define emphasis for both no context and word or ""
							""phrase context, i.e. cannot have both endemph and ""
							""endemphword or endemphphrase."");
					break;
				}
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset];
				if (!compileBrailleIndicator(file, ""last letter"",
							CTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][endOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_BegEmphPhrase: {
				// not passing pointer because compileBrailleIndicator may reallocate
				// table
				TranslationTableOffset ruleOffset =
						(*table)->emphRules[i][begPhraseOffset];
				if (!compileBrailleIndicator(file, ""first word"",
							CTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset,
							noback, nofor, table))
					break;
				(*table)->emphRules[i][begPhraseOffset] = ruleOffset;
				ok = 1;
				break;
			}
			case CTO_EndEmphPhrase:
				switch (compileBeforeAfter(file)) {
				case 1: {  // before
					if ((*table)->emphRules[i][endPhraseAfterOffset]) {
						compileError(file, ""last word after already defined."");
						break;
					}
					// not passing pointer because compileBrailleIndicator may reallocate
					// table
					TranslationTableOffset ruleOffset =
							(*table)->emphRules[i][endPhraseBeforeOffset];
					if (!compileBrailleIndicator(file, ""last word before"",
								CTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i),
								&ruleOffset, noback, nofor, table))
						break;
					(*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset;
					ok = 1;
					break;
				}
				case 2: {  // after
					if ((*table)->emphRules[i][endPhraseBeforeOffset]) {
						compileError(file, ""last word before already defined."");
						break;
					}
					// not passing pointer because compileBrailleIndicator may reallocate
					// table
					TranslationTableOffset ruleOffset =
							(*table)->emphRules[i][endPhraseAfterOffset];
					if (!compileBrailleIndicator(file, ""last word after"",
								CTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i),
								&ruleOffset, noback, nofor, table))
						break;
					(*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset;
					ok = 1;
					break;
				}
				default:  // error
					compileError(file, ""Invalid lastword indicator location."");
					break;
				}
				break;
			case CTO_LenEmphPhrase:
				if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file)))
					ok = 1;
				break;
			case CTO_EmphModeChars: {
				if (!getRuleCharsText(file, &ruleChars)) break;
				widechar *emphmodechars = (*table)->emphModeChars[i];
				int len;
				for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++)
					;
				if (len + ruleChars.length > EMPHMODECHARSSIZE) {
					compileError(file, ""More than %d characters"", EMPHMODECHARSSIZE);
					break;
				}
				ok = 1;
				for (int k = 0; k < ruleChars.length; k++) {
					if (!getChar(ruleChars.chars[k], *table, NULL)) {
						compileError(file, ""Emphasis mode character undefined"");
						ok = 0;
						break;
					}
					emphmodechars[len++] = ruleChars.chars[k];
				}
				break;
			}
			case CTO_NoEmphChars: {
				if (!getRuleCharsText(file, &ruleChars)) break;
				widechar *noemphchars = (*table)->noEmphChars[i];
				int len;
				for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++)
					;
				if (len + ruleChars.length > NOEMPHCHARSSIZE) {
					compileError(file, ""More than %d characters"", NOEMPHCHARSSIZE);
					break;
				}
				ok = 1;
				for (int k = 0; k < ruleChars.length; k++) {
					if (!getChar(ruleChars.chars[k], *table, NULL)) {
						compileError(file, ""Character undefined"");
						ok = 0;
						break;
					}
					noemphchars[len++] = ruleChars.chars[k];
				}
				break;
			}
			default:
				break;
			}
			free(s);
			return ok;
		}
		case CTO_LetterSign: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->letterSign;
			if (!compileBrailleIndicator(file, ""letter sign"", CTO_LetterRule, &ruleOffset,
						noback, nofor, table))
				return 0;
			(*table)->letterSign = ruleOffset;
			return 1;
		}
		case CTO_NoLetsignBefore:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) {
				compileError(file, ""More than %d characters"", LETSIGNBEFORESIZE);
				return 0;
			}
			for (int k = 0; k < ruleChars.length; k++)
				(*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] =
						ruleChars.chars[k];
			return 1;
		case CTO_NoLetsign:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) {
				compileError(file, ""More than %d characters"", LETSIGNSIZE);
				return 0;
			}
			for (int k = 0; k < ruleChars.length; k++)
				(*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k];
			return 1;
		case CTO_NoLetsignAfter:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) {
				compileError(file, ""More than %d characters"", LETSIGNAFTERSIZE);
				return 0;
			}
			for (int k = 0; k < ruleChars.length; k++)
				(*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] =
						ruleChars.chars[k];
			return 1;
		case CTO_NumberSign: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->numberSign;
			if (!compileBrailleIndicator(file, ""number sign"", CTO_NumberRule, &ruleOffset,
						noback, nofor, table))
				return 0;
			(*table)->numberSign = ruleOffset;
			return 1;
		}

		case CTO_NumericModeChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Numeric mode character undefined: %s"",
							_lou_showString(&ruleChars.chars[k], 1, 0));
					return 0;
				}
				c->attributes |= CTC_NumericMode;
				(*table)->usesNumericMode = 1;
			}
			return 1;

		case CTO_MidEndNumericModeChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Midendnumeric mode character undefined"");
					return 0;
				}
				c->attributes |= CTC_MidEndNumericMode;
				(*table)->usesNumericMode = 1;
			}
			return 1;

		case CTO_NumericNoContractChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Numeric no contraction character undefined"");
					return 0;
				}
				c->attributes |= CTC_NumericNoContract;
				(*table)->usesNumericMode = 1;
			}
			return 1;

		case CTO_NoContractSign: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->noContractSign;
			if (!compileBrailleIndicator(file, ""no contractions sign"", CTO_NoContractRule,
						&ruleOffset, noback, nofor, table))
				return 0;
			(*table)->noContractSign = ruleOffset;
			return 1;
		}
		case CTO_SeqDelimiter:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Sequence delimiter character undefined"");
					return 0;
				}
				c->attributes |= CTC_SeqDelimiter;
				(*table)->usesSequences = 1;
			}
			return 1;

		case CTO_SeqBeforeChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Sequence before character undefined"");
					return 0;
				}
				c->attributes |= CTC_SeqBefore;
			}
			return 1;

		case CTO_SeqAfterChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Sequence after character undefined"");
					return 0;
				}
				c->attributes |= CTC_SeqAfter;
			}
			return 1;

		case CTO_SeqAfterPattern:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) {
				compileError(file, ""More than %d characters"", SEQPATTERNSIZE);
				return 0;
			}
			for (int k = 0; k < ruleChars.length; k++)
				(*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k];
			(*table)->seqPatterns[(*table)->seqPatternsCount++] = 0;
			return 1;

		case CTO_SeqAfterExpression:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for ((*table)->seqAfterExpressionLength = 0;
					(*table)->seqAfterExpressionLength < ruleChars.length;
					(*table)->seqAfterExpressionLength++)
				(*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] =
						ruleChars.chars[(*table)->seqAfterExpressionLength];
			(*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = 0;
			return 1;

		case CTO_CapsModeChars:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!c) {
					compileError(file, ""Capital mode character undefined"");
					return 0;
				}
				c->attributes |= CTC_CapsMode;
				(*table)->hasCapsModeChars = 1;
			}
			return 1;

		case CTO_BegComp: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->begComp;
			if (!compileBrailleIndicator(file, ""begin computer braille"", CTO_BegCompRule,
						&ruleOffset, noback, nofor, table))
				return 0;
			(*table)->begComp = ruleOffset;
			return 1;
		}
		case CTO_EndComp: {
			// not passing pointer because compileBrailleIndicator may reallocate table
			TranslationTableOffset ruleOffset = (*table)->endComp;
			if (!compileBrailleIndicator(file, ""end computer braslle"", CTO_EndCompRule,
						&ruleOffset, noback, nofor, table))
				return 0;
			(*table)->endComp = ruleOffset;
			return 1;
		}
		case CTO_NoCross:
			if (nocross) {
				compileError(
						file, ""%s already specified."", _lou_findOpcodeName(CTO_NoCross));
				return 0;
			}
			nocross = 1;
			goto doOpcode;
		case CTO_Syllable:
			(*table)->syllables = 1;
		case CTO_Always:
		case CTO_LargeSign:
		case CTO_WholeWord:
		case CTO_PartWord:
		case CTO_JoinNum:
		case CTO_JoinableWord:
		case CTO_LowWord:
		case CTO_SuffixableWord:
		case CTO_PrefixableWord:
		case CTO_BegWord:
		case CTO_BegMidWord:
		case CTO_MidWord:
		case CTO_MidEndWord:
		case CTO_EndWord:
		case CTO_PrePunc:
		case CTO_PostPunc:
		case CTO_BegNum:
		case CTO_MidNum:
		case CTO_EndNum:
		case CTO_Repeated:
		case CTO_RepWord:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (!getRuleDotsPattern(file, &ruleDots)) return 0;
			if (ruleDots.length == 0)
				// check that all characters in a rule with `=` as second operand are
				// defined (or based on another character)
				for (int k = 0; k < ruleChars.length; k++) {
					TranslationTableCharacter *c =
							getChar(ruleChars.chars[k], *table, NULL);
					if (!(c && (c->definitionRule || c->basechar))) {
						compileError(file, ""Character %s is not defined"",
								_lou_showString(&ruleChars.chars[k], 1, 0));
						return 0;
					}
				}
			TranslationTableRule *r;
			if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r,
						noback, nofor, table))
				return 0;
			if (nocross) r->nocross = 1;
			return 1;
			// if (opcode == CTO_MidNum)
			// {
			//   TranslationTableCharacter *c = getChar(ruleChars.chars[0]);
			//   if(c)
			//     c->attributes |= CTC_NumericMode;
			// }
		case CTO_RepEndWord:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			CharsString dots;
			if (!getToken(file, &dots, ""dots,dots operand"")) return 0;
			int len = dots.length;
			for (int k = 0; k < len - 1; k++) {
				if (dots.chars[k] == ',') {
					dots.length = k;
					if (!parseDots(file, &ruleDots, &dots)) return 0;
					ruleDots.chars[ruleDots.length++] = ',';
					k++;
					if (k == len - 1 && dots.chars[k] == '=') {
						// check that all characters are defined (or based on another
						// character)
						for (int l = 0; l < ruleChars.length; l++) {
							TranslationTableCharacter *c =
									getChar(ruleChars.chars[l], *table, NULL);
							if (!(c && (c->definitionRule || c->basechar))) {
								compileError(file, ""Character %s is not defined"",
										_lou_showString(&ruleChars.chars[l], 1, 0));
								return 0;
							}
						}
					} else {
						CharsString x, y;
						x.length = 0;
						while (k < len) x.chars[x.length++] = dots.chars[k++];
						if (parseDots(file, &y, &x))
							for (int l = 0; l < y.length; l++)
								ruleDots.chars[ruleDots.length++] = y.chars[l];
					}
					return addRule(file, opcode, &ruleChars, &ruleDots, after, before,
							NULL, NULL, noback, nofor, table);
				}
			}
			return 0;
		case CTO_CompDots:
		case CTO_Comp6: {
			TranslationTableOffset ruleOffset;
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (ruleChars.length != 1) {
				compileError(file, ""first operand must be 1 character"");
				return 0;
			}
			if (nofor || noback) {
				compileWarning(file, ""nofor and noback not allowed on comp6 rules"");
			}
			if (!getRuleDotsPattern(file, &ruleDots)) return 0;
			if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset,
						NULL, noback, nofor, table))
				return 0;
			return 1;
		}
		case CTO_ExactDots:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (ruleChars.chars[0] != '@') {
				compileError(file, ""The operand must begin with an at sign (@)"");
				return 0;
			}
			for (int k = 1; k < ruleChars.length; k++)
				scratchPad.chars[k - 1] = ruleChars.chars[k];
			scratchPad.length = ruleChars.length - 1;
			if (!parseDots(file, &ruleDots, &scratchPad)) return 0;
			return addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL,
					noback, nofor, table);
		case CTO_CapsNoCont: {
			TranslationTableOffset ruleOffset;
			ruleChars.length = 1;
			ruleChars.chars[0] = 'a';
			if (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before,
						&ruleOffset, NULL, noback, nofor, table))
				return 0;
			(*table)->capsNoCont = ruleOffset;
			return 1;
		}
		case CTO_Replace:
			if (getRuleCharsText(file, &ruleChars)) {
				if (atEndOfLine(file))
					ruleDots.length = ruleDots.chars[0] = 0;
				else {
					getRuleDotsText(file, &ruleDots);
					if (ruleDots.chars[0] == '#')
						ruleDots.length = ruleDots.chars[0] = 0;
					else if (ruleDots.chars[0] == '\\' && ruleDots.chars[1] == '#')
						memmove(&ruleDots.chars[0], &ruleDots.chars[1],
								ruleDots.length-- * CHARSIZE);
				}
			}
			for (int k = 0; k < ruleChars.length; k++)
				putChar(file, ruleChars.chars[k], table, NULL);
			for (int k = 0; k < ruleDots.length; k++)
				putChar(file, ruleDots.chars[k], table, NULL);
			return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,
					noback, nofor, table);
		case CTO_Correct:
			(*table)->corrections = 1;
			goto doPass;
		case CTO_Pass2:
			if ((*table)->numPasses < 2) (*table)->numPasses = 2;
			goto doPass;
		case CTO_Pass3:
			if ((*table)->numPasses < 3) (*table)->numPasses = 3;
			goto doPass;
		case CTO_Pass4:
			if ((*table)->numPasses < 4) (*table)->numPasses = 4;
		doPass:
		case CTO_Context:
			if (!(nofor || noback)) {
				compileError(file, ""%s or %s must be specified."",
						_lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack));
				return 0;
			}
			return compilePassOpcode(file, opcode, noback, nofor, table);
		case CTO_Contraction:
		case CTO_NoCont:
		case CTO_CompBrl:
		case CTO_Literal:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			// check that all characters in a compbrl, contraction,
			// nocont or literal rule are defined (or based on another
			// character)
			for (int k = 0; k < ruleChars.length; k++) {
				TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL);
				if (!(c && (c->definitionRule || c->basechar))) {
					compileError(file, ""Character %s is not defined"",
							_lou_showString(&ruleChars.chars[k], 1, 0));
					return 0;
				}
			}
			return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL,
					noback, nofor, table);
		case CTO_MultInd: {
			ruleChars.length = 0;
			if (!getToken(file, &token, ""multiple braille indicators"") ||
					!parseDots(file, &cells, &token))
				return 0;
			while (getToken(file, &token, ""multind opcodes"")) {
				opcode = getOpcode(file, &token);
				if (opcode == CTO_None) {
					compileError(file, ""opcode %s not defined."",
							_lou_showString(token.chars, token.length, 0));
					return 0;
				}
				if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) {
					compileError(file, ""Not a braille indicator opcode."");
					return 0;
				}
				ruleChars.chars[ruleChars.length++] = (widechar)opcode;
				if (atEndOfLine(file)) break;
			}
			return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL,
					NULL, noback, nofor, table);
		}

		case CTO_Class:
			compileWarning(file, ""class is deprecated, use attribute instead"");
		case CTO_Attribute: {
			if (nofor || noback) {
				compileWarning(
						file, ""nofor and noback not allowed before class/attribute"");
			}
			if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) ||
					(opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) {
				compileError(file,
						""attribute and class rules must not be both present in a table"");
				return 0;
			}
			if (opcode == CTO_Class)
				(*table)->usesAttributeOrClass = 2;
			else
				(*table)->usesAttributeOrClass = 1;
			if (!getToken(file, &token, ""attribute name"")) {
				compileError(file, ""Expected %s"", ""attribute name"");
				return 0;
			}
			if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
				return 0;
			}

			TranslationTableCharacterAttributes attribute = 0;
			{
				int attrNumber = -1;
				switch (token.chars[0]) {
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					attrNumber = token.chars[0] - '0';
					break;
				}
				if (attrNumber >= 0) {
					if (opcode == CTO_Class) {
						compileError(file,
								""Invalid class name: may not contain digits, use ""
								""attribute instead of class"");
						return 0;
					}
					if (token.length > 1 || attrNumber > 7) {
						compileError(file,
								""Invalid attribute name: must be a digit between 0 and 7 ""
								""or a word containing only letters"");
						return 0;
					}
					if (!(*table)->numberedAttributes[attrNumber])
						// attribute not used before yet: assign it a value
						(*table)->numberedAttributes[attrNumber] =
								getNextNumberedAttribute(*table);
					attribute = (*table)->numberedAttributes[attrNumber];
				} else {
					const CharacterClass *namedAttr = findCharacterClass(&token, *table);
					if (!namedAttr) {
						// no class with that name: create one
						namedAttr = addCharacterClass(
								file, &token.chars[0], token.length, *table, 1);
						if (!namedAttr) return 0;
					}
					// there is a class with that name or a new class was successfully
					// created
					attribute = namedAttr->attribute;
					if (attribute == CTC_UpperCase || attribute == CTC_LowerCase)
						attribute |= CTC_Letter;
				}
			}
			CharsString characters;
			if (!getCharacters(file, &characters)) return 0;
			for (int i = 0; i < characters.length; i++) {
				// get the character from the table, or if it is not defined yet,
				// define it
				TranslationTableCharacter *character =
						putChar(file, characters.chars[i], table, NULL);
				// set the attribute
				character->attributes |= attribute;
				// also set the attribute on the associated dots (if any)
				if (character->basechar)
					character = (TranslationTableCharacter *)&(*table)
										->ruleArea[character->basechar];
				if (character->definitionRule) {
					TranslationTableRule *defRule =
							(TranslationTableRule *)&(*table)
									->ruleArea[character->definitionRule];
					if (defRule->dotslen == 1) {
						TranslationTableCharacter *dots =
								getDots(defRule->charsdots[defRule->charslen], *table);
						if (dots) dots->attributes |= attribute;
					}
				}
			}
			return 1;
		}

			{
				TranslationTableCharacterAttributes *attributes;
				const CharacterClass *class;
			case CTO_After:
				attributes = &after;
				goto doBeforeAfter;
			case CTO_Before:
				attributes = &before;
			doBeforeAfter:
				if (!(*table)->characterClasses) {
					if (!allocateCharacterClasses(*table)) return 0;
				}
				if (!getToken(file, &token, ""attribute name"")) return 0;
				if (!(class = findCharacterClass(&token, *table))) {
					compileError(file, ""attribute not defined"");
					return 0;
				}
				*attributes |= class->attribute;
				goto doOpcode;
			}
		case CTO_Base:
			if (nofor || noback) {
				compileWarning(file, ""nofor and noback not allowed before base"");
			}
			if (!getToken(file, &token, ""attribute name"")) {
				compileError(
						file, ""base opcode must be followed by a valid attribute name."");
				return 0;
			}
			if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) {
				return 0;
			}
			const CharacterClass *mode = findCharacterClass(&token, *table);
			if (!mode) {
				mode = addCharacterClass(file, token.chars, token.length, *table, 1);
				if (!mode) return 0;
			}
			if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) &&
					mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) {
				compileError(file,
						""base opcode must be followed by \""uppercase\"", \""digit\"", or a ""
						""custom attribute name."");
				return 0;
			}
			if (!getRuleCharsText(file, &token)) return 0;
			if (token.length != 1) {
				compileError(file,
						""Exactly one character followed by one base character is ""
						""required."");
				return 0;
			}
			TranslationTableOffset characterOffset;
			TranslationTableCharacter *character =
					putChar(file, token.chars[0], table, &characterOffset);
			if (!getRuleCharsText(file, &token)) return 0;
			if (token.length != 1) {
				compileError(file, ""Exactly one base character is required."");
				return 0;
			}
			if (character->definitionRule) {
				TranslationTableRule *prevRule =
						(TranslationTableRule *)&(*table)
								->ruleArea[character->definitionRule];
				_lou_logMessage(LOU_LOG_DEBUG,
						""%s:%d: Character already defined (%s). The base rule will take ""
						""precedence."",
						file->fileName, file->lineNumber,
						printSource(file, prevRule->sourceFile, prevRule->sourceLine));
				character->definitionRule = 0;
			}
			TranslationTableOffset basechar;
			putChar(file, token.chars[0], table, &basechar);
			// putChar may have moved table, so make sure character is still valid
			character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset];
			if (character->basechar) {
				if (character->basechar == basechar &&
						character->mode == mode->attribute) {
					_lou_logMessage(LOU_LOG_DEBUG, ""%s:%d: Duplicate base rule."",
							file->fileName, file->lineNumber);
				} else {
					_lou_logMessage(LOU_LOG_DEBUG,
							""%s:%d: A different base rule already exists for this ""
							""character (%s). The new rule will take precedence."",
							file->fileName, file->lineNumber,
							printSource(
									file, character->sourceFile, character->sourceLine));
				}
			}
			character->basechar = basechar;
			character->mode = mode->attribute;
			character->sourceFile = file->sourceFile;
			character->sourceLine = file->lineNumber;
			/* some other processing is done at the end of the compilation, in
			 * finalizeTable() */
			return 1;
		case CTO_EmpMatchBefore:
			before |= CTC_EmpMatch;
			goto doOpcode;
		case CTO_EmpMatchAfter:
			after |= CTC_EmpMatch;
			goto doOpcode;

		case CTO_SwapCc:
		case CTO_SwapCd:
		case CTO_SwapDd:
			return compileSwap(file, opcode, noback, nofor, table);
		case CTO_Hyphen:
		case CTO_DecPoint:
			//	case CTO_Apostrophe:
			//	case CTO_Initial:
			if (!getRuleCharsText(file, &ruleChars)) return 0;
			if (!getRuleDotsPattern(file, &ruleDots)) return 0;
			if (ruleChars.length != 1 || ruleDots.length < 1) {
				compileError(file,
						""One Unicode character and at least one cell are ""
						""required."");
				return 0;
			}
			return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL,
					noback, nofor, table);
			// if (opcode == CTO_DecPoint)
			// {
			//   TranslationTableCharacter *c =
			//   getChar(ruleChars.chars[0]);
			//   if(c)
			//     c->attributes |= CTC_NumericMode;
			// }
		default:
			compileError(file, ""unimplemented opcode."");
			return 0;
		}
	}
	return 0;
}",CWE-787,16
0,"WifiNetwork::WifiNetwork()
    : WirelessNetwork(),
      encryption_(SECURITY_NONE) {
  type_ = TYPE_WIFI;
}
",none,24
1,"static int io_read(struct io_kiocb *req, unsigned int issue_flags)
{
	struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
	struct kiocb *kiocb = &req->rw.kiocb;
	struct iov_iter __iter, *iter = &__iter;
	struct io_async_rw *rw = req->async_data;
	ssize_t io_size, ret, ret2;
	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;

	if (rw) {
		iter = &rw->iter;
		iovec = NULL;
	} else {
		ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
		if (ret < 0)
			return ret;
	}
	io_size = iov_iter_count(iter);
	req->result = io_size;

	/* Ensure we clear previously set non-block flag */
	if (!force_nonblock)
		kiocb->ki_flags &= ~IOCB_NOWAIT;
	else
		kiocb->ki_flags |= IOCB_NOWAIT;

	/* If the file doesn't support async, just async punt */
	if (force_nonblock && !io_file_supports_async(req, READ)) {
		ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
		return ret ?: -EAGAIN;
	}

	ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
	if (unlikely(ret)) {
		kfree(iovec);
		return ret;
	}

	ret = io_iter_do_read(req, iter);

	if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
		req->flags &= ~REQ_F_REISSUE;
		/* IOPOLL retry should happen for io-wq threads */
		if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
			goto done;
		/* no retry on NONBLOCK nor RWF_NOWAIT */
		if (req->flags & REQ_F_NOWAIT)
			goto done;
		/* some cases will consume bytes even on error returns */
		iov_iter_revert(iter, io_size - iov_iter_count(iter));
		ret = 0;
	} else if (ret == -EIOCBQUEUED) {
		goto out_free;
	} else if (ret <= 0 || ret == io_size || !force_nonblock ||
		   (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
		/* read all, failed, already did sync or don't want to retry */
		goto done;
	}

	ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
	if (ret2)
		return ret2;

	iovec = NULL;
	rw = req->async_data;
	/* now use our persistent iterator, if we aren't already */
	iter = &rw->iter;

	do {
		io_size -= ret;
		rw->bytes_done += ret;
		/* if we can retry, do so with the callbacks armed */
		if (!io_rw_should_retry(req)) {
			kiocb->ki_flags &= ~IOCB_WAITQ;
			return -EAGAIN;
		}

		/*
		 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
		 * we get -EIOCBQUEUED, then we'll get a notification when the
		 * desired page gets unlocked. We can also get a partial read
		 * here, and if we do, then just retry at the new offset.
		 */
		ret = io_iter_do_read(req, iter);
		if (ret == -EIOCBQUEUED)
			return 0;
		/* we got some bytes, but not all. retry. */
		kiocb->ki_flags &= ~IOCB_WAITQ;
	} while (ret > 0 && ret < io_size);
done:
	kiocb_done(kiocb, ret, issue_flags);
out_free:
	/* it's faster to check here then delegate to kfree */
	if (iovec)
		kfree(iovec);
	return 0;
}",CWE-125,1
1,"gif_internal_decode_frame(gif_animation *gif,
                          unsigned int frame,
                          bool clear_image)
{
        unsigned int index = 0;
        const unsigned char *gif_data, *gif_end;
        ssize_t gif_bytes;
        unsigned int width, height, offset_x, offset_y;
        unsigned int flags, colour_table_size, interlace;
        unsigned int *colour_table;
        unsigned int *frame_data = 0;	// Set to 0 for no warnings
        unsigned int *frame_scanline;
        ssize_t save_buffer_position;
        unsigned int return_value = 0;
        unsigned int x, y, decode_y, burst_bytes;
        register unsigned char colour;

        /* Ensure this frame is supposed to be decoded */
        if (gif->frames[frame].display == false) {
                return GIF_OK;
        }

        /* Ensure the frame is in range to decode */
        if (frame > gif->frame_count_partial) {
                return GIF_INSUFFICIENT_DATA;
        }

        /* done if frame is already decoded */
        if ((!clear_image) &&
            ((int)frame == gif->decoded_frame)) {
                return GIF_OK;
        }

        /* Get the start of our frame data and the end of the GIF data */
        gif_data = gif->gif_data + gif->frames[frame].frame_pointer;
        gif_end = gif->gif_data + gif->buffer_size;
        gif_bytes = (gif_end - gif_data);

        /*
         * Ensure there is a minimal amount of data to proceed.  The shortest
         * block of data is a 10-byte image descriptor + 1-byte gif trailer
         */
        if (gif_bytes < 12) {
                return GIF_INSUFFICIENT_FRAME_DATA;
        }

        /* Save the buffer position */
        save_buffer_position = gif->buffer_position;
        gif->buffer_position = gif_data - gif->gif_data;

        /* Skip any extensions because they have allready been processed */
        if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {
                goto gif_decode_frame_exit;
        }
        gif_data = (gif->gif_data + gif->buffer_position);
        gif_bytes = (gif_end - gif_data);

        /* Ensure we have enough data for the 10-byte image descriptor + 1-byte
         * gif trailer
         */
        if (gif_bytes < 12) {
                return_value = GIF_INSUFFICIENT_FRAME_DATA;
                goto gif_decode_frame_exit;
        }

        /* 10-byte Image Descriptor is:
         *
         *	+0	CHAR	Image Separator (0x2c)
         *	+1	SHORT	Image Left Position
         *	+3	SHORT	Image Top Position
         *	+5	SHORT	Width
         *	+7	SHORT	Height
         *	+9	CHAR	__Packed Fields__
         *			1BIT	Local Colour Table Flag
         *			1BIT	Interlace Flag
         *			1BIT	Sort Flag
         *			2BITS	Reserved
         *			3BITS	Size of Local Colour Table
         */
        if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
                return_value = GIF_DATA_ERROR;
                goto gif_decode_frame_exit;
        }
        offset_x = gif_data[1] | (gif_data[2] << 8);
        offset_y = gif_data[3] | (gif_data[4] << 8);
        width = gif_data[5] | (gif_data[6] << 8);
        height = gif_data[7] | (gif_data[8] << 8);

        /* Boundary checking - shouldn't ever happen except unless the data has
         * been modified since initialisation.
         */
        if ((offset_x + width > gif->width) ||
            (offset_y + height > gif->height)) {
                return_value = GIF_DATA_ERROR;
                goto gif_decode_frame_exit;
        }

        /* Decode the flags */
        flags = gif_data[9];
        colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
        interlace = flags & GIF_INTERLACE_MASK;

        /* Advance data pointer to next block either colour table or image
         * data.
         */
        gif_data += 10;
        gif_bytes = (gif_end - gif_data);

        /* Set up the colour table */
        if (flags & GIF_COLOUR_TABLE_MASK) {
                if (gif_bytes < (int)(3 * colour_table_size)) {
                        return_value = GIF_INSUFFICIENT_FRAME_DATA;
                        goto gif_decode_frame_exit;
                }
                colour_table = gif->local_colour_table;
                if (!clear_image) {
                        for (index = 0; index < colour_table_size; index++) {
                                /* Gif colour map contents are r,g,b.
                                 *
                                 * We want to pack them bytewise into the
                                 * colour table, such that the red component
                                 * is in byte 0 and the alpha component is in
                                 * byte 3.
                                 */
                                unsigned char *entry =
                                        (unsigned char *) &colour_table[index];

                                entry[0] = gif_data[0];	/* r */
                                entry[1] = gif_data[1];	/* g */
                                entry[2] = gif_data[2];	/* b */
                                entry[3] = 0xff;	/* a */

                                gif_data += 3;
                        }
                } else {
                        gif_data += 3 * colour_table_size;
                }
                gif_bytes = (gif_end - gif_data);
        } else {
                colour_table = gif->global_colour_table;
        }

        /* Ensure sufficient data remains */
        if (gif_bytes < 1) {
                return_value = GIF_INSUFFICIENT_FRAME_DATA;
                goto gif_decode_frame_exit;
        }

        /* check for an end marker */
        if (gif_data[0] == GIF_TRAILER) {
                return_value = GIF_OK;
                goto gif_decode_frame_exit;
        }

        /* Get the frame data */
        assert(gif->bitmap_callbacks.bitmap_get_buffer);
        frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
        if (!frame_data) {
                return GIF_INSUFFICIENT_MEMORY;
        }

        /* If we are clearing the image we just clear, if not decode */
        if (!clear_image) {
                lzw_result res;
                const uint8_t *stack_base;
                const uint8_t *stack_pos;

                /* Ensure we have enough data for a 1-byte LZW code size +
                 * 1-byte gif trailer
                 */
                if (gif_bytes < 2) {
                        return_value = GIF_INSUFFICIENT_FRAME_DATA;
                        goto gif_decode_frame_exit;
                }

                /* If we only have a 1-byte LZW code size + 1-byte gif trailer,
                 * we're finished
                 */
                if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {
                        return_value = GIF_OK;
                        goto gif_decode_frame_exit;
                }

                /* If the previous frame's disposal method requires we restore
                 * the background colour or this is the first frame, clear
                 * the frame data
                 */
                if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {
                        memset((char*)frame_data,
                               GIF_TRANSPARENT_COLOUR,
                               gif->width * gif->height * sizeof(int));
                        gif->decoded_frame = frame;
                        /* The line below would fill the image with its
                         * background color, but because GIFs support
                         * transparency we likely wouldn't want to do that. */
                        /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */
                } else if ((frame != 0) &&
                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {
                        return_value = gif_internal_decode_frame(gif,
                                                                 (frame - 1),
                                                                 true);
                        if (return_value != GIF_OK) {
                                goto gif_decode_frame_exit;
                        }

                } else if ((frame != 0) &&
                           (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {
                        /*
                         * If the previous frame's disposal method requires we
                         * restore the previous image, find the last image set
                         * to ""do not dispose"" and get that frame data
                         */
                        int last_undisposed_frame = frame - 2;
                        while ((last_undisposed_frame >= 0) &&
                               (gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) {
                                last_undisposed_frame--;
                        }

                        /* If we don't find one, clear the frame data */
                        if (last_undisposed_frame == -1) {
                                /* see notes above on transparency
                                 * vs. background color
                                 */
                                memset((char*)frame_data,
                                       GIF_TRANSPARENT_COLOUR,
                                       gif->width * gif->height * sizeof(int));
                        } else {
                                return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false);
                                if (return_value != GIF_OK) {
                                        goto gif_decode_frame_exit;
                                }
                                /* Get this frame's data */
                                assert(gif->bitmap_callbacks.bitmap_get_buffer);
                                frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
                                if (!frame_data) {
                                        return GIF_INSUFFICIENT_MEMORY;
                                }
                        }
                }
                gif->decoded_frame = frame;
                gif->buffer_position = (gif_data - gif->gif_data) + 1;

                /* Initialise the LZW decoding */
                res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,
                                gif->buffer_size, gif->buffer_position,
                                gif_data[0], &stack_base, &stack_pos);
                if (res != LZW_OK) {
                        return gif_error_from_lzw(res);
                }

                /* Decompress the data */
                for (y = 0; y < height; y++) {
                        if (interlace) {
                                decode_y = gif_interlaced_line(height, y) + offset_y;
                        } else {
                                decode_y = y + offset_y;
                        }
                        frame_scanline = frame_data + offset_x + (decode_y * gif->width);

                        /* Rather than decoding pixel by pixel, we try to burst
                         * out streams of data to remove the need for end-of
                         * data checks every pixel.
                         */
                        x = width;
                        while (x > 0) {
                                burst_bytes = (stack_pos - stack_base);
                                if (burst_bytes > 0) {
                                        if (burst_bytes > x) {
                                                burst_bytes = x;
                                        }
                                        x -= burst_bytes;
                                        while (burst_bytes-- > 0) {
                                                colour = *--stack_pos;
                                                if (((gif->frames[frame].transparency) &&
                                                     (colour != gif->frames[frame].transparency_index)) ||
                                                    (!gif->frames[frame].transparency)) {
                                                        *frame_scanline = colour_table[colour];
                                                }
                                                frame_scanline++;
                                        }
                                } else {
                                        res = lzw_decode(gif->lzw_ctx, &stack_pos);
                                        if (res != LZW_OK) {
                                                /* Unexpected end of frame, try to recover */
                                                if (res == LZW_OK_EOD) {
                                                        return_value = GIF_OK;
                                                } else {
                                                        return_value = gif_error_from_lzw(res);
                                                }
                                                goto gif_decode_frame_exit;
                                        }
                                }
                        }
                }
        } else {
                /* Clear our frame */
                if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {
                        for (y = 0; y < height; y++) {
                                frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);
                                if (gif->frames[frame].transparency) {
                                        memset(frame_scanline,
                                               GIF_TRANSPARENT_COLOUR,
                                               width * 4);
                                } else {
                                        memset(frame_scanline,
                                               colour_table[gif->background_index],
                                               width * 4);
                                }
                        }
                }
        }
gif_decode_frame_exit:

        /* Check if we should test for optimisation */
        if (gif->frames[frame].virgin) {
                if (gif->bitmap_callbacks.bitmap_test_opaque) {
                        gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);
                } else {
                        gif->frames[frame].opaque = false;
                }
                gif->frames[frame].virgin = false;
        }

        if (gif->bitmap_callbacks.bitmap_set_opaque) {
                gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);
        }

        if (gif->bitmap_callbacks.bitmap_modified) {
                gif->bitmap_callbacks.bitmap_modified(gif->frame_image);
        }

        /* Restore the buffer position */
        gif->buffer_position = save_buffer_position;

        return return_value;
}",CWE-476,12
0,"  int64 global_unlimited_usage() const { return global_unlimited_usage_; }
",none,24
1,"process_button(struct parsed_tag *tag)
{
    Str tmp = NULL;
    char *p, *q, *r, *qq = """";
    int qlen, v;

    if (cur_form_id < 0) {
       char *s = """";
       tmp = process_form(parse_tag(&s, TRUE));
    }
    if (tmp == NULL)
       tmp = Strnew();

    p = ""submit"";
    parsedtag_get_value(tag, ATTR_TYPE, &p);
    q = NULL;
    parsedtag_get_value(tag, ATTR_VALUE, &q);
    r = """";
    parsedtag_get_value(tag, ATTR_NAME, &r);

    v = formtype(p);
    if (v == FORM_UNKNOWN)
       return NULL;

    if (!q) {
       switch (v) {
       case FORM_INPUT_SUBMIT:
       case FORM_INPUT_BUTTON:
           q = ""SUBMIT"";
           break;
       case FORM_INPUT_RESET:
           q = ""RESET"";
           break;
       }
    }
    if (q) {
       qq = html_quote(q);
       qlen = strlen(q);
    }

    /*    Strcat_charp(tmp, """"); */
    Strcat(tmp, Sprintf("""",
                       cur_hseq++, cur_form_id, html_quote(p),
                       html_quote(r), qq));
    return tmp;
}",CWE-119,0
1,"ins_bs(
    int		c,
    int		mode,
    int		*inserted_space_p)
{
    linenr_T	lnum;
    int		cc;
    int		temp = 0;	    // init for GCC
    colnr_T	save_col;
    colnr_T	mincol;
    int		did_backspace = FALSE;
    int		in_indent;
    int		oldState;
    int		cpc[MAX_MCO];	    // composing characters
    int		call_fix_indent = FALSE;

    /*
     * can't delete anything in an empty file
     * can't backup past first character in buffer
     * can't backup past starting point unless 'backspace' > 1
     * can backup to a previous line if 'backspace' == 0
     */
    if (       BUFEMPTY()
	    || (
#ifdef FEAT_RIGHTLEFT
		!revins_on &&
#endif
		((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
		    || (!can_bs(BS_START)
			&& ((arrow_used
#ifdef FEAT_JOB_CHANNEL
				&& !bt_prompt(curbuf)
#endif
			) || (curwin->w_cursor.lnum == Insstart_orig.lnum
				&& curwin->w_cursor.col <= Insstart_orig.col)))
		    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
					 && curwin->w_cursor.col <= ai_col)
		    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
    {
	vim_beep(BO_BS);
	return FALSE;
    }

    if (stop_arrow() == FAIL)
	return FALSE;
    in_indent = inindent(0);
    if (in_indent)
	can_cindent = FALSE;
    end_comment_pending = NUL;	// After BS, don't auto-end comment
#ifdef FEAT_RIGHTLEFT
    if (revins_on)	    // put cursor after last inserted char
	inc_cursor();
#endif

    // Virtualedit:
    //	BACKSPACE_CHAR eats a virtual space
    //	BACKSPACE_WORD eats all coladd
    //	BACKSPACE_LINE eats all coladd and keeps going
    if (curwin->w_cursor.coladd > 0)
    {
	if (mode == BACKSPACE_CHAR)
	{
	    --curwin->w_cursor.coladd;
	    return TRUE;
	}
	if (mode == BACKSPACE_WORD)
	{
	    curwin->w_cursor.coladd = 0;
	    return TRUE;
	}
	curwin->w_cursor.coladd = 0;
    }

    /*
     * Delete newline!
     */
    if (curwin->w_cursor.col == 0)
    {
	lnum = Insstart.lnum;
	if (curwin->w_cursor.lnum == lnum
#ifdef FEAT_RIGHTLEFT
			|| revins_on
#endif
				    )
	{
	    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
			       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
		return FALSE;
	    --Insstart.lnum;
	    Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));
	}
	/*
	 * In replace mode:
	 * cc < 0: NL was inserted, delete it
	 * cc >= 0: NL was replaced, put original characters back
	 */
	cc = -1;
	if (State & REPLACE_FLAG)
	    cc = replace_pop();	    // returns -1 if NL was inserted
	/*
	 * In replace mode, in the line we started replacing, we only move the
	 * cursor.
	 */
	if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
	{
	    dec_cursor();
	}
	else
	{
	    if (!(State & VREPLACE_FLAG)
				   || curwin->w_cursor.lnum > orig_line_count)
	    {
		temp = gchar_cursor();	// remember current char
		--curwin->w_cursor.lnum;

		// When ""aw"" is in 'formatoptions' we must delete the space at
		// the end of the line, otherwise the line will be broken
		// again when auto-formatting.
		if (has_format_option(FO_AUTO)
					   && has_format_option(FO_WHITE_PAR))
		{
		    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
									TRUE);
		    int	    len;

		    len = (int)STRLEN(ptr);
		    if (len > 0 && ptr[len - 1] == ' ')
			ptr[len - 1] = NUL;
		}

		(void)do_join(2, FALSE, FALSE, FALSE, FALSE);
		if (temp == NUL && gchar_cursor() != NUL)
		    inc_cursor();
	    }
	    else
		dec_cursor();

	    /*
	     * In MODE_REPLACE mode we have to put back the text that was
	     * replaced by the NL. On the replace stack is first a
	     * NUL-terminated sequence of characters that were deleted and then
	     * the characters that NL replaced.
	     */
	    if (State & REPLACE_FLAG)
	    {
		/*
		 * Do the next ins_char() in MODE_NORMAL state, to
		 * prevent ins_char() from replacing characters and
		 * avoiding showmatch().
		 */
		oldState = State;
		State = MODE_NORMAL;
		/*
		 * restore characters (blanks) deleted after cursor
		 */
		while (cc > 0)
		{
		    save_col = curwin->w_cursor.col;
		    mb_replace_pop_ins(cc);
		    curwin->w_cursor.col = save_col;
		    cc = replace_pop();
		}
		// restore the characters that NL replaced
		replace_pop_ins();
		State = oldState;
	    }
	}
	did_ai = FALSE;
    }
    else
    {
	/*
	 * Delete character(s) before the cursor.
	 */
#ifdef FEAT_RIGHTLEFT
	if (revins_on)		// put cursor on last inserted char
	    dec_cursor();
#endif
	mincol = 0;
						// keep indent
	if (mode == BACKSPACE_LINE
		&& (curbuf->b_p_ai || cindent_on())
#ifdef FEAT_RIGHTLEFT
		&& !revins_on
#endif
			    )
	{
	    save_col = curwin->w_cursor.col;
	    beginline(BL_WHITE);
	    if (curwin->w_cursor.col < save_col)
	    {
		mincol = curwin->w_cursor.col;
		// should now fix the indent to match with the previous line
		call_fix_indent = TRUE;
	    }
	    curwin->w_cursor.col = save_col;
	}

	/*
	 * Handle deleting one 'shiftwidth' or 'softtabstop'.
	 */
	if (	   mode == BACKSPACE_CHAR
		&& ((p_sta && in_indent)
		    || ((get_sts_value() != 0
#ifdef FEAT_VARTABS
			|| tabstop_count(curbuf->b_p_vsts_array)
#endif
			)
			&& curwin->w_cursor.col > 0
			&& (*(ml_get_cursor() - 1) == TAB
			    || (*(ml_get_cursor() - 1) == ' '
				&& (!*inserted_space_p
				    || arrow_used))))))
	{
	    int		ts;
	    colnr_T	vcol;
	    colnr_T	want_vcol;
	    colnr_T	start_vcol;

	    *inserted_space_p = FALSE;
	    // Compute the virtual column where we want to be.  Since
	    // 'showbreak' may get in the way, need to get the last column of
	    // the previous character.
	    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
	    start_vcol = vcol;
	    dec_cursor();
	    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
	    inc_cursor();
#ifdef FEAT_VARTABS
	    if (p_sta && in_indent)
	    {
		ts = (int)get_sw_value(curbuf);
		want_vcol = (want_vcol / ts) * ts;
	    }
	    else
		want_vcol = tabstop_start(want_vcol, get_sts_value(),
						       curbuf->b_p_vsts_array);
#else
	    if (p_sta && in_indent)
		ts = (int)get_sw_value(curbuf);
	    else
		ts = (int)get_sts_value();
	    want_vcol = (want_vcol / ts) * ts;
#endif

	    // delete characters until we are at or before want_vcol
	    while (vcol > want_vcol
		    && (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))
		ins_bs_one(&vcol);

	    // insert extra spaces until we are at want_vcol
	    while (vcol < want_vcol)
	    {
		// Remember the first char we inserted
		if (curwin->w_cursor.lnum == Insstart_orig.lnum
				   && curwin->w_cursor.col < Insstart_orig.col)
		    Insstart_orig.col = curwin->w_cursor.col;

		if (State & VREPLACE_FLAG)
		    ins_char(' ');
		else
		{
		    ins_str((char_u *)"" "");
		    if ((State & REPLACE_FLAG))
			replace_push(NUL);
		}
		getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
	    }

	    // If we are now back where we started delete one character.  Can
	    // happen when using 'sts' and 'linebreak'.
	    if (vcol >= start_vcol)
		ins_bs_one(&vcol);
	}

	/*
	 * Delete up to starting point, start of line or previous word.
	 */
	else
	{
	    int cclass = 0, prev_cclass = 0;

	    if (has_mbyte)
		cclass = mb_get_class(ml_get_cursor());
	    do
	    {
#ifdef FEAT_RIGHTLEFT
		if (!revins_on) // put cursor on char to be deleted
#endif
		    dec_cursor();

		cc = gchar_cursor();
		// look multi-byte character class
		if (has_mbyte)
		{
		    prev_cclass = cclass;
		    cclass = mb_get_class(ml_get_cursor());
		}

		// start of word?
		if (mode == BACKSPACE_WORD && !vim_isspace(cc))
		{
		    mode = BACKSPACE_WORD_NOT_SPACE;
		    temp = vim_iswordc(cc);
		}
		// end of word?
		else if (mode == BACKSPACE_WORD_NOT_SPACE
			&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)
			|| prev_cclass != cclass))
		{
#ifdef FEAT_RIGHTLEFT
		    if (!revins_on)
#endif
			inc_cursor();
#ifdef FEAT_RIGHTLEFT
		    else if (State & REPLACE_FLAG)
			dec_cursor();
#endif
		    break;
		}
		if (State & REPLACE_FLAG)
		    replace_do_bs(-1);
		else
		{
		    if (enc_utf8 && p_deco)
			(void)utfc_ptr2char(ml_get_cursor(), cpc);
		    (void)del_char(FALSE);
		    /*
		     * If there are combining characters and 'delcombine' is set
		     * move the cursor back.  Don't back up before the base
		     * character.
		     */
		    if (enc_utf8 && p_deco && cpc[0] != NUL)
			inc_cursor();
#ifdef FEAT_RIGHTLEFT
		    if (revins_chars)
		    {
			revins_chars--;
			revins_legal++;
		    }
		    if (revins_on && gchar_cursor() == NUL)
			break;
#endif
		}
		// Just a single backspace?:
		if (mode == BACKSPACE_CHAR)
		    break;
	    } while (
#ifdef FEAT_RIGHTLEFT
		    revins_on ||
#endif
		    (curwin->w_cursor.col > mincol
		    &&  (can_bs(BS_NOSTOP)
			|| (curwin->w_cursor.lnum != Insstart_orig.lnum
			|| curwin->w_cursor.col != Insstart_orig.col)
		    )));
	}
	did_backspace = TRUE;
    }
    did_si = FALSE;
    can_si = FALSE;
    can_si_back = FALSE;
    if (curwin->w_cursor.col <= 1)
	did_ai = FALSE;

    if (call_fix_indent)
	fix_indent();

    /*
     * It's a little strange to put backspaces into the redo
     * buffer, but it makes auto-indent a lot easier to deal
     * with.
     */
    AppendCharToRedobuff(c);

    // If deleted before the insertion point, adjust it
    if (curwin->w_cursor.lnum == Insstart_orig.lnum
				  && curwin->w_cursor.col < Insstart_orig.col)
	Insstart_orig.col = curwin->w_cursor.col;

    // vi behaviour: the cursor moves backward but the character that
    //		     was there remains visible
    // Vim behaviour: the cursor moves backward and the character that
    //		      was there is erased from the screen.
    // We can emulate the vi behaviour by pretending there is a dollar
    // displayed even when there isn't.
    //  --pkv Sun Jan 19 01:56:40 EST 2003
    if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)
	dollar_vcol = curwin->w_virtcol;

#ifdef FEAT_FOLDING
    // When deleting a char the cursor line must never be in a closed fold.
    // E.g., when 'foldmethod' is indent and deleting the first non-white
    // char before a Tab.
    if (did_backspace)
	foldOpenCursor();
#endif

    return did_backspace;
}",CWE-787,16
1,"GF_Err BD_DecMFFieldVec(GF_BifsDecoder * codec, GF_BitStream *bs, GF_Node *node, GF_FieldInfo *field, Bool is_mem_com)
{
	GF_Err e;
	u32 NbBits, nbFields;
	u32 i;
	GF_ChildNodeItem *last;
	u8 qp_local, qp_on, initial_qp;
	GF_FieldInfo sffield;

	memset(&sffield, 0, sizeof(GF_FieldInfo));
	sffield.fieldIndex = field->fieldIndex;
	sffield.fieldType = gf_sg_vrml_get_sf_type(field->fieldType);
	sffield.NDTtype = field->NDTtype;
	sffield.name = field->name;

	initial_qp = qp_local = qp_on = 0;

	//vector description - alloc the MF size before
	NbBits = gf_bs_read_int(bs, 5);
	nbFields = gf_bs_read_int(bs, NbBits);

	if (codec->ActiveQP) {
		initial_qp = 1;
		/*this is for QP 14*/
		gf_bifs_dec_qp14_set_length(codec, nbFields);
	}

	if (field->fieldType != GF_SG_VRML_MFNODE) {
		e = gf_sg_vrml_mf_alloc(field->far_ptr, field->fieldType, nbFields);
		if (e) return e;

		for (i=0; ifar_ptr, field->fieldType, & sffield.far_ptr, i);
			if (e) return e;
			e = gf_bifs_dec_sf_field(codec, bs, node, &sffield, GF_FALSE);
			if (e) return e;
		}
	} else {
		last = NULL;
		for (i=0; iNDTtype);
			if (new_node) {
				e = gf_node_register(new_node, is_mem_com ? NULL : node);
				if (e) return e;

				if (node) {
					/*special case for QP, register as the current QP*/
					if (gf_node_get_tag(new_node) == TAG_MPEG4_QuantizationParameter) {
						qp_local = ((M_QuantizationParameter *)new_node)->isLocal;
						/*we have a QP in the same scope, remove previous
						NB: we assume this is the right behavior, the spec doesn't say
						whether QP is cumulative or not*/
						if (qp_on) gf_bifs_dec_qp_remove(codec, GF_FALSE);

						e = gf_bifs_dec_qp_set(codec, new_node);
						if (e) return e;
						qp_on = 1;
						if (qp_local) qp_local = 2;
						if (codec->force_keep_qp) {
							e = gf_node_list_add_child_last(field->far_ptr, new_node, &last);
							if (e) return e;
						} else {
							gf_node_register(new_node, NULL);
							gf_node_unregister(new_node, node);
						}
					} else {
						e = gf_node_list_add_child_last(field->far_ptr, new_node, &last);
						if (e) return e;
					}
				}
				/*proto coding*/
				else if (codec->pCurrentProto) {
					/*TO DO: what happens if this is a QP node on the interface ?*/
					e = gf_node_list_add_child_last( (GF_ChildNodeItem **)field->far_ptr, new_node, &last);
					if (e) return e;
				}
			} else {
				return codec->LastError ? codec->LastError : GF_NON_COMPLIANT_BITSTREAM;
			}
		}
		/*according to the spec, the QP applies to the current node itself, not just children.
		If IsLocal is TRUE remove the node*/
		if (qp_on && qp_local) {
			if (qp_local == 2) {
//				qp_local = 1;
			} else {
				//ask to get rid of QP and reactivate if we had a QP when entering the node
				gf_bifs_dec_qp_remove(codec, initial_qp);
//				qp_local = 0;
			}
		}
	}
	/*finally delete the QP if any (local or not) as we get out of this node*/
	if (qp_on) gf_bifs_dec_qp_remove(codec, GF_TRUE);
	return GF_OK;
}",CWE-416,10
1,"add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype)
{
	int rc = 0;
	uid_t uid;
	char *mount_user = NULL;
	struct mntent mountent;
	FILE *pmntfile;
	sigset_t mask, oldmask;

	uid = getuid();
	if (uid != 0)
		mount_user = getusername(uid);

	/*
	 * Set the real uid to the effective uid. This prevents unprivileged
	 * users from sending signals to this process, though ^c on controlling
	 * terminal should still work.
	 */
	rc = setreuid(geteuid(), -1);
	if (rc != 0) {
		fprintf(stderr, ""Unable to set real uid to effective uid: %s\n"",
				strerror(errno));
		return EX_FILEIO;
	}

	rc = sigfillset(&mask);
	if (rc) {
		fprintf(stderr, ""Unable to set filled signal mask\n"");
		return EX_FILEIO;
	}

	rc = sigprocmask(SIG_SETMASK, &mask, &oldmask);
	if (rc) {
		fprintf(stderr, ""Unable to make process ignore signals\n"");
		return EX_FILEIO;
	}

	rc = toggle_dac_capability(1, 1);
	if (rc)
		return EX_FILEIO;

	atexit(unlock_mtab);
	rc = lock_mtab();
	if (rc) {
		fprintf(stderr, ""cannot lock mtab"");
		rc = EX_FILEIO;
		goto add_mtab_exit;
	}

	pmntfile = setmntent(MOUNTED, ""a+"");
	if (!pmntfile) {
		fprintf(stderr, ""could not update mount table\n"");
		unlock_mtab();
		rc = EX_FILEIO;
		goto add_mtab_exit;
	}

	mountent.mnt_fsname = devname;
	mountent.mnt_dir = mountpoint;
	mountent.mnt_type = (char *)(void *)fstype;
	mountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1);
	if (mountent.mnt_opts) {
		if (flags & MS_RDONLY)
			strlcat(mountent.mnt_opts, ""ro"", MTAB_OPTIONS_LEN);
		else
			strlcat(mountent.mnt_opts, ""rw"", MTAB_OPTIONS_LEN);

		if (flags & MS_MANDLOCK)
			strlcat(mountent.mnt_opts, "",mand"", MTAB_OPTIONS_LEN);
		if (flags & MS_NOEXEC)
			strlcat(mountent.mnt_opts, "",noexec"", MTAB_OPTIONS_LEN);
		if (flags & MS_NOSUID)
			strlcat(mountent.mnt_opts, "",nosuid"", MTAB_OPTIONS_LEN);
		if (flags & MS_NODEV)
			strlcat(mountent.mnt_opts, "",nodev"", MTAB_OPTIONS_LEN);
		if (flags & MS_SYNCHRONOUS)
			strlcat(mountent.mnt_opts, "",sync"", MTAB_OPTIONS_LEN);
		if (mount_user) {
			strlcat(mountent.mnt_opts, "",user="", MTAB_OPTIONS_LEN);
			strlcat(mountent.mnt_opts, mount_user,
				MTAB_OPTIONS_LEN);
		}
	}
	mountent.mnt_freq = 0;
	mountent.mnt_passno = 0;
	rc = addmntent(pmntfile, &mountent);
	if (rc) {
		fprintf(stderr, ""unable to add mount entry to mtab\n"");
		rc = EX_FILEIO;
	}
	endmntent(pmntfile);
	unlock_mtab();
	SAFE_FREE(mountent.mnt_opts);
add_mtab_exit:
	toggle_dac_capability(1, 0);
	sigprocmask(SIG_SETMASK, &oldmask, NULL);

	return rc;
}",CWE-20,3
0,"  bool AddCallback(GetUsageAndQuotaCallback* callback, bool unlimited) {
    if (unlimited)
      unlimited_callbacks_.push_back(callback);
    else
      callbacks_.push_back(callback);
    return (callbacks_.size() + unlimited_callbacks_.size() == 1);
  }
",none,24
1,"stl_update_connects_remove_1(stl_file *stl, int facet_num) {
  int j;

  if (stl->error) return;
  /* Update list of connected edges */
  j = ((stl->neighbors_start[facet_num].neighbor[0] == -1) +
       (stl->neighbors_start[facet_num].neighbor[1] == -1) +
       (stl->neighbors_start[facet_num].neighbor[2] == -1));
  if(j == 0) {		       /* Facet has 3 neighbors */
    stl->stats.connected_facets_3_edge -= 1;
  } else if(j == 1) {	     /* Facet has 2 neighbors */
    stl->stats.connected_facets_2_edge -= 1;
  } else if(j == 2) {	     /* Facet has 1 neighbor  */
    stl->stats.connected_facets_1_edge -= 1;
  }
}",CWE-125,1
0,"  virtual void EnableOfflineMode(bool enable) {
    if (!EnsureCrosLoaded())
      return;

    if (enable && offline_mode_) {
      VLOG(1) << ""Trying to enable offline mode when it's already enabled."";
      return;
    }
    if (!enable && !offline_mode_) {
      VLOG(1) << ""Trying to disable offline mode when it's already disabled."";
      return;
    }

    if (SetOfflineMode(enable)) {
      offline_mode_ = enable;
    }
  }
",none,24
1,"void ha_maria::drop_table(const char *name)
{
  DBUG_ASSERT(file->s->temporary);
  (void) ha_close();
  (void) maria_delete_table_files(name, 1, MY_WME);
}",CWE-400,9
0,"  ~NetworkLibraryStubImpl() { if (ethernet_) delete ethernet_; }
",none,24
0,"  MockStorageClient* CreateClient(
      const MockOriginData* mock_data, size_t mock_data_size) {
    return new MockStorageClient(quota_manager_->proxy(),
                                 mock_data, mock_data_size);
  }
",none,24
1,"l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
  CallInfo *ci = L->ci;
  const char *msg;
  va_list argp;
  luaC_checkGC(L);  /* error message uses memory */
  va_start(argp, fmt);
  msg = luaO_pushvfstring(L, fmt, argp);  /* format message */
  va_end(argp);
  if (isLua(ci))  /* if Lua function, add source:line information */
    luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
  luaG_errormsg(L);
}",CWE-787,16
0,"  virtual bool wifi_connected() const { return false; }
",none,24
1,"njs_module_path(njs_vm_t *vm, const njs_str_t *dir, njs_module_info_t *info)
{
    char        *p;
    size_t      length;
    njs_bool_t  trail;
    char        src[NJS_MAX_PATH + 1];

    trail = 0;
    length = info->name.length;

    if (dir != NULL) {
        length = dir->length;

        if (length == 0) {
            return NJS_DECLINED;
        }

        trail = (dir->start[dir->length - 1] != '/');

        if (trail) {
            length++;
        }
    }

    if (njs_slow_path(length > NJS_MAX_PATH)) {
        return NJS_ERROR;
    }

    p = &src[0];

    if (dir != NULL) {
        p = (char *) njs_cpymem(p, dir->start, dir->length);

        if (trail) {
            *p++ = '/';
        }
    }

    p = (char *) njs_cpymem(p, info->name.start, info->name.length);
    *p = '\0';

    p = realpath(&src[0], &info->path[0]);
    if (p == NULL) {
        return NJS_DECLINED;
    }

    info->fd = open(&info->path[0], O_RDONLY);
    if (info->fd < 0) {
        return NJS_DECLINED;
    }


    info->file.start = (u_char *) &info->path[0];
    info->file.length = njs_strlen(info->file.start);

    return NJS_OK;
}",CWE-787,16
1,"static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) {
    if (indx == NULL) {
        debug_print(""%s"", ""INDX structure not initialized\n"");
        return MOBI_INIT_FAILED;
    }
    const size_t entry_offset = indx->entries_count;
    const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number];
    mobi_buffer_setpos(buf, idxt.offsets[curr_number]);
    size_t entry_number = curr_number + entry_offset;
    if (entry_number >= indx->total_entries_count) {
        debug_print(""Entry number beyond array: %zu\n"", entry_number);
        return MOBI_DATA_CORRUPT;
    }
    /* save original record maxlen */
    const size_t buf_maxlen = buf->maxlen;
    if (buf->offset + entry_length >= buf_maxlen) {
        debug_print(""Entry length too long: %zu\n"", entry_length);
        return MOBI_DATA_CORRUPT;
    }
    buf->maxlen = buf->offset + entry_length;
    size_t label_length = mobi_buffer_get8(buf);
    if (label_length > entry_length) {
        debug_print(""Label length too long: %zu\n"", label_length);
        return MOBI_DATA_CORRUPT;
    }
    char text[INDX_LABEL_SIZEMAX];
    /* FIXME: what is ORDT1 for? */
    if (ordt->ordt2) {
        label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length);
    } else {
        label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count);
    }
    indx->entries[entry_number].label = malloc(label_length + 1);
    if (indx->entries[entry_number].label == NULL) {
        debug_print(""Memory allocation failed (%zu bytes)\n"", label_length);
        return MOBI_MALLOC_FAILED;
    }
    strncpy(indx->entries[entry_number].label, text, label_length + 1);
    //debug_print(""tag label[%zu]: %s\n"", entry_number, indx->entries[entry_number].label);
    unsigned char *control_bytes;
    control_bytes = buf->data + buf->offset;
    mobi_buffer_seek(buf, (int) tagx->control_byte_count);
    indx->entries[entry_number].tags_count = 0;
    indx->entries[entry_number].tags = NULL;
    if (tagx->tags_count > 0) {
        typedef struct {
            uint8_t tag;
            uint8_t tag_value_count;
            uint32_t value_count;
            uint32_t value_bytes;
        } MOBIPtagx;
        MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx));
        if (ptagx == NULL) {
            debug_print(""Memory allocation failed (%zu bytes)\n"", tagx->tags_count * sizeof(MOBIPtagx));
            return MOBI_MALLOC_FAILED;
        }
        uint32_t ptagx_count = 0;
        size_t len;
        size_t i = 0;
        while (i < tagx->tags_count) {
            if (tagx->tags[i].control_byte == 1) {
                control_bytes++;
                i++;
                continue;
            }
            uint32_t value = control_bytes[0] & tagx->tags[i].bitmask;
            if (value != 0) {
                /* FIXME: is it safe to use MOBI_NOTSET? */
                uint32_t value_count = MOBI_NOTSET;
                uint32_t value_bytes = MOBI_NOTSET;
                /* all bits of masked value are set */
                if (value == tagx->tags[i].bitmask) {
                    /* more than 1 bit set */
                    if (mobi_bitcount(tagx->tags[i].bitmask) > 1) {
                        /* read value bytes from entry */
                        len = 0;
                        value_bytes = mobi_buffer_get_varlen(buf, &len);
                    } else {
                        value_count = 1;
                    }
                } else {
                    uint8_t mask = tagx->tags[i].bitmask;
                    while ((mask & 1) == 0) {
                        mask >>= 1;
                        value >>= 1;
                    }
                    value_count = value;
                }
                ptagx[ptagx_count].tag = tagx->tags[i].tag;
                ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count;
                ptagx[ptagx_count].value_count = value_count;
                ptagx[ptagx_count].value_bytes = value_bytes;
                ptagx_count++;
            }
            i++;
        }
        indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag));
        if (indx->entries[entry_number].tags == NULL) {
            debug_print(""Memory allocation failed (%zu bytes)\n"", tagx->tags_count * sizeof(MOBIIndexTag));
            free(ptagx);
            return MOBI_MALLOC_FAILED;
        }
        i = 0;
        while (i < ptagx_count) {
            uint32_t tagvalues_count = 0;
            /* FIXME: is it safe to use MOBI_NOTSET? */
            /* value count is set */
            uint32_t tagvalues[INDX_TAGVALUES_MAX];
            if (ptagx[i].value_count != MOBI_NOTSET) {
                size_t count = ptagx[i].value_count * ptagx[i].tag_value_count;
                while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) {
                    len = 0;
                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);
                    tagvalues[tagvalues_count++] = value_bytes;
                }
            /* value count is not set */
            } else {
                /* read value_bytes bytes */
                len = 0;
                while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) {
                    const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len);
                    tagvalues[tagvalues_count++] = value_bytes;
                }
            }
            if (tagvalues_count) {
                const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues);
                indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size);
                if (indx->entries[entry_number].tags[i].tagvalues == NULL) {
                    debug_print(""Memory allocation failed (%zu bytes)\n"", arr_size);
                    free(ptagx);
                    return MOBI_MALLOC_FAILED;
                }
                memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size);
            } else {
                indx->entries[entry_number].tags[i].tagvalues = NULL;
            }
            indx->entries[entry_number].tags[i].tagid = ptagx[i].tag;
            indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count;
            indx->entries[entry_number].tags_count++;
            i++;
        }
        free(ptagx);
    }
    /* restore buffer maxlen */
    buf->maxlen = buf_maxlen;
    return MOBI_SUCCESS;
}",CWE-125,1
0,"static ActivationState ParseActivationState(
    const std::string& activation_state) {
  if (activation_state == kActivationStateActivated)
    return ACTIVATION_STATE_ACTIVATED;
  if (activation_state == kActivationStateActivating)
    return ACTIVATION_STATE_ACTIVATING;
  if (activation_state == kActivationStateNotActivated)
    return ACTIVATION_STATE_NOT_ACTIVATED;
  if (activation_state == kActivationStateUnknown)
    return ACTIVATION_STATE_UNKNOWN;
  if (activation_state == kActivationStatePartiallyActivated)
    return ACTIVATION_STATE_PARTIALLY_ACTIVATED;
  return ACTIVATION_STATE_UNKNOWN;
}
",none,24
1,"cmdline_insert_reg(int *gotesc UNUSED)
{
    int		i;
    int		c;

#ifdef USE_ON_FLY_SCROLL
    dont_scroll = TRUE;	// disallow scrolling here
#endif
    putcmdline('""', TRUE);
    ++no_mapping;
    ++allow_keys;
    i = c = plain_vgetc();	// CTRL-R 
    if (i == Ctrl_O)
	i = Ctrl_R;		// CTRL-R CTRL-O == CTRL-R CTRL-R
    if (i == Ctrl_R)
	c = plain_vgetc();	// CTRL-R CTRL-R 
    extra_char = NUL;
    --no_mapping;
    --allow_keys;
#ifdef FEAT_EVAL
    /*
     * Insert the result of an expression.
     * Need to save the current command line, to be able to enter
     * a new one...
     */
    new_cmdpos = -1;
    if (c == '=')
    {
	if (ccline.cmdfirstc == '='  // can't do this recursively
		|| cmdline_star > 0) // or when typing a password
	{
	    beep_flush();
	    c = ESC;
	}
	else
	    c = get_expr_register();
    }
#endif
    if (c != ESC)	    // use ESC to cancel inserting register
    {
	cmdline_paste(c, i == Ctrl_R, FALSE);

#ifdef FEAT_EVAL
	// When there was a serious error abort getting the
	// command line.
	if (aborting())
	{
	    *gotesc = TRUE;  // will free ccline.cmdbuff after
	    // putting it in history
	    return GOTO_NORMAL_MODE;
	}
#endif
	KeyTyped = FALSE;	// Don't do p_wc completion.
#ifdef FEAT_EVAL
	if (new_cmdpos >= 0)
	{
	    // set_cmdline_pos() was used
	    if (new_cmdpos > ccline.cmdlen)
		ccline.cmdpos = ccline.cmdlen;
	    else
		ccline.cmdpos = new_cmdpos;
	}
#endif
    }
    // remove the double quote
    redrawcmd();

    // The text has been stuffed, the command line didn't change yet.
    return CMDLINE_NOT_CHANGED;
}",CWE-787,16
1,"lsquic_qeh_settings (struct qpack_enc_hdl *qeh, unsigned max_table_size,
             unsigned dyn_table_size, unsigned max_risked_streams, int server)
{
    enum lsqpack_enc_opts enc_opts;

    assert(qeh->qeh_flags & QEH_INITIALIZED);

    if (qeh->qeh_flags & QEH_HAVE_SETTINGS)
    {
        LSQ_WARN(""settings already set"");
        return -1;
    }

    enc_opts = LSQPACK_ENC_OPT_STAGE_2
             | (server ? LSQPACK_ENC_OPT_SERVER : 0);
    qeh->qeh_tsu_sz = sizeof(qeh->qeh_tsu_buf);
    if (0 != lsqpack_enc_init(&qeh->qeh_encoder, (void *) qeh->qeh_conn,
                max_table_size, dyn_table_size, max_risked_streams, enc_opts,
                qeh->qeh_tsu_buf, &qeh->qeh_tsu_sz))
    {
        LSQ_INFO(""could not initialize QPACK encoder"");
        return -1;
    }
    LSQ_DEBUG(""%zu-byte post-init TSU"", qeh->qeh_tsu_sz);
    qeh->qeh_flags |= QEH_HAVE_SETTINGS;
    qeh->qeh_max_prefix_size =
                        lsqpack_enc_header_block_prefix_size(&qeh->qeh_encoder);
    LSQ_DEBUG(""have settings: max table size=%u; dyn table size=%u; max risked ""
        ""streams=%u"", max_table_size, dyn_table_size, max_risked_streams);
    if (qeh->qeh_enc_sm_out)
        qeh_begin_out(qeh);
    return 0;
}",CWE-269,6
0,"  WifiNetwork* GetWifiNetworkByName(const std::string& name) {
    for (size_t i = 0; i < wifi_networks_.size(); ++i) {
      if (wifi_networks_[i]->name().compare(name) == 0) {
        return wifi_networks_[i];
      }
    }
    return NULL;
  }
",none,24
1,"pax_decode_header (struct tar_sparse_file *file)
{
  if (file->stat_info->sparse_major > 0)
    {
      uintmax_t u;
      char nbuf[UINTMAX_STRSIZE_BOUND];
      union block *blk;
      char *p;
      size_t i;
      off_t start;
      
#define COPY_BUF(b,buf,src) do                                     \
 {                                                                 \
   char *endp = b->buffer + BLOCKSIZE;                             \
   char *dst = buf;                                                \
   do                                                              \
     {                                                             \
       if (dst == buf + UINTMAX_STRSIZE_BOUND -1)                  \
         {                                                         \
           ERROR ((0, 0, _(""%s: numeric overflow in sparse archive member""), \
	          file->stat_info->orig_file_name));               \
           return false;                                           \
         }                                                         \
       if (src == endp)                                            \
	 {                                                         \
	   set_next_block_after (b);                               \
           b = find_next_block ();                                 \
           src = b->buffer;                                        \
	   endp = b->buffer + BLOCKSIZE;                           \
	 }                                                         \
       *dst = *src++;                                              \
     }                                                             \
   while (*dst++ != '\n');                                         \
   dst[-1] = 0;                                                    \
 } while (0)

      start = current_block_ordinal ();
      set_next_block_after (current_header);
      blk = find_next_block ();
      p = blk->buffer;
      COPY_BUF (blk,nbuf,p);
      if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
	{
	  ERROR ((0, 0, _(""%s: malformed sparse archive member""),
		  file->stat_info->orig_file_name));
	  return false;
	}
      file->stat_info->sparse_map_size = u;
      file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
					     sizeof (*file->stat_info->sparse_map));
      file->stat_info->sparse_map_avail = 0;
      for (i = 0; i < file->stat_info->sparse_map_size; i++)
	{
	  struct sp_array sp;

	  COPY_BUF (blk,nbuf,p);
	  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
	    {
	      ERROR ((0, 0, _(""%s: malformed sparse archive member""),
		      file->stat_info->orig_file_name));
	      return false;
	    }
	  sp.offset = u;
	  COPY_BUF (blk,nbuf,p);
	  if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
	    {
	      ERROR ((0, 0, _(""%s: malformed sparse archive member""),
		      file->stat_info->orig_file_name));
	      return false;
	    }
	  sp.numbytes = u;
	  sparse_add_map (file->stat_info, &sp);
	}
      set_next_block_after (blk);

      file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
    }

  return true;
}",CWE-476,12
0,"  void DidDeleteOriginData(QuotaStatusCode status) {
    DCHECK_GT(remaining_clients_, 0);

    if (status != kQuotaStatusOk)
      ++error_count_;

    if (--remaining_clients_ == 0)
      CallCompleted();
  }
",none,24
1,"struct vfsmount *clone_private_mount(const struct path *path)
{
	struct mount *old_mnt = real_mount(path->mnt);
	struct mount *new_mnt;

	if (IS_MNT_UNBINDABLE(old_mnt))
		return ERR_PTR(-EINVAL);

	new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
	if (IS_ERR(new_mnt))
		return ERR_CAST(new_mnt);

	/* Longterm mount to be removed by kern_unmount*() */
	new_mnt->mnt_ns = MNT_NS_INTERNAL;

	return &new_mnt->mnt;
}",CWE-200,4
0,"  void CallCallbacksAndClear(
      CallbackList* callbacks, QuotaStatusCode status,
      int64 usage, int64 quota) {
    for (CallbackList::iterator iter = callbacks->begin();
         iter != callbacks->end(); ++iter) {
      (*iter)->Run(status, usage, quota);
      delete *iter;
    }
    callbacks->clear();
  }
",none,24
1,"int setup_tests(void)
{
    ADD_ALL_TESTS(call_run_cert, OSSL_NELEM(name_fns));
    return 1;
}",CWE-476,12
0,"  GetLRUOriginTask(
      QuotaManager* manager,
      StorageType type,
      const std::map& origins_in_use,
      const std::map& origins_in_error,
      GetLRUOriginCallback *callback)
      : DatabaseTaskBase(manager),
        type_(type),
        callback_(callback),
        special_storage_policy_(manager->special_storage_policy_) {
    for (std::map::const_iterator p = origins_in_use.begin();
         p != origins_in_use.end();
         ++p) {
      if (p->second > 0)
        exceptions_.insert(p->first);
    }
    for (std::map::const_iterator p = origins_in_error.begin();
         p != origins_in_error.end();
         ++p) {
      if (p->second > QuotaManager::kThresholdOfErrorsToBeBlacklisted)
        exceptions_.insert(p->first);
    }
  }
",none,24
1,"static int ax25_release(struct socket *sock)
{
	struct sock *sk = sock->sk;
	ax25_cb *ax25;
	ax25_dev *ax25_dev;

	if (sk == NULL)
		return 0;

	sock_hold(sk);
	lock_sock(sk);
	sock_orphan(sk);
	ax25 = sk_to_ax25(sk);
	ax25_dev = ax25->ax25_dev;
	if (ax25_dev) {
		dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);
		ax25_dev_put(ax25_dev);
	}

	if (sk->sk_type == SOCK_SEQPACKET) {
		switch (ax25->state) {
		case AX25_STATE_0:
			release_sock(sk);
			ax25_disconnect(ax25, 0);
			lock_sock(sk);
			ax25_destroy_socket(ax25);
			break;

		case AX25_STATE_1:
		case AX25_STATE_2:
			ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
			release_sock(sk);
			ax25_disconnect(ax25, 0);
			lock_sock(sk);
			if (!sock_flag(ax25->sk, SOCK_DESTROY))
				ax25_destroy_socket(ax25);
			break;

		case AX25_STATE_3:
		case AX25_STATE_4:
			ax25_clear_queues(ax25);
			ax25->n2count = 0;

			switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
			case AX25_PROTO_STD_SIMPLEX:
			case AX25_PROTO_STD_DUPLEX:
				ax25_send_control(ax25,
						  AX25_DISC,
						  AX25_POLLON,
						  AX25_COMMAND);
				ax25_stop_t2timer(ax25);
				ax25_stop_t3timer(ax25);
				ax25_stop_idletimer(ax25);
				break;
#ifdef CONFIG_AX25_DAMA_SLAVE
			case AX25_PROTO_DAMA_SLAVE:
				ax25_stop_t3timer(ax25);
				ax25_stop_idletimer(ax25);
				break;
#endif
			}
			ax25_calculate_t1(ax25);
			ax25_start_t1timer(ax25);
			ax25->state = AX25_STATE_2;
			sk->sk_state                = TCP_CLOSE;
			sk->sk_shutdown            |= SEND_SHUTDOWN;
			sk->sk_state_change(sk);
			sock_set_flag(sk, SOCK_DESTROY);
			break;

		default:
			break;
		}
	} else {
		sk->sk_state     = TCP_CLOSE;
		sk->sk_shutdown |= SEND_SHUTDOWN;
		sk->sk_state_change(sk);
		ax25_destroy_socket(ax25);
	}

	sock->sk   = NULL;
	release_sock(sk);
	sock_put(sk);

	return 0;
}",CWE-416,10
1,"bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
                 int depth, int64_t options) {
  // No GC safepoints during JSON parsing, please. Code is not re-entrant.
  NoHandleSurpriseScope no_surprise(SafepointFlags);

  json_parser *json = s_json_parser.get(); /* the parser state */
  // Clear and reuse the thread-local string buffers. They are only freed if
  // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
  // is explicitly flushed (e.g., due to being idle).
  json->initSb(length);
  SCOPE_EXIT {
    constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
    if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
  };
  // SimpleParser only handles the most common set of options. Also, only use it
  // if its array nesting depth check is *more* restrictive than what the user
  // asks for, to ensure that the precise semantics of the general case is
  // applied for all nesting overflows.
  if (assoc &&
      options == (options & (k_JSON_FB_LOOSE |
                             k_JSON_FB_DARRAYS |
                             k_JSON_FB_DARRAYS_AND_VARRAYS |
                             k_JSON_FB_HACK_ARRAYS |
                             k_JSON_FB_THRIFT_SIMPLE_JSON |
                             k_JSON_FB_LEGACY_HACK_ARRAYS)) &&
      depth >= SimpleParser::kMaxArrayDepth &&
      length <= RuntimeOption::EvalSimpleJsonMaxLength &&
      SimpleParser::TryParse(p, length, json->tl_buffer.tv, z,
                             get_container_type_from_options(options),
                             options & k_JSON_FB_THRIFT_SIMPLE_JSON)) {
    return true;
  }

  int b;  /* the next character */
  int c;  /* the next character class */
  int s;  /* the next state */
  int state = 0;

  /**/
  bool const loose = options & k_JSON_FB_LOOSE;
  JSONContainerType const container_type =
    get_container_type_from_options(options);
  int qchr = 0;
  int8_t const *byte_class;
  int8_t const (*next_state_table)[32];
  if (loose) {
    byte_class = loose_ascii_class;
    next_state_table = loose_state_transition_table;
  } else {
    byte_class = ascii_class;
    next_state_table = state_transition_table;
  }
  /**/

  UncheckedBuffer *buf = &json->sb_buf;
  UncheckedBuffer *key = &json->sb_key;

  DataType type = kInvalidDataType;
  unsigned short escaped_bytes = 0;

  auto reset_type = [&] { type = kInvalidDataType; };

  json->depth = depth;
  // Since the stack is maintainined on a per request basis, for performance
  // reasons, it only makes sense to expand if necessary and cycles are wasted
  // contracting. Calls with a depth other than default should be rare.
  if (depth > json->stack.size()) {
    json->stack.resize(depth);
  }
  SCOPE_EXIT {
    if (json->stack.empty()) return;
    for (int i = 0; i <= json->mark; i++) {
      json->stack[i].key.reset();
      json->stack[i].val.unset();
    }
    json->mark = -1;
  };

  json->mark = json->top = -1;
  push(json, Mode::DONE);

  UTF8To16Decoder decoder(p, length, loose);
  for (;;) {
    b = decoder.decode();
    // Fast-case most common transition: append a simple string character.
    if (state == 3 && type == KindOfString) {
      while (b != '\""' &&  b != '\\' && b != '\'' && b <= 127 && b >= ' ') {
        buf->append((char)b);
        b = decoder.decode();
      }
    }
    if (b == UTF8_END) break; // UTF-8 decoding finishes successfully.
    if (b == UTF8_ERROR) {
      s_json_parser->error_code = JSON_ERROR_UTF8;
      return false;
    }
    assertx(b >= 0);

    if ((b & 127) == b) {
      /**/
      c = byte_class[b];
      /**/
      if (c <= S_ERR) {
        s_json_parser->error_code = JSON_ERROR_CTRL_CHAR;
        return false;
      }
    } else {
      c = S_ETC;
    }
    /*
      Get the next state from the transition table.
    */

    /**/
    s = next_state_table[state][c];

    if (s == -4) {
      if (b != qchr) {
        s = 3;
      } else {
        qchr = 0;
      }
    }
    /**/

    if (s < 0) {
      /*
        Perform one of the predefined actions.
      */
      switch (s) {
        /*
          empty }
        */
      case -9:
        /**/
        if (json->top == 1) z = json->stack[json->top].val;
        else {
        /**/
          attach_zval(json, json->stack[json->top].key, assoc, container_type);
        /**/
        }
        /**/
        if (!pop(json, Mode::KEY)) {
          return false;
        }
        state = 9;
        break;
        /*
          {
        */
      case -8:
        if (!push(json, Mode::KEY)) {
          s_json_parser->error_code = JSON_ERROR_DEPTH;
          return false;
        }

        state = 1;
        if (json->top > 0) {
          Variant &top = json->stack[json->top].val;
          /**/
          if (container_type == JSONContainerType::COLLECTIONS) {
            // stable_maps is meaningless
            top = req::make();
          } else {
          /**/
            if (!assoc) {
              top = SystemLib::AllocStdClassObject();
            /*  */
            } else if (container_type == JSONContainerType::HACK_ARRAYS) {
              top = Array::CreateDict();
            } else if (container_type == JSONContainerType::DARRAYS ||
                       container_type == JSONContainerType::DARRAYS_AND_VARRAYS)
            {
              top = Array::CreateDArray();
            /*  */
            } else if (
              container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
              auto arr = staticEmptyDictArray()->copy();
              arr->setLegacyArray(true);
              top = arr;
            } else {
              top = Array::CreateDArray();
            }
          /**/
          }
          /**/
          json->stack[json->top].key = copy_and_clear(*key);
          reset_type();
        }
        break;
        /*
          }
        */
      case -7:
        /*** BEGIN Facebook: json_utf8_loose ***/
        /*
          If this is a trailing comma in an object definition,
          we're in Mode::KEY. In that case, throw that off the
          stack and restore Mode::OBJECT so that we pretend the
          trailing comma just didn't happen.
        */
        if (loose) {
          if (pop(json, Mode::KEY)) {
            push(json, Mode::OBJECT);
          }
        }
        /*** END Facebook: json_utf8_loose ***/

        if (type != kInvalidDataType &&
            json->stack[json->top].mode == Mode::OBJECT) {
          Variant mval;
          json_create_zval(mval, *buf, type, options);
          Variant &top = json->stack[json->top].val;
          object_set(json, top, copy_and_clear(*key),
                     mval, assoc, container_type);
          buf->clear();
          reset_type();
        }

        /**/
        if (json->top == 1) z = json->stack[json->top].val;
        else {
        /**/
          attach_zval(json, json->stack[json->top].key,
            assoc, container_type);
        /**/
        }
        /**/
        if (!pop(json, Mode::OBJECT)) {
          s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
          return false;
        }
        state = 9;
        break;
        /*
          [
        */
      case -6:
        if (!push(json, Mode::ARRAY)) {
          s_json_parser->error_code = JSON_ERROR_DEPTH;
          return false;
        }
        state = 2;

        if (json->top > 0) {
          Variant &top = json->stack[json->top].val;
          /**/
          if (container_type == JSONContainerType::COLLECTIONS) {
            top = req::make();
          } else if (container_type == JSONContainerType::HACK_ARRAYS) {
            top = Array::CreateVec();
          } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) {
            top = Array::CreateVArray();
          } else if (container_type == JSONContainerType::DARRAYS) {
            top = Array::CreateDArray();
          } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
            auto arr = staticEmptyVecArray()->copy();
            arr->setLegacyArray(true);
            top = arr;
          } else {
            top = Array::CreateDArray();
          }
          /**/
          json->stack[json->top].key = copy_and_clear(*key);
          reset_type();
        }
        break;
        /*
          ]
        */
      case -5:
        {
          if (type != kInvalidDataType &&
               json->stack[json->top].mode == Mode::ARRAY) {
            Variant mval;
            json_create_zval(mval, *buf, type, options);
            auto& top = json->stack[json->top].val;
            if (container_type == JSONContainerType::COLLECTIONS) {
              collections::append(top.getObjectData(), mval.asTypedValue());
            } else {
              top.asArrRef().append(mval);
            }
            buf->clear();
            reset_type();
          }

          /**/
          if (json->top == 1) z = json->stack[json->top].val;
          else {
          /**/
            attach_zval(json, json->stack[json->top].key, assoc,
              container_type);
          /**/
          }
          /**/
          if (!pop(json, Mode::ARRAY)) {
            s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
            return false;
          }
          state = 9;
        }
        break;
        /*
          ""
        */
      case -4:
        switch (json->stack[json->top].mode) {
        case Mode::KEY:
          state = 27;
          std::swap(buf, key);
          reset_type();
          break;
        case Mode::ARRAY:
        case Mode::OBJECT:
          state = 9;
          break;
        case Mode::DONE:
          if (type == KindOfString) {
            z = copy_and_clear(*buf);
            state = 9;
            break;
          }
          /* fall through if not KindOfString */
        default:
          s_json_parser->error_code = JSON_ERROR_SYNTAX;
          return false;
        }
        break;
        /*
          ,
        */
      case -3:
        {
          Variant mval;
          if (type != kInvalidDataType &&
              (json->stack[json->top].mode == Mode::OBJECT ||
               json->stack[json->top].mode == Mode::ARRAY)) {
            json_create_zval(mval, *buf, type, options);
          }

          switch (json->stack[json->top].mode) {
          case Mode::OBJECT:
            if (pop(json, Mode::OBJECT) &&
                push(json, Mode::KEY)) {
              if (type != kInvalidDataType) {
                Variant &top = json->stack[json->top].val;
                object_set(
                  json,
                  top,
                  copy_and_clear(*key),
                  mval,
                  assoc,
                  container_type
                );
              }
              state = 29;
            }
            break;
          case Mode::ARRAY:
            if (type != kInvalidDataType) {
              auto& top = json->stack[json->top].val;
              if (container_type == JSONContainerType::COLLECTIONS) {
                collections::append(top.getObjectData(), mval.asTypedValue());
              } else {
                top.asArrRef().append(mval);
              }
            }
            state = 28;
            break;
          default:
            s_json_parser->error_code = JSON_ERROR_SYNTAX;
            return false;
          }
          buf->clear();
          reset_type();
          check_non_safepoint_surprise();
        }
        break;

        /**/
        /*
          : (after unquoted string)
        */
      case -10:
        if (json->stack[json->top].mode == Mode::KEY) {
          state = 27;
          std::swap(buf, key);
          reset_type();
          s = -2;
        } else {
          s = 3;
          break;
        }
        /**/

        /*
          :
        */
      case -2:
        if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) {
          state = 28;
          break;
        }
        /*
          syntax error
        */
      case -1:
        s_json_parser->error_code = JSON_ERROR_SYNTAX;
        return false;
      }
    } else {
      /*
        Change the state and iterate.
      */
      bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON;
      if (type == KindOfString) {
        if (/**/(/**/s == 3/**/ || s == 30)/**/ &&
            state != 8) {
          if (state != 4) {
            utf16_to_utf8(*buf, b);
          } else {
            switch (b) {
            case 'b': buf->append('\b'); break;
            case 't': buf->append('\t'); break;
            case 'n': buf->append('\n'); break;
            case 'f': buf->append('\f'); break;
            case 'r': buf->append('\r'); break;
            default:
              utf16_to_utf8(*buf, b);
              break;
            }
          }
        } else if (s == 6) {
          if (UNLIKELY(is_tsimplejson)) {
            if (UNLIKELY(b != '0'))  {
              s_json_parser->error_code = JSON_ERROR_SYNTAX;
              return false;
            }
            escaped_bytes = 0;
          } else {
            escaped_bytes = dehexchar(b) << 12;
          }
        } else if (s == 7) {
          if (UNLIKELY(is_tsimplejson)) {
            if (UNLIKELY(b != '0'))  {
              s_json_parser->error_code = JSON_ERROR_SYNTAX;
              return false;
            }
          } else {
            escaped_bytes += dehexchar(b) << 8;
          }
        } else if (s == 8) {
          escaped_bytes += dehexchar(b) << 4;
        } else if (s == 3 && state == 8) {
          escaped_bytes += dehexchar(b);
          if (UNLIKELY(is_tsimplejson)) {
            buf->append((char)escaped_bytes);
          } else {
            utf16_to_utf8(*buf, escaped_bytes);
          }
        }
      } else if ((type == kInvalidDataType || type == KindOfNull) &&
                 (c == S_DIG || c == S_ZER)) {
        type = KindOfInt64;
        buf->append((char)b);
      } else if (type == KindOfInt64 && s == 24) {
        type = KindOfDouble;
        buf->append((char)b);
      } else if ((type == kInvalidDataType || type == KindOfNull ||
                  type == KindOfInt64) &&
                 c == S_DOT) {
        type = KindOfDouble;
        buf->append((char)b);
      } else if (type != KindOfString && c == S_QUO) {
        type = KindOfString;
        /**/qchr = b;/**/
      } else if ((type == kInvalidDataType || type == KindOfNull ||
                  type == KindOfInt64 || type == KindOfDouble) &&
                 ((state == 12 && s == 9) ||
                  (state == 16 && s == 9))) {
        type = KindOfBoolean;
      } else if (type == kInvalidDataType && state == 19 && s == 9) {
        type = KindOfNull;
      } else if (type != KindOfString && c > S_WSP) {
        utf16_to_utf8(*buf, b);
      }

      state = s;
    }
  }

  if (state == 9 && pop(json, Mode::DONE)) {
    s_json_parser->error_code = JSON_ERROR_NONE;
    return true;
  }

  s_json_parser->error_code = JSON_ERROR_SYNTAX;
  return false;
}",CWE-125,1
1,"bool ConstantFolding::MulConvPushDown(GraphDef* optimized_graph, NodeDef* node,
                                      const GraphProperties& properties) {
  // Push down multiplication on ConvND.
  //                       *                  ConvND
  //                     /   \                /    \
  //                 ConvND  C2    -- >      X      *
  //                  / \                          / \
  //                 X  C1                       C1  C2
  //
  // where C1 and C2 are constants and X is non-constant.
  //
  // TODO(rmlarsen): Use PrepareConstantPushDown() to simplify this code.

  if (!IsAnyMul(*node) || NumNonControlInputs(*node) != 2) return false;

  NodeDef* mul_left_child = node_map_->GetNode(node->input(0));
  NodeDef* mul_right_child = node_map_->GetNode(node->input(1));
  // One child must be constant, and the second must be Conv op.
  const bool left_child_is_constant = IsReallyConstant(*mul_left_child);
  const bool right_child_is_constant = IsReallyConstant(*mul_right_child);
  if (!left_child_is_constant && !right_child_is_constant) {
    return false;
  }
  NodeDef* conv_node =
      left_child_is_constant ? mul_right_child : mul_left_child;
  if (!IsConv2D(*conv_node) && !IsConv3D(*conv_node)) {
    return false;
  }
  if (node->device() != mul_left_child->device() ||
      node->device() != mul_right_child->device()) {
    return false;
  }

  // Make sure that it is safe to change the value of the convolution
  // output.
  if (conv_node->input_size() < 2 ||
      NumNonControlOutputs(*conv_node, *node_map_) > 1 ||
      nodes_to_preserve_.find(conv_node->name()) != nodes_to_preserve_.end()) {
    return false;
  }

  // Identify the nodes to swap.
  NodeDef* conv_left_child = node_map_->GetNode(conv_node->input(0));
  NodeDef* conv_right_child = node_map_->GetNode(conv_node->input(1));
  const bool conv_left_is_constant = IsReallyConstant(*conv_left_child);
  const bool conv_right_is_constant = IsReallyConstant(*conv_right_child);
  if (!conv_left_is_constant && !conv_right_is_constant) {
    // At least one of the convolution inputs should be constant.
    return false;
  }
  if (conv_left_is_constant && conv_right_is_constant) {
    // Leverage regular constant folding to handle this.
    return false;
  }
  const auto& mul_props = properties.GetOutputProperties(node->name());
  const auto& conv_props = properties.GetOutputProperties(conv_node->name());
  if (mul_props.empty() || conv_props.empty()) {
    return false;
  }
  const auto& mul_shape = mul_props[0].shape();
  const auto& conv_shape = conv_props[0].shape();
  if (!ShapesSymbolicallyEqual(mul_shape, conv_shape)) {
    return false;
  }

  const auto& input_props = properties.GetInputProperties(conv_node->name());
  if (input_props.size() < 2) {
    return false;
  }
  const auto& filter_shape = input_props[1].shape();

  NodeDef* const_node =
      left_child_is_constant ? mul_left_child : mul_right_child;
  const auto& const_props = properties.GetOutputProperties(const_node->name());
  if (const_props.empty()) {
    return false;
  }
  const auto& const_shape = const_props[0].shape();
  if (!IsValidConstShapeForMulConvPushDown(
          conv_node->attr().at(""data_format"").s(), filter_shape, const_shape)) {
    return false;
  }

  string mul_new_name = AddPrefixToNodeName(""merged_input"", conv_node->name());
  if (node_map_->NodeExists(mul_new_name)) {
    return false;
  }
  // Make sure we don't introduce loops in the graph by removing control
  // dependencies from the conv2d node to c2.
  string conv_const_input =
      conv_left_is_constant ? conv_node->input(0) : conv_node->input(1);
  if (MaybeRemoveControlInput(conv_node->name(), const_node, optimized_graph,
                              node_map_.get())) {
    // Add a control dep from c1 to c2 to ensure c2 is in the right frame
    MaybeAddControlInput(conv_const_input, const_node, optimized_graph,
                         node_map_.get());
  }

  conv_node->set_name(node->name());
  node->set_name(mul_new_name);
  if (conv_left_is_constant) {
    node_map_->UpdateInput(conv_node->name(), node->input(0), mul_new_name);
    conv_node->set_input(0, mul_new_name);
  } else {
    node_map_->UpdateInput(conv_node->name(), node->input(1), mul_new_name);
    conv_node->set_input(1, mul_new_name);
  }
  NodeDef* conv_const_node =
      conv_left_is_constant ? conv_left_child : conv_right_child;
  if (left_child_is_constant) {
    node->set_input(1, conv_const_node->name());
  } else {
    node->set_input(0, conv_const_node->name());
  }
  node_map_->AddNode(mul_new_name, node);

  return true;
}",CWE-476,12
1,"static void parse_rtcp_bye(pjmedia_rtcp_session *sess,
			   const void *pkt,
			   pj_size_t size)
{
    pj_str_t reason = {""-"", 1};

    /* Check and get BYE reason */
    if (size > 8) {
	reason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_),
                             *((pj_uint8_t*)pkt+8));
	pj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9),
		  reason.slen);
	reason.ptr = sess->stat.peer_sdes_buf_;
    }

    /* Just print RTCP BYE log */
    PJ_LOG(5, (sess->name, ""Received RTCP BYE, reason: %.*s"",
	       reason.slen, reason.ptr));
}",CWE-125,1
1,"_inplace_src_spans (void *abstract_renderer, int y, int h,
		    const cairo_half_open_span_t *spans,
		    unsigned num_spans)
{
    cairo_image_span_renderer_t *r = abstract_renderer;
    uint8_t *m;
    int x0;

    if (num_spans == 0)
	return CAIRO_STATUS_SUCCESS;

    x0 = spans[0].x;
    m = r->_buf;
    do {
	int len = spans[1].x - spans[0].x;
	if (len >= r->u.composite.run_length && spans[0].coverage == 0xff) {
	    if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
		pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
					  r->src, r->mask, r->u.composite.dst,
					  x0 + r->u.composite.src_x,
					  y + r->u.composite.src_y,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
#else
		pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
					  r->mask, NULL, r->u.composite.dst,
					  0, 0,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
		pixman_image_composite32 (PIXMAN_OP_ADD,
					  r->src, r->mask, r->u.composite.dst,
					  x0 + r->u.composite.src_x,
					  y + r->u.composite.src_y,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
#endif
	    }

	    pixman_image_composite32 (PIXMAN_OP_SRC,
				      r->src, NULL, r->u.composite.dst,
				      spans[0].x + r->u.composite.src_x,
				      y + r->u.composite.src_y,
				      0, 0,
				      spans[0].x, y,
				      spans[1].x - spans[0].x, h);

	    m = r->_buf;
	    x0 = spans[1].x;
	} else if (spans[0].coverage == 0x0) {
	    if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
		pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
					  r->src, r->mask, r->u.composite.dst,
					  x0 + r->u.composite.src_x,
					  y + r->u.composite.src_y,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
#else
		pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
					  r->mask, NULL, r->u.composite.dst,
					  0, 0,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
		pixman_image_composite32 (PIXMAN_OP_ADD,
					  r->src, r->mask, r->u.composite.dst,
					  x0 + r->u.composite.src_x,
					  y + r->u.composite.src_y,
					  0, 0,
					  x0, y,
					  spans[0].x - x0, h);
#endif
	    }

	    m = r->_buf;
	    x0 = spans[1].x;
	} else {
	    *m++ = spans[0].coverage;
	    if (len > 1) {
		memset (m, spans[0].coverage, --len);
		m += len;
	    }
	}
	spans++;
    } while (--num_spans > 1);

    if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
	pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
				  r->src, r->mask, r->u.composite.dst,
				  x0 + r->u.composite.src_x,
				  y + r->u.composite.src_y,
				  0, 0,
				  x0, y,
				  spans[0].x - x0, h);
#else
	pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
				  r->mask, NULL, r->u.composite.dst,
				  0, 0,
				  0, 0,
				  x0, y,
				  spans[0].x - x0, h);
	pixman_image_composite32 (PIXMAN_OP_ADD,
				  r->src, r->mask, r->u.composite.dst,
				  x0 + r->u.composite.src_x,
				  y + r->u.composite.src_y,
				  0, 0,
				  x0, y,
				  spans[0].x - x0, h);
#endif
    }

    return CAIRO_STATUS_SUCCESS;
}",CWE-787,16
0,"  void DeleteClientOriginData(QuotaClient* client,
                        const GURL& origin,
                        StorageType type) {
    DCHECK(client);
    quota_status_ = kQuotaStatusUnknown;
    client->DeleteOriginData(origin, type,
        callback_factory_.NewCallback(
            &QuotaManagerTest::StatusCallback));
  }
",none,24
1,"mrb_vm_exec(mrb_state *mrb, const struct RProc *proc, const mrb_code *pc)
{
  /* mrb_assert(MRB_PROC_CFUNC_P(proc)) */
  const mrb_irep *irep = proc->body.irep;
  const mrb_pool_value *pool = irep->pool;
  const mrb_sym *syms = irep->syms;
  mrb_code insn;
  int ai = mrb_gc_arena_save(mrb);
  struct mrb_jmpbuf *prev_jmp = mrb->jmp;
  struct mrb_jmpbuf c_jmp;
  uint32_t a;
  uint16_t b;
  uint16_t c;
  mrb_sym mid;
  const struct mrb_irep_catch_handler *ch;

#ifdef DIRECT_THREADED
  static const void * const optable[] = {
#define OPCODE(x,_) &&L_OP_ ## x,
#include ""mruby/ops.h""
#undef OPCODE
  };
#endif

  mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:

  MRB_TRY(&c_jmp) {

  if (exc_catched) {
    exc_catched = FALSE;
    mrb_gc_arena_restore(mrb, ai);
    if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
      goto L_BREAK;
    goto L_RAISE;
  }
  mrb->jmp = &c_jmp;
  mrb_vm_ci_proc_set(mrb->c->ci, proc);

#define regs (mrb->c->ci->stack)
  INIT_DISPATCH {
    CASE(OP_NOP, Z) {
      /* do nothing */
      NEXT;
    }

    CASE(OP_MOVE, BB) {
      regs[a] = regs[b];
      NEXT;
    }

    CASE(OP_LOADL, BB) {
      switch (pool[b].tt) {   /* number */
      case IREP_TT_INT32:
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i32);
        break;
      case IREP_TT_INT64:
#if defined(MRB_INT64)
        regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
        break;
#else
#if defined(MRB_64BIT)
        if (INT32_MIN <= pool[b].u.i64 && pool[b].u.i64 <= INT32_MAX) {
          regs[a] = mrb_int_value(mrb, (mrb_int)pool[b].u.i64);
          break;
        }
#endif
        goto L_INT_OVERFLOW;
#endif
      case IREP_TT_BIGINT:
        goto L_INT_OVERFLOW;
#ifndef MRB_NO_FLOAT
      case IREP_TT_FLOAT:
        regs[a] = mrb_float_value(mrb, pool[b].u.f);
        break;
#endif
      default:
        /* should not happen (tt:string) */
        regs[a] = mrb_nil_value();
        break;
      }
      NEXT;
    }

    CASE(OP_LOADI, BB) {
      SET_FIXNUM_VALUE(regs[a], b);
      NEXT;
    }

    CASE(OP_LOADINEG, BB) {
      SET_FIXNUM_VALUE(regs[a], -b);
      NEXT;
    }

    CASE(OP_LOADI__1,B) goto L_LOADI;
    CASE(OP_LOADI_0,B) goto L_LOADI;
    CASE(OP_LOADI_1,B) goto L_LOADI;
    CASE(OP_LOADI_2,B) goto L_LOADI;
    CASE(OP_LOADI_3,B) goto L_LOADI;
    CASE(OP_LOADI_4,B) goto L_LOADI;
    CASE(OP_LOADI_5,B) goto L_LOADI;
    CASE(OP_LOADI_6,B) goto L_LOADI;
    CASE(OP_LOADI_7, B) {
    L_LOADI:
      SET_FIXNUM_VALUE(regs[a], (mrb_int)insn - (mrb_int)OP_LOADI_0);
      NEXT;
    }

    CASE(OP_LOADI16, BS) {
      SET_FIXNUM_VALUE(regs[a], (mrb_int)(int16_t)b);
      NEXT;
    }

    CASE(OP_LOADI32, BSS) {
      SET_INT_VALUE(mrb, regs[a], (int32_t)(((uint32_t)b<<16)+c));
      NEXT;
    }

    CASE(OP_LOADSYM, BB) {
      SET_SYM_VALUE(regs[a], syms[b]);
      NEXT;
    }

    CASE(OP_LOADNIL, B) {
      SET_NIL_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADSELF, B) {
      regs[a] = regs[0];
      NEXT;
    }

    CASE(OP_LOADT, B) {
      SET_TRUE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_LOADF, B) {
      SET_FALSE_VALUE(regs[a]);
      NEXT;
    }

    CASE(OP_GETGV, BB) {
      mrb_value val = mrb_gv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETGV, BB) {
      mrb_gv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETSV, BB) {
      mrb_value val = mrb_vm_special_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETSV, BB) {
      mrb_vm_special_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIV, BB) {
      regs[a] = mrb_iv_get(mrb, regs[0], syms[b]);
      NEXT;
    }

    CASE(OP_SETIV, BB) {
      mrb_iv_set(mrb, regs[0], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETCV, BB) {
      mrb_value val;
      val = mrb_vm_cv_get(mrb, syms[b]);
      regs[a] = val;
      NEXT;
    }

    CASE(OP_SETCV, BB) {
      mrb_vm_cv_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETIDX, B) {
      mrb_value va = regs[a], vb = regs[a+1];
      switch (mrb_type(va)) {
      case MRB_TT_ARRAY:
        if (!mrb_integer_p(vb)) goto getidx_fallback;
        regs[a] = mrb_ary_entry(va, mrb_integer(vb));
        break;
      case MRB_TT_HASH:
        va = mrb_hash_get(mrb, va, vb);
        regs[a] = va;
        break;
      case MRB_TT_STRING:
        switch (mrb_type(vb)) {
        case MRB_TT_INTEGER:
        case MRB_TT_STRING:
        case MRB_TT_RANGE:
          va = mrb_str_aref(mrb, va, vb, mrb_undef_value());
          regs[a] = va;
          break;
        default:
          goto getidx_fallback;
        }
        break;
      default:
      getidx_fallback:
        mid = MRB_OPSYM(aref);
        goto L_SEND_SYM;
      }
      NEXT;
    }

    CASE(OP_SETIDX, B) {
      c = 2;
      mid = MRB_OPSYM(aset);
      SET_NIL_VALUE(regs[a+3]);
      goto L_SENDB_SYM;
    }

    CASE(OP_GETCONST, BB) {
      mrb_value v = mrb_vm_const_get(mrb, syms[b]);
      regs[a] = v;
      NEXT;
    }

    CASE(OP_SETCONST, BB) {
      mrb_vm_const_set(mrb, syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETMCNST, BB) {
      mrb_value v = mrb_const_get(mrb, regs[a], syms[b]);
      regs[a] = v;
      NEXT;
    }

    CASE(OP_SETMCNST, BB) {
      mrb_const_set(mrb, regs[a+1], syms[b], regs[a]);
      NEXT;
    }

    CASE(OP_GETUPVAR, BBB) {
      mrb_value *regs_a = regs + a;
      struct REnv *e = uvenv(mrb, c);

      if (e && b < MRB_ENV_LEN(e)) {
        *regs_a = e->stack[b];
      }
      else {
        *regs_a = mrb_nil_value();
      }
      NEXT;
    }

    CASE(OP_SETUPVAR, BBB) {
      struct REnv *e = uvenv(mrb, c);

      if (e) {
        mrb_value *regs_a = regs + a;

        if (b < MRB_ENV_LEN(e)) {
          e->stack[b] = *regs_a;
          mrb_write_barrier(mrb, (struct RBasic*)e);
        }
      }
      NEXT;
    }

    CASE(OP_JMP, S) {
      pc += (int16_t)a;
      JUMP;
    }
    CASE(OP_JMPIF, BS) {
      if (mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNOT, BS) {
      if (!mrb_test(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }
    CASE(OP_JMPNIL, BS) {
      if (mrb_nil_p(regs[a])) {
        pc += (int16_t)b;
        JUMP;
      }
      NEXT;
    }

    CASE(OP_JMPUW, S) {
      a = (uint32_t)((pc - irep->iseq) + (int16_t)a);
      CHECKPOINT_RESTORE(RBREAK_TAG_JUMP) {
        struct RBreak *brk = (struct RBreak*)mrb->exc;
        mrb_value target = mrb_break_value_get(brk);
        mrb_assert(mrb_integer_p(target));
        a = (uint32_t)mrb_integer(target);
        mrb_assert(a >= 0 && a < irep->ilen);
      }
      CHECKPOINT_MAIN(RBREAK_TAG_JUMP) {
        ch = catch_handler_find(mrb, mrb->c->ci, pc, MRB_CATCH_FILTER_ENSURE);
        if (ch) {
          /* avoiding a jump from a catch handler into the same handler */
          if (a < mrb_irep_catch_handler_unpack(ch->begin) || a >= mrb_irep_catch_handler_unpack(ch->end)) {
            THROW_TAGGED_BREAK(mrb, RBREAK_TAG_JUMP, proc, mrb_fixnum_value(a));
          }
        }
      }
      CHECKPOINT_END(RBREAK_TAG_JUMP);

      mrb->exc = NULL; /* clear break object */
      pc = irep->iseq + a;
      JUMP;
    }

    CASE(OP_EXCEPT, B) {
      mrb_value exc;

      if (mrb->exc == NULL) {
        exc = mrb_nil_value();
      }
      else {
        switch (mrb->exc->tt) {
        case MRB_TT_BREAK:
        case MRB_TT_EXCEPTION:
          exc = mrb_obj_value(mrb->exc);
          break;
        default:
          mrb_assert(!""bad mrb_type"");
          exc = mrb_nil_value();
          break;
        }
        mrb->exc = NULL;
      }
      regs[a] = exc;
      NEXT;
    }
    CASE(OP_RESCUE, BB) {
      mrb_value exc = regs[a];  /* exc on stack */
      mrb_value e = regs[b];
      struct RClass *ec;

      switch (mrb_type(e)) {
      case MRB_TT_CLASS:
      case MRB_TT_MODULE:
        break;
      default:
        {
          mrb_value exc;

          exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                    ""class or module required for rescue clause"");
          mrb_exc_set(mrb, exc);
          goto L_RAISE;
        }
      }
      ec = mrb_class_ptr(e);
      regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
      NEXT;
    }

    CASE(OP_RAISEIF, B) {
      mrb_value exc = regs[a];
      if (mrb_break_p(exc)) {
        mrb->exc = mrb_obj_ptr(exc);
        goto L_BREAK;
      }
      mrb_exc_set(mrb, exc);
      if (mrb->exc) {
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_SSEND, BBB) {
      regs[a] = regs[0];
      insn = OP_SEND;
    }
    goto L_SENDB;

    CASE(OP_SSENDB, BBB) {
      regs[a] = regs[0];
    }
    goto L_SENDB;

    CASE(OP_SEND, BBB)
    goto L_SENDB;

    L_SEND_SYM:
    c = 1;
    /* push nil after arguments */
    SET_NIL_VALUE(regs[a+2]);
    goto L_SENDB_SYM;

    CASE(OP_SENDB, BBB)
    L_SENDB:
    mid = syms[b];
    L_SENDB_SYM:
    {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_method_t m;
      struct RClass *cls;
      mrb_value recv, blk;

      ARGUMENT_NORMALIZE(a, &c, insn);

      recv = regs[a];
      cls = mrb_class(mrb, recv);
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &c, blk, 0);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, c);

      if (MRB_METHOD_CFUNC_P(m)) {
        if (MRB_METHOD_PROC_P(m)) {
          struct RProc *p = MRB_METHOD_PROC(m);

          mrb_vm_ci_proc_set(ci, p);
          recv = p->body.func(mrb, recv);
        }
        else {
          if (MRB_METHOD_NOARG_P(m)) {
            check_method_noarg(mrb, ci);
          }
          recv = MRB_METHOD_FUNC(m)(mrb, recv);
        }
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);
          if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
        if (!ci->u.target_class) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return recv;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        ci->stack[0] = recv;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
    }
    JUMP;

    CASE(OP_CALL, Z) {
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv = ci->stack[0];
      struct RProc *m = mrb_proc_ptr(recv);

      /* replace callinfo */
      ci->u.target_class = MRB_PROC_TARGET_CLASS(m);
      mrb_vm_ci_proc_set(ci, m);
      if (MRB_PROC_ENV_P(m)) {
        ci->mid = MRB_PROC_ENV(m)->mid;
      }

      /* prepare stack */
      if (MRB_PROC_CFUNC_P(m)) {
        recv = MRB_PROC_CFUNC(m)(mrb, recv);
        mrb_gc_arena_shrink(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        /* pop stackpos */
        ci = cipop(mrb);
        pc = ci->pc;
        ci[1].stack[0] = recv;
        irep = mrb->c->ci->proc->body.irep;
      }
      else {
        /* setup environment for calling method */
        proc = m;
        irep = m->body.irep;
        if (!irep) {
          mrb->c->ci->stack[0] = mrb_nil_value();
          a = 0;
          c = OP_R_NORMAL;
          goto L_OP_RETURN_BODY;
        }
        mrb_int nargs = mrb_ci_bidx(ci)+1;
        if (nargs < irep->nregs) {
          mrb_stack_extend(mrb, irep->nregs);
          stack_clear(regs+nargs, irep->nregs-nargs);
        }
        if (MRB_PROC_ENV_P(m)) {
          regs[0] = MRB_PROC_ENV(m)->stack[0];
        }
        pc = irep->iseq;
      }
      pool = irep->pool;
      syms = irep->syms;
      JUMP;
    }

    CASE(OP_SUPER, BB) {
      mrb_method_t m;
      struct RClass *cls;
      mrb_callinfo *ci = mrb->c->ci;
      mrb_value recv, blk;
      const struct RProc *p = ci->proc;
      mrb_sym mid = ci->mid;
      struct RClass* target_class = MRB_PROC_TARGET_CLASS(p);

      if (MRB_PROC_ENV_P(p) && p->e.env->mid && p->e.env->mid != mid) { /* alias support */
        mid = p->e.env->mid;    /* restore old mid */
      }

      if (mid == 0 || !target_class) {
        mrb_value exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (target_class->flags & MRB_FL_CLASS_IS_PREPENDED) {
        target_class = mrb_vm_ci_target_class(ci);
      }
      else if (target_class->tt == MRB_TT_MODULE) {
        target_class = mrb_vm_ci_target_class(ci);
        if (target_class->tt != MRB_TT_ICLASS) {
          goto super_typeerror;
        }
      }
      recv = regs[0];
      if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
      super_typeerror: ;
        mrb_value exc = mrb_exc_new_lit(mrb, E_TYPE_ERROR,
                                            ""self has wrong type to call super in this context"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }

      ARGUMENT_NORMALIZE(a, &b, OP_SUPER);

      cls = target_class->super;
      m = mrb_method_search_vm(mrb, &cls, mid);
      if (MRB_METHOD_UNDEF_P(m)) {
        m = prepare_missing(mrb, recv, mid, &cls, a, &b, blk, 1);
        mid = MRB_SYM(method_missing);
      }

      /* push callinfo */
      ci = cipush(mrb, a, 0, cls, NULL, mid, b);

      /* prepare stack */
      ci->stack[0] = recv;

      if (MRB_METHOD_CFUNC_P(m)) {
        mrb_value v;

        if (MRB_METHOD_PROC_P(m)) {
          mrb_vm_ci_proc_set(ci, MRB_METHOD_PROC(m));
        }
        v = MRB_METHOD_CFUNC(m)(mrb, recv);
        mrb_gc_arena_restore(mrb, ai);
        if (mrb->exc) goto L_RAISE;
        ci = mrb->c->ci;
        mrb_assert(!mrb_break_p(v));
        if (!mrb_vm_ci_target_class(ci)) { /* return from context modifying method (resume/yield) */
          if (ci->cci == CINFO_RESUMED) {
            mrb->jmp = prev_jmp;
            return v;
          }
          else {
            mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
            proc = ci[-1].proc;
            irep = proc->body.irep;
            pool = irep->pool;
            syms = irep->syms;
          }
        }
        mrb->c->ci->stack[0] = v;
        ci = cipop(mrb);
        pc = ci->pc;
      }
      else {
        /* setup environment for calling method */
        mrb_vm_ci_proc_set(ci, (proc = MRB_METHOD_PROC(m)));
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, (irep->nregs < 4) ? 4 : irep->nregs);
        pc = irep->iseq;
      }
      JUMP;
    }

    CASE(OP_ARGARY, BS) {
      mrb_int m1 = (b>>11)&0x3f;
      mrb_int r  = (b>>10)&0x1;
      mrb_int m2 = (b>>5)&0x1f;
      mrb_int kd = (b>>4)&0x1;
      mrb_int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (mrb->c->ci->mid == 0 || mrb_vm_ci_target_class(mrb->c->ci) == NULL) {
        mrb_value exc;

      L_NOSUPER:
        exc = mrb_exc_new_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method"");
        mrb_exc_set(mrb, exc);
        goto L_RAISE;
      }
      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e) goto L_NOSUPER;
        if (MRB_ENV_LEN(e) <= m1+r+m2+1)
          goto L_NOSUPER;
        stack = e->stack + 1;
      }
      if (r == 0) {
        regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
      }
      else {
        mrb_value *pp = NULL;
        struct RArray *rest;
        mrb_int len = 0;

        if (mrb_array_p(stack[m1])) {
          struct RArray *ary = mrb_ary_ptr(stack[m1]);

          pp = ARY_PTR(ary);
          len = ARY_LEN(ary);
        }
        regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
        rest = mrb_ary_ptr(regs[a]);
        if (m1 > 0) {
          stack_copy(ARY_PTR(rest), stack, m1);
        }
        if (len > 0) {
          stack_copy(ARY_PTR(rest)+m1, pp, len);
        }
        if (m2 > 0) {
          stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
        }
        ARY_SET_LEN(rest, m1+len+m2);
      }
      if (kd) {
        regs[a+1] = stack[m1+r+m2];
        regs[a+2] = stack[m1+r+m2+1];
      }
      else {
        regs[a+1] = stack[m1+r+m2];
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ENTER, W) {
      mrb_int m1 = MRB_ASPEC_REQ(a);
      mrb_int o  = MRB_ASPEC_OPT(a);
      mrb_int r  = MRB_ASPEC_REST(a);
      mrb_int m2 = MRB_ASPEC_POST(a);
      mrb_int kd = (MRB_ASPEC_KEY(a) > 0 || MRB_ASPEC_KDICT(a))? 1 : 0;
      /* unused
      int b  = MRB_ASPEC_BLOCK(a);
      */
      mrb_int const len = m1 + o + r + m2;

      mrb_callinfo *ci = mrb->c->ci;
      mrb_int argc = ci->n;
      mrb_value *argv = regs+1;
      mrb_value * const argv0 = argv;
      mrb_int const kw_pos = len + kd;    /* where kwhash should be */
      mrb_int const blk_pos = kw_pos + 1; /* where block should be */
      mrb_value blk = regs[mrb_ci_bidx(ci)];
      mrb_value kdict = mrb_nil_value();

      /* keyword arguments */
      if (ci->nk > 0) {
        mrb_int kidx = mrb_ci_kidx(ci);
        kdict = regs[kidx];
        if (!mrb_hash_p(kdict) || mrb_hash_size(mrb, kdict) == 0) {
          kdict = mrb_nil_value();
          ci->nk = 0;
        }
      }
      if (!kd && !mrb_nil_p(kdict)) {
        if (argc < 14) {
          ci->n++;
          argc++;    /* include kdict in normal arguments */
        }
        else if (argc == 14) {
          /* pack arguments and kdict */
          regs[1] = mrb_ary_new_from_values(mrb, argc+1, ®s[1]);
          argc = ci->n = 15;
        }
        else {/* argc == 15 */
          /* push kdict to packed arguments */
          mrb_ary_push(mrb, regs[1], regs[2]);
        }
        ci->nk = 0;
      }
      if (kd && MRB_ASPEC_KEY(a) > 0 && mrb_hash_p(kdict)) {
        kdict = mrb_hash_dup(mrb, kdict);
      }

      /* arguments is passed with Array */
      if (argc == 15) {
        struct RArray *ary = mrb_ary_ptr(regs[1]);
        argv = ARY_PTR(ary);
        argc = (int)ARY_LEN(ary);
        mrb_gc_protect(mrb, regs[1]);
      }

      /* strict argument check */
      if (ci->proc && MRB_PROC_STRICT_P(ci->proc)) {
        if (argc < m1 + m2 || (r == 0 && argc > len)) {
          argnum_error(mrb, m1+m2);
          goto L_RAISE;
        }
      }
      /* extract first argument array to arguments */
      else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
        mrb_gc_protect(mrb, argv[0]);
        argc = (int)RARRAY_LEN(argv[0]);
        argv = RARRAY_PTR(argv[0]);
      }

      /* rest arguments */
      mrb_value rest = mrb_nil_value();
      if (argc < len) {
        mrb_int mlen = m2;
        if (argc < m1+m2) {
          mlen = m1 < argc ? argc - m1 : 0;
        }

        /* copy mandatory and optional arguments */
        if (argv0 != argv && argv) {
          value_move(®s[1], argv, argc-mlen); /* m1 + o */
        }
        if (argc < m1) {
          stack_clear(®s[argc+1], m1-argc);
        }
        /* copy post mandatory arguments */
        if (mlen) {
          value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
        }
        if (mlen < m2) {
          stack_clear(®s[len-m2+mlen+1], m2-mlen);
        }
        /* initialize rest arguments with empty Array */
        if (r) {
          rest = mrb_ary_new_capa(mrb, 0);
          regs[m1+o+1] = rest;
        }
        /* skip initializer of passed arguments */
        if (o > 0 && argc > m1+m2)
          pc += (argc - m1 - m2)*3;
      }
      else {
        mrb_int rnum = 0;
        if (argv0 != argv) {
          value_move(®s[1], argv, m1+o);
        }
        if (r) {
          rnum = argc-m1-o-m2;
          rest = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
          regs[m1+o+1] = rest;
        }
        if (m2 > 0 && argc-m2 > m1) {
          value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
        }
        pc += o*3;
      }

      /* need to be update blk first to protect blk from GC */
      regs[blk_pos] = blk;              /* move block */
      if (kd) {
        if (mrb_nil_p(kdict))
          kdict = mrb_hash_new_capa(mrb, 0);
        regs[kw_pos] = kdict;           /* set kwhash */
      }

      /* format arguments for generated code */
      mrb->c->ci->n = len;

      /* clear local (but non-argument) variables */
      if (irep->nlocals-blk_pos-1 > 0) {
        stack_clear(®s[blk_pos+1], irep->nlocals-blk_pos-1);
      }
      JUMP;
    }

    CASE(OP_KARG, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict, v;

      if (kidx < 0 || !mrb_hash_p(kdict=regs[kidx]) || !mrb_hash_key_p(mrb, kdict, k)) {
        mrb_value str = mrb_format(mrb, ""missing keyword: %v"", k);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      v = mrb_hash_get(mrb, kdict, k);
      regs[a] = v;
      mrb_hash_delete_key(mrb, kdict, k);
      NEXT;
    }

    CASE(OP_KEY_P, BB) {
      mrb_value k = mrb_symbol_value(syms[b]);
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;
      mrb_bool key_p = FALSE;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx])) {
        key_p = mrb_hash_key_p(mrb, kdict, k);
      }
      regs[a] = mrb_bool_value(key_p);
      NEXT;
    }

    CASE(OP_KEYEND, Z) {
      mrb_int kidx = mrb_ci_kidx(mrb->c->ci);
      mrb_value kdict;

      if (kidx >= 0 && mrb_hash_p(kdict=regs[kidx]) && !mrb_hash_empty_p(mrb, kdict)) {
        mrb_value keys = mrb_hash_keys(mrb, kdict);
        mrb_value key1 = RARRAY_PTR(keys)[0];
        mrb_value str = mrb_format(mrb, ""unknown keyword: %v"", key1);
        mrb_exc_set(mrb, mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str));
        goto L_RAISE;
      }
      NEXT;
    }

    CASE(OP_BREAK, B) {
      c = OP_R_BREAK;
      goto L_RETURN;
    }
    CASE(OP_RETURN_BLK, B) {
      c = OP_R_RETURN;
      goto L_RETURN;
    }
    CASE(OP_RETURN, B)
    c = OP_R_NORMAL;
    L_RETURN:
    {
      mrb_callinfo *ci;

      ci = mrb->c->ci;
      if (ci->mid) {
        mrb_value blk = regs[mrb_ci_bidx(ci)];

        if (mrb_proc_p(blk)) {
          struct RProc *p = mrb_proc_ptr(blk);

          if (!MRB_PROC_STRICT_P(p) &&
              ci > mrb->c->cibase && MRB_PROC_ENV(p) == mrb_vm_ci_env(&ci[-1])) {
            p->flags |= MRB_PROC_ORPHAN;
          }
        }
      }

      if (mrb->exc) {
      L_RAISE:
        ci = mrb->c->ci;
        if (ci == mrb->c->cibase) {
          ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
          if (ch == NULL) goto L_FTOP;
          goto L_CATCH;
        }
        while ((ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL)) == NULL) {
          ci = cipop(mrb);
          if (ci[1].cci == CINFO_SKIP && prev_jmp) {
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          pc = ci[0].pc;
          if (ci == mrb->c->cibase) {
            ch = catch_handler_find(mrb, ci, pc, MRB_CATCH_FILTER_ALL);
            if (ch == NULL) {
            L_FTOP:             /* fiber top */
              if (mrb->c == mrb->root_c) {
                mrb->c->ci->stack = mrb->c->stbase;
                goto L_STOP;
              }
              else {
                struct mrb_context *c = mrb->c;

                c->status = MRB_FIBER_TERMINATED;
                mrb->c = c->prev;
                c->prev = NULL;
                goto L_RAISE;
              }
            }
            break;
          }
        }
      L_CATCH:
        if (ch == NULL) goto L_STOP;
        if (FALSE) {
        L_CATCH_TAGGED_BREAK: /* from THROW_TAGGED_BREAK() or UNWIND_ENSURE() */
          ci = mrb->c->ci;
        }
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;
        mrb_stack_extend(mrb, irep->nregs);
        pc = irep->iseq + mrb_irep_catch_handler_unpack(ch->target);
      }
      else {
        mrb_int acc;
        mrb_value v;

        ci = mrb->c->ci;
        v = regs[a];
        mrb_gc_protect(mrb, v);
        switch (c) {
        case OP_R_RETURN:
          /* Fall through to OP_R_NORMAL otherwise */
          if (ci->cci == CINFO_NONE && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
            const struct RProc *dst;
            mrb_callinfo *cibase;
            cibase = mrb->c->cibase;
            dst = top_proc(mrb, proc);

            if (MRB_PROC_ENV_P(dst)) {
              struct REnv *e = MRB_PROC_ENV(dst);

              if (!MRB_ENV_ONSTACK_P(e) || (e->cxt && e->cxt != mrb->c)) {
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
            }
            /* check jump destination */
            while (cibase <= ci && ci->proc != dst) {
              if (ci->cci > CINFO_NONE) { /* jump cross C boundary */
                localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
                goto L_RAISE;
              }
              ci--;
            }
            if (ci <= cibase) { /* no jump destination */
              localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
              goto L_RAISE;
            }
            ci = mrb->c->ci;
            while (cibase <= ci && ci->proc != dst) {
              CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_BLOCK) {
                cibase = mrb->c->cibase;
                dst = top_proc(mrb, proc);
              }
              CHECKPOINT_MAIN(RBREAK_TAG_RETURN_BLOCK) {
                UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_BLOCK, proc, v);
              }
              CHECKPOINT_END(RBREAK_TAG_RETURN_BLOCK);
              ci = cipop(mrb);
              pc = ci->pc;
            }
            proc = ci->proc;
            mrb->exc = NULL; /* clear break object */
            break;
          }
          /* fallthrough */
        case OP_R_NORMAL:
        NORMAL_RETURN:
          if (ci == mrb->c->cibase) {
            struct mrb_context *c;
            c = mrb->c;

            if (!c->prev) { /* toplevel return */
              regs[irep->nlocals] = v;
              goto CHECKPOINT_LABEL_MAKE(RBREAK_TAG_STOP);
            }
            if (!c->vmexec && c->prev->ci == c->prev->cibase) {
              mrb_value exc = mrb_exc_new_lit(mrb, E_FIBER_ERROR, ""double resume"");
              mrb_exc_set(mrb, exc);
              goto L_RAISE;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_RETURN_TOPLEVEL) {
              c = mrb->c;
            }
            CHECKPOINT_MAIN(RBREAK_TAG_RETURN_TOPLEVEL) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN_TOPLEVEL, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_RETURN_TOPLEVEL);
            /* automatic yield at the end */
            c->status = MRB_FIBER_TERMINATED;
            mrb->c = c->prev;
            mrb->c->status = MRB_FIBER_RUNNING;
            c->prev = NULL;
            if (c->vmexec) {
              mrb_gc_arena_restore(mrb, ai);
              c->vmexec = FALSE;
              mrb->jmp = prev_jmp;
              return v;
            }
            ci = mrb->c->ci;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_RETURN) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_RETURN) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_RETURN, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_RETURN);
          mrb->exc = NULL; /* clear break object */
          break;
        case OP_R_BREAK:
          if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
          if (MRB_PROC_ORPHAN_P(proc)) {
            mrb_value exc;

          L_BREAK_ERROR:
            exc = mrb_exc_new_lit(mrb, E_LOCALJUMP_ERROR,
                                      ""break from proc-closure"");
            mrb_exc_set(mrb, exc);
            goto L_RAISE;
          }
          if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_ONSTACK_P(MRB_PROC_ENV(proc))) {
            goto L_BREAK_ERROR;
          }
          else {
            struct REnv *e = MRB_PROC_ENV(proc);

            if (e->cxt != mrb->c) {
              goto L_BREAK_ERROR;
            }
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK);
          /* break from fiber block */
          if (ci == mrb->c->cibase && ci->pc) {
            struct mrb_context *c = mrb->c;

            mrb->c = c->prev;
            c->prev = NULL;
            ci = mrb->c->ci;
          }
          if (ci->cci > CINFO_NONE) {
            ci = cipop(mrb);
            mrb_gc_arena_restore(mrb, ai);
            mrb->c->vmexec = FALSE;
            mrb->exc = (struct RObject*)break_new(mrb, RBREAK_TAG_BREAK, proc, v);
            mrb->jmp = prev_jmp;
            MRB_THROW(prev_jmp);
          }
          if (FALSE) {
            struct RBreak *brk;

          L_BREAK:
            brk = (struct RBreak*)mrb->exc;
            proc = mrb_break_proc_get(brk);
            v = mrb_break_value_get(brk);
            ci = mrb->c->ci;

            switch (mrb_break_tag_get(brk)) {
#define DISPATCH_CHECKPOINTS(n, i) case n: goto CHECKPOINT_LABEL_MAKE(n);
              RBREAK_TAG_FOREACH(DISPATCH_CHECKPOINTS)
#undef DISPATCH_CHECKPOINTS
              default:
                mrb_assert(!""wrong break tag"");
            }
          }
          while (mrb->c->cibase < ci && ci[-1].proc != proc->upper) {
            if (ci[-1].cci == CINFO_SKIP) {
              goto L_BREAK_ERROR;
            }
            CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_UPPER) {
              /* do nothing */
            }
            CHECKPOINT_MAIN(RBREAK_TAG_BREAK_UPPER) {
              UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_UPPER, proc, v);
            }
            CHECKPOINT_END(RBREAK_TAG_BREAK_UPPER);
            ci = cipop(mrb);
            pc = ci->pc;
          }
          CHECKPOINT_RESTORE(RBREAK_TAG_BREAK_INTARGET) {
            /* do nothing */
          }
          CHECKPOINT_MAIN(RBREAK_TAG_BREAK_INTARGET) {
            UNWIND_ENSURE(mrb, ci, pc, RBREAK_TAG_BREAK_INTARGET, proc, v);
          }
          CHECKPOINT_END(RBREAK_TAG_BREAK_INTARGET);
          if (ci == mrb->c->cibase) {
            goto L_BREAK_ERROR;
          }
          mrb->exc = NULL; /* clear break object */
          break;
        default:
          /* cannot happen */
          break;
        }
        mrb_assert(ci == mrb->c->ci);
        mrb_assert(mrb->exc == NULL);

        if (mrb->c->vmexec && !mrb_vm_ci_target_class(ci)) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->c->vmexec = FALSE;
          mrb->jmp = prev_jmp;
          return v;
        }
        acc = ci->cci;
        ci = cipop(mrb);
        if (acc == CINFO_SKIP || acc == CINFO_DIRECT) {
          mrb_gc_arena_restore(mrb, ai);
          mrb->jmp = prev_jmp;
          return v;
        }
        pc = ci->pc;
        DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym_name(mrb, ci->mid)));
        proc = ci->proc;
        irep = proc->body.irep;
        pool = irep->pool;
        syms = irep->syms;

        ci[1].stack[0] = v;
        mrb_gc_arena_restore(mrb, ai);
      }
      JUMP;
    }

    CASE(OP_BLKPUSH, BS) {
      int m1 = (b>>11)&0x3f;
      int r  = (b>>10)&0x1;
      int m2 = (b>>5)&0x1f;
      int kd = (b>>4)&0x1;
      int lv = (b>>0)&0xf;
      mrb_value *stack;

      if (lv == 0) stack = regs + 1;
      else {
        struct REnv *e = uvenv(mrb, lv-1);
        if (!e || (!MRB_ENV_ONSTACK_P(e) && e->mid == 0) ||
            MRB_ENV_LEN(e) <= m1+r+m2+1) {
          localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
          goto L_RAISE;
        }
        stack = e->stack + 1;
      }
      if (mrb_nil_p(stack[m1+r+m2+kd])) {
        localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
        goto L_RAISE;
      }
      regs[a] = stack[m1+r+m2+kd];
      NEXT;
    }

  L_INT_OVERFLOW:
    {
      mrb_value exc = mrb_exc_new_lit(mrb, E_RANGE_ERROR, ""integer overflow"");
      mrb_exc_set(mrb, exc);
    }
    goto L_RAISE;

#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH(op_name)                                                    \
  /* need to check if op is overridden */                                   \
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {                  \
    OP_MATH_CASE_INTEGER(op_name);                                          \
    OP_MATH_CASE_FLOAT(op_name, integer, float);                            \
    OP_MATH_CASE_FLOAT(op_name, float,  integer);                           \
    OP_MATH_CASE_FLOAT(op_name, float,  float);                             \
    OP_MATH_CASE_STRING_##op_name();                                        \
    default:                                                                \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATH_CASE_INTEGER(op_name)                                       \
  case TYPES2(MRB_TT_INTEGER, MRB_TT_INTEGER):                              \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = mrb_integer(regs[a+1]), z;      \
      if (mrb_int_##op_name##_overflow(x, y, &z))                           \
        OP_MATH_OVERFLOW_INT();                                             \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATH_CASE_FLOAT(op_name, t1, t2) (void)0
#else
#define OP_MATH_CASE_FLOAT(op_name, t1, t2)                                     \
  case TYPES2(OP_MATH_TT_##t1, OP_MATH_TT_##t2):                                \
    {                                                                           \
      mrb_float z = mrb_##t1(regs[a]) OP_MATH_OP_##op_name mrb_##t2(regs[a+1]); \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                         \
    }                                                                           \
    break
#endif
#define OP_MATH_OVERFLOW_INT() goto L_INT_OVERFLOW
#define OP_MATH_CASE_STRING_add()                                           \
  case TYPES2(MRB_TT_STRING, MRB_TT_STRING):                                \
    regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);                        \
    mrb_gc_arena_restore(mrb, ai);                                          \
    break
#define OP_MATH_CASE_STRING_sub() (void)0
#define OP_MATH_CASE_STRING_mul() (void)0
#define OP_MATH_OP_add +
#define OP_MATH_OP_sub -
#define OP_MATH_OP_mul *
#define OP_MATH_TT_integer MRB_TT_INTEGER
#define OP_MATH_TT_float   MRB_TT_FLOAT

    CASE(OP_ADD, B) {
      OP_MATH(add);
    }

    CASE(OP_SUB, B) {
      OP_MATH(sub);
    }

    CASE(OP_MUL, B) {
      OP_MATH(mul);
    }

    CASE(OP_DIV, B) {
#ifndef MRB_NO_FLOAT
      mrb_float x, y, f;
#endif

      /* need to check if op is overridden */
      switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
      case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):
        {
          mrb_int x = mrb_integer(regs[a]);
          mrb_int y = mrb_integer(regs[a+1]);
          mrb_int div = mrb_div_int(mrb, x, y);
          SET_INT_VALUE(mrb, regs[a], div);
        }
        NEXT;
#ifndef MRB_NO_FLOAT
      case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):
        x = (mrb_float)mrb_integer(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):
        x = mrb_float(regs[a]);
        y = (mrb_float)mrb_integer(regs[a+1]);
        break;
      case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
        x = mrb_float(regs[a]);
        y = mrb_float(regs[a+1]);
        break;
#endif
      default:
        mid = MRB_OPSYM(div);
        goto L_SEND_SYM;
      }

#ifndef MRB_NO_FLOAT
      f = mrb_div_float(x, y);
      SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
      NEXT;
    }

#define OP_MATHI(op_name)                                                   \
  /* need to check if op is overridden */                                   \
  switch (mrb_type(regs[a])) {                                              \
    OP_MATHI_CASE_INTEGER(op_name);                                         \
    OP_MATHI_CASE_FLOAT(op_name);                                           \
    default:                                                                \
      SET_INT_VALUE(mrb,regs[a+1], b);                                      \
      mid = MRB_OPSYM(op_name);                                             \
      goto L_SEND_SYM;                                                      \
  }                                                                         \
  NEXT;
#define OP_MATHI_CASE_INTEGER(op_name)                                      \
  case MRB_TT_INTEGER:                                                      \
    {                                                                       \
      mrb_int x = mrb_integer(regs[a]), y = (mrb_int)b, z;                  \
      if (mrb_int_##op_name##_overflow(x, y, &z))                           \
        OP_MATH_OVERFLOW_INT();                                             \
      else                                                                  \
        SET_INT_VALUE(mrb,regs[a], z);                                      \
    }                                                                       \
    break
#ifdef MRB_NO_FLOAT
#define OP_MATHI_CASE_FLOAT(op_name) (void)0
#else
#define OP_MATHI_CASE_FLOAT(op_name)                                        \
  case MRB_TT_FLOAT:                                                        \
    {                                                                       \
      mrb_float z = mrb_float(regs[a]) OP_MATH_OP_##op_name b;              \
      SET_FLOAT_VALUE(mrb, regs[a], z);                                     \
    }                                                                       \
    break
#endif

    CASE(OP_ADDI, BB) {
      OP_MATHI(add);
    }

    CASE(OP_SUBI, BB) {
      OP_MATHI(sub);
    }

#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))

#ifdef MRB_NO_FLOAT
#define OP_CMP(op,sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#else
#define OP_CMP(op, sym) do {\
  int result;\
  /* need to check if - is overridden */\
  switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_INTEGER,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_INTEGER):\
    result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
    break;\
  case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
    result = OP_CMP_BODY(op,mrb_float,mrb_float);\
    break;\
  default:\
    mid = MRB_OPSYM(sym);\
    goto L_SEND_SYM;\
  }\
  if (result) {\
    SET_TRUE_VALUE(regs[a]);\
  }\
  else {\
    SET_FALSE_VALUE(regs[a]);\
  }\
} while(0)
#endif

    CASE(OP_EQ, B) {
      if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
        SET_TRUE_VALUE(regs[a]);
      }
      else {
        OP_CMP(==,eq);
      }
      NEXT;
    }

    CASE(OP_LT, B) {
      OP_CMP(<,lt);
      NEXT;
    }

    CASE(OP_LE, B) {
      OP_CMP(<=,le);
      NEXT;
    }

    CASE(OP_GT, B) {
      OP_CMP(>,gt);
      NEXT;
    }

    CASE(OP_GE, B) {
      OP_CMP(>=,ge);
      NEXT;
    }

    CASE(OP_ARRAY, BB) {
      regs[a] = mrb_ary_new_from_values(mrb, b, ®s[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_ARRAY2, BBB) {
      regs[a] = mrb_ary_new_from_values(mrb, c, ®s[b]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYCAT, B) {
      mrb_value splat = mrb_ary_splat(mrb, regs[a+1]);
      if (mrb_nil_p(regs[a])) {
        regs[a] = splat;
      }
      else {
        mrb_assert(mrb_array_p(regs[a]));
        mrb_ary_concat(mrb, regs[a], splat);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_ARYPUSH, BB) {
      mrb_assert(mrb_array_p(regs[a]));
      for (mrb_int i=0; i pre + post) {
        v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
        regs[a++] = v;
        while (post--) {
          regs[a++] = ARY_PTR(ary)[len-post-1];
        }
      }
      else {
        v = mrb_ary_new_capa(mrb, 0);
        regs[a++] = v;
        for (idx=0; idx+pre> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        sym = mrb_intern_static(mrb, pool[b].u.str, len);
      }
      else {
        sym  = mrb_intern(mrb, pool[b].u.str, len);
      }
      regs[a] = mrb_symbol_value(sym);
      NEXT;
    }

    CASE(OP_STRING, BB) {
      mrb_int len;

      mrb_assert((pool[b].tt&IREP_TT_NFLAG)==0);
      len = pool[b].tt >> 2;
      if (pool[b].tt & IREP_TT_SFLAG) {
        regs[a] = mrb_str_new_static(mrb, pool[b].u.str, len);
      }
      else {
        regs[a] = mrb_str_new(mrb, pool[b].u.str, len);
      }
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_STRCAT, B) {
      mrb_assert(mrb_string_p(regs[a]));
      mrb_str_concat(mrb, regs[a], regs[a+1]);
      NEXT;
    }

    CASE(OP_HASH, BB) {
      mrb_value hash = mrb_hash_new_capa(mrb, b);
      int i;
      int lim = a+b*2;

      for (i=a; ireps[b];

      if (c & OP_L_CAPTURE) {
        p = mrb_closure_new(mrb, nirep);
      }
      else {
        p = mrb_proc_new(mrb, nirep);
        p->flags |= MRB_PROC_SCOPE;
      }
      if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
      regs[a] = mrb_obj_value(p);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }
    CASE(OP_BLOCK, BB) {
      c = OP_L_BLOCK;
      goto L_MAKE_LAMBDA;
    }
    CASE(OP_METHOD, BB) {
      c = OP_L_METHOD;
      goto L_MAKE_LAMBDA;
    }

    CASE(OP_RANGE_INC, B) {
      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], FALSE);
      regs[a] = v;
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_RANGE_EXC, B) {
      mrb_value v = mrb_range_new(mrb, regs[a], regs[a+1], TRUE);
      regs[a] = v;
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_OCLASS, B) {
      regs[a] = mrb_obj_value(mrb->object_class);
      NEXT;
    }

    CASE(OP_CLASS, BB) {
      struct RClass *c = 0, *baseclass;
      mrb_value base, super;
      mrb_sym id = syms[b];

      base = regs[a];
      super = regs[a+1];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      c = mrb_vm_define_class(mrb, base, super, id);
      regs[a] = mrb_obj_value(c);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_MODULE, BB) {
      struct RClass *cls = 0, *baseclass;
      mrb_value base;
      mrb_sym id = syms[b];

      base = regs[a];
      if (mrb_nil_p(base)) {
        baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
        if (!baseclass) baseclass = mrb->object_class;
        base = mrb_obj_value(baseclass);
      }
      cls = mrb_vm_define_module(mrb, base, id);
      regs[a] = mrb_obj_value(cls);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_EXEC, BB)
    {
      mrb_value recv = regs[a];
      struct RProc *p;
      const mrb_irep *nirep = irep->reps[b];

      /* prepare closure */
      p = mrb_proc_new(mrb, nirep);
      p->c = NULL;
      mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
      MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
      p->flags |= MRB_PROC_SCOPE;

      /* prepare call stack */
      cipush(mrb, a, 0, mrb_class_ptr(recv), p, 0, 0);

      irep = p->body.irep;
      pool = irep->pool;
      syms = irep->syms;
      mrb_stack_extend(mrb, irep->nregs);
      stack_clear(regs+1, irep->nregs-1);
      pc = irep->iseq;
      JUMP;
    }

    CASE(OP_DEF, BB) {
      struct RClass *target = mrb_class_ptr(regs[a]);
      struct RProc *p = mrb_proc_ptr(regs[a+1]);
      mrb_method_t m;
      mrb_sym mid = syms[b];

      MRB_METHOD_FROM_PROC(m, p);
      mrb_define_method_raw(mrb, target, mid, m);
      mrb_method_added(mrb, target, mid);
      mrb_gc_arena_restore(mrb, ai);
      regs[a] = mrb_symbol_value(mid);
      NEXT;
    }

    CASE(OP_SCLASS, B) {
      regs[a] = mrb_singleton_class(mrb, regs[a]);
      mrb_gc_arena_restore(mrb, ai);
      NEXT;
    }

    CASE(OP_TCLASS, B) {
      struct RClass *target = check_target_class(mrb);
      if (!target) goto L_RAISE;
      regs[a] = mrb_obj_value(target);
      NEXT;
    }

    CASE(OP_ALIAS, BB) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_alias_method(mrb, target, syms[a], syms[b]);
      mrb_method_added(mrb, target, syms[a]);
      NEXT;
    }
    CASE(OP_UNDEF, B) {
      struct RClass *target = check_target_class(mrb);

      if (!target) goto L_RAISE;
      mrb_undef_method_id(mrb, target, syms[a]);
      NEXT;
    }

    CASE(OP_DEBUG, Z) {
      FETCH_BBB();
#ifdef MRB_USE_DEBUG_HOOK
      mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_NO_STDIO
      printf(""OP_DEBUG %d %d %d\n"", a, b, c);
#else
      abort();
#endif
#endif
      NEXT;
    }

    CASE(OP_ERR, B) {
      size_t len = pool[a].tt >> 2;
      mrb_value exc;

      mrb_assert((pool[a].tt&IREP_TT_NFLAG)==0);
      exc = mrb_exc_new(mrb, E_LOCALJUMP_ERROR, pool[a].u.str, len);
      mrb_exc_set(mrb, exc);
      goto L_RAISE;
    }

    CASE(OP_EXT1, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _1(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT2, Z) {
      insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _2(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }
    CASE(OP_EXT3, Z) {
      uint8_t insn = READ_B();
      switch (insn) {
#define OPCODE(insn,ops) case OP_ ## insn: FETCH_ ## ops ## _3(); mrb->c->ci->pc = pc; goto L_OP_ ## insn ## _BODY;
#include ""mruby/ops.h""
#undef OPCODE
      }
      pc--;
      NEXT;
    }

    CASE(OP_STOP, Z) {
      /*        stop VM */
      CHECKPOINT_RESTORE(RBREAK_TAG_STOP) {
        /* do nothing */
      }
      CHECKPOINT_MAIN(RBREAK_TAG_STOP) {
        UNWIND_ENSURE(mrb, mrb->c->ci, pc, RBREAK_TAG_STOP, proc, mrb_nil_value());
      }
      CHECKPOINT_END(RBREAK_TAG_STOP);
    L_STOP:
      mrb->jmp = prev_jmp;
      if (mrb->exc) {
        mrb_assert(mrb->exc->tt == MRB_TT_EXCEPTION);
        return mrb_obj_value(mrb->exc);
      }
      return regs[irep->nlocals];
    }
  }
  END_DISPATCH;
#undef regs
  }
  MRB_CATCH(&c_jmp) {
    mrb_callinfo *ci = mrb->c->ci;
    while (ci > mrb->c->cibase && ci->cci == CINFO_DIRECT) {
      ci = cipop(mrb);
    }
    exc_catched = TRUE;
    pc = ci->pc;
    goto RETRY_TRY_BLOCK;
  }
  MRB_END_EXC(&c_jmp);
}",CWE-476,12
0,"  virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {
    if (!network_manager_observers_.HasObserver(observer))
      network_manager_observers_.AddObserver(observer);
  }
",none,24
0,"  virtual void ConnectToWifiNetwork(const WifiNetwork* network,
                                    const std::string& password,
                                    const std::string& identity,
                                    const std::string& certpath) {}
",none,24
1,"static RList *symbols(RBinFile *bf) {
	RList *res = r_list_newf ((RListFree)r_bin_symbol_free);
	r_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);
	RCoreSymCacheElement *element = bf->o->bin_obj;
	size_t i;
	HtUU *hash = ht_uu_new0 ();
	if (!hash) {
		return res;
	}
	bool found = false;
	for (i = 0; i < element->hdr->n_lined_symbols; i++) {
		RCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];
		ht_uu_find (hash, sym->paddr, &found);
		if (found) {
			continue;
		}
		RBinSymbol *s = bin_symbol_from_symbol (element, sym);
		if (s) {
			r_list_append (res, s);
			ht_uu_insert (hash, sym->paddr, 1);
		}
	}
	if (element->symbols) {
		for (i = 0; i < element->hdr->n_symbols; i++) {
			RCoreSymCacheElementSymbol *sym = &element->symbols[i];
			ht_uu_find (hash, sym->paddr, &found);
			if (found) {
				continue;
			}
			RBinSymbol *s = bin_symbol_from_symbol (element, sym);
			if (s) {
				r_list_append (res, s);
			}
		}
	}
	ht_uu_free (hash);
	return res;
}",CWE-476,12
0,"void Network::Clear() {
  state_ = STATE_UNKNOWN;
  error_ = ERROR_UNKNOWN;
  service_path_.clear();
  device_path_.clear();
  ip_address_.clear();
  is_active_ = false;
}
",none,24
0,"  virtual const Network* active_network() const {
    if (ethernet_ && ethernet_->is_active())
      return ethernet_;
    if (wifi_ && wifi_->is_active())
      return wifi_;
    if (cellular_ && cellular_->is_active())
      return cellular_;
    return NULL;
  }
",none,24
1,"static void parse_relocation_info(struct MACH0_(obj_t) *bin, RSkipList *relocs, ut32 offset, ut32 num) {
	if (!num || !offset || (st32)num < 0) {
		return;
	}

	ut64 total_size = num * sizeof (struct relocation_info);
	if (offset > bin->size) {
		return;
	}
	if (total_size > bin->size) {
		total_size = bin->size - offset;
		num = total_size /= sizeof (struct relocation_info);
	}
	struct relocation_info *info = calloc (num, sizeof (struct relocation_info));
	if (!info) {
		return;
	}

	if (r_buf_read_at (bin->b, offset, (ut8 *) info, total_size) < total_size) {
		free (info);
		return;
	}

	size_t i;
	for (i = 0; i < num; i++) {
		struct relocation_info a_info = info[i];
		ut32 sym_num = a_info.r_symbolnum;
		if (sym_num > bin->nsymtab) {
			continue;
		}

		ut32 stridx = bin->symtab[sym_num].n_strx;
		char *sym_name = get_name (bin, stridx, false);
		if (!sym_name) {
			continue;
		}

		struct reloc_t *reloc = R_NEW0 (struct reloc_t);
		if (!reloc) {
			free (info);
			free (sym_name);
			return;
		}

		reloc->addr = offset_to_vaddr (bin, a_info.r_address);
		reloc->offset = a_info.r_address;
		reloc->ord = sym_num;
		reloc->type = a_info.r_type; // enum RelocationInfoType
		reloc->external = a_info.r_extern;
		reloc->pc_relative = a_info.r_pcrel;
		reloc->size = a_info.r_length;
		r_str_ncpy (reloc->name, sym_name, sizeof (reloc->name) - 1);
		r_skiplist_insert (relocs, reloc);
		free (sym_name);
	}
	free (info);
}",CWE-787,16
1,"glob (const char *pattern, int flags, int (*errfunc) (const char *, int),
      glob_t *pglob)
{
  const char *filename;
  char *dirname = NULL;
  size_t dirlen;
  int status;
  size_t oldcount;
  int meta;
  int dirname_modified;
  int malloc_dirname = 0;
  glob_t dirs;
  int retval = 0;
  size_t alloca_used = 0;

  if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
    {
      __set_errno (EINVAL);
      return -1;
    }

  /* POSIX requires all slashes to be matched.  This means that with
     a trailing slash we must match only directories.  */
  if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
    flags |= GLOB_ONLYDIR;

  if (!(flags & GLOB_DOOFFS))
    /* Have to do this so 'globfree' knows where to start freeing.  It
       also makes all the code that uses gl_offs simpler. */
    pglob->gl_offs = 0;

  if (!(flags & GLOB_APPEND))
    {
      pglob->gl_pathc = 0;
      if (!(flags & GLOB_DOOFFS))
        pglob->gl_pathv = NULL;
      else
        {
          size_t i;

          if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *))
            return GLOB_NOSPACE;

          pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1)
                                              * sizeof (char *));
          if (pglob->gl_pathv == NULL)
            return GLOB_NOSPACE;

          for (i = 0; i <= pglob->gl_offs; ++i)
            pglob->gl_pathv[i] = NULL;
        }
    }

  if (flags & GLOB_BRACE)
    {
      const char *begin;

      if (flags & GLOB_NOESCAPE)
        begin = strchr (pattern, '{');
      else
        {
          begin = pattern;
          while (1)
            {
              if (*begin == '\0')
                {
                  begin = NULL;
                  break;
                }

              if (*begin == '\\' && begin[1] != '\0')
                ++begin;
              else if (*begin == '{')
                break;

              ++begin;
            }
        }

      if (begin != NULL)
        {
          /* Allocate working buffer large enough for our work.  Note that
             we have at least an opening and closing brace.  */
          size_t firstc;
          char *alt_start;
          const char *p;
          const char *next;
          const char *rest;
          size_t rest_len;
          char *onealt;
          size_t pattern_len = strlen (pattern) - 1;
          int alloca_onealt = glob_use_alloca (alloca_used, pattern_len);
          if (alloca_onealt)
            onealt = alloca_account (pattern_len, alloca_used);
          else
            {
              onealt = malloc (pattern_len);
              if (onealt == NULL)
                return GLOB_NOSPACE;
            }

          /* We know the prefix for all sub-patterns.  */
          alt_start = mempcpy (onealt, pattern, begin - pattern);

          /* Find the first sub-pattern and at the same time find the
             rest after the closing brace.  */
          next = next_brace_sub (begin + 1, flags);
          if (next == NULL)
            {
              /* It is an invalid expression.  */
            illegal_brace:
              if (__glibc_unlikely (!alloca_onealt))
                free (onealt);
              flags &= ~GLOB_BRACE;
              goto no_brace;
            }

          /* Now find the end of the whole brace expression.  */
          rest = next;
          while (*rest != '}')
            {
              rest = next_brace_sub (rest + 1, flags);
              if (rest == NULL)
                /* It is an illegal expression.  */
                goto illegal_brace;
            }
          /* Please note that we now can be sure the brace expression
             is well-formed.  */
          rest_len = strlen (++rest) + 1;

          /* We have a brace expression.  BEGIN points to the opening {,
             NEXT points past the terminator of the first element, and END
             points past the final }.  We will accumulate result names from
             recursive runs for each brace alternative in the buffer using
             GLOB_APPEND.  */
          firstc = pglob->gl_pathc;

          p = begin + 1;
          while (1)
            {
              int result;

              /* Construct the new glob expression.  */
              mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len);

              result = glob (onealt,
                             ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC))
                              | GLOB_APPEND), errfunc, pglob);

              /* If we got an error, return it.  */
              if (result && result != GLOB_NOMATCH)
                {
                  if (__glibc_unlikely (!alloca_onealt))
                    free (onealt);
                  if (!(flags & GLOB_APPEND))
                    {
                      globfree (pglob);
                      pglob->gl_pathc = 0;
                    }
                  return result;
                }

              if (*next == '}')
                /* We saw the last entry.  */
                break;

              p = next + 1;
              next = next_brace_sub (p, flags);
              assert (next != NULL);
            }

          if (__glibc_unlikely (!alloca_onealt))
            free (onealt);

          if (pglob->gl_pathc != firstc)
            /* We found some entries.  */
            return 0;
          else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
            return GLOB_NOMATCH;
        }
    }

 no_brace:
  oldcount = pglob->gl_pathc + pglob->gl_offs;

  /* Find the filename.  */
  filename = strrchr (pattern, '/');

#if defined __MSDOS__ || defined WINDOWS32
  /* The case of ""d:pattern"".  Since ':' is not allowed in
     file names, we can safely assume that wherever it
     happens in pattern, it signals the filename part.  This
     is so we could some day support patterns like ""[a-z]:foo"".  */
  if (filename == NULL)
    filename = strchr (pattern, ':');
#endif /* __MSDOS__ || WINDOWS32 */

  dirname_modified = 0;
  if (filename == NULL)
    {
      /* This can mean two things: a simple name or ""~name"".  The latter
         case is nothing but a notation for a directory.  */
      if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~')
        {
          dirname = (char *) pattern;
          dirlen = strlen (pattern);

          /* Set FILENAME to NULL as a special flag.  This is ugly but
             other solutions would require much more code.  We test for
             this special case below.  */
          filename = NULL;
        }
      else
        {
          if (__glibc_unlikely (pattern[0] == '\0'))
            {
              dirs.gl_pathv = NULL;
              goto no_matches;
            }

          filename = pattern;
          dirname = (char *) ""."";
          dirlen = 0;
        }
    }
  else if (filename == pattern
           || (filename == pattern + 1 && pattern[0] == '\\'
               && (flags & GLOB_NOESCAPE) == 0))
    {
      /* ""/pattern"" or ""\\/pattern"".  */
      dirname = (char *) ""/"";
      dirlen = 1;
      ++filename;
    }
  else
    {
      char *newp;
      dirlen = filename - pattern;

#if defined __MSDOS__ || defined WINDOWS32
      if (*filename == ':'
          || (filename > pattern + 1 && filename[-1] == ':'))
        {
          char *drive_spec;

          ++dirlen;
          drive_spec = __alloca (dirlen + 1);
          *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0';
          /* For now, disallow wildcards in the drive spec, to
             prevent infinite recursion in glob.  */
          if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE)))
            return GLOB_NOMATCH;
          /* If this is ""d:pattern"", we need to copy ':' to DIRNAME
             as well.  If it's ""d:/pattern"", don't remove the slash
             from ""d:/"", since ""d:"" and ""d:/"" are not the same.*/
        }
#endif

      if (glob_use_alloca (alloca_used, dirlen + 1))
        newp = alloca_account (dirlen + 1, alloca_used);
      else
        {
          newp = malloc (dirlen + 1);
          if (newp == NULL)
            return GLOB_NOSPACE;
          malloc_dirname = 1;
        }
      *((char *) mempcpy (newp, pattern, dirlen)) = '\0';
      dirname = newp;
      ++filename;

#if defined __MSDOS__ || defined WINDOWS32
      bool drive_root = (dirlen > 1
                         && (dirname[dirlen - 1] == ':'
                             || (dirlen > 2 && dirname[dirlen - 2] == ':'
                                 && dirname[dirlen - 1] == '/')));
#else
      bool drive_root = false;
#endif

      if (filename[0] == '\0' && dirlen > 1 && !drive_root)
        /* ""pattern/"".  Expand ""pattern"", appending slashes.  */
        {
          int orig_flags = flags;
          if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\')
            {
              /* ""pattern\\/"".  Remove the final backslash if it hasn't
                 been quoted.  */
              char *p = (char *) &dirname[dirlen - 1];

              while (p > dirname && p[-1] == '\\') --p;
              if ((&dirname[dirlen] - p) & 1)
                {
                  *(char *) &dirname[--dirlen] = '\0';
                  flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
                }
            }
          int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
          if (val == 0)
            pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK)
                               | (flags & GLOB_MARK));
          else if (val == GLOB_NOMATCH && flags != orig_flags)
            {
              /* Make sure globfree (&dirs); is a nop.  */
              dirs.gl_pathv = NULL;
              flags = orig_flags;
              oldcount = pglob->gl_pathc + pglob->gl_offs;
              goto no_matches;
            }
          retval = val;
          goto out;
        }
    }

  if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~')
    {
      if (dirname[1] == '\0' || dirname[1] == '/'
          || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\'
              && (dirname[2] == '\0' || dirname[2] == '/')))
        {
          /* Look up home directory.  */
          char *home_dir = getenv (""HOME"");
          int malloc_home_dir = 0;
          if (home_dir == NULL || home_dir[0] == '\0')
            {
#ifdef WINDOWS32
              /* Windows NT defines HOMEDRIVE and HOMEPATH.  But give
                 preference to HOME, because the user can change HOME.  */
              const char *home_drive = getenv (""HOMEDRIVE"");
              const char *home_path = getenv (""HOMEPATH"");

              if (home_drive != NULL && home_path != NULL)
                {
                  size_t home_drive_len = strlen (home_drive);
                  size_t home_path_len = strlen (home_path);
                  char *mem = alloca (home_drive_len + home_path_len + 1);

                  memcpy (mem, home_drive, home_drive_len);
                  memcpy (mem + home_drive_len, home_path, home_path_len + 1);
                  home_dir = mem;
                }
              else
                home_dir = ""c:/users/default""; /* poor default */
#else
              int err;
              struct passwd *p;
              struct passwd pwbuf;
              struct scratch_buffer s;
              scratch_buffer_init (&s);
              while (true)
                {
                  p = NULL;
                  err = __getlogin_r (s.data, s.length);
                  if (err == 0)
                    {
# if defined HAVE_GETPWNAM_R || defined _LIBC
                      size_t ssize = strlen (s.data) + 1;
                      err = getpwnam_r (s.data, &pwbuf, s.data + ssize,
                                        s.length - ssize, &p);
# else
                      p = getpwnam (s.data);
                      if (p == NULL)
                        err = errno;
# endif
                    }
                  if (err != ERANGE)
                    break;
                  if (!scratch_buffer_grow (&s))
                    {
                      retval = GLOB_NOSPACE;
                      goto out;
                    }
                }
              if (err == 0)
                {
                  home_dir = strdup (p->pw_dir);
                  malloc_home_dir = 1;
                }
              scratch_buffer_free (&s);
              if (err == 0 && home_dir == NULL)
                {
                  retval = GLOB_NOSPACE;
                  goto out;
                }
#endif /* WINDOWS32 */
            }
          if (home_dir == NULL || home_dir[0] == '\0')
            {
              if (__glibc_unlikely (malloc_home_dir))
                free (home_dir);
              if (flags & GLOB_TILDE_CHECK)
                {
                  retval = GLOB_NOMATCH;
                  goto out;
                }
              else
                {
                  home_dir = (char *) ""~""; /* No luck.  */
                  malloc_home_dir = 0;
                }
            }
          /* Now construct the full directory.  */
          if (dirname[1] == '\0')
            {
              if (__glibc_unlikely (malloc_dirname))
                free (dirname);

              dirname = home_dir;
              dirlen = strlen (dirname);
              malloc_dirname = malloc_home_dir;
            }
          else
            {
              char *newp;
              size_t home_len = strlen (home_dir);
              int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen);
              if (use_alloca)
                newp = alloca_account (home_len + dirlen, alloca_used);
              else
                {
                  newp = malloc (home_len + dirlen);
                  if (newp == NULL)
                    {
                      if (__glibc_unlikely (malloc_home_dir))
                        free (home_dir);
                      retval = GLOB_NOSPACE;
                      goto out;
                    }
                }

              mempcpy (mempcpy (newp, home_dir, home_len),
                       &dirname[1], dirlen);

              if (__glibc_unlikely (malloc_dirname))
                free (dirname);

              dirname = newp;
              dirlen += home_len - 1;
              malloc_dirname = !use_alloca;

              if (__glibc_unlikely (malloc_home_dir))
                free (home_dir);
            }
          dirname_modified = 1;
        }
      else
        {
#ifndef WINDOWS32
          char *end_name = strchr (dirname, '/');
          char *user_name;
          int malloc_user_name = 0;
          char *unescape = NULL;

          if (!(flags & GLOB_NOESCAPE))
            {
              if (end_name == NULL)
                {
                  unescape = strchr (dirname, '\\');
                  if (unescape)
                    end_name = strchr (unescape, '\0');
                }
              else
                unescape = memchr (dirname, '\\', end_name - dirname);
            }
          if (end_name == NULL)
            user_name = dirname + 1;
          else
            {
              char *newp;
              if (glob_use_alloca (alloca_used, end_name - dirname))
                newp = alloca_account (end_name - dirname, alloca_used);
              else
                {
                  newp = malloc (end_name - dirname);
                  if (newp == NULL)
                    {
                      retval = GLOB_NOSPACE;
                      goto out;
                    }
                  malloc_user_name = 1;
                }
              if (unescape != NULL)
                {
                  char *p = mempcpy (newp, dirname + 1,
                                     unescape - dirname - 1);
                  char *q = unescape;
                  while (*q != '\0')
                    {
                      if (*q == '\\')
                        {
                          if (q[1] == '\0')
                            {
                              /* ""~fo\\o\\"" unescape to user_name ""foo\\"",
                                 but ""~fo\\o\\/"" unescape to user_name
                                 ""foo"".  */
                              if (filename == NULL)
                                *p++ = '\\';
                              break;
                            }
                          ++q;
                        }
                      *p++ = *q++;
                    }
                  *p = '\0';
                }
              else
                *((char *) mempcpy (newp, dirname + 1, end_name - dirname))
                  = '\0';
              user_name = newp;
            }

          /* Look up specific user's home directory.  */
          {
            struct passwd *p;
            struct scratch_buffer pwtmpbuf;
            scratch_buffer_init (&pwtmpbuf);

#  if defined HAVE_GETPWNAM_R || defined _LIBC
            struct passwd pwbuf;

            while (getpwnam_r (user_name, &pwbuf,
                               pwtmpbuf.data, pwtmpbuf.length, &p)
                   == ERANGE)
              {
                if (!scratch_buffer_grow (&pwtmpbuf))
                  {
                    retval = GLOB_NOSPACE;
                    goto out;
                  }
              }
#  else
            p = getpwnam (user_name);
#  endif

            if (__glibc_unlikely (malloc_user_name))
              free (user_name);

            /* If we found a home directory use this.  */
            if (p != NULL)
              {
                size_t home_len = strlen (p->pw_dir);
                size_t rest_len = end_name == NULL ? 0 : strlen (end_name);
                char *d;

                if (__glibc_unlikely (malloc_dirname))
                  free (dirname);
                malloc_dirname = 0;

                if (glob_use_alloca (alloca_used, home_len + rest_len + 1))
                  dirname = alloca_account (home_len + rest_len + 1,
                                            alloca_used);
                else
                  {
                    dirname = malloc (home_len + rest_len + 1);
                    if (dirname == NULL)
                      {
                        scratch_buffer_free (&pwtmpbuf);
                        retval = GLOB_NOSPACE;
                        goto out;
                      }
                    malloc_dirname = 1;
                  }
                d = mempcpy (dirname, p->pw_dir, home_len);
                if (end_name != NULL)
                  d = mempcpy (d, end_name, rest_len);
                *d = '\0';

                dirlen = home_len + rest_len;
                dirname_modified = 1;
              }
            else
              {
                if (flags & GLOB_TILDE_CHECK)
                  {
                    /* We have to regard it as an error if we cannot find the
                       home directory.  */
                    retval = GLOB_NOMATCH;
                    goto out;
                  }
              }
            scratch_buffer_free (&pwtmpbuf);
          }
#endif /* !WINDOWS32 */
        }
    }

  /* Now test whether we looked for ""~"" or ""~NAME"".  In this case we
     can give the answer now.  */
  if (filename == NULL)
    {
      size_t newcount = pglob->gl_pathc + pglob->gl_offs;
      char **new_gl_pathv;

      if (newcount > SIZE_MAX / sizeof (char *) - 2)
        {
        nospace:
          free (pglob->gl_pathv);
          pglob->gl_pathv = NULL;
          pglob->gl_pathc = 0;
          retval = GLOB_NOSPACE;
          goto out;
        }

      new_gl_pathv = realloc (pglob->gl_pathv,
                              (newcount + 2) * sizeof (char *));
      if (new_gl_pathv == NULL)
        goto nospace;
      pglob->gl_pathv = new_gl_pathv;

      if (flags & GLOB_MARK && is_dir (dirname, flags, pglob))
        {
          char *p;
          pglob->gl_pathv[newcount] = malloc (dirlen + 2);
          if (pglob->gl_pathv[newcount] == NULL)
            goto nospace;
          p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen);
          p[0] = '/';
          p[1] = '\0';
          if (__glibc_unlikely (malloc_dirname))
            free (dirname);
        }
      else
        {
          if (__glibc_unlikely (malloc_dirname))
            pglob->gl_pathv[newcount] = dirname;
          else
            {
              pglob->gl_pathv[newcount] = strdup (dirname);
              if (pglob->gl_pathv[newcount] == NULL)
                goto nospace;
            }
        }
      pglob->gl_pathv[++newcount] = NULL;
      ++pglob->gl_pathc;
      pglob->gl_flags = flags;

      return 0;
    }

  meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE));
  /* meta is 1 if correct glob pattern containing metacharacters.
     If meta has bit (1 << 2) set, it means there was an unterminated
     [ which we handle the same, using fnmatch.  Broken unterminated
     pattern bracket expressions ought to be rare enough that it is
     not worth special casing them, fnmatch will do the right thing.  */
  if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET))
    {
      /* The directory name contains metacharacters, so we
         have to glob for the directory, and then glob for
         the pattern in each directory found.  */
      size_t i;

      if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\')
        {
          /* ""foo\\/bar"".  Remove the final backslash from dirname
             if it has not been quoted.  */
          char *p = (char *) &dirname[dirlen - 1];

          while (p > dirname && p[-1] == '\\') --p;
          if ((&dirname[dirlen] - p) & 1)
            *(char *) &dirname[--dirlen] = '\0';
        }

      if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0))
        {
          /* Use the alternative access functions also in the recursive
             call.  */
          dirs.gl_opendir = pglob->gl_opendir;
          dirs.gl_readdir = pglob->gl_readdir;
          dirs.gl_closedir = pglob->gl_closedir;
          dirs.gl_stat = pglob->gl_stat;
          dirs.gl_lstat = pglob->gl_lstat;
        }

      status = glob (dirname,
                     ((flags & (GLOB_ERR | GLOB_NOESCAPE
                                | GLOB_ALTDIRFUNC))
                      | GLOB_NOSORT | GLOB_ONLYDIR),
                     errfunc, &dirs);
      if (status != 0)
        {
          if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH)
            {
              retval = status;
              goto out;
            }
          goto no_matches;
        }

      /* We have successfully globbed the preceding directory name.
         For each name we found, call glob_in_dir on it and FILENAME,
         appending the results to PGLOB.  */
      for (i = 0; i < dirs.gl_pathc; ++i)
        {
          size_t old_pathc;

          old_pathc = pglob->gl_pathc;
          status = glob_in_dir (filename, dirs.gl_pathv[i],
                                ((flags | GLOB_APPEND)
                                 & ~(GLOB_NOCHECK | GLOB_NOMAGIC)),
                                errfunc, pglob, alloca_used);
          if (status == GLOB_NOMATCH)
            /* No matches in this directory.  Try the next.  */
            continue;

          if (status != 0)
            {
              globfree (&dirs);
              globfree (pglob);
              pglob->gl_pathc = 0;
              retval = status;
              goto out;
            }

          /* Stick the directory on the front of each name.  */
          if (prefix_array (dirs.gl_pathv[i],
                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],
                            pglob->gl_pathc - old_pathc))
            {
              globfree (&dirs);
              globfree (pglob);
              pglob->gl_pathc = 0;
              retval = GLOB_NOSPACE;
              goto out;
            }
        }

      flags |= GLOB_MAGCHAR;

      /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls.
         But if we have not found any matching entry and the GLOB_NOCHECK
         flag was set we must return the input pattern itself.  */
      if (pglob->gl_pathc + pglob->gl_offs == oldcount)
        {
        no_matches:
          /* No matches.  */
          if (flags & GLOB_NOCHECK)
            {
              size_t newcount = pglob->gl_pathc + pglob->gl_offs;
              char **new_gl_pathv;

              if (newcount > SIZE_MAX / sizeof (char *) - 2)
                {
                nospace2:
                  globfree (&dirs);
                  retval = GLOB_NOSPACE;
                  goto out;
                }

              new_gl_pathv = realloc (pglob->gl_pathv,
                                      (newcount + 2) * sizeof (char *));
              if (new_gl_pathv == NULL)
                goto nospace2;
              pglob->gl_pathv = new_gl_pathv;

              pglob->gl_pathv[newcount] = strdup (pattern);
              if (pglob->gl_pathv[newcount] == NULL)
                {
                  globfree (&dirs);
                  globfree (pglob);
                  pglob->gl_pathc = 0;
                  retval = GLOB_NOSPACE;
                  goto out;
                }

              ++pglob->gl_pathc;
              ++newcount;

              pglob->gl_pathv[newcount] = NULL;
              pglob->gl_flags = flags;
            }
          else
            {
              globfree (&dirs);
              retval = GLOB_NOMATCH;
              goto out;
            }
        }

      globfree (&dirs);
    }
  else
    {
      size_t old_pathc = pglob->gl_pathc;
      int orig_flags = flags;

      if (meta & GLOBPAT_BACKSLASH)
        {
          char *p = strchr (dirname, '\\'), *q;
          /* We need to unescape the dirname string.  It is certainly
             allocated by alloca, as otherwise filename would be NULL
             or dirname wouldn't contain backslashes.  */
          q = p;
          do
            {
              if (*p == '\\')
                {
                  *q = *++p;
                  --dirlen;
                }
              else
                *q = *p;
              ++q;
            }
          while (*p++ != '\0');
          dirname_modified = 1;
        }
      if (dirname_modified)
        flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC);
      status = glob_in_dir (filename, dirname, flags, errfunc, pglob,
                            alloca_used);
      if (status != 0)
        {
          if (status == GLOB_NOMATCH && flags != orig_flags
              && pglob->gl_pathc + pglob->gl_offs == oldcount)
            {
              /* Make sure globfree (&dirs); is a nop.  */
              dirs.gl_pathv = NULL;
              flags = orig_flags;
              goto no_matches;
            }
          retval = status;
          goto out;
        }

      if (dirlen > 0)
        {
          /* Stick the directory on the front of each name.  */
          if (prefix_array (dirname,
                            &pglob->gl_pathv[old_pathc + pglob->gl_offs],
                            pglob->gl_pathc - old_pathc))
            {
              globfree (pglob);
              pglob->gl_pathc = 0;
              retval = GLOB_NOSPACE;
              goto out;
            }
        }
    }

  if (flags & GLOB_MARK)
    {
      /* Append slashes to directory names.  */
      size_t i;

      for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i)
        if (is_dir (pglob->gl_pathv[i], flags, pglob))
          {
            size_t len = strlen (pglob->gl_pathv[i]) + 2;
            char *new = realloc (pglob->gl_pathv[i], len);
            if (new == NULL)
              {
                globfree (pglob);
                pglob->gl_pathc = 0;
                retval = GLOB_NOSPACE;
                goto out;
              }
            strcpy (&new[len - 2], ""/"");
            pglob->gl_pathv[i] = new;
          }
    }

  if (!(flags & GLOB_NOSORT))
    {
      /* Sort the vector.  */
      qsort (&pglob->gl_pathv[oldcount],
             pglob->gl_pathc + pglob->gl_offs - oldcount,
             sizeof (char *), collated_compare);
    }

 out:
  if (__glibc_unlikely (malloc_dirname))
    free (dirname);

  return retval;
}",CWE-119,0
1,"int tcp_emu(struct socket *so, struct mbuf *m)
{
    Slirp *slirp = so->slirp;
    unsigned n1, n2, n3, n4, n5, n6;
    char buff[257];
    uint32_t laddr;
    unsigned lport;
    char *bptr;

    DEBUG_CALL(""tcp_emu"");
    DEBUG_ARG(""so = %p"", so);
    DEBUG_ARG(""m = %p"", m);

    switch (so->so_emu) {
        int x, i;

        /* TODO: IPv6 */
    case EMU_IDENT:
        /*
         * Identification protocol as per rfc-1413
         */

        {
            struct socket *tmpso;
            struct sockaddr_in addr;
            socklen_t addrlen = sizeof(struct sockaddr_in);
            char *eol = g_strstr_len(m->m_data, m->m_len, ""\r\n"");

            if (!eol) {
                return 1;
            }

            *eol = '\0';
            if (sscanf(m->m_data, ""%u%*[ ,]%u"", &n1, &n2) == 2) {
                HTONS(n1);
                HTONS(n2);
                /* n2 is the one on our host */
                for (tmpso = slirp->tcb.so_next; tmpso != &slirp->tcb;
                     tmpso = tmpso->so_next) {
                    if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&
                        tmpso->so_lport == n2 &&
                        tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&
                        tmpso->so_fport == n1) {
                        if (getsockname(tmpso->s, (struct sockaddr *)&addr,
                                        &addrlen) == 0)
                            n2 = addr.sin_port;
                        break;
                    }
                }
                NTOHS(n1);
                NTOHS(n2);
                m_inc(m, snprintf(NULL, 0, ""%d,%d\r\n"", n1, n2) + 1);
                m->m_len = snprintf(m->m_data, M_ROOM(m), ""%d,%d\r\n"", n1, n2);
                assert(m->m_len < M_ROOM(m));
            } else {
                *eol = '\r';
            }

            return 1;
        }

    case EMU_FTP: /* ftp */
        m_inc(m, m->m_len + 1);
        *(m->m_data + m->m_len) = 0; /* NUL terminate for strstr */
        if ((bptr = (char *)strstr(m->m_data, ""ORT"")) != NULL) {
            /*
             * Need to emulate the PORT command
             */
            x = sscanf(bptr, ""ORT %u,%u,%u,%u,%u,%u\r\n%256[^\177]"", &n1, &n2,
                       &n3, &n4, &n5, &n6, buff);
            if (x < 6)
                return 1;

            laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));
            lport = htons((n5 << 8) | (n6));

            if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport,
                                 SS_FACCEPTONCE)) == NULL) {
                return 1;
            }
            n6 = ntohs(so->so_fport);

            n5 = (n6 >> 8) & 0xff;
            n6 &= 0xff;

            laddr = ntohl(so->so_faddr.s_addr);

            n1 = ((laddr >> 24) & 0xff);
            n2 = ((laddr >> 16) & 0xff);
            n3 = ((laddr >> 8) & 0xff);
            n4 = (laddr & 0xff);

            m->m_len = bptr - m->m_data; /* Adjust length */
            m->m_len += snprintf(bptr, m->m_size - m->m_len,
                                 ""ORT %d,%d,%d,%d,%d,%d\r\n%s"", n1, n2, n3, n4,
                                 n5, n6, x == 7 ? buff : """");
            return 1;
        } else if ((bptr = (char *)strstr(m->m_data, ""27 Entering"")) != NULL) {
            /*
             * Need to emulate the PASV response
             */
            x = sscanf(
                bptr,
                ""27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n%256[^\177]"",
                &n1, &n2, &n3, &n4, &n5, &n6, buff);
            if (x < 6)
                return 1;

            laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));
            lport = htons((n5 << 8) | (n6));

            if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport,
                                 SS_FACCEPTONCE)) == NULL) {
                return 1;
            }
            n6 = ntohs(so->so_fport);

            n5 = (n6 >> 8) & 0xff;
            n6 &= 0xff;

            laddr = ntohl(so->so_faddr.s_addr);

            n1 = ((laddr >> 24) & 0xff);
            n2 = ((laddr >> 16) & 0xff);
            n3 = ((laddr >> 8) & 0xff);
            n4 = (laddr & 0xff);

            m->m_len = bptr - m->m_data; /* Adjust length */
            m->m_len +=
                snprintf(bptr, m->m_size - m->m_len,
                         ""27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s"",
                         n1, n2, n3, n4, n5, n6, x == 7 ? buff : """");

            return 1;
        }

        return 1;

    case EMU_KSH:
        /*
         * The kshell (Kerberos rsh) and shell services both pass
         * a local port port number to carry signals to the server
         * and stderr to the client.  It is passed at the beginning
         * of the connection as a NUL-terminated decimal ASCII string.
         */
        so->so_emu = 0;
        for (lport = 0, i = 0; i < m->m_len - 1; ++i) {
            if (m->m_data[i] < '0' || m->m_data[i] > '9')
                return 1; /* invalid number */
            lport *= 10;
            lport += m->m_data[i] - '0';
        }
        if (m->m_data[m->m_len - 1] == '\0' && lport != 0 &&
            (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,
                             htons(lport), SS_FACCEPTONCE)) != NULL)
            m->m_len =
                snprintf(m->m_data, m->m_size, ""%d"", ntohs(so->so_fport)) + 1;
        return 1;

    case EMU_IRC:
        /*
         * Need to emulate DCC CHAT, DCC SEND and DCC MOVE
         */
        m_inc(m, m->m_len + 1);
        *(m->m_data + m->m_len) = 0; /* NULL terminate the string for strstr */
        if ((bptr = (char *)strstr(m->m_data, ""DCC"")) == NULL)
            return 1;

        /* The %256s is for the broken mIRC */
        if (sscanf(bptr, ""DCC CHAT %256s %u %u"", buff, &laddr, &lport) == 3) {
            if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
                                 htons(lport), SS_FACCEPTONCE)) == NULL) {
                return 1;
            }
            m->m_len = bptr - m->m_data; /* Adjust length */
            m->m_len += snprintf(bptr, m->m_size, ""DCC CHAT chat %lu %u%c\n"",
                                 (unsigned long)ntohl(so->so_faddr.s_addr),
                                 ntohs(so->so_fport), 1);
        } else if (sscanf(bptr, ""DCC SEND %256s %u %u %u"", buff, &laddr, &lport,
                          &n1) == 4) {
            if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
                                 htons(lport), SS_FACCEPTONCE)) == NULL) {
                return 1;
            }
            m->m_len = bptr - m->m_data; /* Adjust length */
            m->m_len +=
                snprintf(bptr, m->m_size, ""DCC SEND %s %lu %u %u%c\n"", buff,
                         (unsigned long)ntohl(so->so_faddr.s_addr),
                         ntohs(so->so_fport), n1, 1);
        } else if (sscanf(bptr, ""DCC MOVE %256s %u %u %u"", buff, &laddr, &lport,
                          &n1) == 4) {
            if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
                                 htons(lport), SS_FACCEPTONCE)) == NULL) {
                return 1;
            }
            m->m_len = bptr - m->m_data; /* Adjust length */
            m->m_len +=
                snprintf(bptr, m->m_size, ""DCC MOVE %s %lu %u %u%c\n"", buff,
                         (unsigned long)ntohl(so->so_faddr.s_addr),
                         ntohs(so->so_fport), n1, 1);
        }
        return 1;

    case EMU_REALAUDIO:
        /*
         * RealAudio emulation - JP. We must try to parse the incoming
         * data and try to find the two characters that contain the
         * port number. Then we redirect an udp port and replace the
         * number with the real port we got.
         *
         * The 1.0 beta versions of the player are not supported
         * any more.
         *
         * A typical packet for player version 1.0 (release version):
         *
         * 0000:50 4E 41 00 05
         * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P
         * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH
         * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v
         * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB
         *
         * Now the port number 0x1BD7 is found at offset 0x04 of the
         * Now the port number 0x1BD7 is found at offset 0x04 of the
         * second packet. This time we received five bytes first and
         * then the rest. You never know how many bytes you get.
         *
         * A typical packet for player version 2.0 (beta):
         *
         * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............
         * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0
         * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/
         * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas
         * 0040:65 2E 72 61 79 53 00 00 06 36 42                e.rayS...6B
         *
         * Port number 0x1BC1 is found at offset 0x0d.
         *
         * This is just a horrible switch statement. Variable ra tells
         * us where we're going.
         */

        bptr = m->m_data;
        while (bptr < m->m_data + m->m_len) {
            uint16_t p;
            static int ra = 0;
            char ra_tbl[4];

            ra_tbl[0] = 0x50;
            ra_tbl[1] = 0x4e;
            ra_tbl[2] = 0x41;
            ra_tbl[3] = 0;

            switch (ra) {
            case 0:
            case 2:
            case 3:
                if (*bptr++ != ra_tbl[ra]) {
                    ra = 0;
                    continue;
                }
                break;

            case 1:
                /*
                 * We may get 0x50 several times, ignore them
                 */
                if (*bptr == 0x50) {
                    ra = 1;
                    bptr++;
                    continue;
                } else if (*bptr++ != ra_tbl[ra]) {
                    ra = 0;
                    continue;
                }
                break;

            case 4:
                /*
                 * skip version number
                 */
                bptr++;
                break;

            case 5:
                /*
                 * The difference between versions 1.0 and
                 * 2.0 is here. For future versions of
                 * the player this may need to be modified.
                 */
                if (*(bptr + 1) == 0x02)
                    bptr += 8;
                else
                    bptr += 4;
                break;

            case 6:
                /* This is the field containing the port
                 * number that RA-player is listening to.
                 */
                lport = (((uint8_t *)bptr)[0] << 8) + ((uint8_t *)bptr)[1];
                if (lport < 6970)
                    lport += 256; /* don't know why */
                if (lport < 6970 || lport > 7170)
                    return 1; /* failed */

                /* try to get udp port between 6970 - 7170 */
                for (p = 6970; p < 7071; p++) {
                    if (udp_listen(slirp, INADDR_ANY, htons(p),
                                   so->so_laddr.s_addr, htons(lport),
                                   SS_FACCEPTONCE)) {
                        break;
                    }
                }
                if (p == 7071)
                    p = 0;
                *(uint8_t *)bptr++ = (p >> 8) & 0xff;
                *(uint8_t *)bptr = p & 0xff;
                ra = 0;
                return 1; /* port redirected, we're done */
                break;

            default:
                ra = 0;
            }
            ra++;
        }
        return 1;

    default:
        /* Ooops, not emulated, won't call tcp_emu again */
        so->so_emu = 0;
        return 1;
    }
}",CWE-787,16
0,"  void GetLRUOrigin(StorageType type) {
    lru_origin_ = GURL();
    quota_manager_->GetLRUOrigin(type,
        callback_factory_.NewCallback(&QuotaManagerTest::DidGetLRUOrigin));
  }
",none,24
1,"extract_group_icon_cursor_resource(WinLibrary *fi, WinResource *wr, char *lang,
                                   int *ressize, bool is_icon)
{
	Win32CursorIconDir *icondir;
	Win32CursorIconFileDir *fileicondir;
	char *memory;
	int c, size, offset, skipped;

	/* get resource data and size */
	icondir = (Win32CursorIconDir *) get_resource_entry(fi, wr, &size);
	if (icondir == NULL) {
		/* get_resource_entry will print error */
		return NULL;
	}

	/* calculate total size of output file */
	RETURN_IF_BAD_POINTER(NULL, icondir->count);
	skipped = 0;
	for (c = 0 ; c < icondir->count ; c++) {
		int level;
	    	int iconsize;
		char name[14];
		WinResource *fwr;

		RETURN_IF_BAD_POINTER(NULL, icondir->entries[c]);
		/*printf(""%d. bytes_in_res=%d width=%d height=%d planes=%d bit_count=%d\n"", c,
			icondir->entries[c].bytes_in_res,
			(is_icon ? icondir->entries[c].res_info.icon.width : icondir->entries[c].res_info.cursor.width),
			(is_icon ? icondir->entries[c].res_info.icon.height : icondir->entries[c].res_info.cursor.height),
			icondir->entries[c].plane_count,
			icondir->entries[c].bit_count);*/

		/* find the corresponding icon resource */
		snprintf(name, sizeof(name)/sizeof(char), ""-%d"", icondir->entries[c].res_id);
		fwr = find_resource(fi, (is_icon ? ""-3"" : ""-1""), name, lang, &level);
		if (fwr == NULL) {
			warn(_(""%s: could not find `%s' in `%s' resource.""),
			 	fi->name, &name[1], (is_icon ? ""group_icon"" : ""group_cursor""));
			return NULL;
		}

		if (get_resource_entry(fi, fwr, &iconsize) != NULL) {
		    if (iconsize == 0) {
			warn(_(""%s: icon resource `%s' is empty, skipping""), fi->name, name);
			skipped++;
			continue;
		    }
		    if (iconsize != icondir->entries[c].bytes_in_res) {
			warn(_(""%s: mismatch of size in icon resource `%s' and group (%d vs %d)""), fi->name, name, iconsize, icondir->entries[c].bytes_in_res);
		    }
		    size += iconsize < icondir->entries[c].bytes_in_res ? icondir->entries[c].bytes_in_res : iconsize;

		    /* cursor resources have two additional WORDs that contain
		     * hotspot info */
		    if (!is_icon)
			size -= sizeof(uint16_t)*2;
		}
	}
	offset = sizeof(Win32CursorIconFileDir) + (icondir->count-skipped) * sizeof(Win32CursorIconFileDirEntry);
	size += offset;
	*ressize = size;

	/* allocate that much memory */
	memory = xmalloc(size);
	fileicondir = (Win32CursorIconFileDir *) memory;

	/* transfer Win32CursorIconDir structure members */
	fileicondir->reserved = icondir->reserved;
	fileicondir->type = icondir->type;
	fileicondir->count = icondir->count - skipped;

	/* transfer each cursor/icon: Win32CursorIconDirEntry and data */
	skipped = 0;
	for (c = 0 ; c < icondir->count ; c++) {
		int level;
		char name[14];
		WinResource *fwr;
		char *data;
	
		/* find the corresponding icon resource */
		snprintf(name, sizeof(name)/sizeof(char), ""-%d"", icondir->entries[c].res_id);
		fwr = find_resource(fi, (is_icon ? ""-3"" : ""-1""), name, lang, &level);
		if (fwr == NULL) {
			warn(_(""%s: could not find `%s' in `%s' resource.""),
			 	fi->name, &name[1], (is_icon ? ""group_icon"" : ""group_cursor""));
			return NULL;
		}

		/* get data and size of that resource */
		data = get_resource_entry(fi, fwr, &size);
		if (data == NULL) {
			/* get_resource_entry has printed error */
			return NULL;
		}
    	    	if (size == 0) {
		    skipped++;
		    continue;
		}

		/* copy ICONDIRENTRY (not including last dwImageOffset) */
		memcpy(&fileicondir->entries[c-skipped], &icondir->entries[c],
			sizeof(Win32CursorIconFileDirEntry)-sizeof(uint32_t));

		/* special treatment for cursors */
		if (!is_icon) {
			fileicondir->entries[c-skipped].width = icondir->entries[c].res_info.cursor.width;
			fileicondir->entries[c-skipped].height = icondir->entries[c].res_info.cursor.height / 2;
			fileicondir->entries[c-skipped].color_count = 0;
			fileicondir->entries[c-skipped].reserved = 0;
		}

		/* set image offset and increase it */
		fileicondir->entries[c-skipped].dib_offset = offset;

		/* transfer resource into file memory */
		if (is_icon) {
			memcpy(&memory[offset], data, icondir->entries[c].bytes_in_res);
		} else {
			fileicondir->entries[c-skipped].hotspot_x = ((uint16_t *) data)[0];
			fileicondir->entries[c-skipped].hotspot_y = ((uint16_t *) data)[1];
			memcpy(&memory[offset], data+sizeof(uint16_t)*2,
				   icondir->entries[c].bytes_in_res-sizeof(uint16_t)*2);
			offset -= sizeof(uint16_t)*2;
		}

		/* increase the offset pointer */
		offset += icondir->entries[c].bytes_in_res;
	}

	return (void *) memory;
}",CWE-119,0
0,"  GetModifiedSinceTask(
      QuotaManager* manager,
      StorageType type,
      base::Time modified_since,
      GetOriginsCallback* callback)
      : DatabaseTaskBase(manager),
        type_(type),
        modified_since_(modified_since),
        callback_(callback) {}
",none,24
0,"  int64 quota() const { return quota_; }
",none,24
0,"  virtual bool cellular_enabled() const {
    return enabled_devices_ & (1 << TYPE_CELLULAR);
  }
",none,24
1,"static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  Image *image, *image2=NULL,
   *rotated_image;
  register Quantum *q;

  unsigned int status;
  MATHeader MATLAB_HDR;
  size_t size;  
  size_t CellType;
  QuantumInfo *quantum_info;
  ImageInfo *clone_info;
  int i;
  ssize_t ldblk;
  unsigned char *BImgBuff = NULL;
  double MinVal, MaxVal;
  unsigned z, z2;
  unsigned Frames;
  int logging;
  int sample_size;
  MagickOffsetType filepos=0x80;
  BlobInfo *blob;
  size_t one;
  
  unsigned int (*ReadBlobXXXLong)(Image *image);
  unsigned short (*ReadBlobXXXShort)(Image *image);
  void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
  void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);


  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); 

  /*
     Open image file.
   */
  image = AcquireImage(image_info,exception);

  status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
     Read MATLAB image.
   */
  clone_info=CloneImageInfo(image_info);
  if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
  MATLAB_HDR.Version = ReadBlobLSBShort(image);
  if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");

  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""  Endian %c%c"",
        MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
  if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2))
  {
    ReadBlobXXXLong = ReadBlobLSBLong;
    ReadBlobXXXShort = ReadBlobLSBShort;
    ReadBlobDoublesXXX = ReadBlobDoublesLSB;
    ReadBlobFloatsXXX = ReadBlobFloatsLSB;
    image->endian = LSBEndian;
  } 
  else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2))
  {
    ReadBlobXXXLong = ReadBlobMSBLong;
    ReadBlobXXXShort = ReadBlobMSBShort;
    ReadBlobDoublesXXX = ReadBlobDoublesMSB;
    ReadBlobFloatsXXX = ReadBlobFloatsMSB;
    image->endian = MSBEndian;
  }
  else 
    goto MATLAB_KO;    /* unsupported endian */

  if (strncmp(MATLAB_HDR.identific, ""MATLAB"", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,""ImproperImageHeader"");

  filepos = TellBlob(image);
  while(!EOFBlob(image)) /* object parser loop */
  {
    Frames = 1;
    (void) SeekBlob(image,filepos,SEEK_SET);
    /* printf(""pos=%X\n"",TellBlob(image)); */

    MATLAB_HDR.DataType = ReadBlobXXXLong(image);
    if(EOFBlob(image)) break;
    MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
    if(EOFBlob(image)) break;
    filepos += MATLAB_HDR.ObjectSize + 4 + 4;

    image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
    if(MATLAB_HDR.DataType == miCOMPRESSED)
    {
      image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
      if(image2==NULL) continue;
      MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
    }
#endif    

    if(MATLAB_HDR.DataType!=miMATRIX) continue;  /* skip another objects. */
 
    MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
    MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);  

    MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
    MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
    MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;  

    MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
    if(image!=image2)
      MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */
    MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
    MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
    MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
    MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);  
   

    switch(MATLAB_HDR.DimFlag)
    {     
      case  8: z2=z=1; break;      /* 2D matrix*/
      case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
           (void) ReadBlobXXXLong(image2);
         if(z!=3) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported"");
         break;
      case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
         if(z!=3 && z!=1)
            ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported"");
           Frames = ReadBlobXXXLong(image2);
         break;
      default: ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported"");
    }  

    MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
    MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);

    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
          ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass);
    if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && 
        MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */
        MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */
        MATLAB_HDR.StructureClass != mxINT8_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */
        MATLAB_HDR.StructureClass != mxINT16_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */
        MATLAB_HDR.StructureClass != mxINT32_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */
        MATLAB_HDR.StructureClass != mxINT64_CLASS &&
        MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */
      ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix"");

    switch (MATLAB_HDR.NameFlag)
    {
      case 0:
        size = ReadBlobXXXLong(image2);  /* Object name string size */
        size = 4 * (ssize_t) ((size + 3 + 1) / 4);
        (void) SeekBlob(image2, size, SEEK_CUR);
        break;
      case 1:
      case 2:
      case 3:
      case 4:
        (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
        break;
      default:
        goto MATLAB_KO;
    }

    CellType = ReadBlobXXXLong(image2);    /* Additional object type */
    if (logging)
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
        ""MATLAB_HDR.CellType: %.20g"",(double) CellType);
  
    (void) ReadBlob(image2, 4, (unsigned char *) &size);     /* data size */

    NEXT_FRAME:
    switch (CellType)
    {
      case miINT8:
      case miUINT8:
        sample_size = 8;
        if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) 
          image->depth = 1;
        else
          image->depth = 8;         /* Byte type cell */
        ldblk = (ssize_t) MATLAB_HDR.SizeX;      
        break;
      case miINT16:
      case miUINT16:
        sample_size = 16;
        image->depth = 16;        /* Word type cell */
        ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
        break;
      case miINT32:
      case miUINT32:
        sample_size = 32;
        image->depth = 32;        /* Dword type cell */
        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);      
        break;
      case miINT64:
      case miUINT64:
        sample_size = 64;
        image->depth = 64;        /* Qword type cell */
        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);      
        break;   
      case miSINGLE:
        sample_size = 32;
        image->depth = 32;        /* double type cell */
        (void) SetImageOption(clone_info,""quantum:format"",""floating-point"");
        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
  {              /* complex float type cell */
  }
        ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
        break;
      case miDOUBLE:
        sample_size = 64; 
        image->depth = 64;        /* double type cell */
        (void) SetImageOption(clone_info,""quantum:format"",""floating-point"");
DisableMSCWarning(4127)
        if (sizeof(double) != 8)
RestoreMSCWarning
          ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble"");
        if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
  {                         /* complex double type cell */        
  }
        ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
        break;
      default:
        ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix"");
    }
    (void) sample_size;
    image->columns = MATLAB_HDR.SizeX;
    image->rows = MATLAB_HDR.SizeY;    
    quantum_info=AcquireQuantumInfo(clone_info,image);
    if (quantum_info == (QuantumInfo *) NULL)
      ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");
    one=1;
    image->colors = one << image->depth;
    if (image->columns == 0 || image->rows == 0)
      goto MATLAB_KO;
    /* Image is gray when no complex flag is set and 2D Matrix */
    if ((MATLAB_HDR.DimFlag == 8) &&
        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
      {
        image->type=GrayscaleType;
        SetImageColorspace(image,GRAYColorspace,exception);
      }


    /*
      If ping is true, then only set image size and colors without
      reading any image data.
    */
    if (image_info->ping)
    {
      size_t temp = image->columns;
      image->columns = image->rows;
      image->rows = temp;
      goto done_reading; /* !!!!!! BAD  !!!! */
    }  
    status=SetImageExtent(image,image->columns,image->rows,exception);
    if (status == MagickFalse)
      return(DestroyImageList(image));

  /* ----- Load raster data ----- */
    BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
    if (BImgBuff == NULL)
      ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");

    MinVal = 0;
    MaxVal = 0;
    if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
    {
      CalcMinMax(image2, image_info->endian,  MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
    }

    /* Main loop for reading all scanlines */
    if(z==1) z=0; /* read grey scanlines */
    /* else read color scanlines */
    do
    {
      for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
      {
        q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
        if (q == (Quantum *) NULL)
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
              ""  MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto done_reading;    /* Skip image rotation, when cannot set image pixels    */
  }
        if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
             ""  MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto ExitLoop;
  }
        if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
        {
          FixLogical((unsigned char *)BImgBuff,ldblk);
          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
    {
ImportQuantumPixelsFailed:
      if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
              ""  MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1));
      break;
    }
        }
        else
        {
          if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
      goto ImportQuantumPixelsFailed;


          if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */
          (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
      FixSignedValues(image,q,MATLAB_HDR.SizeX);
        }

        if (!SyncAuthenticPixels(image,exception))
  {
    if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
            ""  MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1));
    goto ExitLoop;
  }
      }
    } while(z-- >= 2);
ExitLoop:


    /* Read complex part of numbers here */
    if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
    {        /* Find Min and Max Values for complex parts of floats */
      CellType = ReadBlobXXXLong(image2);    /* Additional object type */
      i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/

      if (CellType==miDOUBLE || CellType==miSINGLE)
      {
        CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);      
      }

      if (CellType==miDOUBLE)
        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
  {
          ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
          InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
            exception);
  }

      if (CellType==miSINGLE)
        for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
  {
          ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
          InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
            exception);
  }    
    }

      /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
    if ((MATLAB_HDR.DimFlag == 8) &&
        ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
      image->type=GrayscaleType;
    if (image->depth == 1)
      image->type=BilevelType;

    if(image2==image)
        image2 = NULL;    /* Remove shadow copy to an image before rotation. */

      /*  Rotate image. */
    rotated_image = RotateImage(image, 90.0, exception);
    if (rotated_image != (Image *) NULL)
    {
        /* Remove page offsets added by RotateImage */
      rotated_image->page.x=0;
      rotated_image->page.y=0;

      blob = rotated_image->blob;
      rotated_image->blob = image->blob;
      rotated_image->colors = image->colors;
      image->blob = blob;
      AppendImageToList(&image,rotated_image);      
      DeleteImageFromList(&image);      
    }

done_reading:

    if(image2!=NULL)
      if(image2!=image)
      {
        DeleteImageFromList(&image2); 
  if(clone_info)
  {
          if(clone_info->file)
    {
            fclose(clone_info->file);
            clone_info->file = NULL;
            (void) remove_utf8(clone_info->filename);
    }
        }    
      }

      /* Allocate next image structure. */    
    AcquireNextImage(image_info,image,exception);
    if (image->next == (Image *) NULL) break;                
    image=SyncNextImageInList(image);
    image->columns=image->rows=0;
    image->colors=0;    

      /* row scan buffer is no longer needed */
    RelinquishMagickMemory(BImgBuff);
    BImgBuff = NULL;

    if(--Frames>0)
    {
      z = z2;
      if(image2==NULL) image2 = image;
      goto NEXT_FRAME;
    }
    if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */
      {
/*  CloseBlob(image2); */
        DeleteImageFromList(&image2);
        if(clone_info)
        {
          if(clone_info->file)
          {
            fclose(clone_info->file);
            clone_info->file = NULL;
            (void) remove_utf8(clone_info->filename);
          }
        }
        }
  }

  clone_info=DestroyImageInfo(clone_info);
  RelinquishMagickMemory(BImgBuff);
  CloseBlob(image);


  {
    Image *p;    
    ssize_t scene=0;
    
    /*
      Rewind list, removing any empty images while rewinding.
    */
    p=image;
    image=NULL;
    while (p != (Image *) NULL)
      {
        Image *tmp=p;
        if ((p->rows == 0) || (p->columns == 0)) {
          p=p->previous;
          DeleteImageFromList(&tmp);
        } else {
          image=p;
          p=p->previous;
        }
      }
    
    /*
      Fix scene numbers
    */
    for (p=image; p != (Image *) NULL; p=p->next)
      p->scene=scene++;
  }

  if(clone_info != NULL)  /* cleanup garbage file from compression */
  {
    if(clone_info->file)
    {
      fclose(clone_info->file);
      clone_info->file = NULL;
      (void) remove_utf8(clone_info->filename);
    }
    DestroyImageInfo(clone_info);
    clone_info = NULL;
  }
  if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return"");
  if(image==NULL)
    ThrowReaderException(CorruptImageError,""ImproperImageHeader"");
  return (image);
}",CWE-125,1
0,"  virtual ~UsageAndQuotaDispatcherTask() {
    STLDeleteContainerPointers(callbacks_.begin(), callbacks_.end());
    STLDeleteContainerPointers(unlimited_callbacks_.begin(),
                               unlimited_callbacks_.end());
  }
",none,24
1,"static void mkiss_close(struct tty_struct *tty)
{
	struct mkiss *ax;

	write_lock_irq(&disc_data_lock);
	ax = tty->disc_data;
	tty->disc_data = NULL;
	write_unlock_irq(&disc_data_lock);

	if (!ax)
		return;

	/*
	 * We have now ensured that nobody can start using ap from now on, but
	 * we have to wait for all existing users to finish.
	 */
	if (!refcount_dec_and_test(&ax->refcnt))
		wait_for_completion(&ax->dead);
	/*
	 * Halt the transmit queue so that a new transmit cannot scribble
	 * on our buffers
	 */
	netif_stop_queue(ax->dev);

	ax->tty = NULL;

	unregister_netdev(ax->dev);

	/* Free all AX25 frame buffers after unreg. */
	kfree(ax->rbuff);
	kfree(ax->xbuff);

	free_netdev(ax->dev);
}",CWE-416,10
0,"  UpdatePersistentHostQuotaTask(
      QuotaManager* manager,
      const std::string& host,
      int new_quota,
      HostQuotaCallback* callback)
      : DatabaseTaskBase(manager),
        host_(host),
        new_quota_(new_quota),
        callback_(callback) {
    DCHECK_GE(new_quota_, 0);
  }
",none,24
1,"void jfs_evict_inode(struct inode *inode)
{
	struct jfs_inode_info *ji = JFS_IP(inode);

	jfs_info(""In jfs_evict_inode, inode = 0x%p"", inode);

	if (!inode->i_nlink && !is_bad_inode(inode)) {
		dquot_initialize(inode);

		if (JFS_IP(inode)->fileset == FILESYSTEM_I) {
			truncate_inode_pages_final(&inode->i_data);

			if (test_cflag(COMMIT_Freewmap, inode))
				jfs_free_zero_link(inode);

			if (JFS_SBI(inode->i_sb)->ipimap)
				diFree(inode);

			/*
			 * Free the inode from the quota allocation.
			 */
			dquot_free_inode(inode);
		}
	} else {
		truncate_inode_pages_final(&inode->i_data);
	}
	clear_inode(inode);
	dquot_drop(inode);

	BUG_ON(!list_empty(&ji->anon_inode_list));

	spin_lock_irq(&ji->ag_lock);
	if (ji->active_ag != -1) {
		struct bmap *bmap = JFS_SBI(inode->i_sb)->bmap;
		atomic_dec(&bmap->db_active[ji->active_ag]);
		ji->active_ag = -1;
	}
	spin_unlock_irq(&ji->ag_lock);
}",CWE-476,12
0,"void QuotaManager::DidGetGlobalQuotaForEviction(
    QuotaStatusCode status,
    StorageType type,
    int64 quota) {
  DCHECK_EQ(type, kStorageTypeTemporary);
  if (status != kQuotaStatusOk) {
    eviction_context_.get_usage_and_quota_callback->Run(
        status, 0, 0, 0, 0);
    eviction_context_.get_usage_and_quota_callback.reset();
    return;
  }

  eviction_context_.quota = quota;
  GetAvailableSpace(callback_factory_.
      NewCallback(&QuotaManager::DidGetAvailableSpaceForEviction));
}
",none,24
0,"  virtual void AddNetworkObserver(const std::string& service_path,
                                  NetworkObserver* observer) {}
",none,24
1,"xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
                  const xmlChar **URI, int *tlen) {
    const xmlChar *localname;
    const xmlChar *prefix;
    const xmlChar *attname;
    const xmlChar *aprefix;
    const xmlChar *nsname;
    xmlChar *attvalue;
    const xmlChar **atts = ctxt->atts;
    int maxatts = ctxt->maxatts;
    int nratts, nbatts, nbdef;
    int i, j, nbNs, attval, oldline, oldcol;
    const xmlChar *base;
    unsigned long cur;
    int nsNr = ctxt->nsNr;

    if (RAW != '<') return(NULL);
    NEXT1;

    /*
     * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
     *       point since the attribute values may be stored as pointers to
     *       the buffer and calling SHRINK would destroy them !
     *       The Shrinking is only possible once the full set of attribute
     *       callbacks have been done.
     */
reparse:
    SHRINK;
    base = ctxt->input->base;
    cur = ctxt->input->cur - ctxt->input->base;
    oldline = ctxt->input->line;
    oldcol = ctxt->input->col;
    nbatts = 0;
    nratts = 0;
    nbdef = 0;
    nbNs = 0;
    attval = 0;
    /* Forget any namespaces added during an earlier parse of this element. */
    ctxt->nsNr = nsNr;

    localname = xmlParseQName(ctxt, &prefix);
    if (localname == NULL) {
	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
		       ""StartTag: invalid element name\n"");
        return(NULL);
    }
    *tlen = ctxt->input->cur - ctxt->input->base - cur;

    /*
     * Now parse the attributes, it ends up with the ending
     *
     * (S Attribute)* S?
     */
    SKIP_BLANKS;
    GROW;
    if (ctxt->input->base != base) goto base_changed;

    while (((RAW != '>') &&
	   ((RAW != '/') || (NXT(1) != '>')) &&
	   (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
	const xmlChar *q = CUR_PTR;
	unsigned int cons = ctxt->input->consumed;
	int len = -1, alloc = 0;

	attname = xmlParseAttribute2(ctxt, prefix, localname,
	                             &aprefix, &attvalue, &len, &alloc);
	if (ctxt->input->base != base) {
	    if ((attvalue != NULL) && (alloc != 0))
	        xmlFree(attvalue);
	    attvalue = NULL;
	    goto base_changed;
	}
        if ((attname != NULL) && (attvalue != NULL)) {
	    if (len < 0) len = xmlStrlen(attvalue);
            if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
	        const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
		xmlURIPtr uri;

                if (URL == NULL) {
		    xmlErrMemory(ctxt, ""dictionary allocation failure"");
		    if ((attvalue != NULL) && (alloc != 0))
			xmlFree(attvalue);
		    return(NULL);
		}
                if (*URL != 0) {
		    uri = xmlParseURI((const char *) URL);
		    if (uri == NULL) {
			xmlNsErr(ctxt, XML_WAR_NS_URI,
			         ""xmlns: '%s' is not a valid URI\n"",
					   URL, NULL, NULL);
		    } else {
			if (uri->scheme == NULL) {
			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
				      ""xmlns: URI %s is not absolute\n"",
				      URL, NULL, NULL);
			}
			xmlFreeURI(uri);
		    }
		    if (URL == ctxt->str_xml_ns) {
			if (attname != ctxt->str_xml) {
			    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			 ""xml namespace URI cannot be the default namespace\n"",
				     NULL, NULL, NULL);
			}
			goto skip_default_ns;
		    }
		    if ((len == 29) &&
			(xmlStrEqual(URL,
				 BAD_CAST ""http://www.w3.org/2000/xmlns/""))) {
			xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""reuse of the xmlns namespace name is forbidden\n"",
				 NULL, NULL, NULL);
			goto skip_default_ns;
		    }
		}
		/*
		 * check that it's not a defined namespace
		 */
		for (j = 1;j <= nbNs;j++)
		    if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
			break;
		if (j <= nbNs)
		    xmlErrAttributeDup(ctxt, NULL, attname);
		else
		    if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
skip_default_ns:
		if (alloc != 0) xmlFree(attvalue);
		if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
		    break;
		if (!IS_BLANK_CH(RAW)) {
		    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
				   ""attributes construct error\n"");
		    break;
		}
		SKIP_BLANKS;
		continue;
	    }
            if (aprefix == ctxt->str_xmlns) {
	        const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
		xmlURIPtr uri;

                if (attname == ctxt->str_xml) {
		    if (URL != ctxt->str_xml_ns) {
		        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			         ""xml namespace prefix mapped to wrong URI\n"",
			         NULL, NULL, NULL);
		    }
		    /*
		     * Do not keep a namespace definition node
		     */
		    goto skip_ns;
		}
                if (URL == ctxt->str_xml_ns) {
		    if (attname != ctxt->str_xml) {
		        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			         ""xml namespace URI mapped to wrong prefix\n"",
			         NULL, NULL, NULL);
		    }
		    goto skip_ns;
		}
                if (attname == ctxt->str_xmlns) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""redefinition of the xmlns prefix is forbidden\n"",
			     NULL, NULL, NULL);
		    goto skip_ns;
		}
		if ((len == 29) &&
		    (xmlStrEqual(URL,
		                 BAD_CAST ""http://www.w3.org/2000/xmlns/""))) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
			     ""reuse of the xmlns namespace name is forbidden\n"",
			     NULL, NULL, NULL);
		    goto skip_ns;
		}
		if ((URL == NULL) || (URL[0] == 0)) {
		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
		             ""xmlns:%s: Empty XML namespace is not allowed\n"",
			          attname, NULL, NULL);
		    goto skip_ns;
		} else {
		    uri = xmlParseURI((const char *) URL);
		    if (uri == NULL) {
			xmlNsErr(ctxt, XML_WAR_NS_URI,
			     ""xmlns:%s: '%s' is not a valid URI\n"",
					   attname, URL, NULL);
		    } else {
			if ((ctxt->pedantic) && (uri->scheme == NULL)) {
			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
				      ""xmlns:%s: URI %s is not absolute\n"",
				      attname, URL, NULL);
			}
			xmlFreeURI(uri);
		    }
		}

		/*
		 * check that it's not a defined namespace
		 */
		for (j = 1;j <= nbNs;j++)
		    if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
			break;
		if (j <= nbNs)
		    xmlErrAttributeDup(ctxt, aprefix, attname);
		else
		    if (nsPush(ctxt, attname, URL) > 0) nbNs++;
skip_ns:
		if (alloc != 0) xmlFree(attvalue);
		if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
		    break;
		if (!IS_BLANK_CH(RAW)) {
		    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
				   ""attributes construct error\n"");
		    break;
		}
		SKIP_BLANKS;
		if (ctxt->input->base != base) goto base_changed;
		continue;
	    }

	    /*
	     * Add the pair to atts
	     */
	    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
	        if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
		    if (attvalue[len] == 0)
			xmlFree(attvalue);
		    goto failed;
		}
	        maxatts = ctxt->maxatts;
		atts = ctxt->atts;
	    }
	    ctxt->attallocs[nratts++] = alloc;
	    atts[nbatts++] = attname;
	    atts[nbatts++] = aprefix;
	    atts[nbatts++] = NULL; /* the URI will be fetched later */
	    atts[nbatts++] = attvalue;
	    attvalue += len;
	    atts[nbatts++] = attvalue;
	    /*
	     * tag if some deallocation is needed
	     */
	    if (alloc != 0) attval = 1;
	} else {
	    if ((attvalue != NULL) && (attvalue[len] == 0))
		xmlFree(attvalue);
	}

failed:

	GROW
        if (ctxt->instate == XML_PARSER_EOF)
            break;
	if (ctxt->input->base != base) goto base_changed;
	if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
	    break;
	if (!IS_BLANK_CH(RAW)) {
	    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
			   ""attributes construct error\n"");
	    break;
	}
	SKIP_BLANKS;
        if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
            (attname == NULL) && (attvalue == NULL)) {
	    xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
	         ""xmlParseStartTag: problem parsing attributes\n"");
	    break;
	}
        GROW;
	if (ctxt->input->base != base) goto base_changed;
    }

    /*
     * The attributes defaulting
     */
    if (ctxt->attsDefault != NULL) {
        xmlDefAttrsPtr defaults;

	defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
	if (defaults != NULL) {
	    for (i = 0;i < defaults->nbAttrs;i++) {
	        attname = defaults->values[5 * i];
		aprefix = defaults->values[5 * i + 1];

                /*
		 * special work for namespaces defaulted defs
		 */
		if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, NULL);
		    if (nsname != defaults->values[5 * i + 2]) {
			if (nsPush(ctxt, NULL,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else if (aprefix == ctxt->str_xmlns) {
		    /*
		     * check that it's not a defined namespace
		     */
		    for (j = 1;j <= nbNs;j++)
		        if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
			    break;
	            if (j <= nbNs) continue;

		    nsname = xmlGetNamespace(ctxt, attname);
		    if (nsname != defaults->values[2]) {
			if (nsPush(ctxt, attname,
			           defaults->values[5 * i + 2]) > 0)
			    nbNs++;
		    }
		} else {
		    /*
		     * check that it's not a defined attribute
		     */
		    for (j = 0;j < nbatts;j+=5) {
			if ((attname == atts[j]) && (aprefix == atts[j+1]))
			    break;
		    }
		    if (j < nbatts) continue;

		    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
			if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
			    return(NULL);
			}
			maxatts = ctxt->maxatts;
			atts = ctxt->atts;
		    }
		    atts[nbatts++] = attname;
		    atts[nbatts++] = aprefix;
		    if (aprefix == NULL)
			atts[nbatts++] = NULL;
		    else
		        atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
		    atts[nbatts++] = defaults->values[5 * i + 2];
		    atts[nbatts++] = defaults->values[5 * i + 3];
		    if ((ctxt->standalone == 1) &&
		        (defaults->values[5 * i + 4] != NULL)) {
			xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
	  ""standalone: attribute %s on %s defaulted from external subset\n"",
	                                 attname, localname);
		    }
		    nbdef++;
		}
	    }
	}
    }

    /*
     * The attributes checkings
     */
    for (i = 0; i < nbatts;i += 5) {
        /*
	* The default namespace does not apply to attribute names.
	*/
	if (atts[i + 1] != NULL) {
	    nsname = xmlGetNamespace(ctxt, atts[i + 1]);
	    if (nsname == NULL) {
		xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
		    ""Namespace prefix %s for %s on %s is not defined\n"",
		    atts[i + 1], atts[i], localname);
	    }
	    atts[i + 2] = nsname;
	} else
	    nsname = NULL;
	/*
	 * [ WFC: Unique Att Spec ]
	 * No attribute name may appear more than once in the same
	 * start-tag or empty-element tag.
	 * As extended by the Namespace in XML REC.
	 */
        for (j = 0; j < i;j += 5) {
	    if (atts[i] == atts[j]) {
	        if (atts[i+1] == atts[j+1]) {
		    xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
		    break;
		}
		if ((nsname != NULL) && (atts[j + 2] == nsname)) {
		    xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
			     ""Namespaced Attribute %s in '%s' redefined\n"",
			     atts[i], nsname, NULL);
		    break;
		}
	    }
	}
    }

    nsname = xmlGetNamespace(ctxt, prefix);
    if ((prefix != NULL) && (nsname == NULL)) {
	xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
	         ""Namespace prefix %s on %s is not defined\n"",
		 prefix, localname, NULL);
    }
    *pref = prefix;
    *URI = nsname;

    /*
     * SAX: Start of Element !
     */
    if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
	(!ctxt->disableSAX)) {
	if (nbNs > 0)
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
			  nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
			  nbatts / 5, nbdef, atts);
	else
	    ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
	                  nsname, 0, NULL, nbatts / 5, nbdef, atts);
    }

    /*
     * Free up attribute allocated strings if needed
     */
    if (attval != 0) {
	for (i = 3,j = 0; j < nratts;i += 5,j++)
	    if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
	        xmlFree((xmlChar *) atts[i]);
    }

    return(localname);

base_changed:
    /*
     * the attribute strings are valid iif the base didn't changed
     */
    if (attval != 0) {
	for (i = 3,j = 0; j < nratts;i += 5,j++)
	    if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
	        xmlFree((xmlChar *) atts[i]);
    }
    ctxt->input->cur = ctxt->input->base + cur;
    ctxt->input->line = oldline;
    ctxt->input->col = oldcol;
    if (ctxt->wellFormed == 1) {
	goto reparse;
    }
    return(NULL);
}",CWE-119,0
1,"int TfLiteIntArrayGetSizeInBytes(int size) {
  static TfLiteIntArray dummy;

  int computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;
#if defined(_MSC_VER)
  // Context for why this is needed is in http://b/189926408#comment21
  computed_size -= sizeof(dummy.data[0]);
#endif
  return computed_size;
}",CWE-190,2
0,"void QuotaManager::NotifyOriginInUse(const GURL& origin) {
  DCHECK(io_thread_->BelongsToCurrentThread());
  origins_in_use_[origin]++;
}
",none,24
1,"MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) {
    MOBI_RET ret;
    const size_t offset = mobi_get_kf8offset(m);
    if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) {
        debug_print(""%s"", ""HUFF/CDIC records metadata not found in MOBI header\n"");
        return MOBI_DATA_CORRUPT;
    }
    const size_t huff_rec_index = *m->mh->huff_rec_index + offset;
    const size_t huff_rec_count = *m->mh->huff_rec_count;
    if (huff_rec_count > HUFF_RECORD_MAXCNT) {
        debug_print(""Too many HUFF record (%zu)\n"", huff_rec_count);
        return MOBI_DATA_CORRUPT;
    }
    const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index);
    if (curr == NULL || huff_rec_count < 2) {
        debug_print(""%s"", ""HUFF/CDIC record not found\n"");
        return MOBI_DATA_CORRUPT;
    }
    if (curr->size < HUFF_RECORD_MINSIZE) {
        debug_print(""HUFF record too short (%zu b)\n"", curr->size);
        return MOBI_DATA_CORRUPT;
    }
    ret = mobi_parse_huff(huffcdic, curr);
    if (ret != MOBI_SUCCESS) {
        debug_print(""%s"", ""HUFF parsing failed\n"");
        return ret;
    }
    curr = curr->next;
    /* allocate memory for symbols data in each CDIC record */
    huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols));
    if (huffcdic->symbols == NULL) {
        debug_print(""%s\n"", ""Memory allocation failed"");
        return MOBI_MALLOC_FAILED;
    }
    /* get following CDIC records */
    size_t i = 0;
    while (i < huff_rec_count - 1) {
        if (curr == NULL) {
            debug_print(""%s\n"", ""CDIC record not found"");
            return MOBI_DATA_CORRUPT;
        }
        ret = mobi_parse_cdic(huffcdic, curr, i++);
        if (ret != MOBI_SUCCESS) {
            debug_print(""%s"", ""CDIC parsing failed\n"");
            return ret;
        }
        curr = curr->next;
    }
    return MOBI_SUCCESS;
}",CWE-119,0
0,"void QuotaManager::DidRunInitialGetTemporaryGlobalUsage(
    StorageType type, int64 usage_unused, int64 unlimited_usage_unused) {
  DCHECK_EQ(type, kStorageTypeTemporary);
  scoped_refptr task(
      new InitializeTemporaryOriginsInfoTask(
          this, temporary_usage_tracker_.get()));
  task->Start();
}
",none,24
1,"static int tc_new_tfilter(struct sk_buff *skb, struct nlmsghdr *n,
			  struct netlink_ext_ack *extack)
{
	struct net *net = sock_net(skb->sk);
	struct nlattr *tca[TCA_MAX + 1];
	char name[IFNAMSIZ];
	struct tcmsg *t;
	u32 protocol;
	u32 prio;
	bool prio_allocate;
	u32 parent;
	u32 chain_index;
	struct Qdisc *q = NULL;
	struct tcf_chain_info chain_info;
	struct tcf_chain *chain = NULL;
	struct tcf_block *block;
	struct tcf_proto *tp;
	unsigned long cl;
	void *fh;
	int err;
	int tp_created;
	bool rtnl_held = false;
	u32 flags;

	if (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN))
		return -EPERM;

replay:
	tp_created = 0;

	err = nlmsg_parse_deprecated(n, sizeof(*t), tca, TCA_MAX,
				     rtm_tca_policy, extack);
	if (err < 0)
		return err;

	t = nlmsg_data(n);
	protocol = TC_H_MIN(t->tcm_info);
	prio = TC_H_MAJ(t->tcm_info);
	prio_allocate = false;
	parent = t->tcm_parent;
	tp = NULL;
	cl = 0;
	block = NULL;
	flags = 0;

	if (prio == 0) {
		/* If no priority is provided by the user,
		 * we allocate one.
		 */
		if (n->nlmsg_flags & NLM_F_CREATE) {
			prio = TC_H_MAKE(0x80000000U, 0U);
			prio_allocate = true;
		} else {
			NL_SET_ERR_MSG(extack, ""Invalid filter command with priority of zero"");
			return -ENOENT;
		}
	}

	/* Find head of filter chain. */

	err = __tcf_qdisc_find(net, &q, &parent, t->tcm_ifindex, false, extack);
	if (err)
		return err;

	if (tcf_proto_check_kind(tca[TCA_KIND], name)) {
		NL_SET_ERR_MSG(extack, ""Specified TC filter name too long"");
		err = -EINVAL;
		goto errout;
	}

	/* Take rtnl mutex if rtnl_held was set to true on previous iteration,
	 * block is shared (no qdisc found), qdisc is not unlocked, classifier
	 * type is not specified, classifier is not unlocked.
	 */
	if (rtnl_held ||
	    (q && !(q->ops->cl_ops->flags & QDISC_CLASS_OPS_DOIT_UNLOCKED)) ||
	    !tcf_proto_is_unlocked(name)) {
		rtnl_held = true;
		rtnl_lock();
	}

	err = __tcf_qdisc_cl_find(q, parent, &cl, t->tcm_ifindex, extack);
	if (err)
		goto errout;

	block = __tcf_block_find(net, q, cl, t->tcm_ifindex, t->tcm_block_index,
				 extack);
	if (IS_ERR(block)) {
		err = PTR_ERR(block);
		goto errout;
	}
	block->classid = parent;

	chain_index = tca[TCA_CHAIN] ? nla_get_u32(tca[TCA_CHAIN]) : 0;
	if (chain_index > TC_ACT_EXT_VAL_MASK) {
		NL_SET_ERR_MSG(extack, ""Specified chain index exceeds upper limit"");
		err = -EINVAL;
		goto errout;
	}
	chain = tcf_chain_get(block, chain_index, true);
	if (!chain) {
		NL_SET_ERR_MSG(extack, ""Cannot create specified filter chain"");
		err = -ENOMEM;
		goto errout;
	}

	mutex_lock(&chain->filter_chain_lock);
	tp = tcf_chain_tp_find(chain, &chain_info, protocol,
			       prio, prio_allocate);
	if (IS_ERR(tp)) {
		NL_SET_ERR_MSG(extack, ""Filter with specified priority/protocol not found"");
		err = PTR_ERR(tp);
		goto errout_locked;
	}

	if (tp == NULL) {
		struct tcf_proto *tp_new = NULL;

		if (chain->flushing) {
			err = -EAGAIN;
			goto errout_locked;
		}

		/* Proto-tcf does not exist, create new one */

		if (tca[TCA_KIND] == NULL || !protocol) {
			NL_SET_ERR_MSG(extack, ""Filter kind and protocol must be specified"");
			err = -EINVAL;
			goto errout_locked;
		}

		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
			NL_SET_ERR_MSG(extack, ""Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"");
			err = -ENOENT;
			goto errout_locked;
		}

		if (prio_allocate)
			prio = tcf_auto_prio(tcf_chain_tp_prev(chain,
							       &chain_info));

		mutex_unlock(&chain->filter_chain_lock);
		tp_new = tcf_proto_create(name, protocol, prio, chain,
					  rtnl_held, extack);
		if (IS_ERR(tp_new)) {
			err = PTR_ERR(tp_new);
			goto errout_tp;
		}

		tp_created = 1;
		tp = tcf_chain_tp_insert_unique(chain, tp_new, protocol, prio,
						rtnl_held);
		if (IS_ERR(tp)) {
			err = PTR_ERR(tp);
			goto errout_tp;
		}
	} else {
		mutex_unlock(&chain->filter_chain_lock);
	}

	if (tca[TCA_KIND] && nla_strcmp(tca[TCA_KIND], tp->ops->kind)) {
		NL_SET_ERR_MSG(extack, ""Specified filter kind does not match existing one"");
		err = -EINVAL;
		goto errout;
	}

	fh = tp->ops->get(tp, t->tcm_handle);

	if (!fh) {
		if (!(n->nlmsg_flags & NLM_F_CREATE)) {
			NL_SET_ERR_MSG(extack, ""Need both RTM_NEWTFILTER and NLM_F_CREATE to create a new filter"");
			err = -ENOENT;
			goto errout;
		}
	} else if (n->nlmsg_flags & NLM_F_EXCL) {
		tfilter_put(tp, fh);
		NL_SET_ERR_MSG(extack, ""Filter already exists"");
		err = -EEXIST;
		goto errout;
	}

	if (chain->tmplt_ops && chain->tmplt_ops != tp->ops) {
		NL_SET_ERR_MSG(extack, ""Chain template is set to a different filter kind"");
		err = -EINVAL;
		goto errout;
	}

	if (!(n->nlmsg_flags & NLM_F_CREATE))
		flags |= TCA_ACT_FLAGS_REPLACE;
	if (!rtnl_held)
		flags |= TCA_ACT_FLAGS_NO_RTNL;
	err = tp->ops->change(net, skb, tp, cl, t->tcm_handle, tca, &fh,
			      flags, extack);
	if (err == 0) {
		tfilter_notify(net, skb, n, tp, block, q, parent, fh,
			       RTM_NEWTFILTER, false, rtnl_held);
		tfilter_put(tp, fh);
		/* q pointer is NULL for shared blocks */
		if (q)
			q->flags &= ~TCQ_F_CAN_BYPASS;
	}

errout:
	if (err && tp_created)
		tcf_chain_tp_delete_empty(chain, tp, rtnl_held, NULL);
errout_tp:
	if (chain) {
		if (tp && !IS_ERR(tp))
			tcf_proto_put(tp, rtnl_held, NULL);
		if (!tp_created)
			tcf_chain_put(chain);
	}
	tcf_block_release(q, block, rtnl_held);

	if (rtnl_held)
		rtnl_unlock();

	if (err == -EAGAIN) {
		/* Take rtnl lock in case EAGAIN is caused by concurrent flush
		 * of target chain.
		 */
		rtnl_held = true;
		/* Replay the request. */
		goto replay;
	}
	return err;

errout_locked:
	mutex_unlock(&chain->filter_chain_lock);
	goto errout;
}",CWE-416,10
1,"bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
{
    SQObjectPtr temp;
    bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;
    if(_locked && !belongs_to_static_table)
        return false; //the class already has an instance so cannot be modified
    if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value
    {
        _defaultvalues[_member_idx(temp)].val = val;
        return true;
    }
    if(belongs_to_static_table) {
        SQInteger mmidx;
        if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&
            (mmidx = ss->GetMetaMethodIdxByName(key)) != -1) {
            _metamethods[mmidx] = val;
        }
        else {
            SQObjectPtr theval = val;
            if(_base && sq_type(val) == OT_CLOSURE) {
                theval = _closure(val)->Clone();
                _closure(theval)->_base = _base;
                __ObjAddRef(_base); //ref for the closure
            }
            if(sq_type(temp) == OT_NULL) {
                bool isconstructor;
                SQVM::IsEqual(ss->_constructoridx, key, isconstructor);
                if(isconstructor) {
                    _constructoridx = (SQInteger)_methods.size();
                }
                SQClassMember m;
                m.val = theval;
                _members->NewSlot(key,SQObjectPtr(_make_method_idx(_methods.size())));
                _methods.push_back(m);
            }
            else {
                _methods[_member_idx(temp)].val = theval;
            }
        }
        return true;
    }
    SQClassMember m;
    m.val = val;
    _members->NewSlot(key,SQObjectPtr(_make_field_idx(_defaultvalues.size())));
    _defaultvalues.push_back(m);
    return true;
}",CWE-125,1
0,"  void NotifyNetworkChanged(Network* network) {
    DCHECK(network);
    NetworkObserverMap::const_iterator iter = network_observers_.find(
        network->service_path());
    if (iter != network_observers_.end()) {
      FOR_EACH_OBSERVER(NetworkObserver,
                        *(iter->second),
                        OnNetworkChanged(this, network));
    } else {
      NOTREACHED() <<
          ""There weren't supposed to be any property change observers of "" <<
           network->service_path();
    }
  }
",none,24
1,"void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)
{
	minify = dominify;
	if (prog->type == AST_LIST)
		pstmlist(-1, prog);
	else {
		pstm(0, prog);
		nl();
	}
	if (minify > 1)
		putchar('\n');
}",CWE-476,12
1,"xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
		      int what, xmlChar end, xmlChar  end2, xmlChar end3) {
    xmlChar *buffer = NULL;
    size_t buffer_size = 0;
    size_t nbchars = 0;

    xmlChar *current = NULL;
    xmlChar *rep = NULL;
    const xmlChar *last;
    xmlEntityPtr ent;
    int c,l;

    if ((ctxt == NULL) || (str == NULL) || (len < 0))
	return(NULL);
    last = str + len;

    if (((ctxt->depth > 40) &&
         ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
	(ctxt->depth > 1024)) {
	xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
	return(NULL);
    }

    /*
     * allocate a translation buffer.
     */
    buffer_size = XML_PARSER_BIG_BUFFER_SIZE;
    buffer = (xmlChar *) xmlMallocAtomic(buffer_size);
    if (buffer == NULL) goto mem_error;

    /*
     * OK loop until we reach one of the ending char or a size limit.
     * we are operating on already parsed values.
     */
    if (str < last)
	c = CUR_SCHAR(str, l);
    else
        c = 0;
    while ((c != 0) && (c != end) && /* non input consuming loop */
	   (c != end2) && (c != end3)) {

	if (c == 0) break;
        if ((c == '&') && (str[1] == '#')) {
	    int val = xmlParseStringCharRef(ctxt, &str);
	    if (val != 0) {
		COPY_BUF(0,buffer,nbchars,val);
	    }
	    if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
	        growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
	    }
	} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
	    if (xmlParserDebugEntities)
		xmlGenericError(xmlGenericErrorContext,
			""String decoding Entity Reference: %.30s\n"",
			str);
	    ent = xmlParseStringEntityRef(ctxt, &str);
	    if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
	        (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
	        goto int_error;
	    xmlParserEntityCheck(ctxt, 0, ent, 0);
	    if (ent != NULL)
	        ctxt->nbentities += ent->checked / 2;
	    if ((ent != NULL) &&
		(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
		if (ent->content != NULL) {
		    COPY_BUF(0,buffer,nbchars,ent->content[0]);
		    if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
			growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
		    }
		} else {
		    xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
			    ""predefined entity has no content\n"");
		}
	    } else if ((ent != NULL) && (ent->content != NULL)) {
		ctxt->depth++;
		rep = xmlStringDecodeEntities(ctxt, ent->content, what,
			                      0, 0, 0);
		ctxt->depth--;

		if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
		    (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
		    goto int_error;

		if (rep != NULL) {
		    current = rep;
		    while (*current != 0) { /* non input consuming loop */
			buffer[nbchars++] = *current++;
			if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
			    if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
				goto int_error;
			    growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
			}
		    }
		    xmlFree(rep);
		    rep = NULL;
		}
	    } else if (ent != NULL) {
		int i = xmlStrlen(ent->name);
		const xmlChar *cur = ent->name;

		buffer[nbchars++] = '&';
		if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) {
		    growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);
		}
		for (;i > 0;i--)
		    buffer[nbchars++] = *cur++;
		buffer[nbchars++] = ';';
	    }
	} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {
	    if (xmlParserDebugEntities)
		xmlGenericError(xmlGenericErrorContext,
			""String decoding PE Reference: %.30s\n"", str);
	    ent = xmlParseStringPEReference(ctxt, &str);
	    if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
	        goto int_error;
	    xmlParserEntityCheck(ctxt, 0, ent, 0);
	    if (ent != NULL)
	        ctxt->nbentities += ent->checked / 2;
	    if (ent != NULL) {
                if (ent->content == NULL) {
		    xmlLoadEntityContent(ctxt, ent);
		}
		ctxt->depth++;
		rep = xmlStringDecodeEntities(ctxt, ent->content, what,
			                      0, 0, 0);
		ctxt->depth--;
		if (rep != NULL) {
		    current = rep;
		    while (*current != 0) { /* non input consuming loop */
			buffer[nbchars++] = *current++;
			if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
			    if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
			        goto int_error;
			    growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
			}
		    }
		    xmlFree(rep);
		    rep = NULL;
		}
	    }
	} else {
	    COPY_BUF(l,buffer,nbchars,c);
	    str += l;
	    if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
	        growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
	    }
	}
	if (str < last)
	    c = CUR_SCHAR(str, l);
	else
	    c = 0;
    }
    buffer[nbchars] = 0;
    return(buffer);

mem_error:
    xmlErrMemory(ctxt, NULL);
int_error:
    if (rep != NULL)
        xmlFree(rep);
    if (buffer != NULL)
        xmlFree(buffer);
    return(NULL);
}",CWE-20,3
0,"WirelessNetwork::WirelessNetwork(const ServiceInfo* service)
    : Network(service) {
  name_ = SafeString(service->name);
  strength_ = service->strength;
  auto_connect_ = service->auto_connect;
  favorite_ = service->favorite;
}
",none,24
1,"static void sixpack_close(struct tty_struct *tty)
{
	struct sixpack *sp;

	write_lock_irq(&disc_data_lock);
	sp = tty->disc_data;
	tty->disc_data = NULL;
	write_unlock_irq(&disc_data_lock);
	if (!sp)
		return;

	/*
	 * We have now ensured that nobody can start using ap from now on, but
	 * we have to wait for all existing users to finish.
	 */
	if (!refcount_dec_and_test(&sp->refcnt))
		wait_for_completion(&sp->dead);

	/* We must stop the queue to avoid potentially scribbling
	 * on the free buffers. The sp->dead completion is not sufficient
	 * to protect us from sp->xbuff access.
	 */
	netif_stop_queue(sp->dev);

	del_timer_sync(&sp->tx_t);
	del_timer_sync(&sp->resync_t);

	/* Free all 6pack frame buffers. */
	kfree(sp->rbuff);
	kfree(sp->xbuff);

	unregister_netdev(sp->dev);
}",CWE-416,10
1,"static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {
	RBuffer *fbuf = r_buf_ref (buf);
	struct MACH0_(opts_t) opts;
	MACH0_(opts_set_default) (&opts, bf);
	struct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts);
	if (!main_mach0) {
		return false;
	}

	RRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0);
	RKernelCacheObj *obj = NULL;

	RPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0);
	if (!prelink_range) {
		goto beach;
	}

	obj = R_NEW0 (RKernelCacheObj);
	if (!obj) {
		R_FREE (prelink_range);
		goto beach;
	}

	RCFValueDict *prelink_info = NULL;
	if (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) {
		prelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset,
				prelink_range->range.size, R_CF_OPTION_SKIP_NSDATA);
		if (!prelink_info) {
			R_FREE (prelink_range);
			R_FREE (obj);
			goto beach;
		}
	}

	if (!pending_bin_files) {
		pending_bin_files = r_list_new ();
		if (!pending_bin_files) {
			R_FREE (prelink_range);
			R_FREE (obj);
			R_FREE (prelink_info);
			goto beach;
		}
	}

	obj->mach0 = main_mach0;
	obj->rebase_info = rebase_info;
	obj->prelink_info = prelink_info;
	obj->cache_buf = fbuf;
	obj->pa2va_exec = prelink_range->pa2va_exec;
	obj->pa2va_data = prelink_range->pa2va_data;

	R_FREE (prelink_range);

	*bin_obj = obj;

	r_list_push (pending_bin_files, bf);

	if (rebase_info || main_mach0->chained_starts) {
		RIO *io = bf->rbin->iob.io;
		swizzle_io_read (obj, io);
	}

	return true;

beach:
	r_buf_free (fbuf);
	obj->cache_buf = NULL;
	MACH0_(mach0_free) (main_mach0);
	return false;
}",CWE-476,12
1,"static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CropBox  ""CropBox""
#define DeviceCMYK  ""DeviceCMYK""
#define MediaBox  ""MediaBox""
#define RenderPCLText  ""  Rendering PCL...  ""

  char
    command[MagickPathExtent],
    *density,
    filename[MagickPathExtent],
    geometry[MagickPathExtent],
    *options,
    input_filename[MagickPathExtent];

  const DelegateInfo
    *delegate_info;

  Image
    *image,
    *next_image;

  ImageInfo
    *read_info;

  MagickBooleanType
    cmyk,
    status;

  PointInfo
    delta;

  RectangleInfo
    bounding_box,
    page;

  char
    *p;

  ssize_t
    c;

  SegmentInfo
    bounds;

  size_t
    height,
    width;

  ssize_t
    count;

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  /*
    Open image file.
  */
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
  if (status == MagickFalse)
    {
      ThrowFileException(exception,FileOpenError,""UnableToCreateTemporaryFile"",
        image_info->filename);
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Set the page density.
  */
  delta.x=DefaultResolution;
  delta.y=DefaultResolution;
  if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
    {
      GeometryInfo
        geometry_info;

      MagickStatusType
        flags;

      flags=ParseGeometry(PSDensityGeometry,&geometry_info);
      if ((flags & RhoValue) != 0)
        image->resolution.x=geometry_info.rho;
      image->resolution.y=image->resolution.x;
      if ((flags & SigmaValue) != 0)
        image->resolution.y=geometry_info.sigma;
    }
  /*
    Determine page geometry from the PCL media box.
  */
  cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
  count=0;
  (void) memset(&bounding_box,0,sizeof(bounding_box));
  (void) memset(&bounds,0,sizeof(bounds));
  (void) memset(&page,0,sizeof(page));
  (void) memset(command,0,sizeof(command));
  p=command;
  for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
  {
    if (image_info->page != (char *) NULL)
      continue;
    /*
      Note PCL elements.
    */
    *p++=(char) c;
    if ((c != (int) '/') && (c != '\n') &&
        ((size_t) (p-command) < (MagickPathExtent-1)))
      continue;
    *p='\0';
    p=command;
    /*
      Is this a CMYK document?
    */
    if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
      cmyk=MagickTrue;
    if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
      {
        /*
          Note region defined by crop box.
        */
        count=(ssize_t) sscanf(command,""CropBox [%lf %lf %lf %lf"",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,""CropBox[%lf %lf %lf %lf"",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
      {
        /*
          Note region defined by media box.
        */
        count=(ssize_t) sscanf(command,""MediaBox [%lf %lf %lf %lf"",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,""MediaBox[%lf %lf %lf %lf"",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (count != 4)
      continue;
    /*
      Set PCL render geometry.
    */
    width=(size_t) floor(bounds.x2-bounds.x1+0.5);
    height=(size_t) floor(bounds.y2-bounds.y1+0.5);
    if (width > page.width)
      page.width=width;
    if (height > page.height)
      page.height=height;
  }
  (void) CloseBlob(image);
  /*
    Render PCL with the GhostPCL delegate.
  */
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  (void) FormatLocaleString(geometry,MagickPathExtent,""%.20gx%.20g"",(double)
    page.width,(double) page.height);
  if (image_info->monochrome != MagickFalse)
    delegate_info=GetDelegateInfo(""pcl:mono"",(char *) NULL,exception);
  else
     if (cmyk != MagickFalse)
       delegate_info=GetDelegateInfo(""pcl:cmyk"",(char *) NULL,exception);
     else
       delegate_info=GetDelegateInfo(""pcl:color"",(char *) NULL,exception);
  if (delegate_info == (const DelegateInfo *) NULL)
    {
      image=DestroyImage(image);
      return((Image *) NULL);
    }
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  density=AcquireString("""");
  options=AcquireString("""");
  (void) FormatLocaleString(density,MagickPathExtent,""%gx%g"",
    image->resolution.x,image->resolution.y);
  if (image_info->ping != MagickFalse)
    (void) FormatLocaleString(density,MagickPathExtent,""2.0x2.0"");
  page.width=(size_t) floor(page.width*image->resolution.x/delta.x+0.5);
  page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5);
  (void) FormatLocaleString(options,MagickPathExtent,""-g%.20gx%.20g "",(double)
    page.width,(double) page.height);
  image=DestroyImage(image);
  read_info=CloneImageInfo(image_info);
  *read_info->magick='\0';
  if (read_info->number_scenes != 0)
    {
      if (read_info->number_scenes != 1)
        (void) FormatLocaleString(options,MagickPathExtent,""-dLastPage=%.20g"",
          (double) (read_info->scene+read_info->number_scenes));
      else
        (void) FormatLocaleString(options,MagickPathExtent,
          ""-dFirstPage=%.20g -dLastPage=%.20g"",(double) read_info->scene+1,
          (double) (read_info->scene+read_info->number_scenes));
      read_info->number_scenes=0;
      if (read_info->scenes != (char *) NULL)
        *read_info->scenes='\0';
    }
  (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);
  (void) AcquireUniqueFilename(read_info->filename);
  (void) FormatLocaleString(command,MagickPathExtent,
    GetDelegateCommands(delegate_info),
    read_info->antialias != MagickFalse ? 4 : 1,
    read_info->antialias != MagickFalse ? 4 : 1,density,options,
    read_info->filename,input_filename);
  options=DestroyString(options);
  density=DestroyString(density);
  status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command,
    (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse;
  image=ReadImage(read_info,exception);
  (void) RelinquishUniqueFileResource(read_info->filename);
  (void) RelinquishUniqueFileResource(input_filename);
  read_info=DestroyImageInfo(read_info);
  if (image == (Image *) NULL)
    ThrowReaderException(DelegateError,""PCLDelegateFailed"");
  if (LocaleCompare(image->magick,""BMP"") == 0)
    {
      Image
        *cmyk_image;

      cmyk_image=ConsolidateCMYKImages(image,exception);
      if (cmyk_image != (Image *) NULL)
        {
          image=DestroyImageList(image);
          image=cmyk_image;
        }
    }
  do
  {
    (void) CopyMagickString(image->filename,filename,MagickPathExtent);
    image->page=page;
    if (image_info->ping != MagickFalse)
      {
        image->magick_columns*=image->resolution.x/2.0;
        image->magick_rows*=image->resolution.y/2.0;
        image->columns*=image->resolution.x/2.0;
        image->rows*=image->resolution.y/2.0;
      }
    next_image=SyncNextImageInList(image);
    if (next_image != (Image *) NULL)
      image=next_image;
  } while (next_image != (Image *) NULL);
  return(GetFirstImageInList(image));
}",CWE-190,2
1,"static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
	struct inode **i)
{
	struct squashfs_dir_header dirh;
	char buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]
		__attribute__((aligned));
	struct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;
	long long start;
	int bytes = 0, dir_count, size, res;
	struct dir_ent *ent, *cur_ent = NULL;
	struct dir *dir;

	TRACE(""squashfs_opendir: inode start block %d, offset %d\n"",
		block_start, offset);

	*i = read_inode(block_start, offset);

	dir = malloc(sizeof(struct dir));
	if(dir == NULL)
		MEM_ERROR();

	dir->dir_count = 0;
	dir->cur_entry = NULL;
	dir->mode = (*i)->mode;
	dir->uid = (*i)->uid;
	dir->guid = (*i)->gid;
	dir->mtime = (*i)->time;
	dir->xattr = (*i)->xattr;
	dir->dirs = NULL;

	if ((*i)->data == 3)
		/*
		 * if the directory is empty, skip the unnecessary
		 * lookup_entry, this fixes the corner case with
		 * completely empty filesystems where lookup_entry correctly
		 * returning -1 is incorrectly treated as an error
		 */
		return dir;

	start = sBlk.s.directory_table_start + (*i)->start;
	offset = (*i)->offset;
	size = (*i)->data + bytes - 3;

	while(bytes < size) {			
		res = read_directory_data(&dirh, &start, &offset, sizeof(dirh));
		if(res == FALSE)
			goto corrupted;

		SQUASHFS_INSWAP_DIR_HEADER(&dirh);
	
		dir_count = dirh.count + 1;
		TRACE(""squashfs_opendir: Read directory header @ byte position ""
			""%d, %d directory entries\n"", bytes, dir_count);
		bytes += sizeof(dirh);

		/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
		if(dir_count > SQUASHFS_DIR_COUNT) {
			ERROR(""File system corrupted: too many entries in directory\n"");
			goto corrupted;
		}

		while(dir_count--) {
			res = read_directory_data(dire, &start, &offset, sizeof(*dire));
			if(res == FALSE)
				goto corrupted;

			SQUASHFS_INSWAP_DIR_ENTRY(dire);

			bytes += sizeof(*dire);

			/* size should never be SQUASHFS_NAME_LEN or larger */
			if(dire->size >= SQUASHFS_NAME_LEN) {
				ERROR(""File system corrupted: filename too long\n"");
				goto corrupted;
			}

			res = read_directory_data(dire->name, &start, &offset,
								dire->size + 1);
			if(res == FALSE)
				goto corrupted;

			dire->name[dire->size + 1] = '\0';

			/* check name for invalid characters (i.e /, ., ..) */
			if(check_name(dire->name, dire->size + 1) == FALSE) {
				ERROR(""File system corrupted: invalid characters in name\n"");
				goto corrupted;
			}

			TRACE(""squashfs_opendir: directory entry %s, inode ""
				""%d:%d, type %d\n"", dire->name,
				dirh.start_block, dire->offset, dire->type);

			ent = malloc(sizeof(struct dir_ent));
			if(ent == NULL)
				MEM_ERROR();

			ent->name = strdup(dire->name);
			ent->start_block = dirh.start_block;
			ent->offset = dire->offset;
			ent->type = dire->type;
			ent->next = NULL;
			if(cur_ent == NULL)
				dir->dirs = ent;
			else
				cur_ent->next = ent;
			cur_ent = ent;
			dir->dir_count ++;
			bytes += dire->size + 1;
		}
	}

	return dir;

corrupted:
	squashfs_closedir(dir);
	return NULL;
}",CWE-200,4
1,"  void DecodePngV2(OpKernelContext* context, StringPiece input) {
    int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16;
    png::DecodeContext decode;
    OP_REQUIRES(
        context, png::CommonInitDecode(input, channels_, channel_bits, &decode),
        errors::InvalidArgument(""Invalid PNG. Failed to initialize decoder.""));

    // Verify that width and height are not too large:
    // - verify width and height don't overflow int.
    // - width can later be multiplied by channels_ and sizeof(uint16), so
    //   verify single dimension is not too large.
    // - verify when width and height are multiplied together, there are a few
    //   bits to spare as well.
    const int width = static_cast(decode.width);
    const int height = static_cast(decode.height);
    const int64_t total_size =
        static_cast(width) * static_cast(height);
    if (width != static_cast(decode.width) || width <= 0 ||
        width >= (1LL << 27) || height != static_cast(decode.height) ||
        height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) {
      png::CommonFreeDecode(&decode);
      OP_REQUIRES(context, false,
                  errors::InvalidArgument(""PNG size too large for int: "",
                                          decode.width, "" by "", decode.height));
    }

    Tensor* output = nullptr;
    Status status;
    // By the existing API, we support decoding PNG with `DecodeGif` op.
    // We need to make sure to return 4-D shapes when using `DecodeGif`.
    if (op_type_ == ""DecodeGif"") {
      status = context->allocate_output(
          0, TensorShape({1, height, width, decode.channels}), &output);
    } else {
      status = context->allocate_output(
          0, TensorShape({height, width, decode.channels}), &output);
    }

    if (op_type_ == ""DecodeBmp"") {
      // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here
      // because currently `decode_(jpeg|png|gif)` ops can decode any one of
      // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode
      // anything but bmp formats. This behavior needs to be revisited. For more
      // details, please refer to the bug.
      OP_REQUIRES(context, false,
                  errors::InvalidArgument(
                      ""Trying to decode PNG format using DecodeBmp op. Use ""
                      ""`decode_png` or `decode_image` instead.""));
    } else if (op_type_ == ""DecodeAndCropJpeg"") {
      OP_REQUIRES(context, false,
                  errors::InvalidArgument(
                      ""DecodeAndCropJpeg operation can run on JPEG only, but ""
                      ""detected PNG.""));
    }

    if (!status.ok()) png::CommonFreeDecode(&decode);
    OP_REQUIRES_OK(context, status);

    if (data_type_ == DataType::DT_UINT8) {
      OP_REQUIRES(
          context,
          png::CommonFinishDecode(
              reinterpret_cast(output->flat().data()),
              decode.channels * width * sizeof(uint8), &decode),
          errors::InvalidArgument(""Invalid PNG data, size "", input.size()));
    } else if (data_type_ == DataType::DT_UINT16) {
      OP_REQUIRES(
          context,
          png::CommonFinishDecode(
              reinterpret_cast(output->flat().data()),
              decode.channels * width * sizeof(uint16), &decode),
          errors::InvalidArgument(""Invalid PNG data, size "", input.size()));
    } else if (data_type_ == DataType::DT_FLOAT) {
      // `png::CommonFinishDecode` does not support `float`. First allocate
      // uint16 buffer for the image and decode in uint16 (lossless). Wrap the
      // buffer in `unique_ptr` so that we don't forget to delete the buffer.
      std::unique_ptr buffer(
          new uint16[height * width * decode.channels]);
      OP_REQUIRES(
          context,
          png::CommonFinishDecode(reinterpret_cast(buffer.get()),
                                  decode.channels * width * sizeof(uint16),
                                  &decode),
          errors::InvalidArgument(""Invalid PNG data, size "", input.size()));

      // Convert uint16 image data to desired data type.
      // Use eigen threadpooling to speed up the copy operation.
      const auto& device = context->eigen_device();
      TTypes::UnalignedConstTensor buf(buffer.get(), height, width,
                                                  decode.channels);
      float scale = 1. / std::numeric_limits::max();
      // Fill output tensor with desired dtype.
      output->tensor().device(device) = buf.cast() * scale;
    }
  }",CWE-416,10
1,"static void write_response(ESPState *s)
{
    uint32_t n;

    trace_esp_write_response(s->status);

    fifo8_reset(&s->fifo);
    esp_fifo_push(s, s->status);
    esp_fifo_push(s, 0);

    if (s->dma) {
        if (s->dma_memory_write) {
            s->dma_memory_write(s->dma_opaque,
                                (uint8_t *)fifo8_pop_buf(&s->fifo, 2, &n), 2);
            s->rregs[ESP_RSTAT] = STAT_TC | STAT_ST;
            s->rregs[ESP_RINTR] |= INTR_BS | INTR_FC;
            s->rregs[ESP_RSEQ] = SEQ_CD;
        } else {
            s->pdma_cb = write_response_pdma_cb;
            esp_raise_drq(s);
            return;
        }
    } else {
        s->ti_size = 2;
        s->rregs[ESP_RFLAGS] = 2;
    }
    esp_raise_irq(s);
}",CWE-476,12
0,"  void DidGetGlobalQuota(QuotaStatusCode status,
                         StorageType type,
                         int64 quota) {
    DCHECK_EQ(type_, type);
    quota_status_ = status;
    quota_ = quota;
    CheckCompleted();
  }
",none,24
1,"dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)
{
    size_t i, j;
	// Insert 'local-zone: ""2.dnscrypt-cert.example.com"" deny'
    if(!cfg_str2list_insert(&cfg->local_zones,
                            strdup(dnscenv->provider_name),
                            strdup(""deny""))) {
        log_err(""Could not load dnscrypt local-zone: %s deny"",
                dnscenv->provider_name);
        return -1;
    }

    // Add local data entry of type:
    // 2.dnscrypt-cert.example.com 86400 IN TXT ""DNSC......""
    for(i=0; isigned_certs_count; i++) {
        const char *ttl_class_type = "" 86400 IN TXT \"""";
        int rotated_cert = 0;
	uint32_t serial;
	uint16_t rrlen;
	char* rr;
        struct SignedCert *cert = dnscenv->signed_certs + i;
		// Check if the certificate is being rotated and should not be published
        for(j=0; jrotated_certs_count; j++){
            if(cert == dnscenv->rotated_certs[j]) {
                rotated_cert = 1;
                break;
            }
        }
		memcpy(&serial, cert->serial, sizeof serial);
		serial = htonl(serial);
        if(rotated_cert) {
            verbose(VERB_OPS,
                ""DNSCrypt: not adding cert with serial #%""
                PRIu32
                "" to local-data as it is rotated"",
                serial
            );
            continue;
        }
        rrlen = strlen(dnscenv->provider_name) +
                         strlen(ttl_class_type) +
                         4 * sizeof(struct SignedCert) + // worst case scenario
                         1 + // trailing double quote
                         1;
        rr = malloc(rrlen);
        if(!rr) {
            log_err(""Could not allocate memory"");
            return -2;
        }
        snprintf(rr, rrlen - 1, ""%s 86400 IN TXT \"""", dnscenv->provider_name);
        for(j=0; jlocal_data, strdup(rr));
        free(rr);
    }
    return dnscenv->signed_certs_count;
}",CWE-190,2
0,"  virtual void AddNetworkManagerObserver(NetworkManagerObserver* observer) {}
",none,24
0,"  void UpdateNetworkStatus(const char* path,
                           const char* key,
                           const Value* value) {
    if (key == NULL || value == NULL)
      return;
    if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          NewRunnableMethod(this,
                            &NetworkLibraryImpl::UpdateNetworkStatus,
                            path, key, value));
      return;
    }

    bool boolval = false;
    int intval = 0;
    std::string stringval;
    Network* network;
    if (ethernet_->service_path() == path) {
      network = ethernet_;
    } else {
      CellularNetwork* cellular =
          GetWirelessNetworkByPath(cellular_networks_, path);
      WifiNetwork* wifi =
          GetWirelessNetworkByPath(wifi_networks_, path);
      if (cellular == NULL && wifi == NULL)
        return;

      WirelessNetwork* wireless;
      if (wifi != NULL)
        wireless = static_cast(wifi);
      else
        wireless = static_cast(cellular);

      if (strcmp(key, kSignalStrengthProperty) == 0) {
        if (value->GetAsInteger(&intval))
          wireless->set_strength(intval);
      } else if (cellular != NULL) {
        if (strcmp(key, kRestrictedPoolProperty) == 0) {
          if (value->GetAsBoolean(&boolval))
            cellular->set_restricted_pool(boolval);
        } else if (strcmp(key, kActivationStateProperty) == 0) {
          if (value->GetAsString(&stringval))
            cellular->set_activation_state(ParseActivationState(stringval));
        } else if (strcmp(key, kPaymentURLProperty) == 0) {
          if (value->GetAsString(&stringval))
            cellular->set_payment_url(stringval);
        } else if (strcmp(key, kNetworkTechnologyProperty) == 0) {
          if (value->GetAsString(&stringval))
            cellular->set_network_technology(
                ParseNetworkTechnology(stringval));
        } else if (strcmp(key, kRoamingStateProperty) == 0) {
          if (value->GetAsString(&stringval))
            cellular->set_roaming_state(ParseRoamingState(stringval));
        }
      }
      network = wireless;
    }
    if (strcmp(key, kIsActiveProperty) == 0) {
      if (value->GetAsBoolean(&boolval))
        network->set_active(boolval);
    } else if (strcmp(key, kStateProperty) == 0) {
      if (value->GetAsString(&stringval))
        network->set_state(ParseState(stringval));
    }
    NotifyNetworkChanged(network);
  }
",none,24
0,"  QuotaDatabase* database() const { return database_; }
",none,24
1,"  void Compute(OpKernelContext* ctx) override {
    const Tensor& in0 = ctx->input(0);
    const Tensor& in1 = ctx->input(1);
    auto in0_flat = in0.flat();
    auto in1_flat = in1.flat();
    const Device& eigen_device = ctx->eigen_device();

    Tensor* out = nullptr;
    if (std::is_same::value) {
      OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
                              {0, 1}, 0, in0.shape(), &out));
    } else {
      OP_REQUIRES_OK(ctx, ctx->allocate_output(0, in0.shape(), &out));
    }
    auto out_flat = out->flat();
    functor::SimpleBinaryFunctor()(eigen_device, out_flat,
                                                    in0_flat, in1_flat);
  }",CWE-787,16
1,"  void Compute(OpKernelContext* context) override {
    const Tensor& indices = context->input(0);
    const Tensor& values = context->input(1);
    const Tensor& shape = context->input(2);
    const Tensor& weights = context->input(3);
    bool use_weights = weights.NumElements() > 0;

    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),
                errors::InvalidArgument(
                    ""Input indices must be a 2-dimensional tensor. Got: "",
                    indices.shape().DebugString()));

    if (use_weights) {
      OP_REQUIRES(
          context, weights.shape() == values.shape(),
          errors::InvalidArgument(
              ""Weights and values must have the same shape. Weight shape: "",
              weights.shape().DebugString(),
              ""; values shape: "", values.shape().DebugString()));
    }

    OP_REQUIRES(context, shape.NumElements() != 0,
                errors::InvalidArgument(
                    ""The shape argument requires at least one element.""));

    bool is_1d = shape.NumElements() == 1;
    auto shape_vector = shape.flat();
    int num_batches = is_1d ? 1 : shape_vector(0);
    int num_values = values.NumElements();

    for (int b = 0; b < shape_vector.size(); b++) {
      OP_REQUIRES(context, shape_vector(b) >= 0,
                  errors::InvalidArgument(
                      ""Elements in dense_shape must be >= 0. Instead got:"",
                      shape.DebugString()));
    }

    OP_REQUIRES(context, num_values == indices.shape().dim_size(0),
                errors::InvalidArgument(
                    ""Number of values must match first dimension of indices."",
                    ""Got "", num_values,
                    "" values, indices shape: "", indices.shape().DebugString()));

    const auto indices_values = indices.matrix();
    const auto values_values = values.flat();
    const auto weight_values = weights.flat();

    auto per_batch_counts = BatchedMap(num_batches);

    T max_value = 0;

    OP_REQUIRES(context, num_values <= indices.shape().dim_size(0),
                errors::InvalidArgument(
                    ""The first dimension of indices must be equal to or ""
                    ""greather than number of values. ( "",
                    indices.shape().dim_size(0), "" vs. "", num_values, "" )""));
    OP_REQUIRES(context, indices.shape().dim_size(1) > 0,
                errors::InvalidArgument(""The second dimension of indices must ""
                                        ""be greater than 0. Received: "",
                                        indices.shape().dim_size(1)));

    for (int idx = 0; idx < num_values; ++idx) {
      int batch = is_1d ? 0 : indices_values(idx, 0);
      if (batch >= num_batches) {
        OP_REQUIRES(context, batch < num_batches,
                    errors::InvalidArgument(
                        ""Indices value along the first dimension must be "",
                        ""lower than the first index of the shape."", ""Got "",
                        batch, "" as batch and "", num_batches,
                        "" as the first dimension of the shape.""));
      }
      const auto& value = values_values(idx);
      if (value >= 0 && (maxlength_ <= 0 || value < maxlength_)) {
        if (binary_output_) {
          per_batch_counts[batch][value] = 1;
        } else if (use_weights) {
          per_batch_counts[batch][value] += weight_values(idx);
        } else {
          per_batch_counts[batch][value]++;
        }
        if (value > max_value) {
          max_value = value;
        }
      }
    }

    int num_output_values = GetOutputSize(max_value, maxlength_, minlength_);
    OP_REQUIRES_OK(context, OutputSparse(per_batch_counts, num_output_values,
                                            is_1d, context));
  }",CWE-787,16
0,"  virtual void EnableWifiNetworkDevice(bool enable) {
    EnableNetworkDeviceType(TYPE_WIFI, enable);
  }
",none,24
0,"void QuotaManagerProxy::NotifyStorageModified(
    QuotaClient::ID client_id,
    const GURL& origin,
    StorageType type,
    int64 delta) {
  if (!io_thread_->BelongsToCurrentThread()) {
    io_thread_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &QuotaManagerProxy::NotifyStorageModified,
        client_id, origin, type, delta));
    return;
  }
  if (manager_)
    manager_->NotifyStorageModified(client_id, origin, type, delta);
}
",none,24
1,"void SparseFillEmptyRowsOpImpl(OpKernelContext* context,
                               AsyncOpKernel::DoneCallback done = nullptr) {
  // Note that setting this empty lambda as the default parameter value directly
  // can cause strange compiler/linker errors, so we do it like this instead.
  if (!done) {
    done = [] {};
  }

  const int kIndicesInput = 0;
  const int kValuesInput = 1;
  const int kDenseShapeInput = 2;
  const int kDefaultValueInput = 3;

  const Tensor& indices_t = context->input(kIndicesInput);
  const Tensor& values_t = context->input(kValuesInput);
  const Tensor& dense_shape_t = context->input(kDenseShapeInput);
  const Tensor& default_value_t = context->input(kDefaultValueInput);

  OP_REQUIRES_ASYNC(
      context, TensorShapeUtils::IsVector(dense_shape_t.shape()),
      errors::InvalidArgument(""dense_shape must be a vector, saw: "",
                              dense_shape_t.shape().DebugString()),
      done);
  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()),
                    errors::InvalidArgument(""indices must be a matrix, saw: "",
                                            indices_t.shape().DebugString()),
                    done);
  OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()),
                    errors::InvalidArgument(""values must be a vector, saw: "",
                                            values_t.shape().DebugString()),
                    done);
  OP_REQUIRES_ASYNC(
      context, TensorShapeUtils::IsScalar(default_value_t.shape()),
      errors::InvalidArgument(""default_value must be a scalar, saw: "",
                              default_value_t.shape().DebugString()),
      done);
  // TODO(ebrevdo): add shape checks between values, indices,
  // Also add check that dense rank > 0.
  OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0,
                    errors::InvalidArgument(""Dense shape cannot be empty.""),
                    done);

  using FunctorType = functor::SparseFillEmptyRows;
  OP_REQUIRES_OK_ASYNC(context,
                       FunctorType()(context, default_value_t, indices_t,
                                     values_t, dense_shape_t, done),
                       done);
}",CWE-125,1
1,"static void *seq_buf_alloc(unsigned long size)
{
	return kvmalloc(size, GFP_KERNEL_ACCOUNT);
}",CWE-787,16
0,"  virtual void RemoveObserverForAllNetworks(NetworkObserver* observer) {}
",none,24
1,"static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)
{
	struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;
	struct tipc_aead_key *skey = NULL;
	u16 key_gen = msg_key_gen(hdr);
	u16 size = msg_data_sz(hdr);
	u8 *data = msg_data(hdr);

	spin_lock(&rx->lock);
	if (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) {
		pr_err(""%s: key existed <%p>, gen %d vs %d\n"", rx->name,
		       rx->skey, key_gen, rx->key_gen);
		goto exit;
	}

	/* Allocate memory for the key */
	skey = kmalloc(size, GFP_ATOMIC);
	if (unlikely(!skey)) {
		pr_err(""%s: unable to allocate memory for skey\n"", rx->name);
		goto exit;
	}

	/* Copy key from msg data */
	skey->keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME)));
	memcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME);
	memcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32),
	       skey->keylen);

	/* Sanity check */
	if (unlikely(size != tipc_aead_key_size(skey))) {
		kfree(skey);
		skey = NULL;
		goto exit;
	}

	rx->key_gen = key_gen;
	rx->skey_mode = msg_key_mode(hdr);
	rx->skey = skey;
	rx->nokey = 0;
	mb(); /* for nokey flag */

exit:
	spin_unlock(&rx->lock);

	/* Schedule the key attaching on this crypto */
	if (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0)))
		return true;

	return false;
}",CWE-20,3
0,"  virtual bool has_cellular_networks() const {
    return cellular_networks_.begin() != cellular_networks_.end();
  }
",none,24
1,"  void Compute(OpKernelContext* context) override {
    const Tensor* input_indices;
    const Tensor* input_values;
    const Tensor* input_shape;
    SparseTensorsMap* map;

    OP_REQUIRES_OK(context, context->input(""sparse_indices"", &input_indices));
    OP_REQUIRES_OK(context, context->input(""sparse_values"", &input_values));
    OP_REQUIRES_OK(context, context->input(""sparse_shape"", &input_shape));
    OP_REQUIRES_OK(context, GetMap(context, true /* is_writing */, &map));

    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices->shape()),
                errors::InvalidArgument(
                    ""Input indices should be a matrix but received shape "",
                    input_indices->shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values->shape()),
                errors::InvalidArgument(
                    ""Input values should be a vector but received shape "",
                    input_values->shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape->shape()),
                errors::InvalidArgument(
                    ""Input shape should be a vector but received shape "",
                    input_shape->shape().DebugString()));
    OP_REQUIRES(
        context,
        input_values->shape().dim_size(0) == input_indices->shape().dim_size(0),
        errors::InvalidArgument(
            ""Number of values must match first dimension of indices. "", ""Got "",
            input_values->shape().dim_size(0),
            "" values, indices shape: "", input_indices->shape().DebugString()));
    OP_REQUIRES(
        context,
        input_shape->shape().dim_size(0) == input_indices->shape().dim_size(1),
        errors::InvalidArgument(
            ""Number of dimensions must match second dimension of indices. "",
            ""Got "", input_shape->shape().dim_size(0),
            "" dimensions, indices shape: "",
            input_indices->shape().DebugString()));

    int rank = input_shape->NumElements();

    OP_REQUIRES(
        context, rank > 1,
        errors::InvalidArgument(
            ""Rank of input SparseTensor should be > 1, but saw rank: "", rank));

    auto input_shape_vec = input_shape->vec();
    int new_num_elements = 1;
    bool overflow_ocurred = false;
    for (int i = 0; i < input_shape_vec.size(); i++) {
      new_num_elements =
          MultiplyWithoutOverflow(new_num_elements, input_shape_vec(i));
      if (new_num_elements < 0) {
        overflow_ocurred = true;
        break;
      }
    }

    OP_REQUIRES(
        context, !overflow_ocurred,
        errors::Internal(""Encountered overflow from large input shape.""));

    TensorShape tensor_input_shape(input_shape_vec);
    gtl::InlinedVector std_order(rank);
    std::iota(std_order.begin(), std_order.end(), 0);
    SparseTensor input_st;
    OP_REQUIRES_OK(context, SparseTensor::Create(*input_indices, *input_values,
                                                 tensor_input_shape, std_order,
                                                 &input_st));

    const int64_t N = input_shape_vec(0);

    Tensor sparse_handles(DT_INT64, TensorShape({N}));
    auto sparse_handles_t = sparse_handles.vec();

    OP_REQUIRES_OK(context, input_st.IndicesValid());

    // We can generate the output shape proto string now, for all
    // minibatch entries.
    TensorShape output_shape;
    OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(
                                input_shape_vec.data() + 1,
                                input_shape->NumElements() - 1, &output_shape));

    // Get groups by minibatch dimension
    std::unordered_set visited;
    sparse::GroupIterable minibatch = input_st.group({0});
    for (const auto& subset : minibatch) {
      const int64_t b = subset.group()[0];
      visited.insert(b);
      OP_REQUIRES(
          context, b > -1 && b < N,
          errors::InvalidArgument(
              ""Received unexpected column 0 value in input SparseTensor: "", b,
              "" < 0 or >= N (= "", N, "")""));

      const auto indices = subset.indices();
      const auto values = subset.values();
      const int64_t num_entries = values.size();

      Tensor output_indices = Tensor(DT_INT64, {num_entries, rank - 1});
      Tensor output_values = Tensor(DataTypeToEnum::value, {num_entries});

      auto output_indices_t = output_indices.matrix();
      auto output_values_t = output_values.vec();

      for (int i = 0; i < num_entries; ++i) {
        for (int d = 1; d < rank; ++d) {
          output_indices_t(i, d - 1) = indices(i, d);
        }
        output_values_t(i) = values(i);
      }

      SparseTensor st_i;
      OP_REQUIRES_OK(context,
                     SparseTensor::Create(output_indices, output_values,
                                          output_shape, &st_i));
      int64_t handle;
      OP_REQUIRES_OK(context, map->AddSparseTensor(context, st_i, &handle));
      sparse_handles_t(b) = handle;
    }

    // Fill in any gaps; we must provide an empty ST for batch entries
    // the grouper didn't find.
    if (visited.size() < N) {
      Tensor empty_indices(DT_INT64, {0, rank - 1});
      Tensor empty_values(DataTypeToEnum::value, {0});
      SparseTensor empty_st;
      OP_REQUIRES_OK(context, SparseTensor::Create(empty_indices, empty_values,
                                                   output_shape, &empty_st));

      for (int64_t b = 0; b < N; ++b) {
        // We skipped this batch entry.
        if (visited.find(b) == visited.end()) {
          int64_t handle;
          OP_REQUIRES_OK(context,
                         map->AddSparseTensor(context, empty_st, &handle));
          sparse_handles_t(b) = handle;
        }
      }
    }

    context->set_output(0, sparse_handles);
  }",CWE-190,2
1,"njs_await_fulfilled(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
    njs_index_t unused)
{
    njs_int_t           ret;
    njs_value_t         **cur_local, **cur_closures, **cur_temp, *value;
    njs_frame_t         *frame, *async_frame;
    njs_function_t      *function;
    njs_async_ctx_t     *ctx;
    njs_native_frame_t  *top, *async;

    ctx = vm->top_frame->function->context;

    value = njs_arg(args, nargs, 1);
    if (njs_is_error(value)) {
        goto failed;
    }

    async_frame = ctx->await;
    async = &async_frame->native;
    async->previous = vm->top_frame;

    function = async->function;

    cur_local = vm->levels[NJS_LEVEL_LOCAL];
    cur_closures = vm->levels[NJS_LEVEL_CLOSURE];
    cur_temp = vm->levels[NJS_LEVEL_TEMP];
    top = vm->top_frame;
    frame = vm->active_frame;

    vm->levels[NJS_LEVEL_LOCAL] = async->local;
    vm->levels[NJS_LEVEL_CLOSURE] = njs_function_closures(async->function);
    vm->levels[NJS_LEVEL_TEMP] = async->temp;

    vm->top_frame = async;
    vm->active_frame = async_frame;

    *njs_scope_value(vm, ctx->index) = *value;
    vm->retval = *value;

    vm->top_frame->retval = &vm->retval;

    function->context = ctx->capability;
    function->await = ctx;

    ret = njs_vmcode_interpreter(vm, ctx->pc);

    function->context = NULL;
    function->await = NULL;

    vm->levels[NJS_LEVEL_LOCAL] = cur_local;
    vm->levels[NJS_LEVEL_CLOSURE] = cur_closures;
    vm->levels[NJS_LEVEL_TEMP] = cur_temp;

    vm->top_frame = top;
    vm->active_frame = frame;

    if (ret == NJS_OK) {
        ret = njs_function_call(vm, njs_function(&ctx->capability->resolve),
                            &njs_value_undefined, &vm->retval, 1, &vm->retval);

        njs_async_context_free(vm, ctx);

    } else if (ret == NJS_AGAIN) {
        ret = NJS_OK;

    } else if (ret == NJS_ERROR) {
        if (njs_is_memory_error(vm, &vm->retval)) {
            return NJS_ERROR;
        }

        value = &vm->retval;

        goto failed;
    }

    return ret;

failed:

    (void) njs_function_call(vm, njs_function(&ctx->capability->reject),
                             &njs_value_undefined, value, 1, &vm->retval);

    njs_async_context_free(vm, ctx);

    return NJS_ERROR;
}",CWE-416,10
1,"static GF_Err gf_isom_parse_movie_boxes_internal(GF_ISOFile *mov, u32 *boxType, u64 *bytesMissing, Bool progressive_mode)
{
	GF_Box *a;
	u64 totSize, mdat_end=0;
	GF_Err e = GF_OK;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
	if (mov->single_moof_mode && mov->single_moof_state == 2) {
		return e;
	}

	/*restart from where we stopped last*/
	totSize = mov->current_top_box_start;
	if (mov->bytes_removed) {
		assert(totSize >= mov->bytes_removed);
		totSize -= mov->bytes_removed;
	}
	gf_bs_seek(mov->movieFileMap->bs, totSize);
#endif


	/*while we have some data, parse our boxes*/
	while (gf_bs_available(mov->movieFileMap->bs)) {
		*bytesMissing = 0;
#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		mov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[iso file] Parsing a top-level box at position %d\n"", mov->current_top_box_start));
#endif

		e = gf_isom_parse_root_box(&a, mov->movieFileMap->bs, boxType, bytesMissing, progressive_mode);

		if (e >= 0) {

		} else if (e == GF_ISOM_INCOMPLETE_FILE) {
			/*our mdat is uncomplete, only valid for READ ONLY files...*/
			if (mov->openMode != GF_ISOM_OPEN_READ) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Incomplete MDAT while file is not read-only\n""));
				return GF_ISOM_INVALID_FILE;
			}
			if ((mov->openMode == GF_ISOM_OPEN_READ) && !progressive_mode) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Incomplete file while reading for dump - aborting parsing\n""));
				break;
			}
			return e;
		} else {
			return e;
		}

		switch (a->type) {
		/*MOOV box*/
		case GF_ISOM_BOX_TYPE_MOOV:
			if (mov->moov) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate MOOV detected!\n""));
				gf_isom_box_del(a);
				return GF_ISOM_INVALID_FILE;
			}
			mov->moov = (GF_MovieBox *)a;
			mov->original_moov_offset = mov->current_top_box_start;
			/*set our pointer to the movie*/
			mov->moov->mov = mov;
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (mov->moov->mvex) mov->moov->mvex->mov = mov;

#ifdef GF_ENABLE_CTRN
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				gf_isom_setup_traf_inheritance(mov);
			}
#endif

#endif
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;

			totSize += a->size;

            if (!mov->moov->mvhd) {
                GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing MovieHeaderBox\n""));
                return GF_ISOM_INVALID_FILE;
            }

            if (mov->meta) {
				gf_isom_meta_restore_items_ref(mov, mov->meta);
			}

			//dump senc info in dump mode
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				u32 k;
				for (k=0; kmoov->trackList); k++) {
					GF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);

					if (trak->sample_encryption) {
						e = senc_Parse(mov->movieFileMap->bs, trak, NULL, trak->sample_encryption);
						if (e) return e;
					}
				}
			} else {
				u32 k;
				for (k=0; kmoov->trackList); k++) {
					GF_TrackBox *trak = (GF_TrackBox *)gf_list_get(mov->moov->trackList, k);
					if (trak->Media->information->sampleTable->sampleGroups) {
						convert_compact_sample_groups(trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroups);
					}
				}
			}

            if (mdat_end && mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {
                gf_isom_push_mdat_end(mov, mdat_end);
                mdat_end=0;
            }
			break;

		/*META box*/
		case GF_ISOM_BOX_TYPE_META:
			if (mov->meta) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate META detected!\n""));
				gf_isom_box_del(a);
				return GF_ISOM_INVALID_FILE;
			}
			mov->meta = (GF_MetaBox *)a;
			mov->original_meta_offset = mov->current_top_box_start;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) {
				return e;
			}
			totSize += a->size;
			gf_isom_meta_restore_items_ref(mov, mov->meta);
			break;

		/*we only keep the MDAT in READ for dump purposes*/
		case GF_ISOM_BOX_TYPE_MDAT:
			if (!mov->first_data_toplevel_offset) {
				mov->first_data_toplevel_offset = mov->current_top_box_start;
				mov->first_data_toplevel_size = a->size;
			}
			totSize += a->size;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
			if (mov->emsgs) {
				gf_isom_box_array_del(mov->emsgs);
				mov->emsgs = NULL;
			}
#endif

			if (mov->openMode == GF_ISOM_OPEN_READ) {
				if (!mov->mdat) {
					mov->mdat = (GF_MediaDataBox *) a;
					e = gf_list_add(mov->TopBoxes, mov->mdat);
					if (e) {
						return e;
					}
				}
#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
				else if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) gf_list_add(mov->TopBoxes, a);
#endif
				else gf_isom_box_del(a); //in other modes we don't care


				if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) ) {
                    mdat_end = gf_bs_get_position(mov->movieFileMap->bs);
                    if (mov->moov) {
                        gf_isom_push_mdat_end(mov, mdat_end);
                        mdat_end=0;
                    }
				}
			}
			/*if we don't have any MDAT yet, create one (edit-write mode)
			We only work with one mdat, but we're puting it at the place
			of the first mdat found when opening a file for editing*/
			else if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {
				gf_isom_box_del(a);
				mov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);
				if (!mov->mdat) return GF_OUT_OF_MEM;
				e = gf_list_add(mov->TopBoxes, mov->mdat);
				if (e) {
					return e;
				}
			} else {
				gf_isom_box_del(a);
			}
			break;
		case GF_ISOM_BOX_TYPE_FTYP:
			/*ONE AND ONLY ONE FTYP*/
			if (mov->brand) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'ftyp' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}
			mov->brand = (GF_FileTypeBox *)a;
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;

		case GF_ISOM_BOX_TYPE_OTYP:
			/*ONE AND ONLY ONE FTYP*/
			if (mov->otyp) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'otyp' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}

			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				mov->otyp = (GF_Box *)a;
				totSize += a->size;
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			} else {
				GF_FileTypeBox *brand = (GF_FileTypeBox *) gf_isom_box_find_child(a->child_boxes, GF_ISOM_BOX_TYPE_FTYP);
				if (brand) {
					s32 pos;
					gf_list_del_item(a->child_boxes, brand);
					pos = gf_list_del_item(mov->TopBoxes, mov->brand);
					gf_isom_box_del((GF_Box *) mov->brand);
					mov->brand = brand;
					if (pos<0) pos=0;
					gf_list_insert(mov->TopBoxes, brand, pos);
				}
				gf_isom_box_del(a);
			}
			break;

		case GF_ISOM_BOX_TYPE_PDIN:
			/*ONE AND ONLY ONE PDIN*/
			if (mov->pdin) {
				gf_isom_box_del(a);
				GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Duplicate 'pdin'' detected!\n""));
				return GF_ISOM_INVALID_FILE;
			}
			mov->pdin = (GF_ProgressiveDownloadBox *) a;
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;


#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		case GF_ISOM_BOX_TYPE_STYP:
		{
			u32 brand = ((GF_FileTypeBox *)a)->majorBrand;
			switch (brand) {
			case GF_ISOM_BRAND_SISX:
			case GF_ISOM_BRAND_RISX:
			case GF_ISOM_BRAND_SSSS:
				mov->is_index_segment = GF_TRUE;
				break;
			default:
				break;
			}
		}
		/*fall-through*/

		case GF_ISOM_BOX_TYPE_SIDX:
		case GF_ISOM_BOX_TYPE_SSIX:
			if (mov->moov && !mov->first_data_toplevel_offset) {
				mov->first_data_toplevel_offset = mov->current_top_box_start;
				mov->first_data_toplevel_size = a->size;
			}
			totSize += a->size;
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			} else if (mov->signal_frag_bounds && !(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)  && (mov->openMode!=GF_ISOM_OPEN_KEEP_FRAGMENTS)
			) {
				if (a->type==GF_ISOM_BOX_TYPE_SIDX) {
					if (mov->root_sidx) gf_isom_box_del( (GF_Box *) mov->root_sidx);
					mov->root_sidx = (GF_SegmentIndexBox *) a;
					mov->sidx_start_offset = mov->current_top_box_start;
					mov->sidx_end_offset = gf_bs_get_position(mov->movieFileMap->bs);

				}
				else if (a->type==GF_ISOM_BOX_TYPE_STYP) {
					mov->styp_start_offset = mov->current_top_box_start;

					if (mov->seg_styp) gf_isom_box_del(mov->seg_styp);
					mov->seg_styp = a;
				} else if (a->type==GF_ISOM_BOX_TYPE_SSIX) {
					if (mov->seg_ssix) gf_isom_box_del(mov->seg_ssix);
					mov->seg_ssix = a;
				} else {
					gf_isom_box_del(a);
				}
				gf_isom_push_mdat_end(mov, mov->current_top_box_start);
			} else if (!mov->NextMoofNumber && (a->type==GF_ISOM_BOX_TYPE_SIDX)) {
				if (mov->main_sidx) gf_isom_box_del( (GF_Box *) mov->main_sidx);
				mov->main_sidx = (GF_SegmentIndexBox *) a;
				mov->main_sidx_end_pos = mov->current_top_box_start + a->size;
			} else {
				gf_isom_box_del(a);
			}
			break;

		case GF_ISOM_BOX_TYPE_MOOF:
			//no support for inplace rewrite for fragmented files
			gf_isom_disable_inplace_rewrite(mov);
			if (!mov->moov) {
				GF_LOG(mov->moof ? GF_LOG_DEBUG : GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] Movie fragment but no moov (yet) - possibly broken parsing!\n""));
			}
			if (mov->single_moof_mode) {
				mov->single_moof_state++;
				if (mov->single_moof_state > 1) {
					gf_isom_box_del(a);
					return GF_OK;
				}
			}
			((GF_MovieFragmentBox *)a)->mov = mov;

			totSize += a->size;
			mov->moof = (GF_MovieFragmentBox *) a;

			/*some smooth streaming streams contain a SDTP under the TRAF: this is incorrect, convert it*/
			FixTrackID(mov);
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				FixSDTPInTRAF(mov->moof);
			} else {
				u32 k;
				for (k=0; kmoof->TrackList); k++) {
					GF_TrackFragmentBox *traf = (GF_TrackFragmentBox *)gf_list_get(mov->moof->TrackList, k);
					if (traf->sampleGroups) {
						convert_compact_sample_groups(traf->child_boxes, traf->sampleGroups);
					}
				}
			}

			/*read & debug: store at root level*/
			if (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG) {
				u32 k;
				gf_list_add(mov->TopBoxes, a);
				/*also update pointers to trex for debug*/
				if (mov->moov) {
					for (k=0; kmoof->TrackList); k++) {
						GF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);
						if (traf->tfhd && mov->moov->mvex && mov->moov->mvex->TrackExList) {
							GF_TrackBox *trak = gf_isom_get_track_from_id(mov->moov, traf->tfhd->trackID);
							u32 j=0;
							while ((traf->trex = (GF_TrackExtendsBox*)gf_list_enum(mov->moov->mvex->TrackExList, &j))) {
								if (traf->trex->trackID == traf->tfhd->trackID) {
									if (!traf->trex->track) traf->trex->track = trak;
									break;
								}
								traf->trex = NULL;
							}
						}
						//we should only parse senc/psec when no saiz/saio is present, otherwise we fetch the info directly
						if (traf->trex && traf->tfhd && traf->trex->track && traf->sample_encryption) {
							GF_TrackBox *trak = GetTrackbyID(mov->moov, traf->tfhd->trackID);
							if (trak) {
								trak->current_traf_stsd_idx = traf->tfhd->sample_desc_index ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index;
								e = senc_Parse(mov->movieFileMap->bs, trak, traf, traf->sample_encryption);
								if (e) return e;
								trak->current_traf_stsd_idx = 0;
							}
						}
					}
				} else {
					for (k=0; kmoof->TrackList); k++) {
						GF_TrackFragmentBox *traf = gf_list_get(mov->moof->TrackList, k);
						if (traf->sample_encryption) {
							e = senc_Parse(mov->movieFileMap->bs, NULL, traf, traf->sample_encryption);
							if (e) return e;
						}
					}

				}
			} else if (mov->openMode==GF_ISOM_OPEN_KEEP_FRAGMENTS) {
				mov->NextMoofNumber = mov->moof->mfhd->sequence_number+1;
				mov->moof = NULL;
				gf_isom_box_del(a);
			} else {
				/*merge all info*/
				e = MergeFragment((GF_MovieFragmentBox *)a, mov);
				gf_isom_box_del(a);
				if (e) return e;
			}

			//done with moov
			if (mov->root_sidx) {
				gf_isom_box_del((GF_Box *) mov->root_sidx);
				mov->root_sidx = NULL;
			}
			if (mov->root_ssix) {
				gf_isom_box_del(mov->seg_ssix);
				mov->root_ssix = NULL;
			}
			if (mov->seg_styp) {
				gf_isom_box_del(mov->seg_styp);
				mov->seg_styp = NULL;
			}
			mov->sidx_start_offset = 0;
			mov->sidx_end_offset = 0;
			mov->styp_start_offset = 0;
			break;
#endif
		case GF_ISOM_BOX_TYPE_UNKNOWN:
		{
			GF_UnknownBox *box = (GF_UnknownBox*)a;
			if (box->original_4cc == GF_ISOM_BOX_TYPE_JP) {
				u8 *c = (u8 *) box->data;
				if ((box->dataSize==4) && (GF_4CC(c[0],c[1],c[2],c[3])==(u32)0x0D0A870A))
					mov->is_jp2 = 1;
				gf_isom_box_del(a);
			} else {
				e = gf_list_add(mov->TopBoxes, a);
				if (e) return e;
			}
		}
		break;

		case GF_ISOM_BOX_TYPE_PRFT:
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (!(mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				//keep the last one read
				if (mov->last_producer_ref_time)
					gf_isom_box_del(a);
				else
					mov->last_producer_ref_time = (GF_ProducerReferenceTimeBox *)a;
				break;
			}
#endif
		//fallthrough
		case GF_ISOM_BOX_TYPE_EMSG:
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				if (!mov->emsgs) mov->emsgs = gf_list_new();
				gf_list_add(mov->emsgs, a);
				break;
			}
#endif
		case GF_ISOM_BOX_TYPE_MFRA:
		case GF_ISOM_BOX_TYPE_MFRO:
			//only keep for dump mode, otherwise we ignore these boxes and we don't want to carry them over in non-fragmented file
			if (! (mov->FragmentsFlags & GF_ISOM_FRAG_READ_DEBUG)) {
				totSize += a->size;
				gf_isom_box_del(a);
				break;
			}
		default:
			totSize += a->size;
			e = gf_list_add(mov->TopBoxes, a);
			if (e) return e;
			break;
		}

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		/*remember where we left, in case we append an entire number of movie fragments*/
		mov->current_top_box_start = gf_bs_get_position(mov->movieFileMap->bs) + mov->bytes_removed;
#endif
	}

	/*we need at least moov or meta*/
	if (!mov->moov && !mov->meta
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
	        && !mov->moof && !mov->is_index_segment
#endif
	   ) {
		return GF_ISOM_INCOMPLETE_FILE;
	}
	/*we MUST have movie header*/
	if (!gf_opts_get_bool(""core"", ""no-check"")) {
		if (mov->moov && !mov->moov->mvhd) {
			GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing MVHD in MOOV!\n""));
			return GF_ISOM_INVALID_FILE;
		}

		/*we MUST have meta handler*/
		if (mov->meta && !mov->meta->handler) {
			GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing handler in META!\n""));
			return GF_ISOM_INVALID_FILE;
		}
	}

#ifndef GPAC_DISABLE_ISOM_WRITE

	if (mov->moov) {
		/*set the default interleaving time*/
		mov->interleavingTime = mov->moov->mvhd->timeScale;

#ifndef	GPAC_DISABLE_ISOM_FRAGMENTS
		/*in edit mode with successfully loaded fragments, delete all fragment signaling since
		file is no longer fragmented*/
		if ((mov->openMode > GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS) && mov->moov->mvex) {
			gf_isom_box_del_parent(&mov->moov->child_boxes, (GF_Box *)mov->moov->mvex);
			mov->moov->mvex = NULL;
		}
#endif

	}

	//create a default mdat if none was found
	if (!mov->mdat && (mov->openMode != GF_ISOM_OPEN_READ) && (mov->openMode != GF_ISOM_OPEN_KEEP_FRAGMENTS)) {
		mov->mdat = (GF_MediaDataBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MDAT);
		if (!mov->mdat) return GF_OUT_OF_MEM;
		e = gf_list_add(mov->TopBoxes, mov->mdat);
		if (e) return e;
	}
#endif /*GPAC_DISABLE_ISOM_WRITE*/

	return GF_OK;
}",CWE-476,12
1,"EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params)
{
    int ok = 0, tmp;
    EC_GROUP *ret = NULL, *dup = NULL;
    BIGNUM *p = NULL, *a = NULL, *b = NULL;
    EC_POINT *point = NULL;
    long field_bits;
    int curve_name = NID_undef;
    BN_CTX *ctx = NULL;

    if (!params->fieldID || !params->fieldID->fieldType ||
        !params->fieldID->p.ptr) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
        goto err;
    }

    /*
     * Now extract the curve parameters a and b. Note that, although SEC 1
     * specifies the length of their encodings, historical versions of OpenSSL
     * encoded them incorrectly, so we must accept any length for backwards
     * compatibility.
     */
    if (!params->curve || !params->curve->a ||
        !params->curve->a->data || !params->curve->b ||
        !params->curve->b->data) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
        goto err;
    }
    a = BN_bin2bn(params->curve->a->data, params->curve->a->length, NULL);
    if (a == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);
        goto err;
    }
    b = BN_bin2bn(params->curve->b->data, params->curve->b->length, NULL);
    if (b == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);
        goto err;
    }

    /* get the field parameters */
    tmp = OBJ_obj2nid(params->fieldID->fieldType);
    if (tmp == NID_X9_62_characteristic_two_field)
#ifdef OPENSSL_NO_EC2M
    {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_GF2M_NOT_SUPPORTED);
        goto err;
    }
#else
    {
        X9_62_CHARACTERISTIC_TWO *char_two;

        char_two = params->fieldID->p.char_two;

        field_bits = char_two->m;
        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);
            goto err;
        }

        if ((p = BN_new()) == NULL) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);
            goto err;
        }

        /* get the base type */
        tmp = OBJ_obj2nid(char_two->type);

        if (tmp == NID_X9_62_tpBasis) {
            long tmp_long;

            if (!char_two->p.tpBasis) {
                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
                goto err;
            }

            tmp_long = ASN1_INTEGER_get(char_two->p.tpBasis);

            if (!(char_two->m > tmp_long && tmp_long > 0)) {
                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,
                      EC_R_INVALID_TRINOMIAL_BASIS);
                goto err;
            }

            /* create the polynomial */
            if (!BN_set_bit(p, (int)char_two->m))
                goto err;
            if (!BN_set_bit(p, (int)tmp_long))
                goto err;
            if (!BN_set_bit(p, 0))
                goto err;
        } else if (tmp == NID_X9_62_ppBasis) {
            X9_62_PENTANOMIAL *penta;

            penta = char_two->p.ppBasis;
            if (!penta) {
                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
                goto err;
            }

            if (!
                (char_two->m > penta->k3 && penta->k3 > penta->k2
                 && penta->k2 > penta->k1 && penta->k1 > 0)) {
                ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS,
                      EC_R_INVALID_PENTANOMIAL_BASIS);
                goto err;
            }

            /* create the polynomial */
            if (!BN_set_bit(p, (int)char_two->m))
                goto err;
            if (!BN_set_bit(p, (int)penta->k1))
                goto err;
            if (!BN_set_bit(p, (int)penta->k2))
                goto err;
            if (!BN_set_bit(p, (int)penta->k3))
                goto err;
            if (!BN_set_bit(p, 0))
                goto err;
        } else if (tmp == NID_X9_62_onBasis) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_NOT_IMPLEMENTED);
            goto err;
        } else {                /* error */

            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
            goto err;
        }

        /* create the EC_GROUP structure */
        ret = EC_GROUP_new_curve_GF2m(p, a, b, NULL);
    }
#endif
    else if (tmp == NID_X9_62_prime_field) {
        /* we have a curve over a prime field */
        /* extract the prime number */
        if (!params->fieldID->p.prime) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
            goto err;
        }
        p = ASN1_INTEGER_to_BN(params->fieldID->p.prime, NULL);
        if (p == NULL) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);
            goto err;
        }

        if (BN_is_negative(p) || BN_is_zero(p)) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);
            goto err;
        }

        field_bits = BN_num_bits(p);
        if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_FIELD_TOO_LARGE);
            goto err;
        }

        /* create the EC_GROUP structure */
        ret = EC_GROUP_new_curve_GFp(p, a, b, NULL);
    } else {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_FIELD);
        goto err;
    }

    if (ret == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);
        goto err;
    }

    /* extract seed (optional) */
    if (params->curve->seed != NULL) {
        OPENSSL_free(ret->seed);
        if ((ret->seed = OPENSSL_malloc(params->curve->seed->length)) == NULL) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_MALLOC_FAILURE);
            goto err;
        }
        memcpy(ret->seed, params->curve->seed->data,
               params->curve->seed->length);
        ret->seed_len = params->curve->seed->length;
    }

    if (!params->order || !params->base || !params->base->data) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
        goto err;
    }

    if ((point = EC_POINT_new(ret)) == NULL)
        goto err;

    /* set the point conversion form */
    EC_GROUP_set_point_conversion_form(ret, (point_conversion_form_t)
                                       (params->base->data[0] & ~0x01));

    /* extract the ec point */
    if (!EC_POINT_oct2point(ret, point, params->base->data,
                            params->base->length, NULL)) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);
        goto err;
    }

    /* extract the order */
    if ((a = ASN1_INTEGER_to_BN(params->order, a)) == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);
        goto err;
    }
    if (BN_is_negative(a) || BN_is_zero(a)) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);
        goto err;
    }
    if (BN_num_bits(a) > (int)field_bits + 1) { /* Hasse bound */
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_INVALID_GROUP_ORDER);
        goto err;
    }

    /* extract the cofactor (optional) */
    if (params->cofactor == NULL) {
        BN_free(b);
        b = NULL;
    } else if ((b = ASN1_INTEGER_to_BN(params->cofactor, b)) == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_ASN1_LIB);
        goto err;
    }
    /* set the generator, order and cofactor (if present) */
    if (!EC_GROUP_set_generator(ret, point, a, b)) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);
        goto err;
    }

    /*
     * Check if the explicit parameters group just created matches one of the
     * built-in curves.
     *
     * We create a copy of the group just built, so that we can remove optional
     * fields for the lookup: we do this to avoid the possibility that one of
     * the optional parameters is used to force the library into using a less
     * performant and less secure EC_METHOD instead of the specialized one.
     * In any case, `seed` is not really used in any computation, while a
     * cofactor different from the one in the built-in table is just
     * mathematically wrong anyway and should not be used.
     */
    if ((ctx = BN_CTX_new()) == NULL) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_BN_LIB);
        goto err;
    }
    if ((dup = EC_GROUP_dup(ret)) == NULL
            || EC_GROUP_set_seed(dup, NULL, 0) != 1
            || !EC_GROUP_set_generator(dup, point, a, NULL)) {
        ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);
        goto err;
    }
    if ((curve_name = ec_curve_nid_from_params(dup, ctx)) != NID_undef) {
        /*
         * The input explicit parameters successfully matched one of the
         * built-in curves: often for built-in curves we have specialized
         * methods with better performance and hardening.
         *
         * In this case we replace the `EC_GROUP` created through explicit
         * parameters with one created from a named group.
         */
        EC_GROUP *named_group = NULL;

#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
        /*
         * NID_wap_wsg_idm_ecid_wtls12 and NID_secp224r1 are both aliases for
         * the same curve, we prefer the SECP nid when matching explicit
         * parameters as that is associated with a specialized EC_METHOD.
         */
        if (curve_name == NID_wap_wsg_idm_ecid_wtls12)
            curve_name = NID_secp224r1;
#endif /* !def(OPENSSL_NO_EC_NISTP_64_GCC_128) */

        if ((named_group = EC_GROUP_new_by_curve_name(curve_name)) == NULL) {
            ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, ERR_R_EC_LIB);
            goto err;
        }
        EC_GROUP_free(ret);
        ret = named_group;

        /*
         * Set the flag so that EC_GROUPs created from explicit parameters are
         * serialized using explicit parameters by default.
         */
        EC_GROUP_set_asn1_flag(ret, OPENSSL_EC_EXPLICIT_CURVE);

        /*
         * If the input params do not contain the optional seed field we make
         * sure it is not added to the returned group.
         *
         * The seed field is not really used inside libcrypto anyway, and
         * adding it to parsed explicit parameter keys would alter their DER
         * encoding output (because of the extra field) which could impact
         * applications fingerprinting keys by their DER encoding.
         */
        if (params->curve->seed == NULL) {
            if (EC_GROUP_set_seed(ret, NULL, 0) != 1)
                goto err;
        }
    }

    ok = 1;

 err:
    if (!ok) {
        EC_GROUP_free(ret);
        ret = NULL;
    }
    EC_GROUP_free(dup);

    BN_free(p);
    BN_free(a);
    BN_free(b);
    EC_POINT_free(point);

    BN_CTX_free(ctx);

    return ret;
}",CWE-125,1
1,"PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len, 
				      pjstun_msg *msg)
{
    pj_uint16_t msg_type, msg_len;
    char *p_attr;

    PJ_CHECK_STACK();

    msg->hdr = (pjstun_msg_hdr*)buf;
    msg_type = pj_ntohs(msg->hdr->type);

    switch (msg_type) {
    case PJSTUN_BINDING_REQUEST:
    case PJSTUN_BINDING_RESPONSE:
    case PJSTUN_BINDING_ERROR_RESPONSE:
    case PJSTUN_SHARED_SECRET_REQUEST:
    case PJSTUN_SHARED_SECRET_RESPONSE:
    case PJSTUN_SHARED_SECRET_ERROR_RESPONSE:
	break;
    default:
	PJ_LOG(4,(THIS_FILE, ""Error: unknown msg type %d"", msg_type));
	return PJLIB_UTIL_ESTUNINMSGTYPE;
    }

    msg_len = pj_ntohs(msg->hdr->length);
    if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) {
	PJ_LOG(4,(THIS_FILE, ""Error: invalid msg_len %d (expecting %d)"", 
			     msg_len, buf_len - sizeof(pjstun_msg_hdr)));
	return PJLIB_UTIL_ESTUNINMSGLEN;
    }

    msg->attr_count = 0;
    p_attr = (char*)buf + sizeof(pjstun_msg_hdr);

    while (msg_len > 0) {
	pjstun_attr_hdr **attr = &msg->attr[msg->attr_count];
	pj_uint32_t len;
	pj_uint16_t attr_type;

	*attr = (pjstun_attr_hdr*)p_attr;
	len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr);
	len = (len + 3) & ~3;

	if (msg_len < len) {
	    PJ_LOG(4,(THIS_FILE, ""Error: length mismatch in attr %d"", 
				 msg->attr_count));
	    return PJLIB_UTIL_ESTUNINATTRLEN;
	}

	attr_type = pj_ntohs((*attr)->type);
	if (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&
	    attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)
	{
	    PJ_LOG(5,(THIS_FILE, ""Warning: unknown attr type %x in attr %d. ""
				 ""Attribute was ignored."",
				 attr_type, msg->attr_count));
	}

	msg_len = (pj_uint16_t)(msg_len - len);
	p_attr += len;
	++msg->attr_count;
    }

    return PJ_SUCCESS;
}",CWE-787,16
0,"  bool Connected() const {
    return ethernet_connected() || wifi_connected() || cellular_connected();
  }
",none,24
0,"void QuotaManager::DeleteOnCorrectThread() const {
  if (!io_thread_->BelongsToCurrentThread()) {
    io_thread_->DeleteSoon(FROM_HERE, this);
    return;
  }
  delete this;
}
",none,24
0,"  void DidGetHostQuota(QuotaStatusCode status,
                       const std::string& host,
                       StorageType type,
                       int64 quota) {
    DCHECK_EQ(host_, host);
    DCHECK_EQ(type_, type);
    quota_status_ = status;
    quota_ = quota;
    CheckCompleted();
  }
",none,24
0,"  template T GetWirelessNetworkByPath(
      std::vector& networks, const std::string& path) {
    typedef typename std::vector::iterator iter_t;
    iter_t iter = std::find_if(networks.begin(), networks.end(),
                               WirelessNetwork::ServicePathEq(path));
    return (iter != networks.end()) ? *iter : NULL;
  }
",none,24
1,"static void fix_dl_name(MEM_ROOT *root, LEX_STRING *dl)
{
  const size_t so_ext_len= sizeof(SO_EXT) - 1;
  if (my_strcasecmp(&my_charset_latin1, dl->str + dl->length - so_ext_len,
                    SO_EXT))
  {
    char *s= (char*)alloc_root(root, dl->length + so_ext_len + 1);
    memcpy(s, dl->str, dl->length);
    strcpy(s + dl->length, SO_EXT);
    dl->str= s;
    dl->length+= so_ext_len;
  }
}",CWE-416,10
1,"extract_archive_thread (GSimpleAsyncResult *result,
			GObject            *object,
			GCancellable       *cancellable)
{
	ExtractData          *extract_data;
	LoadData             *load_data;
	GHashTable           *checked_folders;
	struct archive       *a;
	struct archive_entry *entry;
	int                   r;

	extract_data = g_simple_async_result_get_op_res_gpointer (result);
	load_data = LOAD_DATA (extract_data);

	checked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
	fr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract);

	a = archive_read_new ();
	archive_read_support_filter_all (a);
	archive_read_support_format_all (a);
	archive_read_open (a, load_data, load_data_open, load_data_read, load_data_close);
	while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {
		const char    *pathname;
		char          *fullpath;
		GFile         *file;
		GFile         *parent;
		GOutputStream *ostream;
		const void    *buffer;
		size_t         buffer_size;
		int64_t        offset;
		GError        *local_error = NULL;
		__LA_MODE_T    filetype;

		if (g_cancellable_is_cancelled (cancellable))
			break;

		pathname = archive_entry_pathname (entry);
		if (! extract_data_get_extraction_requested (extract_data, pathname)) {
			archive_read_data_skip (a);
			continue;
		}

		fullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat (""/"", pathname, NULL);
		file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (fullpath, extract_data->base_dir, extract_data->junk_paths));

		/* honor the skip_older and overwrite options */

		if (extract_data->skip_older || ! extract_data->overwrite) {
			GFileInfo *info;

			info = g_file_query_info (file,
						  G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "","" G_FILE_ATTRIBUTE_TIME_MODIFIED,
						  G_FILE_QUERY_INFO_NONE,
						  cancellable,
						  &local_error);
			if (info != NULL) {
				gboolean skip = FALSE;

				if (! extract_data->overwrite) {
					skip = TRUE;
				}
				else if (extract_data->skip_older) {
					GTimeVal modification_time;

					g_file_info_get_modification_time (info, &modification_time);
					if (archive_entry_mtime (entry) < modification_time.tv_sec)
						skip = TRUE;
				}

				g_object_unref (info);

				if (skip) {
					g_object_unref (file);

					archive_read_data_skip (a);
					fr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0);

					if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {
						r = ARCHIVE_EOF;
						break;
					}

					continue;
				}
			}
			else {
				if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
					load_data->error = local_error;
					g_object_unref (info);
					break;
				}
				g_error_free (local_error);
			}
		}

		fr_archive_progress_inc_completed_files (load_data->archive, 1);

		/* create the file parents */

		parent = g_file_get_parent (file);

		if ((parent != NULL)
		    && (g_hash_table_lookup (checked_folders, parent) == NULL)
		    && ! g_file_query_exists (parent, cancellable))
		{
			if (g_file_make_directory_with_parents (parent, cancellable, &load_data->error)) {
				GFile *grandparent;

				grandparent = g_object_ref (parent);
				while (grandparent != NULL) {
					if (g_hash_table_lookup (checked_folders, grandparent) == NULL)
						g_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1));
					grandparent = g_file_get_parent (grandparent);
				}
			}
		}
		g_object_unref (parent);

		/* create the file */

		filetype = archive_entry_filetype (entry);

		if (load_data->error == NULL) {
			const char  *linkname;

			linkname = archive_entry_hardlink (entry);
			if (linkname != NULL) {
				char  *link_fullpath;
				GFile *link_file;
				char  *oldname;
				char  *newname;
				int    r;

				link_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat (""/"", linkname, NULL);
				link_file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (link_fullpath, extract_data->base_dir, extract_data->junk_paths));
				oldname = g_file_get_path (link_file);
				newname = g_file_get_path (file);

				if ((oldname != NULL) && (newname != NULL))
					r = link (oldname, newname);
				else
					r = -1;

				if (r == 0) {
					__LA_INT64_T filesize;

					if (archive_entry_size_is_set (entry))
						filesize = archive_entry_size (entry);
					else
						filesize = -1;

					if (filesize > 0)
						filetype = AE_IFREG; /* treat as a regular file to save the data */
				}
				else {
					char *uri;
					char *msg;

					uri = g_file_get_uri (file);
					msg = g_strdup_printf (""Could not create the hard link %s"", uri);
					load_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg);

					g_free (msg);
					g_free (uri);
				}

				g_free (newname);
				g_free (oldname);
				g_object_unref (link_file);
				g_free (link_fullpath);
			}
		}

		if (load_data->error == NULL) {
			switch (filetype) {
			case AE_IFDIR:
				if (! g_file_make_directory (file, cancellable, &local_error)) {
					if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
						load_data->error = g_error_copy (local_error);
					g_error_free (local_error);
				}
				else
					_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);
				archive_read_data_skip (a);
				break;

			case AE_IFREG:
				ostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error);
				if (ostream == NULL)
					break;

				while ((r = archive_read_data_block (a, &buffer, &buffer_size, &offset)) == ARCHIVE_OK) {
					if (g_output_stream_write (ostream, buffer, buffer_size, cancellable, &load_data->error) == -1)
						break;
					fr_archive_progress_inc_completed_bytes (load_data->archive, buffer_size);
				}
				_g_object_unref (ostream);

				if (r != ARCHIVE_EOF)
					load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));
				else
					_g_file_set_attributes_from_entry (file, entry, extract_data, cancellable);
				break;

			case AE_IFLNK:
				if (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) {
					if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
						load_data->error = g_error_copy (local_error);
					g_error_free (local_error);
				}
				archive_read_data_skip (a);
				break;

			default:
				archive_read_data_skip (a);
				break;
			}
		}

		g_object_unref (file);
		g_free (fullpath);

		if (load_data->error != NULL)
			break;

		if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) {
			r = ARCHIVE_EOF;
			break;
		}
	}

	if ((load_data->error == NULL) && (r != ARCHIVE_EOF))
		load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a));
	if (load_data->error == NULL)
		g_cancellable_set_error_if_cancelled (cancellable, &load_data->error);
	if (load_data->error != NULL)
		g_simple_async_result_set_from_error (result, load_data->error);

	g_hash_table_unref (checked_folders);
	archive_read_free (a);
	extract_data_free (extract_data);
}",CWE-22,5
0,"  NetworkLibraryImpl()
      : network_manager_monitor_(NULL),
        data_plan_monitor_(NULL),
        ethernet_(NULL),
        wifi_(NULL),
        cellular_(NULL),
        available_devices_(0),
        enabled_devices_(0),
        connected_devices_(0),
        offline_mode_(false) {
    if (EnsureCrosLoaded()) {
      Init();
      network_manager_monitor_ =
          MonitorNetworkManager(&NetworkManagerStatusChangedHandler,
                                this);
      data_plan_monitor_ = MonitorCellularDataPlan(&DataPlanUpdateHandler,
                                                   this);
    } else {
      InitTestData();
    }
  }
",none,24
0,"  static void ParseSystem(SystemInfo* system,
      EthernetNetwork** ethernet,
      WifiNetworkVector* wifi_networks,
      CellularNetworkVector* cellular_networks,
      WifiNetworkVector* remembered_wifi_networks) {
    DVLOG(1) << ""ParseSystem:"";
    DCHECK(!(*ethernet));
    for (int i = 0; i < system->service_size; i++) {
      const ServiceInfo* service = system->GetServiceInfo(i);
      DVLOG(1) << ""  ("" << service->type << "") "" << service->name
               << "" mode="" << service->mode
               << "" state="" << service->state
               << "" sec="" << service->security
               << "" req="" << service->passphrase_required
               << "" pass="" << service->passphrase
               << "" id="" << service->identity
               << "" certpath="" << service->cert_path
               << "" str="" << service->strength
               << "" fav="" << service->favorite
               << "" auto="" << service->auto_connect
               << "" is_active="" << service->is_active
               << "" error="" << service->error;
      if (service->type == TYPE_ETHERNET)
        (*ethernet) = new EthernetNetwork(service);
      else if (service->type == TYPE_WIFI) {
        wifi_networks->push_back(new WifiNetwork(service));
      } else if (service->type == TYPE_CELLULAR) {
        cellular_networks->push_back(new CellularNetwork(service));
      }
    }

    if (!(*ethernet))
      (*ethernet) = new EthernetNetwork();

    DVLOG(1) << ""Remembered networks:"";
    for (int i = 0; i < system->remembered_service_size; i++) {
      const ServiceInfo* service = system->GetRememberedServiceInfo(i);
      if (service->auto_connect) {
        DVLOG(1) << ""  ("" << service->type << "") "" << service->name
                 << "" mode="" << service->mode
                 << "" sec="" << service->security
                 << "" pass="" << service->passphrase
                 << "" id="" << service->identity
                 << "" certpath="" << service->cert_path
                 << "" auto="" << service->auto_connect;
        if (service->type == TYPE_WIFI) {
          remembered_wifi_networks->push_back(new WifiNetwork(service));
        }
      }
    }
  }
",none,24
0,"  virtual bool wifi_enabled() const { return false; }
",none,24
1,"  void Compute(OpKernelContext *ctx) override {
    const Tensor *indices_t, *values_t, *shape_t, *dense_t;
    OP_REQUIRES_OK(ctx, ctx->input(""sp_indices"", &indices_t));
    OP_REQUIRES_OK(ctx, ctx->input(""sp_values"", &values_t));
    OP_REQUIRES_OK(ctx, ctx->input(""sp_shape"", &shape_t));
    OP_REQUIRES_OK(ctx, ctx->input(""dense"", &dense_t));

    // Validations.
    OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices_t->shape()),
                errors::InvalidArgument(
                    ""Input sp_indices should be a matrix but received shape: "",
                    indices_t->shape().DebugString()));
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(values_t->shape()) &&
                    TensorShapeUtils::IsVector(shape_t->shape()),
                errors::InvalidArgument(
                    ""Inputs sp_values and sp_shape should be vectors ""
                    ""but received shapes: "",
                    values_t->shape().DebugString(), "" and "",
                    shape_t->shape().DebugString()));
    OP_REQUIRES(
        ctx, TensorShapeUtils::IsVector(shape_t->shape()),
        errors::InvalidArgument(""Input sp_shape must be a vector. Got: "",
                                shape_t->shape().DebugString()));
    OP_REQUIRES(
        ctx, values_t->dim_size(0) == indices_t->dim_size(0),
        errors::InvalidArgument(
            ""The first dimension of values and indices should match. ("",
            values_t->dim_size(0), "" vs. "", indices_t->dim_size(0), "")""));
    OP_REQUIRES(
        ctx, shape_t->shape().dim_size(0) == indices_t->shape().dim_size(1),
        errors::InvalidArgument(
            ""Number of dimensions must match second dimension of indices. "",
            ""Got "", shape_t->shape().dim_size(0),
            "" dimensions, indices shape: "", indices_t->shape().DebugString()));
    OP_REQUIRES(ctx, shape_t->NumElements() > 0,
                errors::InvalidArgument(
                    ""The shape argument requires at least one element.""));

    const auto indices_mat = indices_t->matrix();
    const auto shape_vec = shape_t->vec();
    const auto lhs_dims = BCast::FromShape(TensorShape(shape_vec));
    const auto rhs_dims = BCast::FromShape(dense_t->shape());
    BCast b(lhs_dims, rhs_dims, false);  // false for keeping the same num dims.

    // True iff (size(lhs) >= size(rhs)) and all dims in lhs is greater or equal
    // to dims in rhs (from right to left).
    auto VecGreaterEq = [](ArraySlice lhs, ArraySlice rhs) {
      if (lhs.size() < rhs.size()) return false;
      for (size_t i = 0; i < rhs.size(); ++i) {
        if (lhs[lhs.size() - 1 - i] < rhs[rhs.size() - 1 - i]) return false;
      }
      return true;
    };
    OP_REQUIRES(ctx, VecGreaterEq(lhs_dims, rhs_dims) && b.IsValid(),
                errors::InvalidArgument(
                    ""SparseDenseBinaryOpShared broadcasts dense to sparse ""
                    ""only; got incompatible shapes: ["",
                    absl::StrJoin(lhs_dims, "",""), ""] vs. ["",
                    absl::StrJoin(rhs_dims, "",""), ""]""));

    Tensor *output_values = nullptr;
    Tensor dense_gathered;
    const int64_t nnz = indices_t->dim_size(0);
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_output(0, TensorShape({nnz}), &output_values));
    OP_REQUIRES_OK(
        ctx, ctx->allocate_temp(DataTypeToEnum::value, TensorShape({nnz}),
                                &dense_gathered));
    bool op_is_div = false;
    if (absl::StrContains(ctx->op_kernel().type_string_view(), ""Div"")) {
      op_is_div = true;
    }
    // Pulls relevant entries from the dense side, with reshape and broadcasting
    // *of the dense side* taken into account.  Use a TensorRef to avoid blowing
    // up memory.
    //
    // We can directly use the sparse indices to look up dense side, because
    // ""b.y_reshape()"" and ""b.y_bcast()"" are guaranteed to have rank ""ndims"".
    auto dense_gathered_flat = dense_gathered.flat();
    const int ndims = lhs_dims.size();
    switch (ndims) {
#define CASE(NDIM)                                                             \
  case NDIM: {                                                                 \
    TensorRef> rhs_ref =         \
        dense_t->shaped(b.y_reshape())                                \
            .broadcast(BCast::ToIndexArray(b.y_bcast()));                \
    Eigen::array idx;                                 \
    bool indices_valid = true;                                                 \
    for (int i = 0; i < nnz; ++i) {                                            \
      for (int d = 0; d < NDIM; ++d) {                                         \
        idx[d] = internal::SubtleMustCopy(indices_mat(i, d));                  \
        if (!FastBoundsCheck(idx[d], rhs_ref.dimension(d))) {                  \
          indices_valid = false;                                               \
        }                                                                      \
      }                                                                        \
      OP_REQUIRES(                                                             \
          ctx, indices_valid,                                                  \
          errors::InvalidArgument(""Provided indices are out-of-bounds w.r.t. "" \
                                  ""dense side with broadcasted shape""));       \
      dense_gathered_flat(i) = rhs_ref.coeff(idx);                             \
      if (op_is_div) {                                                         \
        OP_REQUIRES(ctx, dense_gathered_flat(i) != 0,                          \
                    errors::InvalidArgument(                                   \
                        ""SparseDenseCwiseDiv cannot divide by zero,""           \
                        ""but input dense tensor contains zero ""));             \
      }                                                                        \
    }                                                                          \
    break;                                                                     \
  }

      CASE(1);
      CASE(2);
      CASE(3);
      CASE(4);
      CASE(5);
      default:
        OP_REQUIRES(
            ctx, false,
            errors::InvalidArgument(""Only tensors with ranks between 1 and 5 ""
                                    ""are currently supported.  Tensor rank: "",
                                    ndims));
#undef CASE
    }

    output_values->flat().device(ctx->eigen_device()) =
        values_t->flat().binaryExpr(dense_gathered_flat,
                                       typename Functor::func());
  }",CWE-190,2
0,"bool WifiNetwork::IsCertificateLoaded() const {
  static const std::string settings_string(""SETTINGS:"");
  static const std::string pkcs11_key(""key_id"");
  if (cert_path_.find(settings_string) == 0) {
    std::string::size_type idx = cert_path_.find(pkcs11_key);
    if (idx != std::string::npos)
      idx = cert_path_.find_first_not_of(kWhitespaceASCII,
                                         idx + pkcs11_key.length());
    if (idx != std::string::npos && cert_path_[idx] == '=')
      return true;
  }
  return false;
}
",none,24
0,"  virtual bool offline_mode() const { return offline_mode_; }
",none,24
1,"do_window(
    int		nchar,
    long	Prenum,
    int		xchar)	    // extra char from "":wincmd gx"" or NUL
{
    long	Prenum1;
    win_T	*wp;
#if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID)
    char_u	*ptr;
    linenr_T    lnum = -1;
#endif
#ifdef FEAT_FIND_ID
    int		type = FIND_DEFINE;
    int		len;
#endif
    char_u	cbuf[40];

    if (ERROR_IF_ANY_POPUP_WINDOW)
	return;

#ifdef FEAT_CMDWIN
# define CHECK_CMDWIN \
    do { \
	if (cmdwin_type != 0) \
	{ \
	    emsg(_(e_invalid_in_cmdline_window)); \
	    return; \
	} \
    } while (0)
#else
# define CHECK_CMDWIN do { /**/ } while (0)
#endif

    Prenum1 = Prenum == 0 ? 1 : Prenum;

    switch (nchar)
    {
// split current window in two parts, horizontally
    case 'S':
    case Ctrl_S:
    case 's':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
#ifdef FEAT_QUICKFIX
		// When splitting the quickfix window open a new buffer in it,
		// don't replicate the quickfix buffer.
		if (bt_quickfix(curbuf))
		    goto newwindow;
#endif
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		(void)win_split((int)Prenum, 0);
		break;

// split current window in two parts, vertically
    case Ctrl_V:
    case 'v':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
#ifdef FEAT_QUICKFIX
		// When splitting the quickfix window open a new buffer in it,
		// don't replicate the quickfix buffer.
		if (bt_quickfix(curbuf))
		    goto newwindow;
#endif
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		(void)win_split((int)Prenum, WSP_VERT);
		break;

// split current window and edit alternate file
    case Ctrl_HAT:
    case '^':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode

		if (buflist_findnr(Prenum == 0
					? curwin->w_alt_fnum : Prenum) == NULL)
		{
		    if (Prenum == 0)
			emsg(_(e_no_alternate_file));
		    else
			semsg(_(e_buffer_nr_not_found), Prenum);
		    break;
		}

		if (!curbuf_locked() && win_split(0, 0) == OK)
		    (void)buflist_getfile(
			    Prenum == 0 ? curwin->w_alt_fnum : Prenum,
			    (linenr_T)0, GETF_ALT, FALSE);
		break;

// open new window
    case Ctrl_N:
    case 'n':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
#ifdef FEAT_QUICKFIX
newwindow:
#endif
		if (Prenum)
		    // window height
		    vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, ""%ld"", Prenum);
		else
		    cbuf[0] = NUL;
#if defined(FEAT_QUICKFIX)
		if (nchar == 'v' || nchar == Ctrl_V)
		    STRCAT(cbuf, ""v"");
#endif
		STRCAT(cbuf, ""new"");
		do_cmdline_cmd(cbuf);
		break;

// quit current window
    case Ctrl_Q:
    case 'q':
		reset_VIsual_and_resel();	// stop Visual mode
		cmd_with_count(""quit"", cbuf, sizeof(cbuf), Prenum);
		do_cmdline_cmd(cbuf);
		break;

// close current window
    case Ctrl_C:
    case 'c':
		reset_VIsual_and_resel();	// stop Visual mode
		cmd_with_count(""close"", cbuf, sizeof(cbuf), Prenum);
		do_cmdline_cmd(cbuf);
		break;

#if defined(FEAT_QUICKFIX)
// close preview window
    case Ctrl_Z:
    case 'z':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
		do_cmdline_cmd((char_u *)""pclose"");
		break;

// cursor to preview window
    case 'P':
		FOR_ALL_WINDOWS(wp)
		    if (wp->w_p_pvw)
			break;
		if (wp == NULL)
		    emsg(_(e_there_is_no_preview_window));
		else
		    win_goto(wp);
		break;
#endif

// close all but current window
    case Ctrl_O:
    case 'o':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
		cmd_with_count(""only"", cbuf, sizeof(cbuf), Prenum);
		do_cmdline_cmd(cbuf);
		break;

// cursor to next window with wrap around
    case Ctrl_W:
    case 'w':
// cursor to previous window with wrap around
    case 'W':
		CHECK_CMDWIN;
		if (ONE_WINDOW && Prenum != 1)	// just one window
		    beep_flush();
		else
		{
		    if (Prenum)			// go to specified window
		    {
			for (wp = firstwin; --Prenum > 0; )
			{
			    if (wp->w_next == NULL)
				break;
			    else
				wp = wp->w_next;
			}
		    }
		    else
		    {
			if (nchar == 'W')	    // go to previous window
			{
			    wp = curwin->w_prev;
			    if (wp == NULL)
				wp = lastwin;	    // wrap around
			}
			else			    // go to next window
			{
			    wp = curwin->w_next;
			    if (wp == NULL)
				wp = firstwin;	    // wrap around
			}
		    }
		    win_goto(wp);
		}
		break;

// cursor to window below
    case 'j':
    case K_DOWN:
    case Ctrl_J:
		CHECK_CMDWIN;
		win_goto_ver(FALSE, Prenum1);
		break;

// cursor to window above
    case 'k':
    case K_UP:
    case Ctrl_K:
		CHECK_CMDWIN;
		win_goto_ver(TRUE, Prenum1);
		break;

// cursor to left window
    case 'h':
    case K_LEFT:
    case Ctrl_H:
    case K_BS:
		CHECK_CMDWIN;
		win_goto_hor(TRUE, Prenum1);
		break;

// cursor to right window
    case 'l':
    case K_RIGHT:
    case Ctrl_L:
		CHECK_CMDWIN;
		win_goto_hor(FALSE, Prenum1);
		break;

// move window to new tab page
    case 'T':
		CHECK_CMDWIN;
		if (one_window())
		    msg(_(m_onlyone));
		else
		{
		    tabpage_T	*oldtab = curtab;
		    tabpage_T	*newtab;

		    // First create a new tab with the window, then go back to
		    // the old tab and close the window there.
		    wp = curwin;
		    if (win_new_tabpage((int)Prenum) == OK
						     && valid_tabpage(oldtab))
		    {
			newtab = curtab;
			goto_tabpage_tp(oldtab, TRUE, TRUE);
			if (curwin == wp)
			    win_close(curwin, FALSE);
			if (valid_tabpage(newtab))
			    goto_tabpage_tp(newtab, TRUE, TRUE);
		    }
		}
		break;

// cursor to top-left window
    case 't':
    case Ctrl_T:
		win_goto(firstwin);
		break;

// cursor to bottom-right window
    case 'b':
    case Ctrl_B:
		win_goto(lastwin);
		break;

// cursor to last accessed (previous) window
    case 'p':
    case Ctrl_P:
		if (!win_valid(prevwin))
		    beep_flush();
		else
		    win_goto(prevwin);
		break;

// exchange current and next window
    case 'x':
    case Ctrl_X:
		CHECK_CMDWIN;
		win_exchange(Prenum);
		break;

// rotate windows downwards
    case Ctrl_R:
    case 'r':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
		win_rotate(FALSE, (int)Prenum1);    // downwards
		break;

// rotate windows upwards
    case 'R':
		CHECK_CMDWIN;
		reset_VIsual_and_resel();	// stop Visual mode
		win_rotate(TRUE, (int)Prenum1);	    // upwards
		break;

// move window to the very top/bottom/left/right
    case 'K':
    case 'J':
    case 'H':
    case 'L':
		CHECK_CMDWIN;
		win_totop((int)Prenum,
			((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)
			| ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT));
		break;

// make all windows the same height
    case '=':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_equal(NULL, FALSE, 'b');
		break;

// increase current window height
    case '+':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setheight(curwin->w_height + (int)Prenum1);
		break;

// decrease current window height
    case '-':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setheight(curwin->w_height - (int)Prenum1);
		break;

// set current window height
    case Ctrl__:
    case '_':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setheight(Prenum ? (int)Prenum : 9999);
		break;

// increase current window width
    case '>':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setwidth(curwin->w_width + (int)Prenum1);
		break;

// decrease current window width
    case '<':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setwidth(curwin->w_width - (int)Prenum1);
		break;

// set current window width
    case '|':
#ifdef FEAT_GUI
		need_mouse_correct = TRUE;
#endif
		win_setwidth(Prenum != 0 ? (int)Prenum : 9999);
		break;

// jump to tag and split window if tag exists (in preview window)
#if defined(FEAT_QUICKFIX)
    case '}':
		CHECK_CMDWIN;
		if (Prenum)
		    g_do_tagpreview = Prenum;
		else
		    g_do_tagpreview = p_pvh;
#endif
		// FALLTHROUGH
    case ']':
    case Ctrl_RSB:
		CHECK_CMDWIN;
		// keep Visual mode, can select words to use as a tag
		if (Prenum)
		    postponed_split = Prenum;
		else
		    postponed_split = -1;
#ifdef FEAT_QUICKFIX
		if (nchar != '}')
		    g_do_tagpreview = 0;
#endif

		// Execute the command right here, required when ""wincmd ]""
		// was used in a function.
		do_nv_ident(Ctrl_RSB, NUL);
		break;

#ifdef FEAT_SEARCHPATH
// edit file name under cursor in a new window
    case 'f':
    case 'F':
    case Ctrl_F:
wingotofile:
		CHECK_CMDWIN;

		ptr = grab_file_name(Prenum1, &lnum);
		if (ptr != NULL)
		{
		    tabpage_T	*oldtab = curtab;
		    win_T	*oldwin = curwin;
# ifdef FEAT_GUI
		    need_mouse_correct = TRUE;
# endif
		    setpcmark();
		    if (win_split(0, 0) == OK)
		    {
			RESET_BINDING(curwin);
			if (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL,
						   ECMD_HIDE, NULL) == FAIL)
			{
			    // Failed to open the file, close the window
			    // opened for it.
			    win_close(curwin, FALSE);
			    goto_tabpage_win(oldtab, oldwin);
			}
			else if (nchar == 'F' && lnum >= 0)
			{
			    curwin->w_cursor.lnum = lnum;
			    check_cursor_lnum();
			    beginline(BL_SOL | BL_FIX);
			}
		    }
		    vim_free(ptr);
		}
		break;
#endif

#ifdef FEAT_FIND_ID
// Go to the first occurrence of the identifier under cursor along path in a
// new window -- webb
    case 'i':			    // Go to any match
    case Ctrl_I:
		type = FIND_ANY;
		// FALLTHROUGH
    case 'd':			    // Go to definition, using 'define'
    case Ctrl_D:
		CHECK_CMDWIN;
		if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
		    break;
		find_pattern_in_path(ptr, 0, len, TRUE,
			Prenum == 0 ? TRUE : FALSE, type,
			Prenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM);
		curwin->w_set_curswant = TRUE;
		break;
#endif

// Quickfix window only: view the result under the cursor in a new split.
#if defined(FEAT_QUICKFIX)
    case K_KENTER:
    case CAR:
		if (bt_quickfix(curbuf))
		    qf_view_result(TRUE);
		break;
#endif

// CTRL-W g  extended commands
    case 'g':
    case Ctrl_G:
		CHECK_CMDWIN;
#ifdef USE_ON_FLY_SCROLL
		dont_scroll = TRUE;		// disallow scrolling here
#endif
		++no_mapping;
		++allow_keys;   // no mapping for xchar, but allow key codes
		if (xchar == NUL)
		    xchar = plain_vgetc();
		LANGMAP_ADJUST(xchar, TRUE);
		--no_mapping;
		--allow_keys;
#ifdef FEAT_CMDL_INFO
		(void)add_to_showcmd(xchar);
#endif
		switch (xchar)
		{
#if defined(FEAT_QUICKFIX)
		    case '}':
			xchar = Ctrl_RSB;
			if (Prenum)
			    g_do_tagpreview = Prenum;
			else
			    g_do_tagpreview = p_pvh;
#endif
			// FALLTHROUGH
		    case ']':
		    case Ctrl_RSB:
			// keep Visual mode, can select words to use as a tag
			if (Prenum)
			    postponed_split = Prenum;
			else
			    postponed_split = -1;

			// Execute the command right here, required when
			// ""wincmd g}"" was used in a function.
			do_nv_ident('g', xchar);
			break;

#ifdef FEAT_SEARCHPATH
		    case 'f':	    // CTRL-W gf: ""gf"" in a new tab page
		    case 'F':	    // CTRL-W gF: ""gF"" in a new tab page
			cmdmod.cmod_tab = tabpage_index(curtab) + 1;
			nchar = xchar;
			goto wingotofile;
#endif
		    case 't':	    // CTRL-W gt: go to next tab page
			goto_tabpage((int)Prenum);
			break;

		    case 'T':	    // CTRL-W gT: go to previous tab page
			goto_tabpage(-(int)Prenum1);
			break;

		    case TAB:	    // CTRL-W g: go to last used tab page
			if (goto_tabpage_lastused() == FAIL)
			    beep_flush();
			break;

		    default:
			beep_flush();
			break;
		}
		break;

    default:	beep_flush();
		break;
    }
}",CWE-416,10
0,"  virtual bool ethernet_connected() const {
    return ethernet_ ? ethernet_->connected() : false;
  }
",none,24
0,"  template const T GetWirelessNetworkByPath(
      const std::vector& networks, const std::string& path) const {
    typedef typename std::vector::const_iterator iter_t;
    iter_t iter = std::find_if(networks.begin(), networks.end(),
                               WirelessNetwork::ServicePathEq(path));
    return (iter != networks.end()) ? *iter : NULL;
  }
",none,24
1,"static int selinux_ptrace_traceme(struct task_struct *parent)
{
	return avc_has_perm(&selinux_state,
			    task_sid_subj(parent), task_sid_obj(current),
			    SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
}",CWE-416,10
1,"suggest_trie_walk(
    suginfo_T	*su,
    langp_T	*lp,
    char_u	*fword,
    int		soundfold)
{
    char_u	tword[MAXWLEN];	    // good word collected so far
    trystate_T	stack[MAXWLEN];
    char_u	preword[MAXWLEN * 3]; // word found with proper case;
				      // concatenation of prefix compound
				      // words and split word.  NUL terminated
				      // when going deeper but not when coming
				      // back.
    char_u	compflags[MAXWLEN];	// compound flags, one for each word
    trystate_T	*sp;
    int		newscore;
    int		score;
    char_u	*byts, *fbyts, *pbyts;
    idx_T	*idxs, *fidxs, *pidxs;
    int		depth;
    int		c, c2, c3;
    int		n = 0;
    int		flags;
    garray_T	*gap;
    idx_T	arridx;
    int		len;
    char_u	*p;
    fromto_T	*ftp;
    int		fl = 0, tl;
    int		repextra = 0;	    // extra bytes in fword[] from REP item
    slang_T	*slang = lp->lp_slang;
    int		fword_ends;
    int		goodword_ends;
#ifdef DEBUG_TRIEWALK
    // Stores the name of the change made at each level.
    char_u	changename[MAXWLEN][80];
#endif
    int		breakcheckcount = 1000;
#ifdef FEAT_RELTIME
    proftime_T	time_limit;
#endif
    int		compound_ok;

    // Go through the whole case-fold tree, try changes at each node.
    // ""tword[]"" contains the word collected from nodes in the tree.
    // ""fword[]"" the word we are trying to match with (initially the bad
    // word).
    depth = 0;
    sp = &stack[0];
    CLEAR_POINTER(sp);
    sp->ts_curi = 1;

    if (soundfold)
    {
	// Going through the soundfold tree.
	byts = fbyts = slang->sl_sbyts;
	idxs = fidxs = slang->sl_sidxs;
	pbyts = NULL;
	pidxs = NULL;
	sp->ts_prefixdepth = PFD_NOPREFIX;
	sp->ts_state = STATE_START;
    }
    else
    {
	// When there are postponed prefixes we need to use these first.  At
	// the end of the prefix we continue in the case-fold tree.
	fbyts = slang->sl_fbyts;
	fidxs = slang->sl_fidxs;
	pbyts = slang->sl_pbyts;
	pidxs = slang->sl_pidxs;
	if (pbyts != NULL)
	{
	    byts = pbyts;
	    idxs = pidxs;
	    sp->ts_prefixdepth = PFD_PREFIXTREE;
	    sp->ts_state = STATE_NOPREFIX;	// try without prefix first
	}
	else
	{
	    byts = fbyts;
	    idxs = fidxs;
	    sp->ts_prefixdepth = PFD_NOPREFIX;
	    sp->ts_state = STATE_START;
	}
    }
#ifdef FEAT_RELTIME
    // The loop may take an indefinite amount of time. Break out after some
    // time.
    if (spell_suggest_timeout > 0)
	profile_setlimit(spell_suggest_timeout, &time_limit);
#endif

    // Loop to find all suggestions.  At each round we either:
    // - For the current state try one operation, advance ""ts_curi"",
    //   increase ""depth"".
    // - When a state is done go to the next, set ""ts_state"".
    // - When all states are tried decrease ""depth"".
    while (depth >= 0 && !got_int)
    {
	sp = &stack[depth];
	switch (sp->ts_state)
	{
	case STATE_START:
	case STATE_NOPREFIX:
	    // Start of node: Deal with NUL bytes, which means
	    // tword[] may end here.
	    arridx = sp->ts_arridx;	    // current node in the tree
	    len = byts[arridx];		    // bytes in this node
	    arridx += sp->ts_curi;	    // index of current byte

	    if (sp->ts_prefixdepth == PFD_PREFIXTREE)
	    {
		// Skip over the NUL bytes, we use them later.
		for (n = 0; n < len && byts[arridx + n] == 0; ++n)
		    ;
		sp->ts_curi += n;

		// Always past NUL bytes now.
		n = (int)sp->ts_state;
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_ENDNUL;
		sp->ts_save_badflags = su->su_badflags;

		// At end of a prefix or at start of prefixtree: check for
		// following word.
		if (depth < MAXWLEN - 1
			    && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))
		{
		    // Set su->su_badflags to the caps type at this position.
		    // Use the caps type until here for the prefix itself.
		    if (has_mbyte)
			n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
		    else
			n = sp->ts_fidx;
		    flags = badword_captype(su->su_badptr, su->su_badptr + n);
		    su->su_badflags = badword_captype(su->su_badptr + n,
					       su->su_badptr + su->su_badlen);
#ifdef DEBUG_TRIEWALK
		    sprintf(changename[depth], ""prefix"");
#endif
		    go_deeper(stack, depth, 0);
		    ++depth;
		    sp = &stack[depth];
		    sp->ts_prefixdepth = depth - 1;
		    byts = fbyts;
		    idxs = fidxs;
		    sp->ts_arridx = 0;

		    // Move the prefix to preword[] with the right case
		    // and make find_keepcap_word() works.
		    tword[sp->ts_twordlen] = NUL;
		    make_case_word(tword + sp->ts_splitoff,
					  preword + sp->ts_prewordlen, flags);
		    sp->ts_prewordlen = (char_u)STRLEN(preword);
		    sp->ts_splitoff = sp->ts_twordlen;
		}
		break;
	    }

	    if (sp->ts_curi > len || byts[arridx] != 0)
	    {
		// Past bytes in node and/or past NUL bytes.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_ENDNUL;
		sp->ts_save_badflags = su->su_badflags;
		break;
	    }

	    // End of word in tree.
	    ++sp->ts_curi;		// eat one NUL byte

	    flags = (int)idxs[arridx];

	    // Skip words with the NOSUGGEST flag.
	    if (flags & WF_NOSUGGEST)
		break;

	    fword_ends = (fword[sp->ts_fidx] == NUL
			   || (soundfold
			       ? VIM_ISWHITE(fword[sp->ts_fidx])
			       : !spell_iswordp(fword + sp->ts_fidx, curwin)));
	    tword[sp->ts_twordlen] = NUL;

	    if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
					&& (sp->ts_flags & TSF_PREFIXOK) == 0
					&& pbyts != NULL)
	    {
		// There was a prefix before the word.  Check that the prefix
		// can be used with this word.
		// Count the length of the NULs in the prefix.  If there are
		// none this must be the first try without a prefix.
		n = stack[sp->ts_prefixdepth].ts_arridx;
		len = pbyts[n++];
		for (c = 0; c < len && pbyts[n + c] == 0; ++c)
		    ;
		if (c > 0)
		{
		    c = valid_word_prefix(c, n, flags,
				       tword + sp->ts_splitoff, slang, FALSE);
		    if (c == 0)
			break;

		    // Use the WF_RARE flag for a rare prefix.
		    if (c & WF_RAREPFX)
			flags |= WF_RARE;

		    // Tricky: when checking for both prefix and compounding
		    // we run into the prefix flag first.
		    // Remember that it's OK, so that we accept the prefix
		    // when arriving at a compound flag.
		    sp->ts_flags |= TSF_PREFIXOK;
		}
	    }

	    // Check NEEDCOMPOUND: can't use word without compounding.  Do try
	    // appending another compound word below.
	    if (sp->ts_complen == sp->ts_compsplit && fword_ends
						     && (flags & WF_NEEDCOMP))
		goodword_ends = FALSE;
	    else
		goodword_ends = TRUE;

	    p = NULL;
	    compound_ok = TRUE;
	    if (sp->ts_complen > sp->ts_compsplit)
	    {
		if (slang->sl_nobreak)
		{
		    // There was a word before this word.  When there was no
		    // change in this word (it was correct) add the first word
		    // as a suggestion.  If this word was corrected too, we
		    // need to check if a correct word follows.
		    if (sp->ts_fidx - sp->ts_splitfidx
					  == sp->ts_twordlen - sp->ts_splitoff
			    && STRNCMP(fword + sp->ts_splitfidx,
					tword + sp->ts_splitoff,
					 sp->ts_fidx - sp->ts_splitfidx) == 0)
		    {
			preword[sp->ts_prewordlen] = NUL;
			newscore = score_wordcount_adj(slang, sp->ts_score,
						 preword + sp->ts_prewordlen,
						 sp->ts_prewordlen > 0);
			// Add the suggestion if the score isn't too bad.
			if (newscore <= su->su_maxscore)
			    add_suggestion(su, &su->su_ga, preword,
				    sp->ts_splitfidx - repextra,
				    newscore, 0, FALSE,
				    lp->lp_sallang, FALSE);
			break;
		    }
		}
		else
		{
		    // There was a compound word before this word.  If this
		    // word does not support compounding then give up
		    // (splitting is tried for the word without compound
		    // flag).
		    if (((unsigned)flags >> 24) == 0
			    || sp->ts_twordlen - sp->ts_splitoff
						       < slang->sl_compminlen)
			break;
		    // For multi-byte chars check character length against
		    // COMPOUNDMIN.
		    if (has_mbyte
			    && slang->sl_compminlen > 0
			    && mb_charlen(tword + sp->ts_splitoff)
						       < slang->sl_compminlen)
			break;

		    compflags[sp->ts_complen] = ((unsigned)flags >> 24);
		    compflags[sp->ts_complen + 1] = NUL;
		    vim_strncpy(preword + sp->ts_prewordlen,
			    tword + sp->ts_splitoff,
			    sp->ts_twordlen - sp->ts_splitoff);

		    // Verify CHECKCOMPOUNDPATTERN  rules.
		    if (match_checkcompoundpattern(preword,  sp->ts_prewordlen,
							  &slang->sl_comppat))
			compound_ok = FALSE;

		    if (compound_ok)
		    {
			p = preword;
			while (*skiptowhite(p) != NUL)
			    p = skipwhite(skiptowhite(p));
			if (fword_ends && !can_compound(slang, p,
						compflags + sp->ts_compsplit))
			    // Compound is not allowed.  But it may still be
			    // possible if we add another (short) word.
			    compound_ok = FALSE;
		    }

		    // Get pointer to last char of previous word.
		    p = preword + sp->ts_prewordlen;
		    MB_PTR_BACK(preword, p);
		}
	    }

	    // Form the word with proper case in preword.
	    // If there is a word from a previous split, append.
	    // For the soundfold tree don't change the case, simply append.
	    if (soundfold)
		STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
	    else if (flags & WF_KEEPCAP)
		// Must find the word in the keep-case tree.
		find_keepcap_word(slang, tword + sp->ts_splitoff,
						 preword + sp->ts_prewordlen);
	    else
	    {
		// Include badflags: If the badword is onecap or allcap
		// use that for the goodword too.  But if the badword is
		// allcap and it's only one char long use onecap.
		c = su->su_badflags;
		if ((c & WF_ALLCAP)
			&& su->su_badlen == (*mb_ptr2len)(su->su_badptr))
		    c = WF_ONECAP;
		c |= flags;

		// When appending a compound word after a word character don't
		// use Onecap.
		if (p != NULL && spell_iswordp_nmw(p, curwin))
		    c &= ~WF_ONECAP;
		make_case_word(tword + sp->ts_splitoff,
					      preword + sp->ts_prewordlen, c);
	    }

	    if (!soundfold)
	    {
		// Don't use a banned word.  It may appear again as a good
		// word, thus remember it.
		if (flags & WF_BANNED)
		{
		    add_banned(su, preword + sp->ts_prewordlen);
		    break;
		}
		if ((sp->ts_complen == sp->ts_compsplit
			    && WAS_BANNED(su, preword + sp->ts_prewordlen))
						   || WAS_BANNED(su, preword))
		{
		    if (slang->sl_compprog == NULL)
			break;
		    // the word so far was banned but we may try compounding
		    goodword_ends = FALSE;
		}
	    }

	    newscore = 0;
	    if (!soundfold)	// soundfold words don't have flags
	    {
		if ((flags & WF_REGION)
			    && (((unsigned)flags >> 16) & lp->lp_region) == 0)
		    newscore += SCORE_REGION;
		if (flags & WF_RARE)
		    newscore += SCORE_RARE;

		if (!spell_valid_case(su->su_badflags,
				  captype(preword + sp->ts_prewordlen, NULL)))
		    newscore += SCORE_ICASE;
	    }

	    // TODO: how about splitting in the soundfold tree?
	    if (fword_ends
		    && goodword_ends
		    && sp->ts_fidx >= sp->ts_fidxtry
		    && compound_ok)
	    {
		// The badword also ends: add suggestions.
#ifdef DEBUG_TRIEWALK
		if (soundfold && STRCMP(preword, ""smwrd"") == 0)
		{
		    int	    j;

		    // print the stack of changes that brought us here
		    smsg(""------ %s -------"", fword);
		    for (j = 0; j < depth; ++j)
			smsg(""%s"", changename[j]);
		}
#endif
		if (soundfold)
		{
		    // For soundfolded words we need to find the original
		    // words, the edit distance and then add them.
		    add_sound_suggest(su, preword, sp->ts_score, lp);
		}
		else if (sp->ts_fidx > 0)
		{
		    // Give a penalty when changing non-word char to word
		    // char, e.g., ""thes,"" -> ""these"".
		    p = fword + sp->ts_fidx;
		    MB_PTR_BACK(fword, p);
		    if (!spell_iswordp(p, curwin) && *preword != NUL)
		    {
			p = preword + STRLEN(preword);
			MB_PTR_BACK(preword, p);
			if (spell_iswordp(p, curwin))
			    newscore += SCORE_NONWORD;
		    }

		    // Give a bonus to words seen before.
		    score = score_wordcount_adj(slang,
						sp->ts_score + newscore,
						preword + sp->ts_prewordlen,
						sp->ts_prewordlen > 0);

		    // Add the suggestion if the score isn't too bad.
		    if (score <= su->su_maxscore)
		    {
			add_suggestion(su, &su->su_ga, preword,
				    sp->ts_fidx - repextra,
				    score, 0, FALSE, lp->lp_sallang, FALSE);

			if (su->su_badflags & WF_MIXCAP)
			{
			    // We really don't know if the word should be
			    // upper or lower case, add both.
			    c = captype(preword, NULL);
			    if (c == 0 || c == WF_ALLCAP)
			    {
				make_case_word(tword + sp->ts_splitoff,
					      preword + sp->ts_prewordlen,
						      c == 0 ? WF_ALLCAP : 0);

				add_suggestion(su, &su->su_ga, preword,
					sp->ts_fidx - repextra,
					score + SCORE_ICASE, 0, FALSE,
					lp->lp_sallang, FALSE);
			    }
			}
		    }
		}
	    }

	    // Try word split and/or compounding.
	    if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
		    // Don't split halfway a character.
		    && (!has_mbyte || sp->ts_tcharlen == 0))
	    {
		int	try_compound;
		int	try_split;

		// If past the end of the bad word don't try a split.
		// Otherwise try changing the next word.  E.g., find
		// suggestions for ""the the"" where the second ""the"" is
		// different.  It's done like a split.
		// TODO: word split for soundfold words
		try_split = (sp->ts_fidx - repextra < su->su_badlen)
								&& !soundfold;

		// Get here in several situations:
		// 1. The word in the tree ends:
		//    If the word allows compounding try that.  Otherwise try
		//    a split by inserting a space.  For both check that a
		//    valid words starts at fword[sp->ts_fidx].
		//    For NOBREAK do like compounding to be able to check if
		//    the next word is valid.
		// 2. The badword does end, but it was due to a change (e.g.,
		//    a swap).  No need to split, but do check that the
		//    following word is valid.
		// 3. The badword and the word in the tree end.  It may still
		//    be possible to compound another (short) word.
		try_compound = FALSE;
		if (!soundfold
			&& !slang->sl_nocompoundsugs
			&& slang->sl_compprog != NULL
			&& ((unsigned)flags >> 24) != 0
			&& sp->ts_twordlen - sp->ts_splitoff
						       >= slang->sl_compminlen
			&& (!has_mbyte
			    || slang->sl_compminlen == 0
			    || mb_charlen(tword + sp->ts_splitoff)
						      >= slang->sl_compminlen)
			&& (slang->sl_compsylmax < MAXWLEN
			    || sp->ts_complen + 1 - sp->ts_compsplit
							  < slang->sl_compmax)
			&& (can_be_compound(sp, slang,
					 compflags, ((unsigned)flags >> 24))))

		{
		    try_compound = TRUE;
		    compflags[sp->ts_complen] = ((unsigned)flags >> 24);
		    compflags[sp->ts_complen + 1] = NUL;
		}

		// For NOBREAK we never try splitting, it won't make any word
		// valid.
		if (slang->sl_nobreak && !slang->sl_nocompoundsugs)
		    try_compound = TRUE;

		// If we could add a compound word, and it's also possible to
		// split at this point, do the split first and set
		// TSF_DIDSPLIT to avoid doing it again.
		else if (!fword_ends
			&& try_compound
			&& (sp->ts_flags & TSF_DIDSPLIT) == 0)
		{
		    try_compound = FALSE;
		    sp->ts_flags |= TSF_DIDSPLIT;
		    --sp->ts_curi;	    // do the same NUL again
		    compflags[sp->ts_complen] = NUL;
		}
		else
		    sp->ts_flags &= ~TSF_DIDSPLIT;

		if (try_split || try_compound)
		{
		    if (!try_compound && (!fword_ends || !goodword_ends))
		    {
			// If we're going to split need to check that the
			// words so far are valid for compounding.  If there
			// is only one word it must not have the NEEDCOMPOUND
			// flag.
			if (sp->ts_complen == sp->ts_compsplit
						     && (flags & WF_NEEDCOMP))
			    break;
			p = preword;
			while (*skiptowhite(p) != NUL)
			    p = skipwhite(skiptowhite(p));
			if (sp->ts_complen > sp->ts_compsplit
				&& !can_compound(slang, p,
						compflags + sp->ts_compsplit))
			    break;

			if (slang->sl_nosplitsugs)
			    newscore += SCORE_SPLIT_NO;
			else
			    newscore += SCORE_SPLIT;

			// Give a bonus to words seen before.
			newscore = score_wordcount_adj(slang, newscore,
					   preword + sp->ts_prewordlen, TRUE);
		    }

		    if (TRY_DEEPER(su, stack, depth, newscore))
		    {
			go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
			if (!try_compound && !fword_ends)
			    sprintf(changename[depth], ""%.*s-%s: split"",
				 sp->ts_twordlen, tword, fword + sp->ts_fidx);
			else
			    sprintf(changename[depth], ""%.*s-%s: compound"",
				 sp->ts_twordlen, tword, fword + sp->ts_fidx);
#endif
			// Save things to be restored at STATE_SPLITUNDO.
			sp->ts_save_badflags = su->su_badflags;
			PROF_STORE(sp->ts_state)
			sp->ts_state = STATE_SPLITUNDO;

			++depth;
			sp = &stack[depth];

			// Append a space to preword when splitting.
			if (!try_compound && !fword_ends)
			    STRCAT(preword, "" "");
			sp->ts_prewordlen = (char_u)STRLEN(preword);
			sp->ts_splitoff = sp->ts_twordlen;
			sp->ts_splitfidx = sp->ts_fidx;

			// If the badword has a non-word character at this
			// position skip it.  That means replacing the
			// non-word character with a space.  Always skip a
			// character when the word ends.  But only when the
			// good word can end.
			if (((!try_compound && !spell_iswordp_nmw(fword
							       + sp->ts_fidx,
							       curwin))
				    || fword_ends)
				&& fword[sp->ts_fidx] != NUL
				&& goodword_ends)
			{
			    int	    l;

			    l = mb_ptr2len(fword + sp->ts_fidx);
			    if (fword_ends)
			    {
				// Copy the skipped character to preword.
				mch_memmove(preword + sp->ts_prewordlen,
						      fword + sp->ts_fidx, l);
				sp->ts_prewordlen += l;
				preword[sp->ts_prewordlen] = NUL;
			    }
			    else
				sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
			    sp->ts_fidx += l;
			}

			// When compounding include compound flag in
			// compflags[] (already set above).  When splitting we
			// may start compounding over again.
			if (try_compound)
			    ++sp->ts_complen;
			else
			    sp->ts_compsplit = sp->ts_complen;
			sp->ts_prefixdepth = PFD_NOPREFIX;

			// set su->su_badflags to the caps type at this
			// position
			if (has_mbyte)
			    n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
			else
			    n = sp->ts_fidx;
			su->su_badflags = badword_captype(su->su_badptr + n,
					       su->su_badptr + su->su_badlen);

			// Restart at top of the tree.
			sp->ts_arridx = 0;

			// If there are postponed prefixes, try these too.
			if (pbyts != NULL)
			{
			    byts = pbyts;
			    idxs = pidxs;
			    sp->ts_prefixdepth = PFD_PREFIXTREE;
			    PROF_STORE(sp->ts_state)
			    sp->ts_state = STATE_NOPREFIX;
			}
		    }
		}
	    }
	    break;

	case STATE_SPLITUNDO:
	    // Undo the changes done for word split or compound word.
	    su->su_badflags = sp->ts_save_badflags;

	    // Continue looking for NUL bytes.
	    PROF_STORE(sp->ts_state)
	    sp->ts_state = STATE_START;

	    // In case we went into the prefix tree.
	    byts = fbyts;
	    idxs = fidxs;
	    break;

	case STATE_ENDNUL:
	    // Past the NUL bytes in the node.
	    su->su_badflags = sp->ts_save_badflags;
	    if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)
	    {
		// The badword ends, can't use STATE_PLAIN.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_DEL;
		break;
	    }
	    PROF_STORE(sp->ts_state)
	    sp->ts_state = STATE_PLAIN;
	    // FALLTHROUGH

	case STATE_PLAIN:
	    // Go over all possible bytes at this node, add each to tword[]
	    // and use child node.  ""ts_curi"" is the index.
	    arridx = sp->ts_arridx;
	    if (sp->ts_curi > byts[arridx])
	    {
		// Done all bytes at this node, do next state.  When still at
		// already changed bytes skip the other tricks.
		PROF_STORE(sp->ts_state)
		if (sp->ts_fidx >= sp->ts_fidxtry)
		    sp->ts_state = STATE_DEL;
		else
		    sp->ts_state = STATE_FINAL;
	    }
	    else
	    {
		arridx += sp->ts_curi++;
		c = byts[arridx];

		// Normal byte, go one level deeper.  If it's not equal to the
		// byte in the bad word adjust the score.  But don't even try
		// when the byte was already changed.  And don't try when we
		// just deleted this byte, accepting it is always cheaper than
		// delete + substitute.
		if (c == fword[sp->ts_fidx]
			|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))
		    newscore = 0;
		else
		    newscore = SCORE_SUBST;
		if ((newscore == 0
			    || (sp->ts_fidx >= sp->ts_fidxtry
				&& ((sp->ts_flags & TSF_DIDDEL) == 0
				    || c != fword[sp->ts_delidx])))
			&& TRY_DEEPER(su, stack, depth, newscore))
		{
		    go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
		    if (newscore > 0)
			sprintf(changename[depth], ""%.*s-%s: subst %c to %c"",
				sp->ts_twordlen, tword, fword + sp->ts_fidx,
				fword[sp->ts_fidx], c);
		    else
			sprintf(changename[depth], ""%.*s-%s: accept %c"",
				sp->ts_twordlen, tword, fword + sp->ts_fidx,
				fword[sp->ts_fidx]);
#endif
		    ++depth;
		    sp = &stack[depth];
		    if (fword[sp->ts_fidx] != NUL)
			++sp->ts_fidx;
		    tword[sp->ts_twordlen++] = c;
		    sp->ts_arridx = idxs[arridx];
		    if (newscore == SCORE_SUBST)
			sp->ts_isdiff = DIFF_YES;
		    if (has_mbyte)
		    {
			// Multi-byte characters are a bit complicated to
			// handle: They differ when any of the bytes differ
			// and then their length may also differ.
			if (sp->ts_tcharlen == 0)
			{
			    // First byte.
			    sp->ts_tcharidx = 0;
			    sp->ts_tcharlen = MB_BYTE2LEN(c);
			    sp->ts_fcharstart = sp->ts_fidx - 1;
			    sp->ts_isdiff = (newscore != 0)
						       ? DIFF_YES : DIFF_NONE;
			}
			else if (sp->ts_isdiff == DIFF_INSERT)
			    // When inserting trail bytes don't advance in the
			    // bad word.
			    --sp->ts_fidx;
			if (++sp->ts_tcharidx == sp->ts_tcharlen)
			{
			    // Last byte of character.
			    if (sp->ts_isdiff == DIFF_YES)
			    {
				// Correct ts_fidx for the byte length of the
				// character (we didn't check that before).
				sp->ts_fidx = sp->ts_fcharstart
					    + mb_ptr2len(
						    fword + sp->ts_fcharstart);
				// For changing a composing character adjust
				// the score from SCORE_SUBST to
				// SCORE_SUBCOMP.
				if (enc_utf8
					&& utf_iscomposing(
					    utf_ptr2char(tword
						+ sp->ts_twordlen
							   - sp->ts_tcharlen))
					&& utf_iscomposing(
					    utf_ptr2char(fword
							+ sp->ts_fcharstart)))
				    sp->ts_score -=
						  SCORE_SUBST - SCORE_SUBCOMP;

				// For a similar character adjust score from
				// SCORE_SUBST to SCORE_SIMILAR.
				else if (!soundfold
					&& slang->sl_has_map
					&& similar_chars(slang,
					    mb_ptr2char(tword
						+ sp->ts_twordlen
							   - sp->ts_tcharlen),
					    mb_ptr2char(fword
							+ sp->ts_fcharstart)))
				    sp->ts_score -=
						  SCORE_SUBST - SCORE_SIMILAR;
			    }
			    else if (sp->ts_isdiff == DIFF_INSERT
					 && sp->ts_twordlen > sp->ts_tcharlen)
			    {
				p = tword + sp->ts_twordlen - sp->ts_tcharlen;
				c = mb_ptr2char(p);
				if (enc_utf8 && utf_iscomposing(c))
				{
				    // Inserting a composing char doesn't
				    // count that much.
				    sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
				}
				else
				{
				    // If the previous character was the same,
				    // thus doubling a character, give a bonus
				    // to the score.  Also for the soundfold
				    // tree (might seem illogical but does
				    // give better scores).
				    MB_PTR_BACK(tword, p);
				    if (c == mb_ptr2char(p))
					sp->ts_score -= SCORE_INS
							       - SCORE_INSDUP;
				}
			    }

			    // Starting a new char, reset the length.
			    sp->ts_tcharlen = 0;
			}
		    }
		    else
		    {
			// If we found a similar char adjust the score.
			// We do this after calling go_deeper() because
			// it's slow.
			if (newscore != 0
				&& !soundfold
				&& slang->sl_has_map
				&& similar_chars(slang,
						   c, fword[sp->ts_fidx - 1]))
			    sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
		    }
		}
	    }
	    break;

	case STATE_DEL:
	    // When past the first byte of a multi-byte char don't try
	    // delete/insert/swap a character.
	    if (has_mbyte && sp->ts_tcharlen > 0)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_FINAL;
		break;
	    }
	    // Try skipping one character in the bad word (delete it).
	    PROF_STORE(sp->ts_state)
	    sp->ts_state = STATE_INS_PREP;
	    sp->ts_curi = 1;
	    if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
		// Deleting a vowel at the start of a word counts less, see
		// soundalike_score().
		newscore = 2 * SCORE_DEL / 3;
	    else
		newscore = SCORE_DEL;
	    if (fword[sp->ts_fidx] != NUL
				    && TRY_DEEPER(su, stack, depth, newscore))
	    {
		go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
		sprintf(changename[depth], ""%.*s-%s: delete %c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			fword[sp->ts_fidx]);
#endif
		++depth;

		// Remember what character we deleted, so that we can avoid
		// inserting it again.
		stack[depth].ts_flags |= TSF_DIDDEL;
		stack[depth].ts_delidx = sp->ts_fidx;

		// Advance over the character in fword[].  Give a bonus to the
		// score if the same character is following ""nn"" -> ""n"".  It's
		// a bit illogical for soundfold tree but it does give better
		// results.
		if (has_mbyte)
		{
		    c = mb_ptr2char(fword + sp->ts_fidx);
		    stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);
		    if (enc_utf8 && utf_iscomposing(c))
			stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
		    else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
			stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
		}
		else
		{
		    ++stack[depth].ts_fidx;
		    if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
			stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
		}
		break;
	    }
	    // FALLTHROUGH

	case STATE_INS_PREP:
	    if (sp->ts_flags & TSF_DIDDEL)
	    {
		// If we just deleted a byte then inserting won't make sense,
		// a substitute is always cheaper.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_SWAP;
		break;
	    }

	    // skip over NUL bytes
	    n = sp->ts_arridx;
	    for (;;)
	    {
		if (sp->ts_curi > byts[n])
		{
		    // Only NUL bytes at this node, go to next state.
		    PROF_STORE(sp->ts_state)
		    sp->ts_state = STATE_SWAP;
		    break;
		}
		if (byts[n + sp->ts_curi] != NUL)
		{
		    // Found a byte to insert.
		    PROF_STORE(sp->ts_state)
		    sp->ts_state = STATE_INS;
		    break;
		}
		++sp->ts_curi;
	    }
	    break;

	    // FALLTHROUGH

	case STATE_INS:
	    // Insert one byte.  Repeat this for each possible byte at this
	    // node.
	    n = sp->ts_arridx;
	    if (sp->ts_curi > byts[n])
	    {
		// Done all bytes at this node, go to next state.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_SWAP;
		break;
	    }

	    // Do one more byte at this node, but:
	    // - Skip NUL bytes.
	    // - Skip the byte if it's equal to the byte in the word,
	    //   accepting that byte is always better.
	    n += sp->ts_curi++;
	    c = byts[n];
	    if (soundfold && sp->ts_twordlen == 0 && c == '*')
		// Inserting a vowel at the start of a word counts less,
		// see soundalike_score().
		newscore = 2 * SCORE_INS / 3;
	    else
		newscore = SCORE_INS;
	    if (c != fword[sp->ts_fidx]
				    && TRY_DEEPER(su, stack, depth, newscore))
	    {
		go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
		sprintf(changename[depth], ""%.*s-%s: insert %c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			c);
#endif
		++depth;
		sp = &stack[depth];
		tword[sp->ts_twordlen++] = c;
		sp->ts_arridx = idxs[n];
		if (has_mbyte)
		{
		    fl = MB_BYTE2LEN(c);
		    if (fl > 1)
		    {
			// There are following bytes for the same character.
			// We must find all bytes before trying
			// delete/insert/swap/etc.
			sp->ts_tcharlen = fl;
			sp->ts_tcharidx = 1;
			sp->ts_isdiff = DIFF_INSERT;
		    }
		}
		else
		    fl = 1;
		if (fl == 1)
		{
		    // If the previous character was the same, thus doubling a
		    // character, give a bonus to the score.  Also for
		    // soundfold words (illogical but does give a better
		    // score).
		    if (sp->ts_twordlen >= 2
					   && tword[sp->ts_twordlen - 2] == c)
			sp->ts_score -= SCORE_INS - SCORE_INSDUP;
		}
	    }
	    break;

	case STATE_SWAP:
	    // Swap two bytes in the bad word: ""12"" -> ""21"".
	    // We change ""fword"" here, it's changed back afterwards at
	    // STATE_UNSWAP.
	    p = fword + sp->ts_fidx;
	    c = *p;
	    if (c == NUL)
	    {
		// End of word, can't swap or replace.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_FINAL;
		break;
	    }

	    // Don't swap if the first character is not a word character.
	    // SWAP3 etc. also don't make sense then.
	    if (!soundfold && !spell_iswordp(p, curwin))
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
		break;
	    }

	    if (has_mbyte)
	    {
		n = MB_CPTR2LEN(p);
		c = mb_ptr2char(p);
		if (p[n] == NUL)
		    c2 = NUL;
		else if (!soundfold && !spell_iswordp(p + n, curwin))
		    c2 = c; // don't swap non-word char
		else
		    c2 = mb_ptr2char(p + n);
	    }
	    else
	    {
		if (p[1] == NUL)
		    c2 = NUL;
		else if (!soundfold && !spell_iswordp(p + 1, curwin))
		    c2 = c; // don't swap non-word char
		else
		    c2 = p[1];
	    }

	    // When the second character is NUL we can't swap.
	    if (c2 == NUL)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
		break;
	    }

	    // When characters are identical, swap won't do anything.
	    // Also get here if the second char is not a word character.
	    if (c == c2)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_SWAP3;
		break;
	    }
	    if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
	    {
		go_deeper(stack, depth, SCORE_SWAP);
#ifdef DEBUG_TRIEWALK
		sprintf(changename[depth], ""%.*s-%s: swap %c and %c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			c, c2);
#endif
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_UNSWAP;
		++depth;
		if (has_mbyte)
		{
		    fl = mb_char2len(c2);
		    mch_memmove(p, p + n, fl);
		    mb_char2bytes(c, p + fl);
		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
		}
		else
		{
		    p[0] = c2;
		    p[1] = c;
		    stack[depth].ts_fidxtry = sp->ts_fidx + 2;
		}
	    }
	    else
	    {
		// If this swap doesn't work then SWAP3 won't either.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
	    }
	    break;

	case STATE_UNSWAP:
	    // Undo the STATE_SWAP swap: ""21"" -> ""12"".
	    p = fword + sp->ts_fidx;
	    if (has_mbyte)
	    {
		n = mb_ptr2len(p);
		c = mb_ptr2char(p + n);
		mch_memmove(p + mb_ptr2len(p + n), p, n);
		mb_char2bytes(c, p);
	    }
	    else
	    {
		c = *p;
		*p = p[1];
		p[1] = c;
	    }
	    // FALLTHROUGH

	case STATE_SWAP3:
	    // Swap two bytes, skipping one: ""123"" -> ""321"".  We change
	    // ""fword"" here, it's changed back afterwards at STATE_UNSWAP3.
	    p = fword + sp->ts_fidx;
	    if (has_mbyte)
	    {
		n = MB_CPTR2LEN(p);
		c = mb_ptr2char(p);
		fl = MB_CPTR2LEN(p + n);
		c2 = mb_ptr2char(p + n);
		if (!soundfold && !spell_iswordp(p + n + fl, curwin))
		    c3 = c;	// don't swap non-word char
		else
		    c3 = mb_ptr2char(p + n + fl);
	    }
	    else
	    {
		c = *p;
		c2 = p[1];
		if (!soundfold && !spell_iswordp(p + 2, curwin))
		    c3 = c;	// don't swap non-word char
		else
		    c3 = p[2];
	    }

	    // When characters are identical: ""121"" then SWAP3 result is
	    // identical, ROT3L result is same as SWAP: ""211"", ROT3L result is
	    // same as SWAP on next char: ""112"".  Thus skip all swapping.
	    // Also skip when c3 is NUL.
	    // Also get here when the third character is not a word character.
	    // Second character may any char: ""a.b"" -> ""b.a""
	    if (c == c3 || c3 == NUL)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
		break;
	    }
	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
	    {
		go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
		sprintf(changename[depth], ""%.*s-%s: swap3 %c and %c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			c, c3);
#endif
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_UNSWAP3;
		++depth;
		if (has_mbyte)
		{
		    tl = mb_char2len(c3);
		    mch_memmove(p, p + n + fl, tl);
		    mb_char2bytes(c2, p + tl);
		    mb_char2bytes(c, p + fl + tl);
		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
		}
		else
		{
		    p[0] = p[2];
		    p[2] = c;
		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
		}
	    }
	    else
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
	    }
	    break;

	case STATE_UNSWAP3:
	    // Undo STATE_SWAP3: ""321"" -> ""123""
	    p = fword + sp->ts_fidx;
	    if (has_mbyte)
	    {
		n = mb_ptr2len(p);
		c2 = mb_ptr2char(p + n);
		fl = mb_ptr2len(p + n);
		c = mb_ptr2char(p + n + fl);
		tl = mb_ptr2len(p + n + fl);
		mch_memmove(p + fl + tl, p, n);
		mb_char2bytes(c, p);
		mb_char2bytes(c2, p + tl);
		p = p + tl;
	    }
	    else
	    {
		c = *p;
		*p = p[2];
		p[2] = c;
		++p;
	    }

	    if (!soundfold && !spell_iswordp(p, curwin))
	    {
		// Middle char is not a word char, skip the rotate.  First and
		// third char were already checked at swap and swap3.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
		break;
	    }

	    // Rotate three characters left: ""123"" -> ""231"".  We change
	    // ""fword"" here, it's changed back afterwards at STATE_UNROT3L.
	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
	    {
		go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
		p = fword + sp->ts_fidx;
		sprintf(changename[depth], ""%.*s-%s: rotate left %c%c%c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			p[0], p[1], p[2]);
#endif
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_UNROT3L;
		++depth;
		p = fword + sp->ts_fidx;
		if (has_mbyte)
		{
		    n = MB_CPTR2LEN(p);
		    c = mb_ptr2char(p);
		    fl = MB_CPTR2LEN(p + n);
		    fl += MB_CPTR2LEN(p + n + fl);
		    mch_memmove(p, p + n, fl);
		    mb_char2bytes(c, p + fl);
		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
		}
		else
		{
		    c = *p;
		    *p = p[1];
		    p[1] = p[2];
		    p[2] = c;
		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
		}
	    }
	    else
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
	    }
	    break;

	case STATE_UNROT3L:
	    // Undo ROT3L: ""231"" -> ""123""
	    p = fword + sp->ts_fidx;
	    if (has_mbyte)
	    {
		n = mb_ptr2len(p);
		n += mb_ptr2len(p + n);
		c = mb_ptr2char(p + n);
		tl = mb_ptr2len(p + n);
		mch_memmove(p + tl, p, n);
		mb_char2bytes(c, p);
	    }
	    else
	    {
		c = p[2];
		p[2] = p[1];
		p[1] = *p;
		*p = c;
	    }

	    // Rotate three bytes right: ""123"" -> ""312"".  We change ""fword""
	    // here, it's changed back afterwards at STATE_UNROT3R.
	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
	    {
		go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
		p = fword + sp->ts_fidx;
		sprintf(changename[depth], ""%.*s-%s: rotate right %c%c%c"",
			sp->ts_twordlen, tword, fword + sp->ts_fidx,
			p[0], p[1], p[2]);
#endif
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_UNROT3R;
		++depth;
		p = fword + sp->ts_fidx;
		if (has_mbyte)
		{
		    n = MB_CPTR2LEN(p);
		    n += MB_CPTR2LEN(p + n);
		    c = mb_ptr2char(p + n);
		    tl = MB_CPTR2LEN(p + n);
		    mch_memmove(p + tl, p, n);
		    mb_char2bytes(c, p);
		    stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
		}
		else
		{
		    c = p[2];
		    p[2] = p[1];
		    p[1] = *p;
		    *p = c;
		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
		}
	    }
	    else
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_REP_INI;
	    }
	    break;

	case STATE_UNROT3R:
	    // Undo ROT3R: ""312"" -> ""123""
	    p = fword + sp->ts_fidx;
	    if (has_mbyte)
	    {
		c = mb_ptr2char(p);
		tl = mb_ptr2len(p);
		n = mb_ptr2len(p + tl);
		n += mb_ptr2len(p + tl + n);
		mch_memmove(p, p + tl, n);
		mb_char2bytes(c, p + n);
	    }
	    else
	    {
		c = *p;
		*p = p[1];
		p[1] = p[2];
		p[2] = c;
	    }
	    // FALLTHROUGH

	case STATE_REP_INI:
	    // Check if matching with REP items from the .aff file would work.
	    // Quickly skip if:
	    // - there are no REP items and we are not in the soundfold trie
	    // - the score is going to be too high anyway
	    // - already applied a REP item or swapped here
	    if ((lp->lp_replang == NULL && !soundfold)
		    || sp->ts_score + SCORE_REP >= su->su_maxscore
		    || sp->ts_fidx < sp->ts_fidxtry)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_FINAL;
		break;
	    }

	    // Use the first byte to quickly find the first entry that may
	    // match.  If the index is -1 there is none.
	    if (soundfold)
		sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
	    else
		sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];

	    if (sp->ts_curi < 0)
	    {
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_FINAL;
		break;
	    }

	    PROF_STORE(sp->ts_state)
	    sp->ts_state = STATE_REP;
	    // FALLTHROUGH

	case STATE_REP:
	    // Try matching with REP items from the .aff file.  For each match
	    // replace the characters and check if the resulting word is
	    // valid.
	    p = fword + sp->ts_fidx;

	    if (soundfold)
		gap = &slang->sl_repsal;
	    else
		gap = &lp->lp_replang->sl_rep;
	    while (sp->ts_curi < gap->ga_len)
	    {
		ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
		if (*ftp->ft_from != *p)
		{
		    // past possible matching entries
		    sp->ts_curi = gap->ga_len;
		    break;
		}
		if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
			&& TRY_DEEPER(su, stack, depth, SCORE_REP))
		{
		    go_deeper(stack, depth, SCORE_REP);
#ifdef DEBUG_TRIEWALK
		    sprintf(changename[depth], ""%.*s-%s: replace %s with %s"",
			    sp->ts_twordlen, tword, fword + sp->ts_fidx,
			    ftp->ft_from, ftp->ft_to);
#endif
		    // Need to undo this afterwards.
		    PROF_STORE(sp->ts_state)
		    sp->ts_state = STATE_REP_UNDO;

		    // Change the ""from"" to the ""to"" string.
		    ++depth;
		    fl = (int)STRLEN(ftp->ft_from);
		    tl = (int)STRLEN(ftp->ft_to);
		    if (fl != tl)
		    {
			STRMOVE(p + tl, p + fl);
			repextra += tl - fl;
		    }
		    mch_memmove(p, ftp->ft_to, tl);
		    stack[depth].ts_fidxtry = sp->ts_fidx + tl;
		    stack[depth].ts_tcharlen = 0;
		    break;
		}
	    }

	    if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
	    {
		// No (more) matches.
		PROF_STORE(sp->ts_state)
		sp->ts_state = STATE_FINAL;
	    }

	    break;

	case STATE_REP_UNDO:
	    // Undo a REP replacement and continue with the next one.
	    if (soundfold)
		gap = &slang->sl_repsal;
	    else
		gap = &lp->lp_replang->sl_rep;
	    ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
	    fl = (int)STRLEN(ftp->ft_from);
	    tl = (int)STRLEN(ftp->ft_to);
	    p = fword + sp->ts_fidx;
	    if (fl != tl)
	    {
		STRMOVE(p + fl, p + tl);
		repextra -= tl - fl;
	    }
	    mch_memmove(p, ftp->ft_from, fl);
	    PROF_STORE(sp->ts_state)
	    sp->ts_state = STATE_REP;
	    break;

	default:
	    // Did all possible states at this level, go up one level.
	    --depth;

	    if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
	    {
		// Continue in or go back to the prefix tree.
		byts = pbyts;
		idxs = pidxs;
	    }

	    // Don't check for CTRL-C too often, it takes time.
	    if (--breakcheckcount == 0)
	    {
		ui_breakcheck();
		breakcheckcount = 1000;
#ifdef FEAT_RELTIME
		if (spell_suggest_timeout > 0
					  && profile_passed_limit(&time_limit))
		    got_int = TRUE;
#endif
	    }
	}
    }
}",CWE-787,16
1,"sug_filltree(spellinfo_T *spin, slang_T *slang)
{
    char_u	*byts;
    idx_T	*idxs;
    int		depth;
    idx_T	arridx[MAXWLEN];
    int		curi[MAXWLEN];
    char_u	tword[MAXWLEN];
    char_u	tsalword[MAXWLEN];
    int		c;
    idx_T	n;
    unsigned	words_done = 0;
    int		wordcount[MAXWLEN];

    // We use si_foldroot for the soundfolded trie.
    spin->si_foldroot = wordtree_alloc(spin);
    if (spin->si_foldroot == NULL)
	return FAIL;

    // let tree_add_word() know we're adding to the soundfolded tree
    spin->si_sugtree = TRUE;

    /*
     * Go through the whole case-folded tree, soundfold each word and put it
     * in the trie.
     */
    byts = slang->sl_fbyts;
    idxs = slang->sl_fidxs;

    arridx[0] = 0;
    curi[0] = 1;
    wordcount[0] = 0;

    depth = 0;
    while (depth >= 0 && !got_int)
    {
	if (curi[depth] > byts[arridx[depth]])
	{
	    // Done all bytes at this node, go up one level.
	    idxs[arridx[depth]] = wordcount[depth];
	    if (depth > 0)
		wordcount[depth - 1] += wordcount[depth];

	    --depth;
	    line_breakcheck();
	}
	else
	{

	    // Do one more byte at this node.
	    n = arridx[depth] + curi[depth];
	    ++curi[depth];

	    c = byts[n];
	    if (c == 0)
	    {
		// Sound-fold the word.
		tword[depth] = NUL;
		spell_soundfold(slang, tword, TRUE, tsalword);

		// We use the ""flags"" field for the MSB of the wordnr,
		// ""region"" for the LSB of the wordnr.
		if (tree_add_word(spin, tsalword, spin->si_foldroot,
				words_done >> 16, words_done & 0xffff,
							   0) == FAIL)
		    return FAIL;

		++words_done;
		++wordcount[depth];

		// Reset the block count each time to avoid compression
		// kicking in.
		spin->si_blocks_cnt = 0;

		// Skip over any other NUL bytes (same word with different
		// flags).  But don't go over the end.
		while (n + 1 < slang->sl_fbyts_len && byts[n + 1] == 0)
		{
		    ++n;
		    ++curi[depth];
		}
	    }
	    else
	    {
		// Normal char, go one level deeper.
		tword[depth++] = c;
		arridx[depth] = idxs[n];
		curi[depth] = 1;
		wordcount[depth] = 0;
	    }
	}
    }

    smsg(_(""Total number of words: %d""), words_done);

    return OK;
}",CWE-787,16
0,"std::string Network::GetErrorString() const {
  switch (error_) {
    case ERROR_UNKNOWN:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_UNKNOWN);
    case ERROR_OUT_OF_RANGE:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OUT_OF_RANGE);
    case ERROR_PIN_MISSING:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_PIN_MISSING);
    case ERROR_DHCP_FAILED:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_DHCP_FAILED);
    case ERROR_CONNECT_FAILED:
      return l10n_util::GetStringUTF8(
          IDS_CHROMEOS_NETWORK_ERROR_CONNECT_FAILED);
    case ERROR_BAD_PASSPHRASE:
      return l10n_util::GetStringUTF8(
          IDS_CHROMEOS_NETWORK_ERROR_BAD_PASSPHRASE);
    case ERROR_BAD_WEPKEY:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_BAD_WEPKEY);
    case ERROR_ACTIVATION_FAILED:
      return l10n_util::GetStringUTF8(
          IDS_CHROMEOS_NETWORK_ERROR_ACTIVATION_FAILED);
    case ERROR_NEED_EVDO:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_NEED_EVDO);
    case ERROR_NEED_HOME_NETWORK:
      return l10n_util::GetStringUTF8(
          IDS_CHROMEOS_NETWORK_ERROR_NEED_HOME_NETWORK);
    case ERROR_OTASP_FAILED:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_OTASP_FAILED);
    case ERROR_AAA_FAILED:
      return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_ERROR_AAA_FAILED);
    default:
      break;
  }
  return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED);
}
",none,24
1,"ga_concat_shorten_esc(garray_T *gap, char_u *str)
{
    char_u  *p;
    char_u  *s;
    int	    c;
    int	    clen;
    char_u  buf[NUMBUFLEN];
    int	    same_len;

    if (str == NULL)
    {
	ga_concat(gap, (char_u *)""NULL"");
	return;
    }

    for (p = str; *p != NUL; ++p)
    {
	same_len = 1;
	s = p;
	c = mb_ptr2char_adv(&s);
	clen = s - p;
	while (*s != NUL && c == mb_ptr2char(s))
	{
	    ++same_len;
	    s += clen;
	}
	if (same_len > 20)
	{
	    ga_concat(gap, (char_u *)""\\["");
	    ga_concat_esc(gap, p, clen);
	    ga_concat(gap, (char_u *)"" occurs "");
	    vim_snprintf((char *)buf, NUMBUFLEN, ""%d"", same_len);
	    ga_concat(gap, buf);
	    ga_concat(gap, (char_u *)"" times]"");
	    p = s - 1;
	}
	else
	    ga_concat_esc(gap, p, clen);
    }
}",CWE-787,16
0,"  virtual WifiNetwork* FindWifiNetworkByPath(
      const std::string& path) {
    return GetWirelessNetworkByPath(wifi_networks_, path);
  }
",none,24
0,"static std::string ToHtmlTableHeader(Network* network) {
  std::string str;
  if (network->type() == TYPE_WIFI || network->type() == TYPE_CELLULAR) {
    str += WrapWithTH(""Name"") + WrapWithTH(""Auto-Connect"") +
        WrapWithTH(""Strength"");
    if (network->type() == TYPE_WIFI)
      str += WrapWithTH(""Encryption"") + WrapWithTH(""Passphrase"") +
          WrapWithTH(""Identity"") + WrapWithTH(""Certificate"");
  }
  str += WrapWithTH(""State"") + WrapWithTH(""Error"") + WrapWithTH(""IP Address"");
  return str;
}
",none,24
1,"  void Compute(OpKernelContext* context) override {
    // Read ragged_splits inputs.
    OpInputList ragged_nested_splits_in;
    OP_REQUIRES_OK(context, context->input_list(""rt_nested_splits"",
                                                &ragged_nested_splits_in));
    const int ragged_nested_splits_len = ragged_nested_splits_in.size();
    RaggedTensorVariant batched_ragged_input;
    // Read ragged_values input.
    batched_ragged_input.set_values(context->input(ragged_nested_splits_len));
    batched_ragged_input.mutable_nested_splits()->reserve(
        ragged_nested_splits_len);
    for (int i = 0; i < ragged_nested_splits_len; i++) {
      batched_ragged_input.append_splits(ragged_nested_splits_in[i]);
    }

    if (!batched_input_) {
      // Encode as a Scalar Variant Tensor.
      Tensor* encoded_scalar;
      OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}),
                                                       &encoded_scalar));
      encoded_scalar->scalar()() = std::move(batched_ragged_input);
      return;
    }

    // Unbatch the Ragged Tensor and encode the components.
    std::vector unbatched_ragged_input;
    auto batched_splits_top_vec =
        batched_ragged_input.splits(0).vec();
    int num_components = batched_splits_top_vec.size() - 1;
    OP_REQUIRES(context, num_components >= 0,
                errors::Internal(""Invalid split argument.""));
    OP_REQUIRES_OK(context, UnbatchRaggedZerothDim(
                                batched_ragged_input, &unbatched_ragged_input));

    // Bundle the encoded scalar Variant Tensors into a rank-1 Variant Tensor.
    Tensor* encoded_vector;
    int output_size = unbatched_ragged_input.size();
    OP_REQUIRES_OK(context,
                   context->allocate_output(0, TensorShape({output_size}),
                                            &encoded_vector));
    auto encoded_vector_t = encoded_vector->vec();
    for (int i = 0; i < output_size; i++) {
      encoded_vector_t(i) = unbatched_ragged_input[i];
    }
  }",CWE-125,1
0,"  virtual bool wifi_available() const { return false; }
",none,24
1,"diff_mark_adjust_tp(
    tabpage_T	*tp,
    int		idx,
    linenr_T	line1,
    linenr_T	line2,
    long	amount,
    long	amount_after)
{
    diff_T	*dp;
    diff_T	*dprev;
    diff_T	*dnext;
    int		i;
    int		inserted, deleted;
    int		n, off;
    linenr_T	last;
    linenr_T	lnum_deleted = line1;	// lnum of remaining deletion
    int		check_unchanged;

    if (diff_internal())
    {
	// Will update diffs before redrawing.  Set _invalid to update the
	// diffs themselves, set _update to also update folds properly just
	// before redrawing.
	// Do update marks here, it is needed for :%diffput.
	tp->tp_diff_invalid = TRUE;
	tp->tp_diff_update = TRUE;
    }

    if (line2 == MAXLNUM)
    {
	// mark_adjust(99, MAXLNUM, 9, 0): insert lines
	inserted = amount;
	deleted = 0;
    }
    else if (amount_after > 0)
    {
	// mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines
	inserted = amount_after;
	deleted = 0;
    }
    else
    {
	// mark_adjust(98, 99, MAXLNUM, -2): delete lines
	inserted = 0;
	deleted = -amount_after;
    }

    dprev = NULL;
    dp = tp->tp_first_diff;
    for (;;)
    {
	// If the change is after the previous diff block and before the next
	// diff block, thus not touching an existing change, create a new diff
	// block.  Don't do this when ex_diffgetput() is busy.
	if ((dp == NULL || dp->df_lnum[idx] - 1 > line2
		    || (line2 == MAXLNUM && dp->df_lnum[idx] > line1))
		&& (dprev == NULL
		    || dprev->df_lnum[idx] + dprev->df_count[idx] < line1)
		&& !diff_busy)
	{
	    dnext = diff_alloc_new(tp, dprev, dp);
	    if (dnext == NULL)
		return;

	    dnext->df_lnum[idx] = line1;
	    dnext->df_count[idx] = inserted;
	    for (i = 0; i < DB_COUNT; ++i)
		if (tp->tp_diffbuf[i] != NULL && i != idx)
		{
		    if (dprev == NULL)
			dnext->df_lnum[i] = line1;
		    else
			dnext->df_lnum[i] = line1
			    + (dprev->df_lnum[i] + dprev->df_count[i])
			    - (dprev->df_lnum[idx] + dprev->df_count[idx]);
		    dnext->df_count[i] = deleted;
		}
	}

	// if at end of the list, quit
	if (dp == NULL)
	    break;

	/*
	 * Check for these situations:
	 *	  1  2	3
	 *	  1  2	3
	 * line1     2	3  4  5
	 *	     2	3  4  5
	 *	     2	3  4  5
	 * line2     2	3  4  5
	 *		3     5  6
	 *		3     5  6
	 */
	// compute last line of this change
	last = dp->df_lnum[idx] + dp->df_count[idx] - 1;

	// 1. change completely above line1: nothing to do
	if (last >= line1 - 1)
	{
	    // 6. change below line2: only adjust for amount_after; also when
	    // ""deleted"" became zero when deleted all lines between two diffs
	    if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2)
	    {
		if (amount_after == 0)
		    break;	// nothing left to change
		dp->df_lnum[idx] += amount_after;
	    }
	    else
	    {
		check_unchanged = FALSE;

		// 2. 3. 4. 5.: inserted/deleted lines touching this diff.
		if (deleted > 0)
		{
		    if (dp->df_lnum[idx] >= line1)
		    {
			off = dp->df_lnum[idx] - lnum_deleted;
			if (last <= line2)
			{
			    // 4. delete all lines of diff
			    if (dp->df_next != NULL
				    && dp->df_next->df_lnum[idx] - 1 <= line2)
			    {
				// delete continues in next diff, only do
				// lines until that one
				n = dp->df_next->df_lnum[idx] - lnum_deleted;
				deleted -= n;
				n -= dp->df_count[idx];
				lnum_deleted = dp->df_next->df_lnum[idx];
			    }
			    else
				n = deleted - dp->df_count[idx];
			    dp->df_count[idx] = 0;
			}
			else
			{
			    // 5. delete lines at or just before top of diff
			    n = off;
			    dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1;
			    check_unchanged = TRUE;
			}
			dp->df_lnum[idx] = line1;
		    }
		    else
		    {
			off = 0;
			if (last < line2)
			{
			    // 2. delete at end of diff
			    dp->df_count[idx] -= last - lnum_deleted + 1;
			    if (dp->df_next != NULL
				    && dp->df_next->df_lnum[idx] - 1 <= line2)
			    {
				// delete continues in next diff, only do
				// lines until that one
				n = dp->df_next->df_lnum[idx] - 1 - last;
				deleted -= dp->df_next->df_lnum[idx]
							       - lnum_deleted;
				lnum_deleted = dp->df_next->df_lnum[idx];
			    }
			    else
				n = line2 - last;
			    check_unchanged = TRUE;
			}
			else
			{
			    // 3. delete lines inside the diff
			    n = 0;
			    dp->df_count[idx] -= deleted;
			}
		    }

		    for (i = 0; i < DB_COUNT; ++i)
			if (tp->tp_diffbuf[i] != NULL && i != idx)
			{
			    dp->df_lnum[i] -= off;
			    dp->df_count[i] += n;
			}
		}
		else
		{
		    if (dp->df_lnum[idx] <= line1)
		    {
			// inserted lines somewhere in this diff
			dp->df_count[idx] += inserted;
			check_unchanged = TRUE;
		    }
		    else
			// inserted lines somewhere above this diff
			dp->df_lnum[idx] += inserted;
		}

		if (check_unchanged)
		    // Check if inserted lines are equal, may reduce the
		    // size of the diff.  TODO: also check for equal lines
		    // in the middle and perhaps split the block.
		    diff_check_unchanged(tp, dp);
	    }
	}

	// check if this block touches the previous one, may merge them.
	if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx]
							  == dp->df_lnum[idx])
	{
	    for (i = 0; i < DB_COUNT; ++i)
		if (tp->tp_diffbuf[i] != NULL)
		    dprev->df_count[i] += dp->df_count[i];
	    dprev->df_next = dp->df_next;
	    vim_free(dp);
	    dp = dprev->df_next;
	}
	else
	{
	    // Advance to next entry.
	    dprev = dp;
	    dp = dp->df_next;
	}
    }

    dprev = NULL;
    dp = tp->tp_first_diff;
    while (dp != NULL)
    {
	// All counts are zero, remove this entry.
	for (i = 0; i < DB_COUNT; ++i)
	    if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
		break;
	if (i == DB_COUNT)
	{
	    dnext = dp->df_next;
	    vim_free(dp);
	    dp = dnext;
	    if (dprev == NULL)
		tp->tp_first_diff = dnext;
	    else
		dprev->df_next = dnext;
	}
	else
	{
	    // Advance to next entry.
	    dprev = dp;
	    dp = dp->df_next;
	}

    }

    if (tp == curtab)
    {
	// Don't redraw right away, this updates the diffs, which can be slow.
	need_diff_redraw = TRUE;

	// Need to recompute the scroll binding, may remove or add filler
	// lines (e.g., when adding lines above w_topline). But it's slow when
	// making many changes, postpone until redrawing.
	diff_need_scrollbind = TRUE;
    }
}",CWE-787,16
0,"void QuotaManager::GetHostUsage(const std::string& host, StorageType type,
                                HostUsageCallback* callback) {
  LazyInitialize();
  GetUsageTracker(type)->GetHostUsage(host, callback);
}
",none,24
0,"  virtual std::string GetHtmlInfo(int refresh) {
    std::string output;
    output.append(""About Network"");
    if (refresh > 0)
      output.append("""");
    output.append("""");
    if (refresh > 0) {
      output.append(""(Auto-refreshing page every "" +
                    base::IntToString(refresh) + ""s)"");
    } else {
      output.append(""(To auto-refresh this page: about:network/<secs>)"");
    }

    output.append(""

Ethernet:

""); if (ethernet_ && ethernet_enabled()) { output.append("""" + ToHtmlTableHeader(ethernet_) + """"); output.append("""" + ToHtmlTableRow(ethernet_) + """"); } output.append(""

Wifi:

""); for (size_t i = 0; i < wifi_networks_.size(); ++i) { if (i == 0) output.append("""" + ToHtmlTableHeader(wifi_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(wifi_networks_[i]) + """"); } output.append(""

Cellular:

""); for (size_t i = 0; i < cellular_networks_.size(); ++i) { if (i == 0) output.append("""" + ToHtmlTableHeader(cellular_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(cellular_networks_[i]) + """"); } output.append(""

Remembered Wifi:

""); for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) { if (i == 0) output.append( """" + ToHtmlTableHeader(remembered_wifi_networks_[i]) + """"); output.append("""" + ToHtmlTableRow(remembered_wifi_networks_[i]) + """"); } output.append(""
""); return output; } ",none,24 1,"int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int len, int write, int force, struct page **pages, struct vm_area_struct **vmas) { int i; unsigned int vm_flags; if (len <= 0) return 0; /* * Require read or write permissions. * If 'force' is set, we only require the ""MAY"" flags. */ vm_flags = write ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); vm_flags &= force ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); i = 0; do { struct vm_area_struct *vma; unsigned int foll_flags; vma = find_extend_vma(mm, start); if (!vma && in_gate_area(tsk, start)) { unsigned long pg = start & PAGE_MASK; struct vm_area_struct *gate_vma = get_gate_vma(tsk); pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (write) /* user gate pages are read-only */ return i ? : -EFAULT; if (pg > TASK_SIZE) pgd = pgd_offset_k(pg); else pgd = pgd_offset_gate(mm, pg); BUG_ON(pgd_none(*pgd)); pud = pud_offset(pgd, pg); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, pg); if (pmd_none(*pmd)) return i ? : -EFAULT; pte = pte_offset_map(pmd, pg); if (pte_none(*pte)) { pte_unmap(pte); return i ? : -EFAULT; } if (pages) { struct page *page = vm_normal_page(gate_vma, start, *pte); pages[i] = page; if (page) get_page(page); } pte_unmap(pte); if (vmas) vmas[i] = gate_vma; i++; start += PAGE_SIZE; len--; continue; } if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP)) || !(vm_flags & vma->vm_flags)) return i ? : -EFAULT; if (is_vm_hugetlb_page(vma)) { i = follow_hugetlb_page(mm, vma, pages, vmas, &start, &len, i, write); continue; } foll_flags = FOLL_TOUCH; if (pages) foll_flags |= FOLL_GET; if (!write && !(vma->vm_flags & VM_LOCKED) && (!vma->vm_ops || !vma->vm_ops->fault)) foll_flags |= FOLL_ANON; do { struct page *page; /* * If tsk is ooming, cut off its access to large memory * allocations. It has a pending SIGKILL, but it can't * be processed until returning to user space. */ if (unlikely(test_tsk_thread_flag(tsk, TIF_MEMDIE))) return -ENOMEM; if (write) foll_flags |= FOLL_WRITE; cond_resched(); while (!(page = follow_page(vma, start, foll_flags))) { int ret; ret = handle_mm_fault(mm, vma, start, foll_flags & FOLL_WRITE); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return i ? i : -ENOMEM; else if (ret & VM_FAULT_SIGBUS) return i ? i : -EFAULT; BUG(); } if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; /* * The VM_FAULT_WRITE bit tells us that * do_wp_page has broken COW when necessary, * even if maybe_mkwrite decided not to set * pte_write. We can thus safely do subsequent * page lookups as if they were reads. */ if (ret & VM_FAULT_WRITE) foll_flags &= ~FOLL_WRITE; cond_resched(); } if (pages) { pages[i] = page; flush_anon_page(vma, page, start); flush_dcache_page(page); } if (vmas) vmas[i] = vma; i++; start += PAGE_SIZE; len--; } while (len && start < vma->vm_end); } while (len); return i; }",CWE-20,3 0," virtual void EnableOfflineMode(bool enable) {} ",none,24 0," virtual const WifiNetworkVector& remembered_wifi_networks() const { return remembered_wifi_networks_; } ",none,24 1,"static pj_status_t parse_query(pj_dns_parsed_query *q, pj_pool_t *pool, const pj_uint8_t *pkt, const pj_uint8_t *start, const pj_uint8_t *max, int *parsed_len) { const pj_uint8_t *p = start; int name_len, name_part_len; pj_status_t status; /* Get the length of the name */ status = get_name_len(0, pkt, start, max, &name_part_len, &name_len); if (status != PJ_SUCCESS) return status; /* Allocate memory for the name */ q->name.ptr = (char*) pj_pool_alloc(pool, name_len+4); q->name.slen = 0; /* Get the name */ status = get_name(0, pkt, start, max, &q->name); if (status != PJ_SUCCESS) return status; p = (start + name_part_len); /* Get the type */ pj_memcpy(&q->type, p, 2); q->type = pj_ntohs(q->type); p += 2; /* Get the class */ pj_memcpy(&q->dnsclass, p, 2); q->dnsclass = pj_ntohs(q->dnsclass); p += 2; *parsed_len = (int)(p - start); return PJ_SUCCESS; }",CWE-787,16 1,"void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice, int restore_index) { const Tensor& file_pattern_t = context->input(0); { const int64_t size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( ""Input 0 (file_pattern) must be a string scalar; got a tensor of "", size, ""elements"")); } const string& file_pattern = file_pattern_t.flat()(0); const Tensor& tensor_name_t = context->input(1); const string& tensor_name = tensor_name_t.flat()(restore_index); // If we cannot find a cached reader we will allocate our own. std::unique_ptr allocated_reader; const checkpoint::TensorSliceReader* reader = nullptr; if (context->slice_reader_cache()) { reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); } if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound(""Tensor name \"""", tensor_name, ""\"" not found in checkpoint files "", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(restore_index), errors::InvalidArgument(""Expected to restore a tensor of type "", DataTypeString(context->expected_output_dtype(0)), "", got a tensor of type "", DataTypeString(type), "" instead: tensor_name = "", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice) { const tstring& shape_spec = context->input(2).flat()(restore_index); if (!shape_spec.empty()) { TensorShape parsed_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( ""Shape in shape_and_slice spec does not match the shape in the "" ""save file: "", parsed_shape.DebugString(), "", save file shape: "", saved_shape.DebugString())); } } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(restore_index, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum::value: \ OP_REQUIRES(context, \ reader->CopySliceData(tensor_name, slice_to_load, \ t->flat().data()), \ errors::InvalidArgument(""Error copying slice data"")); \ break; switch (type) { TF_CALL_SAVE_RESTORE_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( ""Restoring data type "", DataTypeString(type), "" not yet supported"")); } #undef READER_COPY }",CWE-476,12 0,"void WirelessNetwork::Clear() { Network::Clear(); name_.clear(); strength_ = 0; auto_connect_ = false; favorite_ = false; } ",none,24 1,"R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) { RIOBank *bank = r_io_bank_get (io, bankid); RIOMap *map = r_io_map_get (io, mapid); r_return_val_if_fail (io && bank && map, false); RIOMapRef *mapref = _mapref_from_map (map); if (!mapref) { return false; } RIOSubMap *sm = r_io_submap_new (io, mapref); if (!sm) { free (mapref); return false; } RRBNode *entry = _find_entry_submap_node (bank, sm); if (!entry) { // no intersection with any submap, so just insert if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } bank->last_used = NULL; RIOSubMap *bd = (RIOSubMap *)entry->data; if (r_io_submap_to (bd) == r_io_submap_to (sm) && r_io_submap_from (bd) >= r_io_submap_from (sm)) { // _find_entry_submap_node guarantees, that there is no submap // prior to bd in the range of sm, so instead of deleting and inserting // we can just memcpy memcpy (bd, sm, sizeof (RIOSubMap)); free (sm); r_list_append (bank->maprefs, mapref); return true; } if (r_io_submap_from (bd) < r_io_submap_from (sm) && r_io_submap_to (sm) < r_io_submap_to (bd)) { // split bd into 2 maps => bd and bdsm RIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd); if (!bdsm) { free (sm); free (mapref); return false; } r_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1); r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); // TODO: insert and check return value, before adjusting sm size if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (bdsm); free (mapref); return false; } if (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) { r_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL); free (sm); free (bdsm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } // guaranteed intersection if (r_io_submap_from (bd) < r_io_submap_from (sm)) { r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); entry = r_rbnode_next (entry); } while (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { //delete all submaps that are completly included in sm RRBNode *next = r_rbnode_next (entry); // this can be optimized, there is no need to do search here r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); entry = next; } if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { bd = (RIOSubMap *)entry->data; r_io_submap_set_from (bd, r_io_submap_to (sm) + 1); } if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; }",CWE-125,1 1,"static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define MaxPixelChannels 32 #define ThrowTIFFException(severity,message) \ { \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity = (float *) NULL, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status = 0; MagickBooleanType more_frames; MagickStatusType status; MemoryInfo *pixel_info = (MemoryInfo *) NULL; QuantumInfo *quantum_info; QuantumType quantum_type; size_t number_pixels; ssize_t i, scanline_size, y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag = 0, bits_per_sample = 0, endian = 0, extra_samples = 0, interlace = 0, max_sample_value = 0, min_sample_value = 0, orientation = 0, pages = 0, photometric = 0, *sample_info = NULL, sample_format = 0, samples_per_pixel = 0, units = 0, value = 0; uint32 height, rows_per_strip, width; unsigned char *pixels; void *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,""rb"",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { if (exception->severity == UndefinedException) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); image=DestroyImageList(image); return((Image *) NULL); } if (exception->severity > ErrorException) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */ photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && ((bits_per_sample <= 0) || (bits_per_sample > 32))) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,""UnsupportedBitsPerPixel""); } if (samples_per_pixel > MaxPixelChannels) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,""MaximumChannelsExceeded""); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,""quantum:format"",""floating-point""); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,""tiff:photometric"",""min-is-black""); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,""tiff:photometric"",""min-is-white""); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,""tiff:photometric"",""palette""); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,""tiff:photometric"",""RGB""); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,""tiff:photometric"",""CIELAB""); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,""tiff:photometric"",""CIE Log2(L)""); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,""tiff:photometric"",""LOGLUV""); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,""tiff:photometric"",""MASK""); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,""tiff:photometric"",""separated""); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,""tiff:photometric"",""YCBCR""); break; } default: { (void) SetImageProperty(image,""tiff:photometric"",""unknown""); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),""Geometry: %ux%u"", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),""Interlace: %u"", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""Bits per sample: %u"",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""Min sample value: %u"",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""Max sample value: %u"",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),""Photometric "" ""interpretation: %s"",GetImageProperty(image,""tiff:photometric"")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),""Image depth: %.20g"", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,""tiff:endian"",""lsb""); image->endian=LSBEndian; } else { (void) SetImageProperty(image,""tiff:endian"",""msb""); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) image->colorspace=GRAYColorspace; if (photometric == PHOTOMETRIC_SEPARATED) image->colorspace=CMYKColorspace; if (photometric == PHOTOMETRIC_CIELAB) image->colorspace=LabColorspace; if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_OJPEG) && (compress_tag != COMPRESSION_JPEG)) image->colorspace=YCbCrColorspace; status=TIFFGetProfiles(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=TIFFGetProperties(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } option=GetImageOption(image_info,""tiff:exif-properties""); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetEXIFProperties(tiff,image); option=GetImageOption(image_info,""tiff:gps-properties""); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetGPSProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1)) { image->page.x=CastDoubleToLong(ceil(x_position* image->x_resolution-0.5)); image->page.y=CastDoubleToLong(ceil(y_position* image->y_resolution-0.5)); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,""CompressNotSupported""); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,""%dx%d"", horizontal,vertical); (void) SetImageProperty(image,""jpeg:sampling-factor"", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""Sampling Factors: %s"",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; #if defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: image->compression=WebPCompression; break; #endif #if defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: image->compression=ZstdCompression; break; #endif default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap = (uint16 *) NULL, *green_colormap = (uint16 *) NULL, *red_colormap = (uint16 *) NULL; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=SetImageColorspace(image,image->colorspace); status&=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } extra_samples=0; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info,sans); if (tiff_status == 1) { (void) SetImageProperty(image,""tiff:alpha"",""unspecified""); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); (void) SetImageProperty(image,""tiff:alpha"",""associated""); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,""tiff:alpha"",""unassociated""); } } } if (image->matte != MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; (void) FormatLocaleString(value,MaxTextExtent,""%u"",(unsigned int) rows_per_strip); (void) SetImageProperty(image,""tiff:rows-per-strip"",value); method=ReadStripMethod; if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; } if (TIFFIsTiled(tiff) != MagickFalse) { uint32 columns, rows; if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,""ImageIsNotTiled""); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,""WidthOrHeightExceedsLimit""); method=ReadTileMethod; } if ((photometric == PHOTOMETRIC_LOGLUV) || (compress_tag == COMPRESSION_CCITTFAX3)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); quantum_info->endian=LSBEndian; scanline_size=TIFFScanlineSize(tiff); if (scanline_size <= 0) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns* rows_per_strip); if ((double) scanline_size > 1.5*number_pixels) ThrowTIFFException(CorruptImageError,""CorruptImage""); number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels); pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32)); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; if (interlace != PLANARCONFIG_SEPARATE) { size_t pad; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class == PseudoClass) quantum_type=IndexAlphaQuantum; else quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; } if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE)) { quantum_type=RGBQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-3,0); if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); } if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); } } switch (method) { case ReadYCCKMethod: { /* Convert YCC TIFF image. */ for (y=0; y < (ssize_t) image->rows; y++) { int status; IndexPacket *indexes; PixelPacket *magick_restrict q; ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { unsigned char *p; size_t extent; ssize_t stride, strip_id; tsize_t strip_size; unsigned char *strip_pixels; /* Convert stripped TIFF image. */ extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff); strip_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*strip_pixels)); if (strip_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels)); stride=TIFFVStripSize(tiff,1); strip_id=0; p=strip_pixels; for (i=0; i < (ssize_t) samples_per_pixel; i++) { size_t rows_remaining; switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } rows_remaining=0; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (rows_remaining == 0) { strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels, TIFFStripSize(tiff)); if (strip_size == -1) break; rows_remaining=rows_per_strip; if ((y+rows_per_strip) > (ssize_t) image->rows) rows_remaining=(rows_per_strip-(y+rows_per_strip- image->rows)); p=strip_pixels; strip_id++; } (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=stride; rows_remaining--; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; } strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels); break; } case ReadTileMethod: { unsigned char *p; size_t extent; uint32 columns, rows; unsigned char *tile_pixels; /* Convert tiled TIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,""ImageIsNotTiled""); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff), TIFFTileSize(tiff)); tile_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*tile_pixels)); if (tile_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels)); for (i=0; i < (ssize_t) samples_per_pixel; i++) { switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } for (y=0; y < (ssize_t) image->rows; y+=rows) { ssize_t x; size_t rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t columns_remaining, row; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y, 0,i); if (tiff_status == -1) break; p=tile_pixels; for (row=0; row < rows_remaining; row++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,x,y+row,columns_remaining,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=TIFFTileRowSize(tiff); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i, samples_per_pixel); if (status == MagickFalse) break; } } tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *generic_info = (MemoryInfo *) NULL; uint32 *p; uint32 *pixels; /* Convert generic TIFF image. */ if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); number_pixels=(MagickSizeType) image->columns*image->rows; generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels)); if (generic_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(uint32 *) GetVirtualMemoryBlob(generic_info); tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); if (tiff_status == -1) { generic_info=RelinquishVirtualMemory(generic_info); break; } p=pixels+(image->columns*image->rows)-1; for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } generic_info=RelinquishVirtualMemory(generic_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (tiff_status == -1) { status=MagickFalse; break; } if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); TIFFReadPhotoshopLayers(image_info,image,exception); return(GetFirstImageInList(image)); }",CWE-787,16 1,"R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) { bool cfg_anal_strings = r_config_get_i (core->config, ""anal.strings""); bool emu_lazy = r_config_get_i (core->config, ""emu.lazy""); bool gp_fixed = r_config_get_i (core->config, ""anal.gpfixed""); RAnalEsil *ESIL = core->anal->esil; ut64 refptr = 0LL; const char *pcname; RAnalOp op = R_EMPTY; ut8 *buf = NULL; bool end_address_set = false; int iend; int minopsize = 4; // XXX this depends on asm->mininstrsize bool archIsArm = false; ut64 addr = core->offset; ut64 start = addr; ut64 end = 0LL; ut64 cur; if (esil_anal_stop || r_cons_is_breaked ()) { // faster ^C return; } mycore = core; if (!strcmp (str, ""?"")) { eprintf (""Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\n""); eprintf ("" aae $SS @ $S - analyze the whole section\n""); eprintf ("" aae $SS str.Hello @ $S - find references for str.Hellow\n""); eprintf ("" aaef - analyze functions discovered with esil\n""); return; } #define CHECKREF(x) ((refptr && (x) == refptr) || !refptr) if (target) { const char *expr = r_str_trim_head_ro (target); if (*expr) { refptr = ntarget = r_num_math (core->num, expr); if (!refptr) { ntarget = refptr = addr; } } else { ntarget = UT64_MAX; refptr = 0LL; } } else { ntarget = UT64_MAX; refptr = 0LL; } RAnalFunction *fcn = NULL; if (!strcmp (str, ""f"")) { fcn = r_anal_get_fcn_in (core->anal, core->offset, 0); if (fcn) { start = r_anal_function_min_addr (fcn); addr = fcn->addr; end = r_anal_function_max_addr (fcn); end_address_set = true; } } if (!end_address_set) { if (str[0] == ' ') { end = addr + r_num_math (core->num, str + 1); } else { RIOMap *map = r_io_map_get_at (core->io, addr); if (map) { end = r_io_map_end (map); } else { end = addr + core->blocksize; } } } iend = end - start; if (iend < 0) { return; } if (iend > MAX_SCAN_SIZE) { eprintf (""Warning: Not going to analyze 0x%08""PFMT64x"" bytes.\n"", (ut64)iend); return; } buf = malloc ((size_t)iend + 2); if (!buf) { perror (""malloc""); return; } esilbreak_last_read = UT64_MAX; r_io_read_at (core->io, start, buf, iend + 1); if (!ESIL) { r_core_cmd0 (core, ""aei""); ESIL = core->anal->esil; if (!ESIL) { eprintf (""ESIL not initialized\n""); return; } r_core_cmd0 (core, ""aeim""); ESIL = core->anal->esil; } const char *spname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP); if (!spname) { eprintf (""Error: No =SP defined in the reg profile.\n""); return; } EsilBreakCtx ctx = { &op, fcn, spname, r_reg_getv (core->anal->reg, spname) }; ESIL->cb.hook_reg_write = &esilbreak_reg_write; //this is necessary for the hook to read the id of analop ESIL->user = &ctx; ESIL->cb.hook_mem_read = &esilbreak_mem_read; ESIL->cb.hook_mem_write = &esilbreak_mem_write; if (fcn && fcn->reg_save_area) { r_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area); } //eprintf (""Analyzing ESIL refs from 0x%""PFMT64x"" - 0x%""PFMT64x""\n"", addr, end); // TODO: backup/restore register state before/after analysis pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC); if (!pcname || !*pcname) { eprintf (""Cannot find program counter register in the current profile.\n""); return; } esil_anal_stop = false; r_cons_break_push (cccb, core); int arch = -1; if (!strcmp (core->anal->cur->arch, ""arm"")) { switch (core->anal->cur->bits) { case 64: arch = R2_ARCH_ARM64; break; case 32: arch = R2_ARCH_ARM32; break; case 16: arch = R2_ARCH_THUMB; break; } archIsArm = true; } ut64 gp = r_config_get_i (core->config, ""anal.gp""); const char *gp_reg = NULL; if (!strcmp (core->anal->cur->arch, ""mips"")) { gp_reg = ""gp""; arch = R2_ARCH_MIPS; } const char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN); if (!sn) { eprintf (""Warning: No SN reg alias for current architecture.\n""); } r_reg_arena_push (core->anal->reg); IterCtx ictx = { start, end, fcn, NULL }; size_t i = addr - start; size_t i_old = 0; do { if (esil_anal_stop || r_cons_is_breaked ()) { break; } cur = start + i; if (!r_io_is_valid_offset (core->io, cur, 0)) { break; } #if 0 // disabled because it causes some tests to fail { RPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY); void **it; r_pvector_foreach (list, it) { RIntervalNode *node = *it; RAnalMetaItem *meta = node->data; switch (meta->type) { case R_META_TYPE_DATA: case R_META_TYPE_STRING: case R_META_TYPE_FORMAT: #if 0 { int msz = r_meta_get_size (core->anal, meta->type); i += (msz > 0)? msz: minopsize; } r_pvector_free (list); goto loopback; #elif 0 { int msz = r_meta_get_size (core->anal, meta->type); i += (msz > 0)? msz: minopsize; i--; } #else i += 4; goto repeat; #endif default: break; } } r_pvector_free (list); } #endif /* realign address if needed */ r_core_seek_arch_bits (core, cur); int opalign = core->anal->pcalign; if (opalign > 0) { cur -= (cur % opalign); } r_anal_op_fini (&op); r_asm_set_pc (core->rasm, cur); i_old = i; #if 1 if (i > iend) { goto repeat; } #endif if (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) { i += minopsize - 1; // XXX dupe in op.size below } if (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) { // i += 2 r_anal_op_fini (&op); goto repeat; } //we need to check again i because buf+i may goes beyond its boundaries //because of i+= minopsize - 1 if (op.size < 1) { i += minopsize - 1; goto repeat; } if (emu_lazy) { if (op.type & R_ANAL_OP_TYPE_REP) { i += op.size - 1; goto repeat; } switch (op.type & R_ANAL_OP_TYPE_MASK) { case R_ANAL_OP_TYPE_JMP: case R_ANAL_OP_TYPE_CJMP: case R_ANAL_OP_TYPE_CALL: case R_ANAL_OP_TYPE_RET: case R_ANAL_OP_TYPE_ILL: case R_ANAL_OP_TYPE_NOP: case R_ANAL_OP_TYPE_UJMP: case R_ANAL_OP_TYPE_IO: case R_ANAL_OP_TYPE_LEAVE: case R_ANAL_OP_TYPE_CRYPTO: case R_ANAL_OP_TYPE_CPL: case R_ANAL_OP_TYPE_SYNC: case R_ANAL_OP_TYPE_SWI: case R_ANAL_OP_TYPE_CMP: case R_ANAL_OP_TYPE_ACMP: case R_ANAL_OP_TYPE_NULL: case R_ANAL_OP_TYPE_CSWI: case R_ANAL_OP_TYPE_TRAP: i += op.size - 1; goto repeat; // those require write support case R_ANAL_OP_TYPE_PUSH: case R_ANAL_OP_TYPE_POP: i += op.size - 1; goto repeat; } } if (sn && op.type == R_ANAL_OP_TYPE_SWI) { r_strf_buffer (64); r_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS); int snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn); RSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1); if (si) { // eprintf (""0x%08""PFMT64x"" SYSCALL %-4d %s\n"", cur, snv, si->name); r_flag_set_next (core->flags, r_strf (""syscall.%s"", si->name), cur, 1); } else { //todo were doing less filtering up top because we can't match against 80 on all platforms // might get too many of this path now.. // eprintf (""0x%08""PFMT64x"" SYSCALL %d\n"", cur, snv); r_flag_set_next (core->flags, r_strf (""syscall.%d"", snv), cur, 1); } r_flag_space_set (core->flags, NULL); r_syscall_item_free (si); } const char *esilstr = R_STRBUF_SAFEGET (&op.esil); i += op.size - 1; if (R_STR_ISEMPTY (esilstr)) { goto repeat; } r_anal_esil_set_pc (ESIL, cur); r_reg_setv (core->anal->reg, pcname, cur + op.size); if (gp_fixed && gp_reg) { r_reg_setv (core->anal->reg, gp_reg, gp); } (void)r_anal_esil_parse (ESIL, esilstr); // looks like ^C is handled by esil_parse !!!! //r_anal_esil_dumpstack (ESIL); //r_anal_esil_stack_free (ESIL); switch (op.type) { case R_ANAL_OP_TYPE_LEA: // arm64 if (core->anal->cur && arch == R2_ARCH_ARM64) { if (CHECKREF (ESIL->cur)) { r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING); } } else if ((target && op.ptr == ntarget) || !target) { if (CHECKREF (ESIL->cur)) { if (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) { r_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING); } else { r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING); } } } if (cfg_anal_strings) { add_string_ref (core, op.addr, op.ptr); } break; case R_ANAL_OP_TYPE_ADD: /* TODO: test if this is valid for other archs too */ if (core->anal->cur && archIsArm) { /* This code is known to work on Thumb, ARM and ARM64 */ ut64 dst = ESIL->cur; if ((target && dst == ntarget) || !target) { if (CHECKREF (dst)) { int type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA; r_anal_xrefs_set (core->anal, cur, dst, type); } } if (cfg_anal_strings) { add_string_ref (core, op.addr, dst); } } else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) { ut64 dst = ESIL->cur; if (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) { break; } if (!strcmp (op.src[0]->reg->name, ""sp"")) { break; } if (!strcmp (op.src[0]->reg->name, ""zero"")) { break; } if ((target && dst == ntarget) || !target) { if (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) { RFlagItem *f; char *str; if (CHECKREF (dst) || CHECKREF (cur)) { r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA); if (cfg_anal_strings) { add_string_ref (core, op.addr, dst); } if ((f = r_core_flag_get_by_spaces (core->flags, dst))) { r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name); } else if ((str = is_string_at (mycore, dst, NULL))) { char *str2 = r_str_newf (""esilref: '%s'"", str); // HACK avoid format string inside string used later as format // string crashes disasm inside agf under some conditions. // https://github.com/radareorg/radare2/issues/6937 r_str_replace_char (str2, '%', '&'); r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2); free (str2); free (str); } } } } } break; case R_ANAL_OP_TYPE_LOAD: { ut64 dst = esilbreak_last_read; if (dst != UT64_MAX && CHECKREF (dst)) { if (myvalid (mycore->io, dst)) { r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA); if (cfg_anal_strings) { add_string_ref (core, op.addr, dst); } } } dst = esilbreak_last_data; if (dst != UT64_MAX && CHECKREF (dst)) { if (myvalid (mycore->io, dst)) { r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA); if (cfg_anal_strings) { add_string_ref (core, op.addr, dst); } } } } break; case R_ANAL_OP_TYPE_JMP: { ut64 dst = op.jump; if (CHECKREF (dst)) { if (myvalid (core->io, dst)) { r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE); } } } break; case R_ANAL_OP_TYPE_CALL: { ut64 dst = op.jump; if (CHECKREF (dst)) { if (myvalid (core->io, dst)) { r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL); } ESIL->old = cur + op.size; getpcfromstack (core, ESIL); } } break; case R_ANAL_OP_TYPE_UJMP: case R_ANAL_OP_TYPE_UCALL: case R_ANAL_OP_TYPE_ICALL: case R_ANAL_OP_TYPE_RCALL: case R_ANAL_OP_TYPE_IRCALL: case R_ANAL_OP_TYPE_MJMP: { ut64 dst = core->anal->esil->jump_target; if (dst == 0 || dst == UT64_MAX) { dst = r_reg_getv (core->anal->reg, pcname); } if (CHECKREF (dst)) { if (myvalid (core->io, dst)) { RAnalRefType ref = (op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL ? R_ANAL_REF_TYPE_CALL : R_ANAL_REF_TYPE_CODE; r_anal_xrefs_set (core->anal, cur, dst, ref); r_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1); // analyze function here #if 0 if (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) { eprintf (""0x%08""PFMT64x"" RCALL TO %llx\n"", cur, dst); } #endif } } } break; default: break; } r_anal_esil_stack_free (ESIL); repeat: if (!r_anal_get_block_at (core->anal, cur)) { size_t fcn_i; for (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) { if (r_anal_get_function_at (core->anal, start + fcn_i)) { i = fcn_i - 1; break; } } } if (i >= iend) { break; } } while (get_next_i (&ictx, &i)); r_list_free (ictx.bbl); r_list_free (ictx.path); r_list_free (ictx.switch_path); free (buf); ESIL->cb.hook_mem_read = NULL; ESIL->cb.hook_mem_write = NULL; ESIL->cb.hook_reg_write = NULL; ESIL->user = NULL; r_anal_op_fini (&op); r_cons_break_pop (); // restore register r_reg_arena_pop (core->anal->reg); }",CWE-416,10 1,"SWTPM_NVRAM_CheckHeader(unsigned char *data, uint32_t length, uint32_t *dataoffset, uint16_t *hdrflags, uint8_t *hdrversion, bool quiet) { blobheader *bh = (blobheader *)data; if (length < sizeof(bh)) { if (!quiet) logprintf(STDERR_FILENO, ""not enough bytes for header: %u\n"", length); return TPM_BAD_PARAMETER; } if (ntohl(bh->totlen) != length) { if (!quiet) logprintf(STDERR_FILENO, ""broken header: bh->totlen %u != %u\n"", htonl(bh->totlen), length); return TPM_BAD_PARAMETER; } if (bh->min_version > BLOB_HEADER_VERSION) { if (!quiet) logprintf(STDERR_FILENO, ""Minimum required version for the blob is %d, we "" ""only support version %d\n"", bh->min_version, BLOB_HEADER_VERSION); return TPM_BAD_VERSION; } *hdrversion = bh->version; *dataoffset = ntohs(bh->hdrsize); *hdrflags = ntohs(bh->flags); return TPM_SUCCESS; }",CWE-125,1 1,"RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) { int i; if (!bin) { return NULL; } RList *segments = r_list_newf (free); for (i = 0; i < bin->ne_header->SegCount; i++) { RBinSection *bs = R_NEW0 (RBinSection); if (!bs) { return segments; } NE_image_segment_entry *se = &bin->segment_entries[i]; bs->size = se->length; bs->vsize = se->minAllocSz ? se->minAllocSz : 64000; bs->bits = R_SYS_BITS_16; bs->is_data = se->flags & IS_DATA; bs->perm = __translate_perms (se->flags); bs->paddr = (ut64)se->offset * bin->alignment; bs->name = r_str_newf (""%s.%"" PFMT64d, se->flags & IS_MOVEABLE ? ""MOVEABLE"" : ""FIXED"", bs->paddr); bs->is_segment = true; r_list_append (segments, bs); } bin->segments = segments; return segments; }",CWE-476,12 0,"std::string Network::GetStateString() const { switch (state_) { case STATE_UNKNOWN: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNKNOWN); case STATE_IDLE: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_IDLE); case STATE_CARRIER: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CARRIER); case STATE_ASSOCIATION: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_ASSOCIATION); case STATE_CONFIGURATION: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_CONFIGURATION); case STATE_READY: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_READY); case STATE_DISCONNECT: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_DISCONNECT); case STATE_FAILURE: return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_FAILURE); case STATE_ACTIVATION_FAILURE: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_STATE_ACTIVATION_FAILURE); default: break; } return l10n_util::GetStringUTF8(IDS_CHROMEOS_NETWORK_STATE_UNRECOGNIZED); } ",none,24 0,"static ConnectionState ParseState(const std::string& state) { if (state == kStateIdle) return STATE_IDLE; if (state == kStateCarrier) return STATE_CARRIER; if (state == kStateAssociation) return STATE_ASSOCIATION; if (state == kStateConfiguration) return STATE_CONFIGURATION; if (state == kStateReady) return STATE_READY; if (state == kStateDisconnect) return STATE_DISCONNECT; if (state == kStateFailure) return STATE_FAILURE; if (state == kStateActivationFailure) return STATE_ACTIVATION_FAILURE; return STATE_UNKNOWN; } ",none,24 1,"gen_assignment(codegen_scope *s, node *tree, node *rhs, int sp, int val) { int idx; int type = nint(tree->car); switch (type) { case NODE_GVAR: case NODE_ARG: case NODE_LVAR: case NODE_IVAR: case NODE_CVAR: case NODE_CONST: case NODE_NIL: case NODE_MASGN: if (rhs) { codegen(s, rhs, VAL); pop(); sp = cursp(); } break; case NODE_COLON2: case NODE_CALL: case NODE_SCALL: /* keep evaluation order */ break; case NODE_NVAR: codegen_error(s, ""Can't assign to numbered parameter""); break; default: codegen_error(s, ""unknown lhs""); break; } tree = tree->cdr; switch (type) { case NODE_GVAR: gen_setxv(s, OP_SETGV, sp, nsym(tree), val); break; case NODE_ARG: case NODE_LVAR: idx = lv_idx(s, nsym(tree)); if (idx > 0) { if (idx != sp) { gen_move(s, idx, sp, val); } break; } else { /* upvar */ gen_setupvar(s, sp, nsym(tree)); } break; case NODE_IVAR: gen_setxv(s, OP_SETIV, sp, nsym(tree), val); break; case NODE_CVAR: gen_setxv(s, OP_SETCV, sp, nsym(tree), val); break; case NODE_CONST: gen_setxv(s, OP_SETCONST, sp, nsym(tree), val); break; case NODE_COLON2: if (sp) { gen_move(s, cursp(), sp, 0); } sp = cursp(); push(); codegen(s, tree->car, VAL); if (rhs) { codegen(s, rhs, VAL); pop(); gen_move(s, sp, cursp(), 0); } pop_n(2); idx = new_sym(s, nsym(tree->cdr)); genop_2(s, OP_SETMCNST, sp, idx); break; case NODE_CALL: case NODE_SCALL: { int noself = 0, safe = (type == NODE_SCALL), skip = 0, top, call, n = 0; mrb_sym mid = nsym(tree->cdr->car); top = cursp(); if (val || sp == cursp()) { push(); /* room for retval */ } call = cursp(); if (!tree->car) { noself = 1; push(); } else { codegen(s, tree->car, VAL); /* receiver */ } if (safe) { int recv = cursp()-1; gen_move(s, cursp(), recv, 1); skip = genjmp2_0(s, OP_JMPNIL, cursp(), val); } tree = tree->cdr->cdr->car; if (tree) { if (tree->car) { /* positional arguments */ n = gen_values(s, tree->car, VAL, (tree->cdr->car)?13:14); if (n < 0) { /* variable length */ n = 15; push(); } } if (tree->cdr->car) { /* keyword arguments */ gen_hash(s, tree->cdr->car->cdr, VAL, 0); if (n < 14) { n++; push(); } else { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } } } if (rhs) { codegen(s, rhs, VAL); pop(); } else { gen_move(s, cursp(), sp, 0); } if (val) { gen_move(s, top, cursp(), 1); } if (n < 14) { n++; } else { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } s->sp = call; if (mid == MRB_OPSYM_2(s->mrb, aref) && n == 2) { genop_1(s, OP_SETIDX, cursp()); } else { genop_3(s, noself ? OP_SSEND : OP_SEND, cursp(), new_sym(s, attrsym(s, mid)), n); } if (safe) { dispatch(s, skip); } s->sp = top; } break; case NODE_MASGN: gen_vmassignment(s, tree->car, sp, val); break; /* splat without assignment */ case NODE_NIL: break; default: codegen_error(s, ""unknown lhs""); break; } if (val) push(); }",CWE-125,1 1,"static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si) { s32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0; /*s->current_picture.reference= h->nal_ref_idc != 0;*/ gf_bs_read_ue_log(bs, ""first_mb_in_slice""); si->slice_type = gf_bs_read_ue_log(bs, ""slice_type""); if (si->slice_type > 9) return -1; pps_id = gf_bs_read_ue_log(bs, ""pps_id""); if (pps_id > 255) return -1; si->pps = &avc->pps[pps_id]; if (!si->pps->slice_group_count) return -2; si->sps = &avc->sps[si->pps->sps_id]; if (!si->sps->log2_max_frame_num) return -2; avc->sps_active_idx = si->pps->sps_id; avc->pps_active_idx = pps_id; si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, ""frame_num""); si->field_pic_flag = 0; si->bottom_field_flag = 0; if (!si->sps->frame_mbs_only_flag) { si->field_pic_flag = gf_bs_read_int_log(bs, 1, ""field_pic_flag""); if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int_log(bs, 1, ""bottom_field_flag""); } if ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag) si->idr_pic_id = gf_bs_read_ue_log(bs, ""idr_pic_id""); if (si->sps->poc_type == 0) { si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, ""poc_lsb""); if (si->pps->pic_order_present && !si->field_pic_flag) { si->delta_poc_bottom = gf_bs_read_se_log(bs, ""poc_lsb""); } } else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) { si->delta_poc[0] = gf_bs_read_se_log(bs, ""delta_poc0""); if ((si->pps->pic_order_present == 1) && !si->field_pic_flag) si->delta_poc[1] = gf_bs_read_se_log(bs, ""delta_poc1""); } if (si->pps->redundant_pic_cnt_present) { si->redundant_pic_cnt = gf_bs_read_ue_log(bs, ""redundant_pic_cnt""); } if (si->slice_type % 5 == GF_AVC_TYPE_B) { gf_bs_read_int_log(bs, 1, ""direct_spatial_mv_pred_flag""); } num_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1; num_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1; if (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) { Bool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, ""num_ref_idx_active_override_flag""); if (num_ref_idx_active_override_flag) { num_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, ""num_ref_idx_l0_active_minus1""); if (si->slice_type % 5 == GF_AVC_TYPE_B) { num_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, ""num_ref_idx_l1_active_minus1""); } } } if (si->nal_unit_type == 20 || si->nal_unit_type == 21) { //ref_pic_list_mvc_modification(); /* specified in Annex H */ GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (""[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\n"")); assert(0); return -1; } else { ref_pic_list_modification(bs, si->slice_type); } if ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP)) || (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) { pred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1); } if (si->nal_ref_idc != 0) { dec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE)); } if (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) { gf_bs_read_ue_log(bs, ""cabac_init_idc""); } /*slice_qp_delta = */gf_bs_read_se(bs); if (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) { if (si->slice_type % 5 == GF_AVC_TYPE_SP) { gf_bs_read_int_log(bs, 1, ""sp_for_switch_flag""); } gf_bs_read_se_log(bs, ""slice_qs_delta""); } if (si->pps->deblocking_filter_control_present_flag) { if (gf_bs_read_ue_log(bs, ""disable_deblocking_filter_idc"") != 1) { gf_bs_read_se_log(bs, ""slice_alpha_c0_offset_div2""); gf_bs_read_se_log(bs, ""slice_beta_offset_div2""); } } if (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) { gf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), ""slice_group_change_cycle""); } return 0; }",CWE-476,12 1,"struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev, const struct pci_device_id *ent, const struct iwl_cfg_trans_params *cfg_trans) { struct iwl_trans_pcie *trans_pcie; struct iwl_trans *trans; int ret, addr_size; ret = pcim_enable_device(pdev); if (ret) return ERR_PTR(ret); if (cfg_trans->gen2) trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, &trans_ops_pcie_gen2); else trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, &trans_ops_pcie); if (!trans) return ERR_PTR(-ENOMEM); trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); trans_pcie->trans = trans; trans_pcie->opmode_down = true; spin_lock_init(&trans_pcie->irq_lock); spin_lock_init(&trans_pcie->reg_lock); mutex_init(&trans_pcie->mutex); init_waitqueue_head(&trans_pcie->ucode_write_waitq); trans_pcie->tso_hdr_page = alloc_percpu(struct iwl_tso_hdr_page); if (!trans_pcie->tso_hdr_page) { ret = -ENOMEM; goto out_no_pci; } trans_pcie->debug_rfkill = -1; if (!cfg_trans->base_params->pcie_l1_allowed) { /* * W/A - seems to solve weird behavior. We need to remove this * if we don't want to stay in L1 all the time. This wastes a * lot of power. */ pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM); } trans_pcie->def_rx_queue = 0; if (cfg_trans->use_tfh) { addr_size = 64; trans_pcie->max_tbs = IWL_TFH_NUM_TBS; trans_pcie->tfd_size = sizeof(struct iwl_tfh_tfd); } else { addr_size = 36; trans_pcie->max_tbs = IWL_NUM_OF_TBS; trans_pcie->tfd_size = sizeof(struct iwl_tfd); } trans->max_skb_frags = IWL_PCIE_MAX_FRAGS(trans_pcie); pci_set_master(pdev); ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(addr_size)); if (!ret) ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(addr_size)); if (ret) { ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (!ret) ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)); /* both attempts failed: */ if (ret) { dev_err(&pdev->dev, ""No suitable DMA available\n""); goto out_no_pci; } } ret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME); if (ret) { dev_err(&pdev->dev, ""pcim_iomap_regions_request_all failed\n""); goto out_no_pci; } trans_pcie->hw_base = pcim_iomap_table(pdev)[0]; if (!trans_pcie->hw_base) { dev_err(&pdev->dev, ""pcim_iomap_table failed\n""); ret = -ENODEV; goto out_no_pci; } /* We disable the RETRY_TIMEOUT register (0x41) to keep * PCI Tx retries from interfering with C3 CPU state */ pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00); trans_pcie->pci_dev = pdev; iwl_disable_interrupts(trans); trans->hw_rev = iwl_read32(trans, CSR_HW_REV); if (trans->hw_rev == 0xffffffff) { dev_err(&pdev->dev, ""HW_REV=0xFFFFFFFF, PCI issues?\n""); ret = -EIO; goto out_no_pci; } /* * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have * changed, and now the revision step also includes bit 0-1 (no more * ""dash"" value). To keep hw_rev backwards compatible - we'll store it * in the old format. */ if (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000) { trans->hw_rev = (trans->hw_rev & 0xfff0) | (CSR_HW_REV_STEP(trans->hw_rev << 2) << 2); ret = iwl_pcie_prepare_card_hw(trans); if (ret) { IWL_WARN(trans, ""Exit HW not ready\n""); goto out_no_pci; } /* * in-order to recognize C step driver should read chip version * id located at the AUX bus MISC address space. */ ret = iwl_finish_nic_init(trans, cfg_trans); if (ret) goto out_no_pci; } IWL_DEBUG_INFO(trans, ""HW REV: 0x%0x\n"", trans->hw_rev); iwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans); trans->hw_id = (pdev->device << 16) + pdev->subsystem_device; snprintf(trans->hw_id_str, sizeof(trans->hw_id_str), ""PCI ID: 0x%04X:0x%04X"", pdev->device, pdev->subsystem_device); /* Initialize the wait queue for commands */ init_waitqueue_head(&trans_pcie->wait_command_queue); init_waitqueue_head(&trans_pcie->sx_waitq); if (trans_pcie->msix_enabled) { ret = iwl_pcie_init_msix_handler(pdev, trans_pcie); if (ret) goto out_no_pci; } else { ret = iwl_pcie_alloc_ict(trans); if (ret) goto out_no_pci; ret = devm_request_threaded_irq(&pdev->dev, pdev->irq, iwl_pcie_isr, iwl_pcie_irq_handler, IRQF_SHARED, DRV_NAME, trans); if (ret) { IWL_ERR(trans, ""Error allocating IRQ %d\n"", pdev->irq); goto out_free_ict; } trans_pcie->inta_mask = CSR_INI_SET_MASK; } trans_pcie->rba.alloc_wq = alloc_workqueue(""rb_allocator"", WQ_HIGHPRI | WQ_UNBOUND, 1); INIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work); #ifdef CONFIG_IWLWIFI_DEBUGFS trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED; mutex_init(&trans_pcie->fw_mon_data.mutex); #endif return trans; out_free_ict: iwl_pcie_free_ict(trans); out_no_pci: free_percpu(trans_pcie->tso_hdr_page); iwl_trans_free(trans); return ERR_PTR(ret); }",CWE-476,12 0," void Init() { VLOG(1) << ""Getting initial CrOS network info.""; UpdateSystemInfo(); } ",none,24 1,"RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) { if (!bin->entry_table) { return NULL; } RList *entries = r_list_newf (free); if (!entries) { return NULL; } RList *segments = r_bin_ne_get_segments (bin); if (!segments) { r_list_free (entries); return NULL; } if (bin->ne_header->csEntryPoint) { RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } entry->bits = 16; ut32 entry_cs = bin->ne_header->csEntryPoint; RBinSection *s = r_list_get_n (segments, entry_cs - 1); entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0); r_list_append (entries, entry); } int off = 0; size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset; while (off < bin->ne_header->EntryTableLength) { if (tableat + off >= r_buf_size (bin->buf)) { break; } ut8 bundle_length = *(ut8 *)(bin->entry_table + off); if (!bundle_length) { break; } off++; ut8 bundle_type = *(ut8 *)(bin->entry_table + off); off++; int i; for (i = 0; i < bundle_length; i++) { if (tableat + off + 4 >= r_buf_size (bin->buf)) { break; } RBinAddr *entry = R_NEW0 (RBinAddr); if (!entry) { r_list_free (entries); return NULL; } off++; if (!bundle_type) { // Skip off--; free (entry); break; } else if (bundle_type == 0xff) { // moveable off += 2; ut8 segnum = *(bin->entry_table + off); off++; ut16 segoff = *(ut16 *)(bin->entry_table + off); if (segnum > 0) { entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff; } } else { // Fixed if (bundle_type < bin->ne_header->SegCount) { entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + *(ut16 *)(bin->entry_table + off); } } off += 2; r_list_append (entries, entry); } } r_list_free (segments); bin->entries = entries; return entries; }",CWE-125,1 1,"change_indent( int type, int amount, int round, int replaced, // replaced character, put on replace stack int call_changed_bytes) // call changed_bytes() { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { orig_line = vim_strsave(ml_get_curline()); // Deal with NULL below orig_col = curwin->w_cursor.col; } // for the following tricks we don't want list mode save_p_list = curwin->w_p_list; curwin->w_p_list = FALSE; vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; // For Replace mode we need to fix the replace stack later, which is only // possible when the cursor is in the indent. Remember the number of // characters before the cursor if it's possible. start_col = curwin->w_cursor.col; // determine offset from first non-blank new_cursor_col = curwin->w_cursor.col; beginline(BL_WHITE); new_cursor_col -= curwin->w_cursor.col; insstart_less = curwin->w_cursor.col; // If the cursor is in the indent, compute how many screen columns the // cursor is to the left of the first non-blank. if (new_cursor_col < 0) vcol = get_indent() - vcol; if (new_cursor_col > 0) // can't fix replace stack start_col = -1; // Set the new indent. The cursor will be put on the first non-blank. if (type == INDENT_SET) (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); else { int save_State = State; // Avoid being called recursively. if (State & VREPLACE_FLAG) State = INSERT; shift_line(type == INDENT_DEC, round, 1, call_changed_bytes); State = save_State; } insstart_less -= curwin->w_cursor.col; // Try to put cursor on same character. // If the cursor is at or after the first non-blank in the line, // compute the cursor column relative to the column of the first // non-blank character. // If we are not in insert mode, leave the cursor on the first non-blank. // If the cursor is before the first non-blank, position it relative // to the first non-blank, counted in screen columns. if (new_cursor_col >= 0) { // When changing the indent while the cursor is touching it, reset // Insstart_col to 0. if (new_cursor_col == 0) insstart_less = MAXCOL; new_cursor_col += curwin->w_cursor.col; } else if (!(State & INSERT)) new_cursor_col = curwin->w_cursor.col; else { // Compute the screen column where the cursor should be. vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); // Advance the cursor until we reach the right screen column. vcol = last_vcol = 0; new_cursor_col = -1; ptr = ml_get_curline(); while (vcol <= (int)curwin->w_virtcol) { last_vcol = vcol; if (has_mbyte && new_cursor_col >= 0) new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col); else ++new_cursor_col; vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol); } vcol = last_vcol; // May need to insert spaces to be able to position the cursor on // the right screen column. if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; i = (int)curwin->w_virtcol - vcol; ptr = alloc(i + 1); if (ptr != NULL) { new_cursor_col += i; ptr[i] = NUL; while (--i >= 0) ptr[i] = ' '; ins_str(ptr); vim_free(ptr); } } // When changing the indent while the cursor is in it, reset // Insstart_col to 0. insstart_less = MAXCOL; } curwin->w_p_list = save_p_list; if (new_cursor_col <= 0) curwin->w_cursor.col = 0; else curwin->w_cursor.col = (colnr_T)new_cursor_col; curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); // May have to adjust the start of the insert. if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) Insstart.col = 0; else Insstart.col -= insstart_less; } if ((int)ai_col <= insstart_less) ai_col = 0; else ai_col -= insstart_less; } // For REPLACE mode, may have to fix the replace stack, if it's possible. // If the number of characters before the cursor decreased, need to pop a // few characters from the replace stack. // If the number of characters before the cursor increased, need to push a // few NULs onto the replace stack. if (REPLACE_NORMAL(State) && start_col >= 0) { while (start_col > (int)curwin->w_cursor.col) { replace_join(0); // remove a NUL from the replace stack --start_col; } while (start_col < (int)curwin->w_cursor.col || replaced) { replace_push(NUL); if (replaced) { replace_push(replaced); replaced = NUL; } ++start_col; } } // For VREPLACE mode, we also have to fix the replace stack. In this case // it is always possible because we backspace over the whole line and then // put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // If orig_line didn't allocate, just return. At least we did the job, // even if you can't backspace. if (orig_line == NULL) return; // Save new line new_line = vim_strsave(ml_get_curline()); if (new_line == NULL) return; // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; // Put back original line ml_replace(curwin->w_cursor.lnum, orig_line, FALSE); curwin->w_cursor.col = orig_col; // Backspace from cursor to start of line backspace_until_column(0); // Insert new stuff into line again ins_bytes(new_line); vim_free(new_line); } }",CWE-787,16 0," virtual void ConnectToWifiNetwork(ConnectionSecurity security, const std::string& ssid, const std::string& password, const std::string& identity, const std::string& certpath, bool auto_connect) { if (!EnsureCrosLoaded()) return; ServiceInfo* service = GetWifiService(ssid.c_str(), security); if (service) { SetAutoConnect(service->service_path, auto_connect); ConnectToNetworkWithCertInfo(service->service_path, password.empty() ? NULL : password.c_str(), identity.empty() ? NULL : identity.c_str(), certpath.empty() ? NULL : certpath.c_str()); FreeServiceInfo(service); } else { LOG(WARNING) << ""Cannot find hidden network: "" << ssid; } } ",none,24 0," virtual EthernetNetwork* ethernet_network() { return ethernet_; } ",none,24 1,"eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate) { char_u *p; char_u *end; int extra = interpolate ? 1 : 0; int off = interpolate ? 0 : 1; int len; // Find the end of the string, skipping backslashed characters. for (p = *arg + off; *p != NUL && *p != '""'; MB_PTR_ADV(p)) { if (*p == '\\' && p[1] != NUL) { ++p; // A ""\"" form occupies at least 4 characters, and produces up // to 9 characters (6 for the char and 3 for a modifier): // reserve space for 5 extra. if (*p == '<') extra += 5; } else if (interpolate && (*p == '{' || *p == '}')) { if (*p == '{' && p[1] != '{') // start of expression break; ++p; if (p[-1] == '}' && *p != '}') // single '}' is an error { semsg(_(e_stray_closing_curly_str), *arg); return FAIL; } --extra; // ""{{"" becomes ""{"", ""}}"" becomes ""}"" } } if (*p != '""' && !(interpolate && *p == '{')) { semsg(_(e_missing_double_quote_str), *arg); return FAIL; } // If only parsing, set *arg and return here if (!evaluate) { *arg = p + off; return OK; } // Copy the string into allocated memory, handling backslashed // characters. rettv->v_type = VAR_STRING; len = (int)(p - *arg + extra); rettv->vval.v_string = alloc(len); if (rettv->vval.v_string == NULL) return FAIL; end = rettv->vval.v_string; for (p = *arg + off; *p != NUL && *p != '""'; ) { if (*p == '\\') { switch (*++p) { case 'b': *end++ = BS; ++p; break; case 'e': *end++ = ESC; ++p; break; case 'f': *end++ = FF; ++p; break; case 'n': *end++ = NL; ++p; break; case 'r': *end++ = CAR; ++p; break; case 't': *end++ = TAB; ++p; break; case 'X': // hex: ""\x1"", ""\x12"" case 'x': case 'u': // Unicode: ""\u0023"" case 'U': if (vim_isxdigit(p[1])) { int n, nr; int c = toupper(*p); if (c == 'X') n = 2; else if (*p == 'u') n = 4; else n = 8; nr = 0; while (--n >= 0 && vim_isxdigit(p[1])) { ++p; nr = (nr << 4) + hex2nr(*p); } ++p; // For ""\u"" store the number according to // 'encoding'. if (c != 'X') end += (*mb_char2bytes)(nr, end); else *end++ = nr; } break; // octal: ""\1"", ""\12"", ""\123"" case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *end = *p++ - '0'; if (*p >= '0' && *p <= '7') { *end = (*end << 3) + *p++ - '0'; if (*p >= '0' && *p <= '7') *end = (*end << 3) + *p++ - '0'; } ++end; break; // Special key, e.g.: ""\"" case '<': { int flags = FSK_KEYCODE | FSK_IN_STRING; if (p[1] != '*') flags |= FSK_SIMPLIFY; extra = trans_special(&p, end, flags, FALSE, NULL); if (extra != 0) { end += extra; if (end >= rettv->vval.v_string + len) iemsg(""eval_string() used more space than allocated""); break; } } // FALLTHROUGH default: MB_COPY_CHAR(p, end); break; } } else { if (interpolate && (*p == '{' || *p == '}')) { if (*p == '{' && p[1] != '{') // start of expression break; ++p; // reduce ""{{"" to ""{"" and ""}}"" to ""}"" } MB_COPY_CHAR(p, end); } } *end = NUL; if (*p == '""' && !interpolate) ++p; *arg = p; return OK; }",CWE-125,1 0,"int64 GetInitialTemporaryStorageQuotaSize(const FilePath& path, bool is_incognito) { int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(path); UMA_HISTOGRAM_MBYTES(""Quota.FreeDiskSpaceForProfile"", free_space); if (free_space < QuotaManager::kTemporaryStorageQuotaDefaultSize * 2) return 0; if (is_incognito) return QuotaManager::kIncognitoDefaultTemporaryQuota; if (free_space < QuotaManager::kTemporaryStorageQuotaDefaultSize * 20) return QuotaManager::kTemporaryStorageQuotaDefaultSize; if (free_space < QuotaManager::kTemporaryStorageQuotaMaxSize * 20) return free_space / 20; return QuotaManager::kTemporaryStorageQuotaMaxSize; } ",none,24 0," bool AppendEntry(const TableEntry& entry) { entries_.push_back(entry); return true; } ",none,24 0,"void QuotaManager::DidGetGlobalUsageForEviction( StorageType type, int64 usage, int64 unlimited_usage) { DCHECK_EQ(type, kStorageTypeTemporary); DCHECK_GE(usage, unlimited_usage); eviction_context_.usage = usage; eviction_context_.unlimited_usage = unlimited_usage; GetTemporaryGlobalQuota(callback_factory_. NewCallback(&QuotaManager::DidGetGlobalQuotaForEviction)); } ",none,24 1,"static Image *ReadPCLImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CropBox ""CropBox"" #define DeviceCMYK ""DeviceCMYK"" #define MediaBox ""MediaBox"" #define RenderPCLText "" Rendering PCL... "" char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], *options, input_filename[MaxTextExtent]; const DelegateInfo *delegate_info; Image *image, *next_image; ImageInfo *read_info; int c; MagickBooleanType cmyk, status; PointInfo delta; RectangleInfo bounding_box, page; char *p; SegmentInfo bounds; size_t height, width; ssize_t count; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,""UnableToCreateTemporaryFile"", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); if ((flags & RhoValue) != 0) image->x_resolution=geometry_info.rho; image->y_resolution=image->x_resolution; if ((flags & SigmaValue) != 0) image->y_resolution=geometry_info.sigma; } /* Determine page geometry from the PCL media box. */ cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; count=0; (void) memset(&bounding_box,0,sizeof(bounding_box)); (void) memset(&bounds,0,sizeof(bounds)); (void) memset(&page,0,sizeof(page)); (void) memset(command,0,sizeof(command)); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if (image_info->page != (char *) NULL) continue; /* Note PCL elements. */ *p++=(char) c; if ((c != (int) '/') && (c != '\n') && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Is this a CMYK document? */ if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,""CropBox [%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,""CropBox[%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,""MediaBox [%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,""MediaBox[%lf %lf %lf %lf"", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; /* Set PCL render geometry. */ width=(size_t) floor(bounds.x2-bounds.x1+0.5); height=(size_t) floor(bounds.y2-bounds.y1+0.5); if (width > page.width) page.width=width; if (height > page.height) page.height=height; } (void) CloseBlob(image); /* Render PCL with the GhostPCL delegate. */ if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); (void) FormatLocaleString(geometry,MaxTextExtent,""%.20gx%.20g"",(double) page.width,(double) page.height); if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo(""pcl:mono"",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo(""pcl:cmyk"",(char *) NULL,exception); else delegate_info=GetDelegateInfo(""pcl:color"",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { image=DestroyImage(image); return((Image *) NULL); } if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); density=AcquireString(""""); options=AcquireString(""""); (void) FormatLocaleString(density,MaxTextExtent,""%gx%g"", image->x_resolution,image->y_resolution); if (image_info->ping != MagickFalse) (void) FormatLocaleString(density,MagickPathExtent,""2.0x2.0""); page.width=(size_t) floor((double) page.width*image->x_resolution/delta.x+ 0.5); page.height=(size_t) floor((double) page.height*image->y_resolution/delta.y+ 0.5); (void) FormatLocaleString(options,MaxTextExtent,""-g%.20gx%.20g "",(double) page.width,(double) page.height); image=DestroyImage(image); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { if (read_info->number_scenes != 1) (void) FormatLocaleString(options,MaxTextExtent,""-dLastPage=%.20g"", (double) (read_info->scene+read_info->number_scenes)); else (void) FormatLocaleString(options,MaxTextExtent, ""-dFirstPage=%.20g -dLastPage=%.20g"",(double) read_info->scene+1, (double) (read_info->scene+read_info->number_scenes)); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options, read_info->filename,input_filename); options=DestroyString(options); density=DestroyString(density); status=ExternalDelegateCommand(MagickFalse,read_info->verbose,command, (char *) NULL,exception) != 0 ? MagickTrue : MagickFalse; image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); (void) RelinquishUniqueFileResource(input_filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) ThrowReaderException(DelegateError,""PCLDelegateFailed""); if (LocaleCompare(image->magick,""BMP"") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(image,&image->exception); if (cmyk_image != (Image *) NULL) { image=DestroyImageList(image); image=cmyk_image; } } do { (void) CopyMagickString(image->filename,filename,MaxTextExtent); image->page=page; if (image_info->ping != MagickFalse) { image->magick_columns*=image->x_resolution/2.0; image->magick_rows*=image->y_resolution/2.0; image->columns*=image->x_resolution/2.0; image->rows*=image->y_resolution/2.0; } next_image=SyncNextImageInList(image); if (next_image != (Image *) NULL) image=next_image; } while (next_image != (Image *) NULL); return(GetFirstImageInList(image)); }",CWE-190,2 0," GlobalUsageCallback* NewWaitableGlobalUsageCallback() { ++waiting_callbacks_; return callback_factory_.NewCallback( &UsageAndQuotaDispatcherTask::DidGetGlobalUsage); } ",none,24 0," virtual bool offline_mode() const { return false; } ",none,24 1,"static MagickBooleanType SetGrayscaleImage(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo *colormap; register ssize_t i; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace,exception); if (image->storage_class == PseudoClass) colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1, sizeof(*colormap_index)); else colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); if (image->storage_class != PseudoClass) { (void) memset(colormap_index,(-1),MaxColormapSize* sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); } image->colors=0; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(image,q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=(double) GetPixelRed(image,q); image->colormap[image->colors].green=(double) GetPixelGreen(image,q); image->colormap[image->colors].blue=(double) GetPixelBlue(image,q); image->colors++; } } SetPixelIndex(image,(Quantum) colormap_index[intensity],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].alpha=(double) i; qsort((void *) image->colormap,image->colors,sizeof(PixelInfo), IntensityCompare); colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap)); if (colormap == (PixelInfo *) NULL) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); } j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].alpha]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap( GetPixelIndex(image,q))],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,exception) != MagickFalse) image->type=BilevelType; return(status); }",CWE-125,1 0," virtual void RemoveNetworkManagerObserver(NetworkManagerObserver* observer) {} ",none,24 1,"setup_seccomp (FlatpakBwrap *bwrap, const char *arch, gulong allowed_personality, FlatpakRunFlags run_flags, GError **error) { gboolean multiarch = (run_flags & FLATPAK_RUN_FLAG_MULTIARCH) != 0; gboolean devel = (run_flags & FLATPAK_RUN_FLAG_DEVEL) != 0; __attribute__((cleanup (cleanup_seccomp))) scmp_filter_ctx seccomp = NULL; /**** BEGIN NOTE ON CODE SHARING * * There are today a number of different Linux container * implementations. That will likely continue for long into the * future. But we can still try to share code, and it's important * to do so because it affects what library and application writers * can do, and we should support code portability between different * container tools. * * This syscall blocklist is copied from linux-user-chroot, which was in turn * clearly influenced by the Sandstorm.io blocklist. * * If you make any changes here, I suggest sending the changes along * to other sandbox maintainers. Using the libseccomp list is also * an appropriate venue: * https://groups.google.com/forum/#!forum/libseccomp * * A non-exhaustive list of links to container tooling that might * want to share this blocklist: * * https://github.com/sandstorm-io/sandstorm * in src/sandstorm/supervisor.c++ * https://github.com/flatpak/flatpak.git * in common/flatpak-run.c * https://git.gnome.org/browse/linux-user-chroot * in src/setup-seccomp.c * **** END NOTE ON CODE SHARING */ struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_blocklist[] = { /* Block dmesg */ {SCMP_SYS (syslog), EPERM}, /* Useless old syscall */ {SCMP_SYS (uselib), EPERM}, /* Don't allow disabling accounting */ {SCMP_SYS (acct), EPERM}, /* 16-bit code is unnecessary in the sandbox, and modify_ldt is a historic source of interesting information leaks. */ {SCMP_SYS (modify_ldt), EPERM}, /* Don't allow reading current quota use */ {SCMP_SYS (quotactl), EPERM}, /* Don't allow access to the kernel keyring */ {SCMP_SYS (add_key), EPERM}, {SCMP_SYS (keyctl), EPERM}, {SCMP_SYS (request_key), EPERM}, /* Scary VM/NUMA ops */ {SCMP_SYS (move_pages), EPERM}, {SCMP_SYS (mbind), EPERM}, {SCMP_SYS (get_mempolicy), EPERM}, {SCMP_SYS (set_mempolicy), EPERM}, {SCMP_SYS (migrate_pages), EPERM}, /* Don't allow subnamespace setups: */ {SCMP_SYS (unshare), EPERM}, {SCMP_SYS (mount), EPERM}, {SCMP_SYS (pivot_root), EPERM}, #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__) /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack * and flags arguments are reversed so the flags come second */ {SCMP_SYS (clone), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #else /* Normally the flags come first */ {SCMP_SYS (clone), EPERM, &SCMP_A0 (SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER)}, #endif /* Don't allow faking input to the controlling tty (CVE-2017-5226) */ {SCMP_SYS (ioctl), EPERM, &SCMP_A1 (SCMP_CMP_MASKED_EQ, 0xFFFFFFFFu, (int) TIOCSTI)}, }; struct { int scall; int errnum; struct scmp_arg_cmp *arg; } syscall_nondevel_blocklist[] = { /* Profiling operations; we expect these to be done by tools from outside * the sandbox. In particular perf has been the source of many CVEs. */ {SCMP_SYS (perf_event_open), EPERM}, /* Don't allow you to switch to bsd emulation or whatnot */ {SCMP_SYS (personality), EPERM, &SCMP_A0 (SCMP_CMP_NE, allowed_personality)}, {SCMP_SYS (ptrace), EPERM} }; /* Blocklist all but unix, inet, inet6 and netlink */ struct { int family; FlatpakRunFlags flags_mask; } socket_family_allowlist[] = { /* NOTE: Keep in numerical order */ { AF_UNSPEC, 0 }, { AF_LOCAL, 0 }, { AF_INET, 0 }, { AF_INET6, 0 }, { AF_NETLINK, 0 }, { AF_CAN, FLATPAK_RUN_FLAG_CANBUS }, { AF_BLUETOOTH, FLATPAK_RUN_FLAG_BLUETOOTH }, }; int last_allowed_family; int i, r; g_auto(GLnxTmpfile) seccomp_tmpf = { 0, }; seccomp = seccomp_init (SCMP_ACT_ALLOW); if (!seccomp) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Initialize seccomp failed"")); if (arch != NULL) { uint32_t arch_id = 0; const uint32_t *extra_arches = NULL; if (strcmp (arch, ""i386"") == 0) { arch_id = SCMP_ARCH_X86; } else if (strcmp (arch, ""x86_64"") == 0) { arch_id = SCMP_ARCH_X86_64; extra_arches = seccomp_x86_64_extra_arches; } else if (strcmp (arch, ""arm"") == 0) { arch_id = SCMP_ARCH_ARM; } #ifdef SCMP_ARCH_AARCH64 else if (strcmp (arch, ""aarch64"") == 0) { arch_id = SCMP_ARCH_AARCH64; extra_arches = seccomp_aarch64_extra_arches; } #endif /* We only really need to handle arches on multiarch systems. * If only one arch is supported the default is fine */ if (arch_id != 0) { /* This *adds* the target arch, instead of replacing the native one. This is not ideal, because we'd like to only allow the target arch, but we can't really disallow the native arch at this point, because then bubblewrap couldn't continue running. */ r = seccomp_arch_add (seccomp, arch_id); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add architecture to seccomp filter"")); if (multiarch && extra_arches != NULL) { for (i = 0; extra_arches[i] != 0; i++) { r = seccomp_arch_add (seccomp, extra_arches[i]); if (r < 0 && r != -EEXIST) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to add multiarch architecture to seccomp filter"")); } } } } /* TODO: Should we filter the kernel keyring syscalls in some way? * We do want them to be used by desktop apps, but they could also perhaps * leak system stuff or secrets from other apps. */ for (i = 0; i < G_N_ELEMENTS (syscall_blocklist); i++) { int scall = syscall_blocklist[i].scall; int errnum = syscall_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } if (!devel) { for (i = 0; i < G_N_ELEMENTS (syscall_nondevel_blocklist); i++) { int scall = syscall_nondevel_blocklist[i].scall; int errnum = syscall_nondevel_blocklist[i].errnum; g_return_val_if_fail (errnum == EPERM || errnum == ENOSYS, FALSE); if (syscall_nondevel_blocklist[i].arg) r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 1, *syscall_nondevel_blocklist[i].arg); else r = seccomp_rule_add (seccomp, SCMP_ACT_ERRNO (errnum), scall, 0); if (r < 0 && r == -EFAULT /* unknown syscall */) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to block syscall %d""), scall); } } /* Socket filtering doesn't work on e.g. i386, so ignore failures here * However, we need to user seccomp_rule_add_exact to avoid libseccomp doing * something else: https://github.com/seccomp/libseccomp/issues/8 */ last_allowed_family = -1; for (i = 0; i < G_N_ELEMENTS (socket_family_allowlist); i++) { int family = socket_family_allowlist[i].family; int disallowed; if (socket_family_allowlist[i].flags_mask != 0 && (socket_family_allowlist[i].flags_mask & run_flags) != socket_family_allowlist[i].flags_mask) continue; for (disallowed = last_allowed_family + 1; disallowed < family; disallowed++) { /* Blocklist the in-between valid families */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_EQ, disallowed)); } last_allowed_family = family; } /* Blocklist the rest */ seccomp_rule_add_exact (seccomp, SCMP_ACT_ERRNO (EAFNOSUPPORT), SCMP_SYS (socket), 1, SCMP_A0 (SCMP_CMP_GE, last_allowed_family + 1)); if (!glnx_open_anonymous_tmpfile_full (O_RDWR | O_CLOEXEC, ""/tmp"", &seccomp_tmpf, error)) return FALSE; if (seccomp_export_bpf (seccomp, seccomp_tmpf.fd) != 0) return flatpak_fail_error (error, FLATPAK_ERROR_SETUP_FAILED, _(""Failed to export bpf"")); lseek (seccomp_tmpf.fd, 0, SEEK_SET); flatpak_bwrap_add_args_data_fd (bwrap, ""--seccomp"", glnx_steal_fd (&seccomp_tmpf.fd), NULL); return TRUE; }",CWE-20,3 1,"static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id) { int i; unsigned long h; h = id->iface; h = MULTIPLIER * h + id->device; h = MULTIPLIER * h + id->subdevice; for (i = 0; id->name[i] && i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN; i++) h = MULTIPLIER * h + id->name[i]; h = MULTIPLIER * h + id->index; h &= LONG_MAX; return h; }",CWE-125,1 0,"UsageTracker* QuotaManager::GetUsageTracker(StorageType type) const { switch (type) { case kStorageTypeTemporary: return temporary_usage_tracker_.get(); case kStorageTypePersistent: return persistent_usage_tracker_.get(); default: NOTREACHED(); } return NULL; } ",none,24 1," void Compute(OpKernelContext* context) override { // Here's the basic idea: // Batch and depth dimension are independent from row and col dimension. And // because FractionalAvgPool currently only support pooling along row and // col, we can basically think of this 4D tensor backpropagation as // operation of a series of 2D planes. // // For each element of a 'slice' (2D plane) of output_backprop, we need to // figure out its contributors when doing FractionalAvgPool operation. This // can be done based on row_pooling_sequence, col_pooling_seq and // overlapping. // Once we figure out the original contributors, we just need to evenly // divide the value of this element among these contributors. // // Internally, we divide the out_backprop tensor and store it in a temporary // tensor of double type. And cast it to the corresponding type. typedef Eigen::Map> ConstEigenMatrixMap; typedef Eigen::Map> EigenDoubleMatrixMap; // Grab the inputs. const Tensor& orig_input_tensor_shape = context->input(0); OP_REQUIRES(context, orig_input_tensor_shape.dims() == 1 && orig_input_tensor_shape.NumElements() == 4, errors::InvalidArgument(""original input tensor shape must be"" ""1-dimensional and 4 elements"")); const Tensor& out_backprop = context->input(1); const Tensor& row_seq_tensor = context->input(2); const Tensor& col_seq_tensor = context->input(3); const int64_t out_batch = out_backprop.dim_size(0); const int64_t out_rows = out_backprop.dim_size(1); const int64_t out_cols = out_backprop.dim_size(2); const int64_t out_depth = out_backprop.dim_size(3); OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows, errors::InvalidArgument(""Given out_backprop shape "", out_backprop.shape().DebugString(), "", row_seq_tensor must have at least "", out_rows + 1, "" elements, but got "", row_seq_tensor.NumElements())); OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols, errors::InvalidArgument(""Given out_backprop shape "", out_backprop.shape().DebugString(), "", col_seq_tensor must have at least "", out_cols + 1, "" elements, but got "", col_seq_tensor.NumElements())); auto row_seq_tensor_flat = row_seq_tensor.flat(); auto col_seq_tensor_flat = col_seq_tensor.flat(); auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat(); const int64_t in_batch = orig_input_tensor_shape_flat(0); const int64_t in_rows = orig_input_tensor_shape_flat(1); const int64_t in_cols = orig_input_tensor_shape_flat(2); const int64_t in_depth = orig_input_tensor_shape_flat(3); constexpr int tensor_in_and_out_dims = 4; // Transform orig_input_tensor_shape into TensorShape TensorShape in_shape; for (auto i = 0; i < tensor_in_and_out_dims; ++i) { in_shape.AddDim(orig_input_tensor_shape_flat(i)); } // Create intermediate in_backprop. Tensor in_backprop_tensor_temp; OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp( {0}, DataTypeToEnum::v(), in_shape, &in_backprop_tensor_temp)); in_backprop_tensor_temp.flat().setZero(); // Transform 4D tensor to 2D matrix. EigenDoubleMatrixMap in_backprop_tensor_temp_mat( in_backprop_tensor_temp.flat().data(), in_depth, in_cols * in_rows * in_batch); ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(), out_depth, out_cols * out_rows * out_batch); // Loop through each element of out_backprop and evenly distribute the // element to the corresponding pooling cell. const int64_t in_max_row_index = in_rows - 1; const int64_t in_max_col_index = in_cols - 1; for (int64_t b = 0; b < out_batch; ++b) { for (int64_t r = 0; r < out_rows; ++r) { const int64_t in_row_start = row_seq_tensor_flat(r); int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1) : row_seq_tensor_flat(r + 1) - 1; in_row_end = std::min(in_row_end, in_max_row_index); for (int64_t c = 0; c < out_cols; ++c) { const int64_t in_col_start = col_seq_tensor_flat(c); int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1) : col_seq_tensor_flat(c + 1) - 1; in_col_end = std::min(in_col_end, in_max_col_index); const int64_t num_elements_in_pooling_cell = (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1); const int64_t out_index = (b * out_rows + r) * out_cols + c; // Now we can evenly distribute out_backprop(b, h, w, *) to // in_backprop(b, hs:he, ws:we, *). for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) { for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) { const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c; // Walk through each channel (depth). for (int64_t d = 0; d < out_depth; ++d) { const double out_backprop_element = static_cast( out_backprop_mat.coeffRef(d, out_index)); double& in_backprop_ref = in_backprop_tensor_temp_mat.coeffRef(d, in_index); in_backprop_ref += out_backprop_element / num_elements_in_pooling_cell; } } } } } } // Depending on the type, cast double to type T. Tensor* in_backprop_tensor = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 0, in_shape, &in_backprop_tensor)); auto in_backprop_tensor_flat = in_backprop_tensor->flat(); auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat(); for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) { in_backprop_tensor_flat(i) = static_cast(in_backprop_tensor_temp_flat(i)); } }",CWE-476,12 1,"cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF((""section len: %u properties %u\n"", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF((""short info (no type)_\n"")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF((""%"" SIZE_T_FORMAT ""u) id=%#x type=%#x offs=%#tx,%#x\n"", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF((""missing CDF_VECTOR length\n"")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF((""CDF_VECTOR with nelements == 0\n"")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF((""nelements = %"" SIZE_T_FORMAT ""u\n"", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF((""o=%"" SIZE_T_FORMAT ""u l=%d(%"" SIZE_T_FORMAT ""u), t=%"" SIZE_T_FORMAT ""u s=%s\n"", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF((""Don't know how to deal with %#x\n"", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; }",CWE-787,16 0,"void QuotaManager::DidGetPersistentGlobalUsageForHistogram( StorageType type, int64 usage, int64 unlimited_usage) { UMA_HISTOGRAM_MBYTES(""Quota.GlobalUsageOfPersistentStorage"", usage); std::set origins; GetCachedOrigins(type, &origins); size_t num_origins = origins.size(); size_t protected_origins = 0; size_t unlimited_origins = 0; CountOriginType(origins, special_storage_policy_, &protected_origins, &unlimited_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfPersistentStorageOrigins"", num_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfProtectedPersistentStorageOrigins"", protected_origins); UMA_HISTOGRAM_COUNTS(""Quota.NumberOfUnlimitedPersistentStorageOrigins"", unlimited_origins); } ",none,24 1,"void Node::RunForwardTypeInference() { VLOG(4) << ""Forward type inference: "" << props_->node_def.DebugString(); if (props_->fwd_type_fn == nullptr) { return; } std::vector input_nodes(props_->input_types.size(), nullptr); std::vector input_idx(props_->input_types.size(), 0); for (const auto& edge : in_edges_) { if (edge->IsControlEdge()) { continue; } DCHECK(edge->dst_input() < input_nodes.size()) << DebugString(); int i = edge->dst_input(); input_nodes.at(i) = edge->src(); input_idx.at(i) = edge->src_output(); } // Note: technically, we could use a very generic type when some of the inputs // are unknown. But there is an expectation that a node will have complete // inputs soon, so updating intermediate types is largely unnecessary. for (const auto* node : input_nodes) { if (node == nullptr) { // Incomplete inputs, bail. ClearTypeInfo(); return; } } static FullTypeDef* no_type = new FullTypeDef(); std::vector> input_types; for (int i = 0; i < input_nodes.size(); i++) { const auto* node = input_nodes[i]; if (node->def().has_experimental_type()) { const auto& node_t = node->def().experimental_type(); if (node_t.type_id() != TFT_UNSET) { int ix = input_idx[i]; DCHECK(ix < node_t.args_size()) << ""input "" << i << "" should have an output "" << ix << "" but instead only has "" << node_t.args_size() << "" outputs: "" << node_t.DebugString(); input_types.emplace_back(node_t.args(ix)); } else { input_types.emplace_back(*no_type); } } else { // Incomplete inputs, bail. ClearTypeInfo(); return; } } const auto infer_type = props_->fwd_type_fn(input_types); const FullTypeDef infer_typedef = infer_type.ValueOrDie(); if (infer_typedef.type_id() != TFT_UNSET) { MaybeCopyOnWrite(); *(props_->node_def.mutable_experimental_type()) = infer_typedef; } }",CWE-125,1 1,"static int string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type, int raw, RBinSection *section) { RBin *bin = bf->rbin; ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; // if list is null it means its gonna dump r_return_val_if_fail (bf, -1); if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from == to) { return 0; } if (from > to) { eprintf (""Invalid range to find strings 0x%""PFMT64x"" .. 0x%""PFMT64x""\n"", from, to); return -1; } st64 len = (st64)(to - from); if (len < 1 || len > ST32_MAX) { eprintf (""String scan range is invalid (%""PFMT64d"" bytes)\n"", len); return -1; } ut8 *buf = calloc (len, 1); if (!buf || !min) { free (buf); return -1; } st64 vdelta = 0, pdelta = 0; RBinSection *s = NULL; bool ascii_only = false; PJ *pj = NULL; if (bf->strmode == R_MODE_JSON && !list) { pj = pj_new (); if (pj) { pj_a (pj); } } r_buf_read_at (bf->buf, from, buf, len); char *charset = r_sys_getenv (""RABIN2_CHARSET""); if (!R_STR_ISEMPTY (charset)) { RCharset *ch = r_charset_new (); if (r_charset_use (ch, charset)) { int outlen = len * 4; ut8 *out = calloc (len, 4); if (out) { int res = r_charset_encode_str (ch, out, outlen, buf, len); int i; // TODO unknown chars should be translated to null bytes for (i = 0; i < res; i++) { if (out[i] == '?') { out[i] = 0; } } len = res; free (buf); buf = out; } else { eprintf (""Cannot allocate\n""); } } else { eprintf (""Invalid value for RABIN2_CHARSET.\n""); } r_charset_free (ch); } free (charset); RConsIsBreaked is_breaked = (bin && bin->consb.is_breaked)? bin->consb.is_breaked: NULL; // may oobread while (needle < to) { if (is_breaked && is_breaked ()) { break; } // smol optimization if (needle + 4 < to) { ut32 n1 = r_read_le32 (buf + needle - from); if (!n1) { needle += 4; continue; } } rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } bool addr_aligned = !(needle % 4); if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if (((to - needle) > 8 + rc)) { // TODO: support le and be bool is_wide32le = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]); // reduce false positives if (is_wide32le) { if (!w[5] && !w[6] && w[7] && w[8]) { is_wide32le = false; } } if (!addr_aligned) { is_wide32le = false; } ///is_wide32be &= (n1 < 0xff && n11 < 0xff); // false; // n11 < 0xff; if (is_wide32le && addr_aligned) { str_type = R_STRING_TYPE_WIDE32; // asume big endian,is there little endian w32? } else { // bool is_wide = (n1 && n2 && n1 < 0xff && (!n2 || n2 < 0xff)); bool is_wide = needle + rc + 4 < to && !w[0] && w[1] && !w[2] && w[3] && !w[4]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { if (rc > 1) { str_type = R_STRING_TYPE_UTF8; // could be charset if set :? } else { str_type = R_STRING_TYPE_ASCII; } } } else if (type == R_STRING_TYPE_UTF8) { str_type = R_STRING_TYPE_ASCII; // initial assumption } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (i = 0; i < sizeof (tmp) - 4 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc || (ascii_only && r > 0x7f)) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (tmp + i, r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr (""\b\v\f\n\r\t\a\033\\"", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = "" abtnvfr e "" "" "" "" "" "" \\""[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes < min && runes >= 2 && str_type == R_STRING_TYPE_ASCII && needle < to) { // back up past the \0 to the last char just in case it starts a wide string needle -= 2; } if (runes >= min) { // reduce false positives int j, num_blocks, *block_list; int *freq_list = NULL, expected_ascii, actual_ascii, num_chars; if (str_type == R_STRING_TYPE_ASCII) { for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } switch (str_type) { case R_STRING_TYPE_UTF8: case R_STRING_TYPE_WIDE: case R_STRING_TYPE_WIDE32: num_blocks = 0; block_list = r_utf_block_list ((const ut8*)tmp, i - 1, str_type == R_STRING_TYPE_WIDE? &freq_list: NULL); if (block_list) { for (j = 0; block_list[j] != -1; j++) { num_blocks++; } } if (freq_list) { num_chars = 0; actual_ascii = 0; for (j = 0; freq_list[j] != -1; j++) { num_chars += freq_list[j]; if (!block_list[j]) { // ASCII actual_ascii = freq_list[j]; } } free (freq_list); expected_ascii = num_blocks ? num_chars / num_blocks : 0; if (actual_ascii > expected_ascii) { ascii_only = true; needle = str_start; free (block_list); continue; } } free (block_list); if (num_blocks > R_STRING_MAX_UNI_BLOCKS) { needle++; continue; } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start - from > 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start - from > 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } if (!s) { if (section) { s = section; } else if (bf->o) { s = r_bin_get_section_at (bf->o, str_start, false); } if (s) { vdelta = s->vaddr; pdelta = s->paddr; } } ut64 baddr = bf->loadaddr && bf->o? bf->o->baddr: bf->loadaddr; bs->paddr = str_start + baddr; bs->vaddr = str_start - pdelta + vdelta + baddr; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); if (bf->o) { ht_up_insert (bf->o->strings_db, bs->vaddr, bs); } } else { print_string (bf, bs, raw, pj); r_bin_string_free (bs); } if (from == 0 && to == bf->size) { /* force lookup section at the next one */ s = NULL; } } ascii_only = false; } free (buf); if (pj) { pj_end (pj); if (bin) { RIO *io = bin->iob.io; if (io) { io->cb_printf (""%s"", pj_string (pj)); } } pj_free (pj); } return count; }",CWE-125,1 0," OriginDataDeleter(QuotaManager* manager, const GURL& origin, StorageType type, StatusCallback* callback) : QuotaTask(manager), origin_(origin), type_(type), error_count_(0), remaining_clients_(-1), callback_(callback), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {} ",none,24 0," void DumpOriginInfoTable() { origin_info_entries_.clear(); quota_manager_->DumpOriginInfoTable( callback_factory_.NewCallback( &QuotaManagerTest::DidDumpOriginInfoTable)); } ",none,24 0," virtual bool ethernet_connecting() const { return false; } ",none,24 0,"void QuotaManager::NotifyStorageAccessedInternal( QuotaClient::ID client_id, const GURL& origin, StorageType type, base::Time accessed_time) { LazyInitialize(); if (type == kStorageTypeTemporary && lru_origin_callback_.get()) { access_notified_origins_.insert(origin); } if (db_disabled_) return; make_scoped_refptr(new UpdateAccessTimeTask( this, origin, type, accessed_time))->Start(); } ",none,24 0,"void QuotaManager::NotifyStorageModifiedInternal( QuotaClient::ID client_id, const GURL& origin, StorageType type, int64 delta, base::Time modified_time) { LazyInitialize(); GetUsageTracker(type)->UpdateUsageCache(client_id, origin, delta); make_scoped_refptr(new UpdateModifiedTimeTask( this, origin, type, modified_time))->Start(); } ",none,24 0," virtual bool cellular_connecting() const { return cellular_ ? cellular_->connecting() : false; } ",none,24 0," void InitTestData() { ethernet_ = new EthernetNetwork(); ethernet_->set_connected(true); ethernet_->set_service_path(""eth1""); STLDeleteElements(&wifi_networks_); wifi_networks_.clear(); WifiNetwork* wifi1 = new WifiNetwork(); wifi1->set_service_path(""fw1""); wifi1->set_name(""Fake Wifi 1""); wifi1->set_strength(90); wifi1->set_connected(false); wifi1->set_encryption(SECURITY_NONE); wifi_networks_.push_back(wifi1); WifiNetwork* wifi2 = new WifiNetwork(); wifi2->set_service_path(""fw2""); wifi2->set_name(""Fake Wifi 2""); wifi2->set_strength(70); wifi2->set_connected(true); wifi2->set_encryption(SECURITY_WEP); wifi_networks_.push_back(wifi2); WifiNetwork* wifi3 = new WifiNetwork(); wifi3->set_service_path(""fw3""); wifi3->set_name(""Fake Wifi 3""); wifi3->set_strength(50); wifi3->set_connected(false); wifi3->set_encryption(SECURITY_WEP); wifi_networks_.push_back(wifi3); wifi_ = wifi2; STLDeleteElements(&cellular_networks_); cellular_networks_.clear(); CellularNetwork* cellular1 = new CellularNetwork(); cellular1->set_service_path(""fc1""); cellular1->set_name(""Fake Cellular 1""); cellular1->set_strength(70); cellular1->set_connected(true); cellular1->set_activation_state(ACTIVATION_STATE_PARTIALLY_ACTIVATED); cellular1->set_payment_url(std::string(""http://www.google.com"")); cellular_networks_.push_back(cellular1); cellular_ = cellular1; remembered_wifi_networks_.clear(); remembered_wifi_networks_.push_back(new WifiNetwork(*wifi2)); int devices = (1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | (1 << TYPE_CELLULAR); available_devices_ = devices; enabled_devices_ = devices; connected_devices_ = devices; offline_mode_ = false; } ",none,24 0,"std::string CellularNetwork::ActivationStateToString( ActivationState activation_state) { switch (activation_state) { case ACTIVATION_STATE_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATED); break; case ACTIVATION_STATE_ACTIVATING: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_ACTIVATING); break; case ACTIVATION_STATE_NOT_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_NOT_ACTIVATED); break; case ACTIVATION_STATE_PARTIALLY_ACTIVATED: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_PARTIALLY_ACTIVATED); break; default: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ACTIVATION_STATE_UNKNOWN); break; } } ",none,24 1,"static int prealloc_elems_and_freelist(struct bpf_stack_map *smap) { u32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size; int err; smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries, smap->map.numa_node); if (!smap->elems) return -ENOMEM; err = pcpu_freelist_init(&smap->freelist); if (err) goto free_elems; pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size, smap->map.max_entries); return 0; free_elems: bpf_map_area_free(smap->elems); return err; }",CWE-787,16 0," void EnableNetworkDeviceType(ConnectionType device, bool enable) { if (!EnsureCrosLoaded()) return; if (enable && (enabled_devices_ & (1 << device))) { LOG(WARNING) << ""Trying to enable a device that's already enabled: "" << device; return; } if (!enable && !(enabled_devices_ & (1 << device))) { LOG(WARNING) << ""Trying to disable a device that's already disabled: "" << device; return; } EnableNetworkDevice(device, enable); } ",none,24 1,"static int MqttClient_WaitType(MqttClient *client, void *packet_obj, byte wait_type, word16 wait_packet_id, int timeout_ms) { int rc; word16 packet_id; MqttPacketType packet_type; #ifdef WOLFMQTT_MULTITHREAD MqttPendResp *pendResp; int readLocked; #endif MqttMsgStat* mms_stat; int waitMatchFound; if (client == NULL || packet_obj == NULL) { return MQTT_CODE_ERROR_BAD_ARG; } /* all packet type structures must have MqttMsgStat at top */ mms_stat = (MqttMsgStat*)packet_obj; wait_again: /* initialize variables */ packet_id = 0; packet_type = MQTT_PACKET_TYPE_RESERVED; #ifdef WOLFMQTT_MULTITHREAD pendResp = NULL; readLocked = 0; #endif waitMatchFound = 0; #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""MqttClient_WaitType: Type %s (%d), ID %d"", MqttPacket_TypeDesc((MqttPacketType)wait_type), wait_type, wait_packet_id); #endif switch ((int)*mms_stat) { case MQTT_MSG_BEGIN: { #ifdef WOLFMQTT_MULTITHREAD /* Lock recv socket mutex */ rc = wm_SemLock(&client->lockRecv); if (rc != 0) { PRINTF(""MqttClient_WaitType: recv lock error!""); return rc; } readLocked = 1; #endif /* reset the packet state */ client->packet.stat = MQTT_PK_BEGIN; } FALL_THROUGH; #ifdef WOLFMQTT_V5 case MQTT_MSG_AUTH: #endif case MQTT_MSG_WAIT: { #ifdef WOLFMQTT_MULTITHREAD /* Check to see if packet type and id have already completed */ pendResp = NULL; rc = wm_SemLock(&client->lockClient); if (rc == 0) { if (MqttClient_RespList_Find(client, (MqttPacketType)wait_type, wait_packet_id, &pendResp)) { if (pendResp->packetDone) { /* pending response is already done, so return */ rc = pendResp->packet_ret; #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""PendResp already Done %p: Rc %d"", pendResp, rc); #endif MqttClient_RespList_Remove(client, pendResp); wm_SemUnlock(&client->lockClient); wm_SemUnlock(&client->lockRecv); return rc; } } wm_SemUnlock(&client->lockClient); } else { break; /* error */ } #endif /* WOLFMQTT_MULTITHREAD */ *mms_stat = MQTT_MSG_WAIT; /* Wait for packet */ rc = MqttPacket_Read(client, client->rx_buf, client->rx_buf_len, timeout_ms); /* handle failure */ if (rc <= 0) { break; } /* capture length read */ client->packet.buf_len = rc; /* Decode Packet - get type and id */ rc = MqttClient_DecodePacket(client, client->rx_buf, client->packet.buf_len, NULL, &packet_type, NULL, &packet_id); if (rc < 0) { break; } #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""Read Packet: Len %d, Type %d, ID %d"", client->packet.buf_len, packet_type, packet_id); #endif *mms_stat = MQTT_MSG_READ; } FALL_THROUGH; case MQTT_MSG_READ: case MQTT_MSG_READ_PAYLOAD: { MqttPacketType use_packet_type; void* use_packet_obj; #ifdef WOLFMQTT_MULTITHREAD readLocked = 1; /* if in this state read is locked */ #endif /* read payload state only happens for publish messages */ if (*mms_stat == MQTT_MSG_READ_PAYLOAD) { packet_type = MQTT_PACKET_TYPE_PUBLISH; } /* Determine if we received data for this request */ if ((wait_type == MQTT_PACKET_TYPE_ANY || wait_type == packet_type || MqttIsPubRespPacket(packet_type) == MqttIsPubRespPacket(wait_type)) && (wait_packet_id == 0 || wait_packet_id == packet_id)) { use_packet_obj = packet_obj; waitMatchFound = 1; } else { /* use generic packet object */ use_packet_obj = &client->msg; } use_packet_type = packet_type; #ifdef WOLFMQTT_MULTITHREAD /* Check to see if we have a pending response for this packet */ pendResp = NULL; rc = wm_SemLock(&client->lockClient); if (rc == 0) { if (MqttClient_RespList_Find(client, packet_type, packet_id, &pendResp)) { /* we found packet match this incoming read packet */ pendResp->packetProcessing = 1; use_packet_obj = pendResp->packet_obj; use_packet_type = pendResp->packet_type; /* req from another thread... not a match */ waitMatchFound = 0; } wm_SemUnlock(&client->lockClient); } else { break; /* error */ } #endif /* WOLFMQTT_MULTITHREAD */ /* Perform packet handling for publish callback and QoS */ rc = MqttClient_HandlePacket(client, use_packet_type, use_packet_obj, timeout_ms); #ifdef WOLFMQTT_NONBLOCK if (rc == MQTT_CODE_CONTINUE) { /* we have received some data, so keep the recv mutex lock active and return */ return rc; } #endif /* handle success case */ if (rc >= 0) { rc = MQTT_CODE_SUCCESS; } #ifdef WOLFMQTT_MULTITHREAD if (pendResp) { /* Mark pending response entry done */ if (wm_SemLock(&client->lockClient) == 0) { pendResp->packetDone = 1; pendResp->packet_ret = rc; #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""PendResp Done %p"", pendResp); #endif pendResp = NULL; wm_SemUnlock(&client->lockClient); } } #endif /* WOLFMQTT_MULTITHREAD */ break; } case MQTT_MSG_WRITE: case MQTT_MSG_WRITE_PAYLOAD: default: { #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""MqttClient_WaitType: Invalid state %d!"", *mms_stat); #endif rc = MQTT_CODE_ERROR_STAT; break; } } /* switch (*mms_stat) */ #ifdef WOLFMQTT_NONBLOCK if (rc != MQTT_CODE_CONTINUE) #endif { /* reset state */ *mms_stat = MQTT_MSG_BEGIN; } #ifdef WOLFMQTT_MULTITHREAD if (readLocked) { wm_SemUnlock(&client->lockRecv); } #endif if (rc < 0) { #ifdef WOLFMQTT_DEBUG_CLIENT PRINTF(""MqttClient_WaitType: Failure: %s (%d)"", MqttClient_ReturnCodeToString(rc), rc); #endif return rc; } if (!waitMatchFound) { /* if we get here, then the we are still waiting for a packet */ goto wait_again; } return rc; }",CWE-787,16 0,"void QuotaManager::GetUsageAndQuotaForEviction( GetUsageAndQuotaForEvictionCallback* callback) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK(!eviction_context_.get_usage_and_quota_callback.get()); eviction_context_.get_usage_and_quota_callback.reset(callback); GetGlobalUsage(kStorageTypeTemporary, callback_factory_. NewCallback(&QuotaManager::DidGetGlobalUsageForEviction)); } ",none,24 0," void DidDumpOriginInfoTable(const OriginInfoTableEntries& entries) { origin_info_entries_ = entries; } ",none,24 0,"std::string CellularNetwork::GetRoamingStateString() const { switch (this->roaming_state_) { case ROAMING_STATE_HOME: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_HOME); break; case ROAMING_STATE_ROAMING: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_ROAMING); break; default: return l10n_util::GetStringUTF8( IDS_CHROMEOS_NETWORK_ROAMING_STATE_UNKNOWN); break; }; } ",none,24 0," void EvictOriginData(const GURL& origin, StorageType type) { quota_status_ = kQuotaStatusUnknown; quota_manager_->EvictOriginData(origin, type, callback_factory_.NewCallback( &QuotaManagerTest::StatusCallback)); } ",none,24 1,"spell_move_to( win_T *wp, int dir, // FORWARD or BACKWARD int allwords, // TRUE for ""[s""/""]s"", FALSE for ""[S""/""]S"" int curline, hlf_T *attrp) // return: attributes of bad word or NULL // (only when ""dir"" is FORWARD) { linenr_T lnum; pos_T found_pos; int found_len = 0; char_u *line; char_u *p; char_u *endp; hlf_T attr; int len; #ifdef FEAT_SYN_HL int has_syntax = syntax_present(wp); #endif int col; int can_spell; char_u *buf = NULL; int buflen = 0; int skip = 0; int capcol = -1; int found_one = FALSE; int wrapped = FALSE; if (no_spell_checking(wp)) return 0; /* * Start looking for bad word at the start of the line, because we can't * start halfway a word, we don't know where it starts or ends. * * When searching backwards, we continue in the line to find the last * bad word (in the cursor line: before the cursor). * * We concatenate the start of the next line, so that wrapped words work * (e.g. ""etcetera""). Doesn't work when searching backwards * though... */ lnum = wp->w_cursor.lnum; CLEAR_POS(&found_pos); while (!got_int) { line = ml_get_buf(wp->w_buffer, lnum, FALSE); len = (int)STRLEN(line); if (buflen < len + MAXWLEN + 2) { vim_free(buf); buflen = len + MAXWLEN + 2; buf = alloc(buflen); if (buf == NULL) break; } // In first line check first word for Capital. if (lnum == 1) capcol = 0; // For checking first word with a capital skip white space. if (capcol == 0) capcol = getwhitecols(line); else if (curline && wp == curwin) { // For spellbadword(): check if first word needs a capital. col = getwhitecols(line); if (check_need_cap(lnum, col)) capcol = col; // Need to get the line again, may have looked at the previous // one. line = ml_get_buf(wp->w_buffer, lnum, FALSE); } // Copy the line into ""buf"" and append the start of the next line if // possible. STRCPY(buf, line); if (lnum < wp->w_buffer->b_ml.ml_line_count) spell_cat_line(buf + STRLEN(buf), ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN); p = buf + skip; endp = buf + len; while (p < endp) { // When searching backward don't search after the cursor. Unless // we wrapped around the end of the buffer. if (dir == BACKWARD && lnum == wp->w_cursor.lnum && !wrapped && (colnr_T)(p - buf) >= wp->w_cursor.col) break; // start of word attr = HLF_COUNT; len = spell_check(wp, p, &attr, &capcol, FALSE); if (attr != HLF_COUNT) { // We found a bad word. Check the attribute. if (allwords || attr == HLF_SPB) { // When searching forward only accept a bad word after // the cursor. if (dir == BACKWARD || lnum != wp->w_cursor.lnum || (wrapped || (colnr_T)(curline ? p - buf + len : p - buf) > wp->w_cursor.col)) { #ifdef FEAT_SYN_HL if (has_syntax) { col = (int)(p - buf); (void)syn_get_id(wp, lnum, (colnr_T)col, FALSE, &can_spell, FALSE); if (!can_spell) attr = HLF_COUNT; } else #endif can_spell = TRUE; if (can_spell) { found_one = TRUE; found_pos.lnum = lnum; found_pos.col = (int)(p - buf); found_pos.coladd = 0; if (dir == FORWARD) { // No need to search further. wp->w_cursor = found_pos; vim_free(buf); if (attrp != NULL) *attrp = attr; return len; } else if (curline) // Insert mode completion: put cursor after // the bad word. found_pos.col += len; found_len = len; } } else found_one = TRUE; } } // advance to character after the word p += len; capcol -= len; } if (dir == BACKWARD && found_pos.lnum != 0) { // Use the last match in the line (before the cursor). wp->w_cursor = found_pos; vim_free(buf); return found_len; } if (curline) break; // only check cursor line // If we are back at the starting line and searched it again there // is no match, give up. if (lnum == wp->w_cursor.lnum && wrapped) break; // Advance to next line. if (dir == BACKWARD) { if (lnum > 1) --lnum; else if (!p_ws) break; // at first line and 'nowrapscan' else { // Wrap around to the end of the buffer. May search the // starting line again and accept the last match. lnum = wp->w_buffer->b_ml.ml_line_count; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(top_bot_msg), TRUE); } capcol = -1; } else { if (lnum < wp->w_buffer->b_ml.ml_line_count) ++lnum; else if (!p_ws) break; // at first line and 'nowrapscan' else { // Wrap around to the start of the buffer. May search the // starting line again and accept the first match. lnum = 1; wrapped = TRUE; if (!shortmess(SHM_SEARCH)) give_warning((char_u *)_(bot_top_msg), TRUE); } // If we are back at the starting line and there is no match then // give up. if (lnum == wp->w_cursor.lnum && !found_one) break; // Skip the characters at the start of the next line that were // included in a match crossing line boundaries. if (attr == HLF_COUNT) skip = (int)(p - endp); else skip = 0; // Capcol skips over the inserted space. --capcol; // But after empty line check first word in next line if (*skipwhite(line) == NUL) capcol = 0; } line_breakcheck(); } vim_free(buf); return 0; }",CWE-416,10 1,"RList *r_bin_ne_get_relocs(r_bin_ne_obj_t *bin) { RList *segments = bin->segments; if (!segments) { return NULL; } RList *entries = bin->entries; if (!entries) { return NULL; } RList *symbols = bin->symbols; if (!symbols) { return NULL; } ut16 *modref = calloc (bin->ne_header->ModRefs, sizeof (ut16)); if (!modref) { return NULL; } r_buf_read_at (bin->buf, (ut64)bin->ne_header->ModRefTable + bin->header_offset, (ut8 *)modref, bin->ne_header->ModRefs * sizeof (ut16)); RList *relocs = r_list_newf (free); if (!relocs) { free (modref); return NULL; } RListIter *it; RBinSection *seg; int index = -1; r_list_foreach (segments, it, seg) { index++; if (!(bin->segment_entries[index].flags & RELOCINFO)) { continue; } ut32 off = seg->paddr + seg->size; ut32 start = off; ut16 length = r_buf_read_le16_at (bin->buf, off); if (!length) { continue; } off += 2; // size_t buf_size = r_buf_size (bin->buf); while (off < start + length * sizeof (NE_image_reloc_item)) { // && off + sizeof (NE_image_reloc_item) < buf_size) NE_image_reloc_item rel = {0}; if (r_buf_read_at (bin->buf, off, (ut8 *)&rel, sizeof (rel)) < 1) { return NULL; } RBinReloc *reloc = R_NEW0 (RBinReloc); if (!reloc) { return NULL; } reloc->paddr = seg->paddr + rel.offset; switch (rel.type) { case LOBYTE: reloc->type = R_BIN_RELOC_8; break; case SEL_16: case OFF_16: reloc->type = R_BIN_RELOC_16; break; case POI_32: case OFF_32: reloc->type = R_BIN_RELOC_32; break; case POI_48: reloc->type = R_BIN_RELOC_64; break; } ut32 offset; if (rel.flags & (IMPORTED_ORD | IMPORTED_NAME)) { RBinImport *imp = R_NEW0 (RBinImport); if (!imp) { free (reloc); break; } char *name; #if NE_BUG if (rel.index > 0 && rel.index < bin->ne_header->ModRefs) { offset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable; name = __read_nonnull_str_at (bin->buf, offset); } else { name = r_str_newf (""UnknownModule%d_%x"", rel.index, off); // ???? } #else if (rel.index > bin->ne_header->ModRefs) { name = r_str_newf (""UnknownModule%d_%x"", rel.index, off); // ???? } else { offset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable; name = __read_nonnull_str_at (bin->buf, offset); } #endif if (rel.flags & IMPORTED_ORD) { imp->ordinal = rel.func_ord; imp->name = r_str_newf (""%s.%s"", name, __func_name_from_ord(name, rel.func_ord)); } else { offset = bin->header_offset + bin->ne_header->ImportNameTable + rel.name_off; char *func = __read_nonnull_str_at (bin->buf, offset); imp->name = r_str_newf (""%s.%s"", name, func); free (func); } free (name); reloc->import = imp; } else if (rel.flags & OSFIXUP) { // TODO } else { if (strstr (seg->name, ""FIXED"")) { RBinSection *s = r_list_get_n (segments, rel.segnum - 1); if (s) { offset = s->paddr + rel.segoff; } else { offset = -1; } } else { RBinAddr *entry = r_list_get_n (entries, rel.entry_ordinal - 1); if (entry) { offset = entry->paddr; } else { offset = -1; } } reloc->addend = offset; RBinSymbol *sym = NULL; RListIter *sit; r_list_foreach (symbols, sit, sym) { if (sym->paddr == reloc->addend) { reloc->symbol = sym; break; } } } if (rel.flags & ADDITIVE) { reloc->additive = 1; r_list_append (relocs, reloc); } else { do { #if NE_BUG if (reloc->paddr + 4 < r_buf_size (bin->buf)) { break; } #endif r_list_append (relocs, reloc); offset = r_buf_read_le16_at (bin->buf, reloc->paddr); RBinReloc *tmp = reloc; reloc = R_NEW0 (RBinReloc); if (!reloc) { break; } *reloc = *tmp; reloc->paddr = seg->paddr + offset; } while (offset != 0xFFFF); free (reloc); } off += sizeof (NE_image_reloc_item); } } free (modref); return relocs; }",CWE-125,1 0,"CellularNetwork::CellularNetwork(const CellularNetwork& network) : WirelessNetwork(network) { activation_state_ = network.activation_state(); network_technology_ = network.network_technology(); roaming_state_ = network.roaming_state(); restricted_pool_ = network.restricted_pool(); service_name_ = network.service_name(); operator_name_ = network.operator_name(); operator_code_ = network.operator_code(); payment_url_ = network.payment_url(); meid_ = network.meid(); imei_ = network.imei(); imsi_ = network.imsi(); esn_ = network.esn(); mdn_ = network.mdn(); min_ = network.min(); model_id_ = network.model_id(); manufacturer_ = network.manufacturer(); firmware_revision_ = network.firmware_revision(); hardware_revision_ = network.hardware_revision(); last_update_ = network.last_update(); prl_version_ = network.prl_version(); type_ = TYPE_CELLULAR; } ",none,24 1,"static void sdhci_do_adma(SDHCIState *s) { unsigned int begin, length; const uint16_t block_size = s->blksize & BLOCK_SIZE_MASK; ADMADescr dscr = {}; int i; if (s->trnmod & SDHC_TRNS_BLK_CNT_EN && !s->blkcnt) { /* Stop Multiple Transfer */ sdhci_end_transfer(s); return; } for (i = 0; i < SDHC_ADMA_DESCS_PER_DELAY; ++i) { s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH; get_adma_description(s, &dscr); trace_sdhci_adma_loop(dscr.addr, dscr.length, dscr.attr); if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) { /* Indicate that error occurred in ST_FDS state */ s->admaerr &= ~SDHC_ADMAERR_STATE_MASK; s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS; /* Generate ADMA error interrupt */ if (s->errintstsen & SDHC_EISEN_ADMAERR) { s->errintsts |= SDHC_EIS_ADMAERR; s->norintsts |= SDHC_NIS_ERR; } sdhci_update_irq(s); return; } length = dscr.length ? dscr.length : 64 * KiB; switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) { case SDHC_ADMA_ATTR_ACT_TRAN: /* data transfer */ if (s->trnmod & SDHC_TRNS_READ) { while (length) { if (s->data_count == 0) { sdbus_read_data(&s->sdbus, s->fifo_buffer, block_size); } begin = s->data_count; if ((length + begin) < block_size) { s->data_count = length + begin; length = 0; } else { s->data_count = block_size; length -= block_size - begin; } dma_memory_write(s->dma_as, dscr.addr, &s->fifo_buffer[begin], s->data_count - begin); dscr.addr += s->data_count - begin; if (s->data_count == block_size) { s->data_count = 0; if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) { s->blkcnt--; if (s->blkcnt == 0) { break; } } } } } else { while (length) { begin = s->data_count; if ((length + begin) < block_size) { s->data_count = length + begin; length = 0; } else { s->data_count = block_size; length -= block_size - begin; } dma_memory_read(s->dma_as, dscr.addr, &s->fifo_buffer[begin], s->data_count - begin); dscr.addr += s->data_count - begin; if (s->data_count == block_size) { sdbus_write_data(&s->sdbus, s->fifo_buffer, block_size); s->data_count = 0; if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) { s->blkcnt--; if (s->blkcnt == 0) { break; } } } } } s->admasysaddr += dscr.incr; break; case SDHC_ADMA_ATTR_ACT_LINK: /* link to next descriptor table */ s->admasysaddr = dscr.addr; trace_sdhci_adma(""link"", s->admasysaddr); break; default: s->admasysaddr += dscr.incr; break; } if (dscr.attr & SDHC_ADMA_ATTR_INT) { trace_sdhci_adma(""interrupt"", s->admasysaddr); if (s->norintstsen & SDHC_NISEN_DMA) { s->norintsts |= SDHC_NIS_DMA; } if (sdhci_update_irq(s) && !(dscr.attr & SDHC_ADMA_ATTR_END)) { /* IRQ delivered, reschedule current transfer */ break; } } /* ADMA transfer terminates if blkcnt == 0 or by END attribute */ if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) { trace_sdhci_adma_transfer_completed(); if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) && (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && s->blkcnt != 0)) { trace_sdhci_error(""SD/MMC host ADMA length mismatch""); s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH | SDHC_ADMAERR_STATE_ST_TFR; if (s->errintstsen & SDHC_EISEN_ADMAERR) { trace_sdhci_error(""Set ADMA error flag""); s->errintsts |= SDHC_EIS_ADMAERR; s->norintsts |= SDHC_NIS_ERR; } sdhci_update_irq(s); } sdhci_end_transfer(s); return; } } /* we have unfinished business - reschedule to continue ADMA */ timer_mod(s->transfer_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY); }",CWE-119,0 1,"int qtm_decompress(struct qtm_stream *qtm, off_t out_bytes) { unsigned int frame_start, frame_end, window_posn, match_offset, range; unsigned char *window, *i_ptr, *i_end, *runsrc, *rundest; int i, j, selector, extra, sym, match_length, ret; unsigned short H, L, C, symf; register unsigned int bit_buffer; register unsigned char bits_left; unsigned char bits_needed, bit_run; /* easy answers */ if (!qtm || (out_bytes < 0)) return CL_ENULLARG; if (qtm->error) return qtm->error; /* flush out any stored-up bytes before we begin */ i = qtm->o_end - qtm->o_ptr; if ((off_t) i > out_bytes) i = (int) out_bytes; if (i) { if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; out_bytes -= i; } if (out_bytes == 0) return CL_SUCCESS; /* restore local state */ QTM_RESTORE_BITS; window = qtm->window; window_posn = qtm->window_posn; frame_start = qtm->frame_start; H = qtm->H; L = qtm->L; C = qtm->C; /* while we do not have enough decoded bytes in reserve: */ while ((qtm->o_end - qtm->o_ptr) < out_bytes) { /* read header if necessary. Initialises H, L and C */ if (!qtm->header_read) { H = 0xFFFF; L = 0; QTM_READ_BITS(C, 16); qtm->header_read = 1; } /* decode more, at most up to to frame boundary */ frame_end = window_posn + (out_bytes - (qtm->o_end - qtm->o_ptr)); if ((frame_start + QTM_FRAME_SIZE) < frame_end) { frame_end = frame_start + QTM_FRAME_SIZE; } while (window_posn < frame_end) { QTM_GET_SYMBOL(qtm->model7, selector); if (selector < 4) { struct qtm_model *mdl = (selector == 0) ? &qtm->model0 : ((selector == 1) ? &qtm->model1 : ((selector == 2) ? &qtm->model2 : &qtm->model3)); QTM_GET_SYMBOL((*mdl), sym); window[window_posn++] = sym; } else { switch (selector) { case 4: /* selector 4 = fixed length match (3 bytes) */ QTM_GET_SYMBOL(qtm->model4, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 3; break; case 5: /* selector 5 = fixed length match (4 bytes) */ QTM_GET_SYMBOL(qtm->model5, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; match_length = 4; break; case 6: /* selector 6 = variable length match */ QTM_GET_SYMBOL(qtm->model6len, sym); QTM_READ_BITS(extra, qtm->length_extra[sym]); match_length = qtm->length_base[sym] + extra + 5; QTM_GET_SYMBOL(qtm->model6, sym); QTM_READ_BITS(extra, qtm->extra_bits[sym]); match_offset = qtm->position_base[sym] + extra + 1; break; default: /* should be impossible, model7 can only return 0-6 */ return qtm->error = CL_EFORMAT; } rundest = &window[window_posn]; i = match_length; /* does match offset wrap the window? */ if (match_offset > window_posn) { /* j = length from match offset to end of window */ j = match_offset - window_posn; if (j > (int) qtm->window_size) { cli_dbgmsg(""qtm_decompress: match offset beyond window boundaries\n""); return qtm->error = CL_EFORMAT; } runsrc = &window[qtm->window_size - j]; if (j < i) { /* if match goes over the window edge, do two copy runs */ i -= j; while (j-- > 0) *rundest++ = *runsrc++; runsrc = window; } while (i-- > 0) *rundest++ = *runsrc++; } else { runsrc = rundest - match_offset; if(i > (int) (qtm->window_size - window_posn)) i = qtm->window_size - window_posn; while (i-- > 0) *rundest++ = *runsrc++; } window_posn += match_length; } } /* while (window_posn < frame_end) */ qtm->o_end = &window[window_posn]; /* another frame completed? */ if ((window_posn - frame_start) >= QTM_FRAME_SIZE) { if ((window_posn - frame_start) != QTM_FRAME_SIZE) { cli_dbgmsg(""qtm_decompress: overshot frame alignment\n""); return qtm->error = CL_EFORMAT; } /* re-align input */ if (bits_left & 7) QTM_REMOVE_BITS(bits_left & 7); do { QTM_READ_BITS(i, 8); } while (i != 0xFF); qtm->header_read = 0; /* window wrap? */ if (window_posn == qtm->window_size) { /* flush all currently stored data */ i = (qtm->o_end - qtm->o_ptr); if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } out_bytes -= i; qtm->o_ptr = &window[0]; qtm->o_end = &window[0]; window_posn = 0; } frame_start = window_posn; } } /* while (more bytes needed) */ if (out_bytes) { i = (int) out_bytes; if (qtm->wflag && (ret = mspack_write(qtm->ofd, qtm->o_ptr, i, qtm->file)) != CL_SUCCESS) { return qtm->error = ret; } qtm->o_ptr += i; } /* store local state */ QTM_STORE_BITS; qtm->window_posn = window_posn; qtm->frame_start = frame_start; qtm->H = H; qtm->L = L; qtm->C = C; return CL_SUCCESS; }",CWE-20,3 0," UpdateModifiedTimeTask( QuotaManager* manager, const GURL& origin, StorageType type, base::Time modified_time) : DatabaseTaskBase(manager), origin_(origin), type_(type), modified_time_(modified_time) {} ",none,24 0,"void QuotaManager::LazyInitialize() { DCHECK(io_thread_->BelongsToCurrentThread()); if (database_.get()) { return; } database_.reset(new QuotaDatabase(is_incognito_ ? FilePath() : profile_path_.AppendASCII(kDatabaseName))); temporary_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypeTemporary, special_storage_policy_)); persistent_usage_tracker_.reset( new UsageTracker(clients_, kStorageTypePersistent, special_storage_policy_)); scoped_refptr task( new InitializeTask(this, profile_path_, is_incognito_)); task->Start(); } ",none,24 1,"get_password(const char *prompt, char *input, int capacity) { #ifdef ENABLE_SYSTEMD int is_systemd_running; struct stat a, b; /* We simply test whether the systemd cgroup hierarchy is * mounted */ is_systemd_running = (lstat(""/sys/fs/cgroup"", &a) == 0) && (lstat(""/sys/fs/cgroup/systemd"", &b) == 0) && (a.st_dev != b.st_dev); if (is_systemd_running) { char *cmd, *ret; FILE *ask_pass_fp = NULL; cmd = ret = NULL; if (asprintf(&cmd, ""systemd-ask-password \""%s\"""", prompt) >= 0) { ask_pass_fp = popen (cmd, ""re""); free (cmd); } if (ask_pass_fp) { ret = fgets(input, capacity, ask_pass_fp); pclose(ask_pass_fp); } if (ret) { int len = strlen(input); if (input[len - 1] == '\n') input[len - 1] = '\0'; return input; } } #endif /* * Falling back to getpass(..) * getpass is obsolete, but there's apparently nothing that replaces it */ char *tmp_pass = getpass(prompt); if (!tmp_pass) return NULL; strncpy(input, tmp_pass, capacity - 1); input[capacity - 1] = '\0'; /* zero-out the static buffer */ memset(tmp_pass, 0, strlen(tmp_pass)); return input; }",CWE-78,15 1,"PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner ) { int chr = *scanner->curptr; if (!chr) { pj_scan_syntax_err(scanner); return 0; } ++scanner->curptr; if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) { pj_scan_skip_whitespace(scanner); } return chr; }",CWE-125,1 0,"void QuotaManager::DidGetAvailableSpaceForEviction( QuotaStatusCode status, int64 available_space) { eviction_context_.get_usage_and_quota_callback->Run(status, eviction_context_.usage, eviction_context_.unlimited_usage, eviction_context_.quota, available_space); eviction_context_.get_usage_and_quota_callback.reset(); } ",none,24 0,"void QuotaManager::DidInitializeTemporaryGlobalQuota(int64 quota) { temporary_global_quota_ = quota; temporary_global_quota_callbacks_.Run( db_disabled_ ? kQuotaErrorInvalidAccess : kQuotaStatusOk, kStorageTypeTemporary, quota); if (db_disabled_ || eviction_disabled_) return; if (!need_initialize_origins_) { StartEviction(); return; } temporary_usage_tracker_->GetGlobalUsage(callback_factory_.NewCallback( &QuotaManager::DidRunInitialGetTemporaryGlobalUsage)); } ",none,24 1,"Field *create_tmp_field_from_field(THD *thd, Field *org_field, const char *name, TABLE *table, Item_field *item) { Field *new_field; new_field= org_field->make_new_field(thd->mem_root, table, table == org_field->table); if (new_field) { new_field->init(table); new_field->orig_table= org_field->orig_table; if (item) item->result_field= new_field; else new_field->field_name= name; new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG); if (org_field->maybe_null() || (item && item->maybe_null)) new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join if (org_field->type() == MYSQL_TYPE_VAR_STRING || org_field->type() == MYSQL_TYPE_VARCHAR) table->s->db_create_options|= HA_OPTION_PACK_RECORD; else if (org_field->type() == FIELD_TYPE_DOUBLE) ((Field_double *) new_field)->not_fixed= TRUE; new_field->vcol_info= 0; new_field->cond_selectivity= 1.0; new_field->next_equal_field= NULL; new_field->option_list= NULL; new_field->option_struct= NULL; } return new_field; }",CWE-89,21 1,"regional_alloc(struct regional *r, size_t size) { size_t a = ALIGN_UP(size, ALIGNMENT); void *s; /* large objects */ if(a > REGIONAL_LARGE_OBJECT_SIZE) { s = malloc(ALIGNMENT + size); if(!s) return NULL; r->total_large += ALIGNMENT+size; *(char**)s = r->large_list; r->large_list = (char*)s; return (char*)s+ALIGNMENT; } /* create a new chunk */ if(a > r->available) { s = malloc(REGIONAL_CHUNK_SIZE); if(!s) return NULL; *(char**)s = r->next; r->next = (char*)s; r->data = (char*)s + ALIGNMENT; r->available = REGIONAL_CHUNK_SIZE - ALIGNMENT; } /* put in this chunk */ r->available -= a; s = r->data; r->data += a; return s; }",CWE-190,2 1,"do_tag( char_u *tag, // tag (pattern) to jump to int type, int count, int forceit, // :ta with ! int verbose) // print ""tag not found"" message { taggy_T *tagstack = curwin->w_tagstack; int tagstackidx = curwin->w_tagstackidx; int tagstacklen = curwin->w_tagstacklen; int cur_match = 0; int cur_fnum = curbuf->b_fnum; int oldtagstackidx = tagstackidx; int prevtagstackidx = tagstackidx; int prev_num_matches; int new_tag = FALSE; int i; int ic; int no_regexp = FALSE; int error_cur_match = 0; int save_pos = FALSE; fmark_T saved_fmark; #ifdef FEAT_CSCOPE int jumped_to_tag = FALSE; #endif int new_num_matches; char_u **new_matches; int use_tagstack; int skip_msg = FALSE; char_u *buf_ffname = curbuf->b_ffname; // name to use for // priority computation int use_tfu = 1; char_u *tofree = NULL; // remember the matches for the last used tag static int num_matches = 0; static int max_num_matches = 0; // limit used for match search static char_u **matches = NULL; static int flags; #ifdef FEAT_EVAL if (tfu_in_use) { emsg(_(e_cannot_modify_tag_stack_within_tagfunc)); return FALSE; } #endif #ifdef EXITFREE if (type == DT_FREE) { // remove the list of matches FreeWild(num_matches, matches); # ifdef FEAT_CSCOPE cs_free_tags(); # endif num_matches = 0; return FALSE; } #endif if (type == DT_HELP) { type = DT_TAG; no_regexp = TRUE; use_tfu = 0; } prev_num_matches = num_matches; free_string_option(nofile_fname); nofile_fname = NULL; CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0 saved_fmark.fnum = 0; /* * Don't add a tag to the tagstack if 'tagstack' has been reset. */ if ((!p_tgst && *tag != NUL)) { use_tagstack = FALSE; new_tag = TRUE; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } #endif } else { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) use_tagstack = FALSE; else #endif use_tagstack = TRUE; // new pattern, add to the tag stack if (*tag != NUL && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP #ifdef FEAT_QUICKFIX || type == DT_LTAG #endif #ifdef FEAT_CSCOPE || type == DT_CSCOPE #endif )) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (ptag_entry.tagname != NULL && STRCMP(ptag_entry.tagname, tag) == 0) { // Jumping to same tag: keep the current match, so that // the CursorHold autocommand example works. cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else { tagstack_clear_entry(&ptag_entry); if ((ptag_entry.tagname = vim_strsave(tag)) == NULL) goto end_do_tag; } } else #endif { /* * If the last used entry is not at the top, delete all tag * stack entries above it. */ while (tagstackidx < tagstacklen) tagstack_clear_entry(&tagstack[--tagstacklen]); // if the tagstack is full: remove oldest entry if (++tagstacklen > TAGSTACKSIZE) { tagstacklen = TAGSTACKSIZE; tagstack_clear_entry(&tagstack[0]); for (i = 1; i < tagstacklen; ++i) tagstack[i - 1] = tagstack[i]; --tagstackidx; } /* * put the tag name in the tag stack */ if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL) { curwin->w_tagstacklen = tagstacklen - 1; goto end_do_tag; } curwin->w_tagstacklen = tagstacklen; save_pos = TRUE; // save the cursor position below } new_tag = TRUE; } else { if ( #if defined(FEAT_QUICKFIX) g_do_tagpreview != 0 ? ptag_entry.tagname == NULL : #endif tagstacklen == 0) { // empty stack emsg(_(e_tag_stack_empty)); goto end_do_tag; } if (type == DT_POP) // go to older position { #ifdef FEAT_FOLDING int old_KeyTyped = KeyTyped; #endif if ((tagstackidx -= count) < 0) { emsg(_(e_at_bottom_of_tag_stack)); if (tagstackidx + count == 0) { // We did [num]^T from the bottom of the stack tagstackidx = 0; goto end_do_tag; } // We weren't at the bottom of the stack, so jump all the // way to the bottom now. tagstackidx = 0; } else if (tagstackidx >= tagstacklen) // count == 0? { emsg(_(e_at_top_of_tag_stack)); goto end_do_tag; } // Make a copy of the fmark, autocommands may invalidate the // tagstack before it's used. saved_fmark = tagstack[tagstackidx].fmark; if (saved_fmark.fnum != curbuf->b_fnum) { /* * Jump to other file. If this fails (e.g. because the * file was changed) keep original position in tag stack. */ if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum, GETF_SETMARK, forceit) == FAIL) { tagstackidx = oldtagstackidx; // back to old posn goto end_do_tag; } // An BufReadPost autocommand may jump to the '"" mark, but // we don't what that here. curwin->w_cursor.lnum = saved_fmark.mark.lnum; } else { setpcmark(); curwin->w_cursor.lnum = saved_fmark.mark.lnum; } curwin->w_cursor.col = saved_fmark.mark.col; curwin->w_set_curswant = TRUE; check_cursor(); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_TAG) && old_KeyTyped) foldOpenCursor(); #endif // remove the old list of matches FreeWild(num_matches, matches); #ifdef FEAT_CSCOPE cs_free_tags(); #endif num_matches = 0; tag_freematch(); goto end_do_tag; } if (type == DT_TAG #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) { #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { // "":tag"" (no argument): go to newer pattern save_pos = TRUE; // save the cursor position below if ((tagstackidx += count - 1) >= tagstacklen) { /* * Beyond the last one, just give an error message and * go to the last one. Don't store the cursor * position. */ tagstackidx = tagstacklen - 1; emsg(_(e_at_top_of_tag_stack)); save_pos = FALSE; } else if (tagstackidx < 0) // must have been count == 0 { emsg(_(e_at_bottom_of_tag_stack)); tagstackidx = 0; goto end_do_tag; } cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } new_tag = TRUE; } else // go to other matching tag { // Save index for when selection is cancelled. prevtagstackidx = tagstackidx; #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { cur_match = ptag_entry.cur_match; cur_fnum = ptag_entry.cur_fnum; } else #endif { if (--tagstackidx < 0) tagstackidx = 0; cur_match = tagstack[tagstackidx].cur_match; cur_fnum = tagstack[tagstackidx].cur_fnum; } switch (type) { case DT_FIRST: cur_match = count - 1; break; case DT_SELECT: case DT_JUMP: #ifdef FEAT_CSCOPE case DT_CSCOPE: #endif case DT_LAST: cur_match = MAXCOL - 1; break; case DT_NEXT: cur_match += count; break; case DT_PREV: cur_match -= count; break; } if (cur_match >= MAXCOL) cur_match = MAXCOL - 1; else if (cur_match < 0) { emsg(_(e_cannot_go_before_first_matching_tag)); skip_msg = TRUE; cur_match = 0; cur_fnum = curbuf->b_fnum; } } } #if defined(FEAT_QUICKFIX) if (g_do_tagpreview != 0) { if (type != DT_SELECT && type != DT_JUMP) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } } else #endif { /* * For "":tag [arg]"" or "":tselect"" remember position before the jump. */ saved_fmark = tagstack[tagstackidx].fmark; if (save_pos) { tagstack[tagstackidx].fmark.mark = curwin->w_cursor; tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum; } // Curwin will change in the call to jumpto_tag() if "":stag"" was // used or an autocommand jumps to another window; store value of // tagstackidx now. curwin->w_tagstackidx = tagstackidx; if (type != DT_SELECT && type != DT_JUMP) { curwin->w_tagstack[tagstackidx].cur_match = cur_match; curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum; } } } // When not using the current buffer get the name of buffer ""cur_fnum"". // Makes sure that the tag order doesn't change when using a remembered // position for ""cur_match"". if (cur_fnum != curbuf->b_fnum) { buf_T *buf = buflist_findnr(cur_fnum); if (buf != NULL) buf_ffname = buf->b_ffname; } /* * Repeat searching for tags, when a file has not been found. */ for (;;) { int other_name; char_u *name; /* * When desired match not found yet, try to find it (and others). */ if (use_tagstack) { // make a copy, the tagstack may change in 'tagfunc' name = vim_strsave(tagstack[tagstackidx].tagname); vim_free(tofree); tofree = name; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) name = ptag_entry.tagname; #endif else name = tag; other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0); if (new_tag || (cur_match >= num_matches && max_num_matches != MAXCOL) || other_name) { if (other_name) { vim_free(tagmatchname); tagmatchname = vim_strsave(name); } if (type == DT_SELECT || type == DT_JUMP #if defined(FEAT_QUICKFIX) || type == DT_LTAG #endif ) cur_match = MAXCOL - 1; if (type == DT_TAG) max_num_matches = MAXCOL; else max_num_matches = cur_match + 1; // when the argument starts with '/', use it as a regexp if (!no_regexp && *name == '/') { flags = TAG_REGEXP; ++name; } else flags = TAG_NOIC; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE) flags = TAG_CSCOPE; #endif if (verbose) flags |= TAG_VERBOSE; if (!use_tfu) flags |= TAG_NO_TAGFUNC; if (find_tags(name, &new_num_matches, &new_matches, flags, max_num_matches, buf_ffname) == OK && new_num_matches < max_num_matches) max_num_matches = MAXCOL; // If less than max_num_matches // found: all matches found. // If there already were some matches for the same name, move them // to the start. Avoids that the order changes when using // "":tnext"" and jumping to another file. if (!new_tag && !other_name) { int j, k; int idx = 0; tagptrs_T tagp, tagp2; // Find the position of each old match in the new list. Need // to use parse_match() to find the tag line. for (j = 0; j < num_matches; ++j) { parse_match(matches[j], &tagp); for (i = idx; i < new_num_matches; ++i) { parse_match(new_matches[i], &tagp2); if (STRCMP(tagp.tagname, tagp2.tagname) == 0) { char_u *p = new_matches[i]; for (k = i; k > idx; --k) new_matches[k] = new_matches[k - 1]; new_matches[idx++] = p; break; } } } } FreeWild(num_matches, matches); num_matches = new_num_matches; matches = new_matches; } if (num_matches <= 0) { if (verbose) semsg(_(e_tag_not_found_str), name); #if defined(FEAT_QUICKFIX) g_do_tagpreview = 0; #endif } else { int ask_for_selection = FALSE; #ifdef FEAT_CSCOPE if (type == DT_CSCOPE && num_matches > 1) { cs_print_tags(); ask_for_selection = TRUE; } else #endif if (type == DT_TAG && *tag != NUL) // If a count is supplied to the "":tag "" command, then // jump to count'th matching tag. cur_match = count > 0 ? count - 1 : 0; else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) { print_tag_list(new_tag, use_tagstack, num_matches, matches); ask_for_selection = TRUE; } #if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL) else if (type == DT_LTAG) { if (add_llist_tags(tag, num_matches, matches) == FAIL) goto end_do_tag; cur_match = 0; // Jump to the first tag } #endif if (ask_for_selection == TRUE) { /* * Ask to select a tag from the list. */ i = prompt_for_number(NULL); if (i <= 0 || i > num_matches || got_int) { // no valid choice: don't change anything if (use_tagstack) { tagstack[tagstackidx].fmark = saved_fmark; tagstackidx = prevtagstackidx; } #ifdef FEAT_CSCOPE cs_free_tags(); jumped_to_tag = TRUE; #endif break; } cur_match = i - 1; } if (cur_match >= num_matches) { // Avoid giving this error when a file wasn't found and we're // looking for a match in another file, which wasn't found. // There will be an emsg(""file doesn't exist"") below then. if ((type == DT_NEXT || type == DT_FIRST) && nofile_fname == NULL) { if (num_matches == 1) emsg(_(e_there_is_only_one_matching_tag)); else emsg(_(e_cannot_go_beyond_last_matching_tag)); skip_msg = TRUE; } cur_match = num_matches - 1; } if (use_tagstack) { tagptrs_T tagp; tagstack[tagstackidx].cur_match = cur_match; tagstack[tagstackidx].cur_fnum = cur_fnum; // store user-provided data originating from tagfunc if (use_tfu && parse_match(matches[cur_match], &tagp) == OK && tagp.user_data) { VIM_CLEAR(tagstack[tagstackidx].user_data); tagstack[tagstackidx].user_data = vim_strnsave( tagp.user_data, tagp.user_data_end - tagp.user_data); } ++tagstackidx; } #if defined(FEAT_QUICKFIX) else if (g_do_tagpreview != 0) { ptag_entry.cur_match = cur_match; ptag_entry.cur_fnum = cur_fnum; } #endif /* * Only when going to try the next match, report that the previous * file didn't exist. Otherwise an emsg() is given below. */ if (nofile_fname != NULL && error_cur_match != cur_match) smsg(_(""File \""%s\"" does not exist""), nofile_fname); ic = (matches[cur_match][0] & MT_IC_OFF); if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP #ifdef FEAT_CSCOPE && type != DT_CSCOPE #endif && (num_matches > 1 || ic) && !skip_msg) { // Give an indication of the number of matching tags sprintf((char *)IObuff, _(""tag %d of %d%s""), cur_match + 1, num_matches, max_num_matches != MAXCOL ? _("" or more"") : """"); if (ic) STRCAT(IObuff, _("" Using tag with different case!"")); if ((num_matches > prev_num_matches || new_tag) && num_matches > 1) { if (ic) msg_attr((char *)IObuff, HL_ATTR(HLF_W)); else msg((char *)IObuff); msg_scroll = TRUE; // don't overwrite this message } else give_warning(IObuff, ic); if (ic && !msg_scrolled && msg_silent == 0) { out_flush(); ui_delay(1007L, TRUE); } } #if defined(FEAT_EVAL) // Let the SwapExists event know what tag we are jumping to. vim_snprintf((char *)IObuff, IOSIZE, "":ta %s\r"", name); set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1); #endif /* * Jump to the desired match. */ i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE); #if defined(FEAT_EVAL) set_vim_var_string(VV_SWAPCOMMAND, NULL, -1); #endif if (i == NOTAGFILE) { // File not found: try again with another matching tag if ((type == DT_PREV && cur_match > 0) || ((type == DT_TAG || type == DT_NEXT || type == DT_FIRST) && (max_num_matches != MAXCOL || cur_match < num_matches - 1))) { error_cur_match = cur_match; if (use_tagstack) --tagstackidx; if (type == DT_PREV) --cur_match; else { type = DT_NEXT; ++cur_match; } continue; } semsg(_(e_file_str_does_not_exist), nofile_fname); } else { // We may have jumped to another window, check that // tagstackidx is still valid. if (use_tagstack && tagstackidx > curwin->w_tagstacklen) tagstackidx = curwin->w_tagstackidx; #ifdef FEAT_CSCOPE jumped_to_tag = TRUE; #endif } } break; } end_do_tag: // Only store the new index when using the tagstack and it's valid. if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) curwin->w_tagstackidx = tagstackidx; postponed_split = 0; // don't split next time # ifdef FEAT_QUICKFIX g_do_tagpreview = 0; // don't do tag preview next time # endif vim_free(tofree); #ifdef FEAT_CSCOPE return jumped_to_tag; #else return FALSE; #endif }",CWE-416,10 0," virtual void ConnectToWifiNetwork(ConnectionSecurity security, const std::string& ssid, const std::string& password, const std::string& identity, const std::string& certpath, bool auto_connect) {} ",none,24 1,"int udf_expand_file_adinicb(struct inode *inode) { struct page *page; char *kaddr; struct udf_inode_info *iinfo = UDF_I(inode); int err; WARN_ON_ONCE(!inode_is_locked(inode)); if (!iinfo->i_lenAlloc) { if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; up_write(&iinfo->i_data_sem); mark_inode_dirty(inode); return 0; } /* * Release i_data_sem so that we can lock a page - page lock ranks * above i_data_sem. i_mutex still protects us against file changes. */ up_write(&iinfo->i_data_sem); page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS); if (!page) return -ENOMEM; if (!PageUptodate(page)) { kaddr = kmap_atomic(page); memset(kaddr + iinfo->i_lenAlloc, 0x00, PAGE_SIZE - iinfo->i_lenAlloc); memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr, iinfo->i_lenAlloc); flush_dcache_page(page); SetPageUptodate(page); kunmap_atomic(kaddr); } down_write(&iinfo->i_data_sem); memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00, iinfo->i_lenAlloc); iinfo->i_lenAlloc = 0; if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; set_page_dirty(page); unlock_page(page); up_write(&iinfo->i_data_sem); err = filemap_fdatawrite(inode->i_mapping); if (err) { /* Restore everything back so that we don't lose data... */ lock_page(page); down_write(&iinfo->i_data_sem); kaddr = kmap_atomic(page); memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size); kunmap_atomic(kaddr); unlock_page(page); iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB; inode->i_data.a_ops = &udf_adinicb_aops; up_write(&iinfo->i_data_sem); } put_page(page); mark_inode_dirty(inode); return err; }",CWE-476,12 1,"GF_Err SetupWriters(MovieWriter *mw, GF_List *writers, u8 interleaving) { u32 i, trackCount; TrackWriter *writer; GF_TrackBox *trak; GF_ISOFile *movie = mw->movie; mw->total_samples = mw->nb_done = 0; if (!movie->moov) return GF_OK; trackCount = gf_list_count(movie->moov->trackList); for (i = 0; i < trackCount; i++) { trak = gf_isom_get_track(movie->moov, i+1); GF_SAFEALLOC(writer, TrackWriter); if (!writer) goto exit; writer->sampleNumber = 1; writer->mdia = trak->Media; writer->stbl = trak->Media->information->sampleTable; writer->timeScale = trak->Media->mediaHeader->timeScale; writer->all_dref_mode = Media_SelfContainedType(writer->mdia); if (trak->sample_encryption) writer->prevent_dispatch = GF_TRUE; writer->isDone = 0; writer->DTSprev = 0; writer->chunkDur = 0; writer->chunkSize = 0; writer->constant_size = writer->constant_dur = 0; if (writer->stbl->SampleSize->sampleSize) writer->constant_size = writer->stbl->SampleSize->sampleSize; if (writer->stbl->TimeToSample->nb_entries==1) { writer->constant_dur = writer->stbl->TimeToSample->entries[0].sampleDelta; if (writer->constant_dur>1) writer->constant_dur = 0; } if (!writer->constant_dur || !writer->constant_size || (writer->constant_size>=10)) writer->constant_size = writer->constant_dur = 0; writer->stsc = (GF_SampleToChunkBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STSC); if (!writer->stsc) return GF_OUT_OF_MEM; if (writer->stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { writer->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_STCO); } else { writer->stco = gf_isom_box_new(GF_ISOM_BOX_TYPE_CO64); } if (!writer->stco) return GF_OUT_OF_MEM; /*stops from chunk escape*/ if (interleaving) writer->stbl->MaxSamplePerChunk = 0; /*for progress, assume only one descIndex*/ if (Media_IsSelfContained(writer->mdia, 1)) mw->total_samples += writer->stbl->SampleSize->sampleCount; /*optimization for interleaving: put audio last (this can be overridden by priorities)*/ if (movie->storageMode != GF_ISOM_STORE_INTERLEAVED) { gf_list_add(writers, writer); } else { if (writer->mdia->information->InfoHeader && writer->mdia->information->InfoHeader->type == GF_ISOM_BOX_TYPE_SMHD) { gf_list_add(writers, writer); } else { gf_list_insert(writers, writer, 0); } } if (movie->sample_groups_in_traf && trak->Media->information->sampleTable) { gf_isom_box_array_del_parent(&trak->Media->information->sampleTable->child_boxes, trak->Media->information->sampleTable->sampleGroupsDescription); trak->Media->information->sampleTable->sampleGroupsDescription = NULL; } } return GF_OK; exit: CleanWriters(writers); return GF_OUT_OF_MEM; }",CWE-476,12 0," void DidGetQuota(QuotaStatusCode status, StorageType type, int64 quota) { quota_status_ = status; type_ = type; quota_ = quota; } ",none,24 1," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const Tensor& input_min_range = ctx->input(1); const Tensor& input_max_range = ctx->input(2); int num_slices = 1; if (axis_ > -1) { num_slices = input.dim_size(axis_); } const TensorShape& minmax_shape = ctx->input(1).shape(); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor* output_min_tensor = nullptr; Tensor* output_max_tensor = nullptr; if (num_slices == 1) { OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor)); const float min_range = input_min_range.template flat()(0); const float max_range = input_max_range.template flat()(0); QuantizeTensor(ctx, input, min_range, max_range, output, output_min_tensor, output_max_tensor); return; } OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST, errors::Unimplemented(""MIN_FIRST mode is not implemented for "" ""Quantize with axis != -1."")); OP_REQUIRES_OK(ctx, ctx->allocate_output(1, minmax_shape, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, minmax_shape, &output_max_tensor)); auto input_tensor = input.template flat_inner_outer_dims(axis_ - 1); int64_t pre_dim = 1, post_dim = 1; for (int i = 0; i < axis_; ++i) { pre_dim *= output->dim_size(i); } for (int i = axis_ + 1; i < output->dims(); ++i) { post_dim *= output->dim_size(i); } auto output_tensor = output->template bit_casted_shaped( {pre_dim, num_slices, post_dim}); auto min_ranges = input_min_range.template vec(); auto max_ranges = input_max_range.template vec(); for (int i = 0; i < num_slices; ++i) { QuantizeSlice(ctx->eigen_device(), ctx, input_tensor.template chip<1>(i), min_ranges(i), max_ranges(i), output_tensor.template chip<1>(i), &output_min_tensor->flat()(i), &output_max_tensor->flat()(i)); } }",CWE-476,12 0,"static std::string SafeString(const char* s) { return s ? std::string(s) : std::string(); } ",none,24 1,"load_image (const gchar *filename, GError **error) { gchar *name; gint fd; BrushHeader bh; guchar *brush_buf = NULL; gint32 image_ID; gint32 layer_ID; GimpParasite *parasite; GimpDrawable *drawable; GimpPixelRgn pixel_rgn; gint bn_size; GimpImageBaseType base_type; GimpImageType image_type; gsize size; fd = g_open (filename, O_RDONLY | _O_BINARY, 0); if (fd == -1) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _(""Could not open '%s' for reading: %s""), gimp_filename_to_utf8 (filename), g_strerror (errno)); return -1; } gimp_progress_init_printf (_(""Opening '%s'""), gimp_filename_to_utf8 (filename)); if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader)) { close (fd); return -1; } /* rearrange the bytes in each unsigned int */ bh.header_size = g_ntohl (bh.header_size); bh.version = g_ntohl (bh.version); bh.width = g_ntohl (bh.width); bh.height = g_ntohl (bh.height); bh.bytes = g_ntohl (bh.bytes); bh.magic_number = g_ntohl (bh.magic_number); bh.spacing = g_ntohl (bh.spacing); /* Sanitize values */ if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) || (bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) || ((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) && (bh.bytes != 18)) || (G_MAXSIZE / bh.width / bh.height / bh.bytes < 1)) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _(""Invalid header data in '%s': width=%lu, height=%lu, "" ""bytes=%lu""), gimp_filename_to_utf8 (filename), (unsigned long int)bh.width, (unsigned long int)bh.height, (unsigned long int)bh.bytes); return -1; } switch (bh.version) { case 1: /* Version 1 didn't have a magic number and had no spacing */ bh.spacing = 25; /* And we need to rewind the handle, 4 due spacing and 4 due magic */ lseek (fd, -8, SEEK_CUR); bh.header_size += 8; break; case 3: /* cinepaint brush */ if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */) { bh.bytes = 2; } else { g_message (_(""Unsupported brush format"")); close (fd); return -1; } /* fallthrough */ case 2: if (bh.magic_number == GBRUSH_MAGIC && bh.header_size > sizeof (BrushHeader)) break; default: g_message (_(""Unsupported brush format"")); close (fd); return -1; } if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0) { gchar *temp = g_new (gchar, bn_size); if ((read (fd, temp, bn_size)) < bn_size) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _(""Error in GIMP brush file '%s'""), gimp_filename_to_utf8 (filename)); close (fd); g_free (temp); return -1; } name = gimp_any_to_utf8 (temp, -1, _(""Invalid UTF-8 string in brush file '%s'.""), gimp_filename_to_utf8 (filename)); g_free (temp); } else { name = g_strdup (_(""Unnamed"")); } /* Now there's just raw data left. */ size = bh.width * bh.height * bh.bytes; brush_buf = g_malloc (size); if (read (fd, brush_buf, size) != size) { close (fd); g_free (brush_buf); g_free (name); return -1; } switch (bh.bytes) { case 1: { PatternHeader ph; /* For backwards-compatibility, check if a pattern follows. The obsolete .gpb format did it this way. */ if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader)) { /* rearrange the bytes in each unsigned int */ ph.header_size = g_ntohl (ph.header_size); ph.version = g_ntohl (ph.version); ph.width = g_ntohl (ph.width); ph.height = g_ntohl (ph.height); ph.bytes = g_ntohl (ph.bytes); ph.magic_number = g_ntohl (ph.magic_number); if (ph.magic_number == GPATTERN_MAGIC && ph.version == 1 && ph.header_size > sizeof (PatternHeader) && ph.bytes == 3 && ph.width == bh.width && ph.height == bh.height && lseek (fd, ph.header_size - sizeof (PatternHeader), SEEK_CUR) > 0) { guchar *plain_brush = brush_buf; gint i; bh.bytes = 4; brush_buf = g_malloc (4 * bh.width * bh.height); for (i = 0; i < ph.width * ph.height; i++) { if (read (fd, brush_buf + i * 4, 3) != 3) { close (fd); g_free (name); g_free (plain_brush); g_free (brush_buf); return -1; } brush_buf[i * 4 + 3] = plain_brush[i]; } g_free (plain_brush); } } } break; case 2: { guint16 *buf = (guint16 *) brush_buf; gint i; for (i = 0; i < bh.width * bh.height; i++, buf++) { union { guint16 u[2]; gfloat f; } short_float; #if G_BYTE_ORDER == G_LITTLE_ENDIAN short_float.u[0] = 0; short_float.u[1] = GUINT16_FROM_BE (*buf); #else short_float.u[0] = GUINT16_FROM_BE (*buf); short_float.u[1] = 0; #endif brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5); } bh.bytes = 1; } break; default: break; } /* * Create a new image of the proper size and * associate the filename with it. */ switch (bh.bytes) { case 1: base_type = GIMP_GRAY; image_type = GIMP_GRAY_IMAGE; break; case 4: base_type = GIMP_RGB; image_type = GIMP_RGBA_IMAGE; break; default: g_message (""Unsupported brush depth: %d\n"" ""GIMP Brushes must be GRAY or RGBA\n"", bh.bytes); g_free (name); return -1; } image_ID = gimp_image_new (bh.width, bh.height, base_type); gimp_image_set_filename (image_ID, filename); parasite = gimp_parasite_new (""gimp-brush-name"", GIMP_PARASITE_PERSISTENT, strlen (name) + 1, name); gimp_image_attach_parasite (image_ID, parasite); gimp_parasite_free (parasite); layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height, image_type, 100, GIMP_NORMAL_MODE); gimp_image_insert_layer (image_ID, layer_ID, -1, 0); g_free (name); drawable = gimp_drawable_get (layer_ID); gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, drawable->width, drawable->height, TRUE, FALSE); gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf, 0, 0, bh.width, bh.height); g_free (brush_buf); if (image_type == GIMP_GRAY_IMAGE) gimp_invert (layer_ID); close (fd); gimp_drawable_flush (drawable); gimp_progress_update (1.0); return image_ID; }",CWE-125,1 1,"static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotated_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t count, y; unsigned char *pixels; unsigned int depth; quantum_info=(QuantumInfo *) NULL; (void) SeekBlob(image,0,SEEK_SET); while (EOFBlob(image) == MagickFalse) { /* Object parser loop. */ ldblk=ReadBlobLSBLong(image); if ((ldblk > 9999) || (ldblk < 0)) break; HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) break; /* Data format */ if (HDR.Type[2] != 0) break; /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if ((HDR.imagf != 0) && (HDR.imagf != 1)) break; if (HDR.nameLen > 0xFFFF) return(DestroyImageList(image)); for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; if ((image->columns == 0) || (image->rows == 0)) return(DestroyImageList(image)); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); if(HDR.imagf==1) ldblk *= 2; SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR); if ((image->columns == 0) || (image->rows == 0)) return(image->previous == (Image *) NULL ? DestroyImageList(image) : image); goto skip_reading_current; } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(DestroyImageList(image)); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; break; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1, exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(image,q,(int) image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ count=ReadBlob(image,depth/8*image->columns,(char *) pixels); if (count == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception); else InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception); } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } rotated_image=RotateImage(image,90.0,exception); if (rotated_image != (Image *) NULL) { rotated_image->page.x=0; rotated_image->page.y=0; rotated_image->colors = image->colors; DestroyBlob(rotated_image); rotated_image->blob=ReferenceBlob(image->blob); AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate next image structure. */ skip_reading_current: AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }",CWE-787,16 0," virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path, std::string* hardware_address) { hardware_address->clear(); NetworkIPConfigVector ipconfig_vector; if (EnsureCrosLoaded() && !device_path.empty()) { IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str()); if (ipconfig_status) { for (int i = 0; i < ipconfig_status->size; i++) { IPConfig ipconfig = ipconfig_status->ips[i]; ipconfig_vector.push_back( NetworkIPConfig(device_path, ipconfig.type, ipconfig.address, ipconfig.netmask, ipconfig.gateway, ipconfig.name_servers)); } *hardware_address = ipconfig_status->hardware_address; FreeIPConfigStatus(ipconfig_status); std::sort(ipconfig_vector.begin(), ipconfig_vector.end()); } } return ipconfig_vector; } ",none,24 1,"GF_Err mpgviddmx_process(GF_Filter *filter) { GF_MPGVidDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u64 byte_offset; s64 vosh_start = -1; s64 vosh_end = -1; GF_Err e; char *data; u8 *start; u32 pck_size; s32 remain; //always reparse duration if (!ctx->duration.num) mpgviddmx_check_dur(filter, ctx); pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { mpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_TRUE); if (ctx->opid) gf_filter_pid_set_eos(ctx->opid); if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = NULL; return GF_EOS; } return GF_OK; } data = (char *) gf_filter_pck_get_data(pck, &pck_size); byte_offset = gf_filter_pck_get_byte_offset(pck); start = data; remain = pck_size; //input pid sets some timescale - we flushed pending data , update cts if (!ctx->resume_from && ctx->timescale) { u64 ts = gf_filter_pck_get_cts(pck); if (ts != GF_FILTER_NO_TS) { if (!ctx->cts || !ctx->recompute_cts) ctx->cts = ts; } ts = gf_filter_pck_get_dts(pck); if (ts != GF_FILTER_NO_TS) { if (!ctx->dts || !ctx->recompute_cts) ctx->dts = ts; if (!ctx->prev_dts) ctx->prev_dts = ts; else if (ctx->prev_dts != ts) { u64 diff = ts; diff -= ctx->prev_dts; if (!ctx->cur_fps.den) ctx->cur_fps.den = (u32) diff; else if (ctx->cur_fps.den > diff) ctx->cur_fps.den = (u32) diff; } } gf_filter_pck_get_framing(pck, &ctx->input_is_au_start, &ctx->input_is_au_end); //this will force CTS recomput of each frame if (ctx->recompute_cts) ctx->input_is_au_start = GF_FALSE; if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = pck; gf_filter_pck_ref_props(&ctx->src_pck); } //we stored some data to find the complete vosh, aggregate this packet with current one if (!ctx->resume_from && ctx->hdr_store_size) { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size) { ctx->hdr_store_alloc = ctx->hdr_store_size + pck_size; ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data, sizeof(char)*pck_size); if (byte_offset != GF_FILTER_NO_BO) { if (byte_offset >= ctx->hdr_store_size) byte_offset -= ctx->hdr_store_size; else byte_offset = GF_FILTER_NO_BO; } ctx->hdr_store_size += pck_size; start = data = ctx->hdr_store; remain = pck_size = ctx->hdr_store_size; } if (ctx->resume_from) { if (gf_filter_pid_would_block(ctx->opid)) return GF_OK; //resume from data copied internally if (ctx->hdr_store_size) { assert(ctx->resume_from <= ctx->hdr_store_size); start = data = ctx->hdr_store + ctx->resume_from; remain = pck_size = ctx->hdr_store_size - ctx->resume_from; } else { assert(remain >= (s32) ctx->resume_from); start += ctx->resume_from; remain -= ctx->resume_from; } ctx->resume_from = 0; } if (!ctx->bs) { ctx->bs = gf_bs_new(start, remain, GF_BITSTREAM_READ); } else { gf_bs_reassign_buffer(ctx->bs, start, remain); } if (!ctx->vparser) { ctx->vparser = gf_m4v_parser_bs_new(ctx->bs, ctx->is_mpg12); } while (remain) { Bool full_frame; u8 *pck_data; s32 current; u8 sc_type, forced_sc_type=0; Bool sc_type_forced = GF_FALSE; Bool skip_pck = GF_FALSE; u8 ftype; u32 tinc; u64 size=0; u64 fstart; Bool is_coded; u32 bytes_from_store = 0; u32 hdr_offset = 0; Bool copy_last_bytes = GF_FALSE; //not enough bytes to parse start code if (remain<5) { memcpy(ctx->hdr_store, start, remain); ctx->bytes_in_header = remain; break; } current = -1; //we have some potential bytes of a start code in the store, copy some more bytes and check if valid start code. //if not, dispatch these bytes as continuation of the data if (ctx->bytes_in_header) { memcpy(ctx->hdr_store + ctx->bytes_in_header, start, 8 - ctx->bytes_in_header); current = mpgviddmx_next_start_code(ctx->hdr_store, 8); //no start code in stored buffer if ((current<0) || (current >= (s32) ctx->bytes_in_header) ) { if (ctx->opid) { dst_pck = gf_filter_pck_new_alloc(ctx->opid, ctx->bytes_in_header, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); memcpy(pck_data, ctx->hdr_store, ctx->bytes_in_header); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - ctx->bytes_in_header); } mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); } if (current<0) current = -1; else current -= ctx->bytes_in_header; ctx->bytes_in_header = 0; } else { //we have a valid start code, check which byte in our store or in the packet payload is the start code type //and remember its location to reinit the parser from there hdr_offset = 4 - ctx->bytes_in_header + current; //bytes still to dispatch bytes_from_store = ctx->bytes_in_header; ctx->bytes_in_header = 0; if (!hdr_offset) { forced_sc_type = ctx->hdr_store[current+3]; } else { forced_sc_type = start[hdr_offset-1]; } sc_type_forced = GF_TRUE; } } //no starcode in store, look for startcode in packet if (current == -1) { //locate next start code current = mpgviddmx_next_start_code(start, remain); //no start code, dispatch the block if (current<0) { u8 b3, b2, b1; if (! ctx->frame_started) { GF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, (""[MPGVid] no start code in block and no frame started, discarding data\n"" )); break; } size = remain; b3 = start[remain-3]; b2 = start[remain-2]; b1 = start[remain-1]; //we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes ! if (!b1 || !b2 || !b3) { copy_last_bytes = GF_TRUE; assert(size >= 3); size -= 3; ctx->bytes_in_header = 3; } dst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); memcpy(pck_data, start, (size_t) size); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_FALSE); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset); } mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); if (copy_last_bytes) { memcpy(ctx->hdr_store, start+remain-3, 3); } break; } } assert(current>=0); //if we are in the middle of parsing the vosh, skip over bytes remaining from previous obj not parsed if ((vosh_start>=0) && current) { assert(remain>=current); start += current; remain -= current; current = 0; } //also skip if no output pid if (!ctx->opid && current) { assert(remain>=current); start += current; remain -= current; current = 0; } //dispatch remaining bytes if (current>0) { //flush remaining dst_pck = gf_filter_pck_new_alloc(ctx->opid, current, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); gf_filter_pck_set_cts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_dts(dst_pck, GF_FILTER_NO_TS); gf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_TRUE); //bytes were partly in store, partly in packet if (bytes_from_store) { if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store); } assert(bytes_from_store>=(u32) current); bytes_from_store -= current; memcpy(pck_data, ctx->hdr_store, current); } else { //bytes were only in packet if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset); } memcpy(pck_data, start, current); assert(remain>=current); start += current; remain -= current; current = 0; } gf_filter_pck_set_carousel_version(dst_pck, 1); mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); } //parse headers //we have a start code loaded, eg the data packet does not have a full start code at the beginning if (sc_type_forced) { gf_bs_reassign_buffer(ctx->bs, start + hdr_offset, remain - hdr_offset); sc_type = forced_sc_type; } else { gf_bs_reassign_buffer(ctx->bs, start, remain); gf_bs_read_int(ctx->bs, 24); sc_type = gf_bs_read_int(ctx->bs, 8); } if (ctx->is_mpg12) { switch (sc_type) { case M2V_SEQ_START_CODE: case M2V_EXT_START_CODE: gf_bs_reassign_buffer(ctx->bs, start, remain); e = gf_m4v_parse_config(ctx->vparser, &ctx->dsi); //not enough data, accumulate until we can parse the full header if (e==GF_EOS) { if (vosh_start<0) vosh_start = 0; if (data == ctx->hdr_store) { memmove(ctx->hdr_store, start, remain); ctx->hdr_store_size = remain; } else { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) { ctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - vosh_start); ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) ); ctx->hdr_store_size += pck_size - (u32) vosh_start; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; } else if (e != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (""[MPGVid] Failed to parse VOS header: %s\n"", gf_error_to_string(e) )); } else { mpgviddmx_check_pid(filter, ctx, 0, NULL); } break; case M2V_PIC_START_CODE: break; default: break; } } else { u8 PL; switch (sc_type) { case M4V_VOS_START_CODE: ctx->dsi.VideoPL = (u8) gf_bs_read_u8(ctx->bs); vosh_start = start - (u8 *)data; skip_pck = GF_TRUE; assert(remain>=5); start += 5; remain -= 5; break; case M4V_VOL_START_CODE: gf_bs_reassign_buffer(ctx->bs, start, remain); PL = ctx->dsi.VideoPL; e = gf_m4v_parse_config(ctx->vparser, &ctx->dsi); ctx->dsi.VideoPL = PL; //not enough data, accumulate until we can parse the full header if (e==GF_EOS) { if (vosh_start<0) vosh_start = 0; if (data == ctx->hdr_store) { memmove(ctx->hdr_store, start, remain); ctx->hdr_store_size = remain; } else { if (ctx->hdr_store_alloc < ctx->hdr_store_size + pck_size - vosh_start) { ctx->hdr_store_alloc = (u32) (ctx->hdr_store_size + pck_size - (u32) vosh_start); ctx->hdr_store = gf_realloc(ctx->hdr_store, sizeof(char)*ctx->hdr_store_alloc); } memcpy(ctx->hdr_store + ctx->hdr_store_size, data + vosh_start, (size_t) (pck_size - vosh_start) ); ctx->hdr_store_size += pck_size - (u32) vosh_start; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; } else if (e != GF_OK) { GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, (""[MPGVid] Failed to parse VOS header: %s\n"", gf_error_to_string(e) )); } else { u32 obj_size = (u32) gf_m4v_get_object_start(ctx->vparser); if (vosh_start<0) vosh_start = 0; vosh_end = start - (u8 *)data + obj_size; vosh_end -= vosh_start; mpgviddmx_check_pid(filter, ctx,(u32) vosh_end, data+vosh_start); skip_pck = GF_TRUE; assert(remain>=(s32) obj_size); start += obj_size; remain -= obj_size; } break; case M4V_VOP_START_CODE: case M4V_GOV_START_CODE: break; case M4V_VO_START_CODE: case M4V_VISOBJ_START_CODE: default: if (vosh_start>=0) { skip_pck = GF_TRUE; assert(remain>=4); start += 4; remain -= 4; } break; } } if (skip_pck) { continue; } if (!ctx->opid) { assert(remain>=4); start += 4; remain -= 4; continue; } if (!ctx->is_playing) { ctx->resume_from = (u32) ((char *)start - (char *)data); return GF_OK; } //at this point, we no longer reaggregate packets ctx->hdr_store_size = 0; if (ctx->in_seek) { u64 nb_frames_at_seek = (u64) (ctx->start_range * ctx->cur_fps.num); if (ctx->cts + ctx->cur_fps.den >= nb_frames_at_seek) { //u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } //may happen that after all our checks, only 4 bytes are left, continue to store these 4 bytes if (remain<5) continue; //good to go gf_m4v_parser_reset(ctx->vparser, sc_type_forced ? forced_sc_type + 1 : 0); size = 0; e = gf_m4v_parse_frame(ctx->vparser, &ctx->dsi, &ftype, &tinc, &size, &fstart, &is_coded); //true if we strip VO and VISOBJ assert(!fstart); //we skipped bytes already in store + end of start code present in packet, so the size of the first object //needs adjustement if (bytes_from_store) { size += bytes_from_store + hdr_offset; } if ((e == GF_EOS) && !ctx->input_is_au_end) { u8 b3 = start[remain-3]; u8 b2 = start[remain-2]; u8 b1 = start[remain-1]; //we may have a startcode at the end of the packet, store it and don't dispatch the last 3 bytes ! if (!b1 || !b2 || !b3) { copy_last_bytes = GF_TRUE; assert(size >= 3); size -= 3; ctx->bytes_in_header = 3; } full_frame = GF_FALSE; } else { full_frame = GF_TRUE; } if (!is_coded) { /*if prev is B and we're parsing a packed bitstream discard n-vop*/ if (ctx->forced_packed && ctx->b_frames) { ctx->is_packed = GF_TRUE; assert(remain>=size); start += size; remain -= (s32) size; continue; } /*policy is to import at variable frame rate, skip*/ if (ctx->vfr) { ctx->is_vfr = GF_TRUE; mpgviddmx_update_time(ctx); assert(remain>=size); start += size; remain -= (s32) size; continue; } /*policy is to keep non coded frame (constant frame rate), add*/ } if (ftype==2) { //count number of B-frames since last ref ctx->b_frames++; ctx->nb_b++; } else { //flush all pending packets mpgviddmx_enqueue_or_dispatch(ctx, NULL, GF_TRUE, GF_FALSE); //remeber the CTS of the last ref ctx->last_ref_cts = ctx->cts; if (ctx->max_b < ctx->b_frames) ctx->max_b = ctx->b_frames; ctx->b_frames = 0; if (ftype) ctx->nb_p++; else ctx->nb_i++; } ctx->nb_frames++; dst_pck = gf_filter_pck_new_alloc(ctx->opid, (u32) size, &pck_data); if (!dst_pck) return GF_OUT_OF_MEM; if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); //bytes come from both our store and the data packet if (bytes_from_store) { memcpy(pck_data, ctx->hdr_store+current, bytes_from_store); assert(size >= bytes_from_store); size -= bytes_from_store; if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset - bytes_from_store); } memcpy(pck_data + bytes_from_store, start, (size_t) size); } else { //bytes only come the data packet memcpy(pck_data, start, (size_t) size); if (byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, byte_offset + start - (u8 *) data); } } assert(pck_data[0] == 0); assert(pck_data[1] == 0); assert(pck_data[2] == 0x01); gf_filter_pck_set_framing(dst_pck, GF_TRUE, (full_frame || ctx->input_is_au_end) ? GF_TRUE : GF_FALSE); gf_filter_pck_set_cts(dst_pck, ctx->cts); gf_filter_pck_set_dts(dst_pck, ctx->dts); if (ctx->input_is_au_start) { ctx->input_is_au_start = GF_FALSE; } else { //we use the carousel flag temporarly to indicate the cts must be recomputed gf_filter_pck_set_carousel_version(dst_pck, 1); } gf_filter_pck_set_sap(dst_pck, ftype ? GF_FILTER_SAP_NONE : GF_FILTER_SAP_1); gf_filter_pck_set_duration(dst_pck, ctx->cur_fps.den); if (ctx->in_seek) gf_filter_pck_set_seek_flag(dst_pck, GF_TRUE); ctx->frame_started = GF_TRUE; mpgviddmx_enqueue_or_dispatch(ctx, dst_pck, GF_FALSE, GF_FALSE); mpgviddmx_update_time(ctx); if (!full_frame) { if (copy_last_bytes) { memcpy(ctx->hdr_store, start+remain-3, 3); } break; } assert(remain>=size); start += size; remain -= (s32) size; } gf_filter_pid_drop_packet(ctx->ipid); return GF_OK; }",CWE-476,12 1,"Status SparseCountSparseOutputShapeFn(InferenceContext *c) { auto rank = c->Dim(c->input(0), 1); auto nvals = c->UnknownDim(); c->set_output(0, c->Matrix(nvals, rank)); // out.indices c->set_output(1, c->Vector(nvals)); // out.values c->set_output(2, c->Vector(rank)); // out.dense_shape return Status::OK(); }",CWE-125,1 0," GetPersistentHostQuotaTask( QuotaManager* manager, const std::string& host, HostQuotaCallback* callback) : DatabaseTaskBase(manager), host_(host), quota_(-1), callback_(callback) { } ",none,24 1,"Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def, string* init_op_name) { const auto& sig_def_map = meta_graph_def.signature_def(); const auto& init_op_sig_it = meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey); if (init_op_sig_it != sig_def_map.end()) { *init_op_name = init_op_sig_it->second.outputs() .find(kSavedModelInitOpSignatureKey) ->second.name(); return Status::OK(); } const auto& collection_def_map = meta_graph_def.collection_def(); string init_op_collection_key; if (collection_def_map.find(kSavedModelMainOpKey) != collection_def_map.end()) { init_op_collection_key = kSavedModelMainOpKey; } else { init_op_collection_key = kSavedModelLegacyInitOpKey; } const auto init_op_it = collection_def_map.find(init_op_collection_key); if (init_op_it != collection_def_map.end()) { if (init_op_it->second.node_list().value_size() != 1) { return errors::FailedPrecondition( strings::StrCat(""Expected exactly one main op in : "", export_dir)); } *init_op_name = init_op_it->second.node_list().value(0); } return Status::OK(); }",CWE-476,12 1,"IRC_PROTOCOL_CALLBACK(352) { char *pos_attr, *pos_hopcount, *pos_realname, *str_host; int arg_start, length; struct t_irc_channel *ptr_channel; struct t_irc_nick *ptr_nick; IRC_PROTOCOL_MIN_ARGS(5); /* silently ignore malformed 352 message (missing infos) */ if (argc < 8) return WEECHAT_RC_OK; pos_attr = NULL; pos_hopcount = NULL; pos_realname = NULL; if (argc > 8) { arg_start = (strcmp (argv[8], ""*"") == 0) ? 9 : 8; if (argv[arg_start][0] == ':') { pos_attr = NULL; pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL; pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL; } else { pos_attr = argv[arg_start]; pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL; pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL; } } ptr_channel = irc_channel_search (server, argv[3]); ptr_nick = (ptr_channel) ? irc_nick_search (server, ptr_channel, argv[7]) : NULL; /* update host in nick */ if (ptr_nick) { length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1; str_host = malloc (length); if (str_host) { snprintf (str_host, length, ""%s@%s"", argv[4], argv[5]); irc_nick_set_host (ptr_nick, str_host); free (str_host); } } /* update away flag in nick */ if (ptr_channel && ptr_nick && pos_attr) { irc_nick_set_away (server, ptr_channel, ptr_nick, (pos_attr[0] == 'G') ? 1 : 0); } /* update realname in nick */ if (ptr_channel && ptr_nick && pos_realname) { if (ptr_nick->realname) free (ptr_nick->realname); if (pos_realname && weechat_hashtable_has_key (server->cap_list, ""extended-join"")) { ptr_nick->realname = strdup (pos_realname); } else { ptr_nick->realname = NULL; } } /* display output of who (manual who from user) */ if (!ptr_channel || (ptr_channel->checking_whox <= 0)) { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, NULL, command, ""who"", NULL), date, irc_protocol_tags (command, ""irc_numeric"", NULL, NULL), ""%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)"", weechat_prefix (""network""), IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_CHANNEL, argv[3], IRC_COLOR_CHAT_DELIMITERS, irc_nick_color_for_msg (server, 1, NULL, argv[7]), argv[7], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_HOST, argv[4], argv[5], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_RESET, (pos_attr) ? pos_attr : """", (pos_attr) ? "" "" : """", (pos_hopcount) ? pos_hopcount : """", (pos_hopcount) ? "" "" : """", (pos_realname) ? pos_realname : """"); } return WEECHAT_RC_OK; }",CWE-476,12 0,"void QuotaManager::SetTemporaryGlobalQuota(int64 new_quota, QuotaCallback* callback) { LazyInitialize(); if (new_quota < 0) { callback->Run(kQuotaErrorInvalidModification, kStorageTypeTemporary, -1); delete callback; return; } if (!db_disabled_) { scoped_refptr task( new UpdateTemporaryGlobalQuotaTask(this, new_quota, callback)); task->Start(); } else { callback->Run(kQuotaErrorInvalidAccess, kStorageTypeTemporary, -1); delete callback; } } ",none,24 1,"static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) { p = g; } } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; }",CWE-125,1 1,"void HierarchicalBitmapRequester::PrepareForDecoding(void) { #if ACCUSOFT_CODE UBYTE i; BuildCommon(); if (m_ppDecodingMCU == NULL) { m_ppDecodingMCU = (struct Line **)m_pEnviron->AllocMem(sizeof(struct Line *) * m_ucCount*8); memset(m_ppDecodingMCU,0,sizeof(struct Line *) * m_ucCount * 8); } if (m_ppUpsampler == NULL) { m_ppUpsampler = (class UpsamplerBase **)m_pEnviron->AllocMem(sizeof(class UpsamplerBase *) * m_ucCount); memset(m_ppUpsampler,0,sizeof(class Upsampler *) * m_ucCount); for(i = 0;i < m_ucCount;i++) { class Component *comp = m_pFrame->ComponentOf(i); UBYTE sx = comp->SubXOf(); UBYTE sy = comp->SubYOf(); if (sx > 1 || sy > 1) { m_ppUpsampler[i] = UpsamplerBase::CreateUpsampler(m_pEnviron,sx,sy, m_ulPixelWidth,m_ulPixelHeight, m_pFrame->TablesOf()->isChromaCentered()); m_bSubsampling = true; } } } if (m_pLargestScale) m_pLargestScale->PrepareForDecoding(); #endif }",CWE-787,16 1,"int hfsplus_find_cat(struct super_block *sb, u32 cnid, struct hfs_find_data *fd) { hfsplus_cat_entry tmp; int err; u16 type; hfsplus_cat_build_key(sb, fd->search_key, cnid, NULL); err = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry)); if (err) return err; type = be16_to_cpu(tmp.type); if (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) { printk(KERN_ERR ""hfs: found bad thread record in catalog\n""); return -EIO; } hfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID), &tmp.thread.nodeName); return hfs_brec_find(fd); }",CWE-119,0 1,"find_next_quote( char_u *line, int col, int quotechar, char_u *escape) // escape characters, can be NULL { int c; for (;;) { c = line[col]; if (c == NUL) return -1; else if (escape != NULL && vim_strchr(escape, c)) ++col; else if (c == quotechar) break; if (has_mbyte) col += (*mb_ptr2len)(line + col); else ++col; } return col; }",CWE-787,16 0,"void QuotaManager::GetTemporaryGlobalQuota(QuotaCallback* callback) { LazyInitialize(); if (temporary_global_quota_ >= 0) { callback->Run(kQuotaStatusOk, kStorageTypeTemporary, temporary_global_quota_); delete callback; return; } temporary_global_quota_callbacks_.Add(callback); } ",none,24 0,"void QuotaManager::EvictOriginData( const GURL& origin, StorageType type, EvictOriginDataCallback* callback) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK_EQ(type, kStorageTypeTemporary); eviction_context_.evicted_origin = origin; eviction_context_.evicted_type = type; eviction_context_.evict_origin_data_callback.reset(callback); DeleteOriginData(origin, type, callback_factory_.NewCallback( &QuotaManager::DidOriginDataEvicted)); } ",none,24 0," int64 host_usage() const { return host_usage_; } ",none,24 0," QuotaManager* manager() const { return manager_; } ",none,24 1,"int cgroup1_parse_param(struct fs_context *fc, struct fs_parameter *param) { struct cgroup_fs_context *ctx = cgroup_fc2context(fc); struct cgroup_subsys *ss; struct fs_parse_result result; int opt, i; opt = fs_parse(fc, cgroup1_fs_parameters, param, &result); if (opt == -ENOPARAM) { if (strcmp(param->key, ""source"") == 0) { if (fc->source) return invalf(fc, ""Multiple sources not supported""); fc->source = param->string; param->string = NULL; return 0; } for_each_subsys(ss, i) { if (strcmp(param->key, ss->legacy_name)) continue; if (!cgroup_ssid_enabled(i) || cgroup1_ssid_disabled(i)) return invalfc(fc, ""Disabled controller '%s'"", param->key); ctx->subsys_mask |= (1 << i); return 0; } return invalfc(fc, ""Unknown subsys name '%s'"", param->key); } if (opt < 0) return opt; switch (opt) { case Opt_none: /* Explicitly have no subsystems */ ctx->none = true; break; case Opt_all: ctx->all_ss = true; break; case Opt_noprefix: ctx->flags |= CGRP_ROOT_NOPREFIX; break; case Opt_clone_children: ctx->cpuset_clone_children = true; break; case Opt_cpuset_v2_mode: ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE; break; case Opt_xattr: ctx->flags |= CGRP_ROOT_XATTR; break; case Opt_release_agent: /* Specifying two release agents is forbidden */ if (ctx->release_agent) return invalfc(fc, ""release_agent respecified""); ctx->release_agent = param->string; param->string = NULL; break; case Opt_name: /* blocked by boot param? */ if (cgroup_no_v1_named) return -ENOENT; /* Can't specify an empty name */ if (!param->size) return invalfc(fc, ""Empty name""); if (param->size > MAX_CGROUP_ROOT_NAMELEN - 1) return invalfc(fc, ""Name too long""); /* Must match [\w.-]+ */ for (i = 0; i < param->size; i++) { char c = param->string[i]; if (isalnum(c)) continue; if ((c == '.') || (c == '-') || (c == '_')) continue; return invalfc(fc, ""Invalid name""); } /* Specifying two names is forbidden */ if (ctx->name) return invalfc(fc, ""name respecified""); ctx->name = param->string; param->string = NULL; break; } return 0; }",CWE-416,10 1,"PlayerGeneric::~PlayerGeneric() { if (mixer) delete mixer; if (player) { if (mixer->isActive() && !mixer->isDeviceRemoved(player)) mixer->removeDevice(player); delete player; } delete[] audioDriverName; delete listener; }",CWE-416,10 0," void DidGetAvailableSpace(QuotaStatusCode status, int64 available_space) { quota_status_ = status; available_space_ = available_space; } ",none,24 1,"load_image (const gchar *filename, GError **error) { FILE *fp; tga_info info; guchar header[18]; guchar footer[26]; guchar extension[495]; long offset; gint32 image_ID = -1; gimp_progress_init_printf (_(""Opening '%s'""), gimp_filename_to_utf8 (filename)); fp = g_fopen (filename, ""rb""); if (! fp) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _(""Could not open '%s' for reading: %s""), gimp_filename_to_utf8 (filename), g_strerror (errno)); return -1; } /* Is file big enough for a footer? */ if (!fseek (fp, -26L, SEEK_END)) { if (fread (footer, sizeof (footer), 1, fp) != 1) { g_message (_(""Cannot read footer from '%s'""), gimp_filename_to_utf8 (filename)); return -1; } else if (memcmp (footer + 8, magic, sizeof (magic)) == 0) { /* Check the signature. */ offset = (footer[0] + footer[1] * 256L + footer[2] * 65536L + footer[3] * 16777216L); if (offset != 0) { if (fseek (fp, offset, SEEK_SET) || fread (extension, sizeof (extension), 1, fp) != 1) { g_message (_(""Cannot read extension from '%s'""), gimp_filename_to_utf8 (filename)); return -1; } /* Eventually actually handle version 2 TGA here */ } } } if (fseek (fp, 0, SEEK_SET) || fread (header, sizeof (header), 1, fp) != 1) { g_message (_(""Cannot read header from '%s'""), gimp_filename_to_utf8 (filename)); return -1; } switch (header[2]) { case 1: info.imageType = TGA_TYPE_MAPPED; info.imageCompression = TGA_COMP_NONE; break; case 2: info.imageType = TGA_TYPE_COLOR; info.imageCompression = TGA_COMP_NONE; break; case 3: info.imageType = TGA_TYPE_GRAY; info.imageCompression = TGA_COMP_NONE; break; case 9: info.imageType = TGA_TYPE_MAPPED; info.imageCompression = TGA_COMP_RLE; break; case 10: info.imageType = TGA_TYPE_COLOR; info.imageCompression = TGA_COMP_RLE; break; case 11: info.imageType = TGA_TYPE_GRAY; info.imageCompression = TGA_COMP_RLE; break; default: info.imageType = 0; } info.idLength = header[0]; info.colorMapType = header[1]; info.colorMapIndex = header[3] + header[4] * 256; info.colorMapLength = header[5] + header[6] * 256; info.colorMapSize = header[7]; info.xOrigin = header[8] + header[9] * 256; info.yOrigin = header[10] + header[11] * 256; info.width = header[12] + header[13] * 256; info.height = header[14] + header[15] * 256; info.bpp = header[16]; info.bytes = (info.bpp + 7) / 8; info.alphaBits = header[17] & 0x0f; /* Just the low 4 bits */ info.flipHoriz = (header[17] & 0x10) ? 1 : 0; info.flipVert = (header[17] & 0x20) ? 0 : 1; /* hack to handle some existing files with incorrect headers, see bug #306675 */ if (info.alphaBits == info.bpp) info.alphaBits = 0; /* hack to handle yet another flavor of incorrect headers, see bug #540969 */ if (info.alphaBits == 0) { if (info.imageType == TGA_TYPE_COLOR && info.bpp == 32) info.alphaBits = 8; if (info.imageType == TGA_TYPE_GRAY && info.bpp == 16) info.alphaBits = 8; } switch (info.imageType) { case TGA_TYPE_MAPPED: if (info.bpp != 8) { g_message (""Unhandled sub-format in '%s' (type = %u, bpp = %u)"", gimp_filename_to_utf8 (filename), info.imageType, info.bpp); return -1; } break; case TGA_TYPE_COLOR: if (info.bpp != 15 && info.bpp != 16 && info.bpp != 24 && info.bpp != 32) { g_message (""Unhandled sub-format in '%s' (type = %u, bpp = %u)"", gimp_filename_to_utf8 (filename), info.imageType, info.bpp); return -1; } break; case TGA_TYPE_GRAY: if (info.bpp != 8 && (info.alphaBits != 8 || (info.bpp != 16 && info.bpp != 15))) { g_message (""Unhandled sub-format in '%s' (type = %u, bpp = %u)"", gimp_filename_to_utf8 (filename), info.imageType, info.bpp); return -1; } break; default: g_message (""Unknown image type %u for '%s'"", info.imageType, gimp_filename_to_utf8 (filename)); return -1; } /* Plausible but unhandled formats */ if (info.bytes * 8 != info.bpp && info.bpp != 15) { g_message (""Unhandled sub-format in '%s' (type = %u, bpp = %u)"", gimp_filename_to_utf8 (filename), info.imageType, info.bpp); return -1; } /* Check that we have a color map only when we need it. */ if (info.imageType == TGA_TYPE_MAPPED && info.colorMapType != 1) { g_message (""Indexed image has invalid color map type %u"", info.colorMapType); return -1; } else if (info.imageType != TGA_TYPE_MAPPED && info.colorMapType != 0) { g_message (""Non-indexed image has invalid color map type %u"", info.colorMapType); return -1; } /* Skip the image ID field. */ if (info.idLength && fseek (fp, info.idLength, SEEK_CUR)) { g_message (""File '%s' is truncated or corrupted"", gimp_filename_to_utf8 (filename)); return -1; } image_ID = ReadImage (fp, &info, filename); fclose (fp); return image_ID; }",CWE-125,1 1,"yank_copy_line(struct block_def *bd, long y_idx, int exclude_trailing_space) { char_u *pnew; if (exclude_trailing_space) bd->endspaces = 0; if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1)) == NULL) return FAIL; y_current->y_array[y_idx] = pnew; vim_memset(pnew, ' ', (size_t)bd->startspaces); pnew += bd->startspaces; mch_memmove(pnew, bd->textstart, (size_t)bd->textlen); pnew += bd->textlen; vim_memset(pnew, ' ', (size_t)bd->endspaces); pnew += bd->endspaces; if (exclude_trailing_space) { int s = bd->textlen + bd->endspaces; while (VIM_ISWHITE(*(bd->textstart + s - 1)) && s > 0) { s = s - (*mb_head_off)(bd->textstart, bd->textstart + s - 1) - 1; pnew--; } } *pnew = NUL; return OK; }",CWE-787,16 0," UsageAndQuotaDispatcherTaskForPersistent( QuotaManager* manager, const std::string& host) : UsageAndQuotaDispatcherTask(manager, host, kStorageTypePersistent) {} ",none,24 1,"static int synic_set_irq(struct kvm_vcpu_hv_synic *synic, u32 sint) { struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic); struct kvm_lapic_irq irq; int ret, vector; if (sint >= ARRAY_SIZE(synic->sint)) return -EINVAL; vector = synic_get_sint_vector(synic_read_sint(synic, sint)); if (vector < 0) return -ENOENT; memset(&irq, 0, sizeof(irq)); irq.shorthand = APIC_DEST_SELF; irq.dest_mode = APIC_DEST_PHYSICAL; irq.delivery_mode = APIC_DM_FIXED; irq.vector = vector; irq.level = 1; ret = kvm_irq_delivery_to_apic(vcpu->kvm, vcpu->arch.apic, &irq, NULL); trace_kvm_hv_synic_set_irq(vcpu->vcpu_id, sint, irq.vector, ret); return ret; }",CWE-476,12 1,"void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *sess, const void *pkt, pj_size_t size) { const pjmedia_rtcp_xr_pkt *rtcp_xr = (pjmedia_rtcp_xr_pkt*) pkt; const pjmedia_rtcp_xr_rb_rr_time *rb_rr_time = NULL; const pjmedia_rtcp_xr_rb_dlrr *rb_dlrr = NULL; const pjmedia_rtcp_xr_rb_stats *rb_stats = NULL; const pjmedia_rtcp_xr_rb_voip_mtc *rb_voip_mtc = NULL; const pjmedia_rtcp_xr_rb_header *rb_hdr = (pjmedia_rtcp_xr_rb_header*) rtcp_xr->buf; unsigned pkt_len, rb_len; if (rtcp_xr->common.pt != RTCP_XR) return; pkt_len = pj_ntohs((pj_uint16_t)rtcp_xr->common.length); if ((pkt_len + 1) > (size / 4)) return; /* Parse report rpt_types */ while ((pj_int32_t*)rb_hdr < (pj_int32_t*)pkt + pkt_len) { rb_len = pj_ntohs((pj_uint16_t)rb_hdr->length); /* Just skip any block with length == 0 (no report content) */ if (rb_len) { switch (rb_hdr->bt) { case BT_RR_TIME: rb_rr_time = (pjmedia_rtcp_xr_rb_rr_time*) rb_hdr; break; case BT_DLRR: rb_dlrr = (pjmedia_rtcp_xr_rb_dlrr*) rb_hdr; break; case BT_STATS: rb_stats = (pjmedia_rtcp_xr_rb_stats*) rb_hdr; break; case BT_VOIP_METRICS: rb_voip_mtc = (pjmedia_rtcp_xr_rb_voip_mtc*) rb_hdr; break; default: break; } } rb_hdr = (pjmedia_rtcp_xr_rb_header*) ((pj_int32_t*)rb_hdr + rb_len + 1); } /* Receiving RR Time */ if (rb_rr_time) { /* Save LRR from NTP timestamp of the RR time block report */ sess->rx_lrr = ((pj_ntohl(rb_rr_time->ntp_sec) & 0x0000FFFF) << 16) | ((pj_ntohl(rb_rr_time->ntp_frac) >> 16) & 0xFFFF); /* Calculate RR arrival time for DLRR */ pj_get_timestamp(&sess->rx_lrr_time); TRACE_((sess->name, ""Rx RTCP SR: ntp_ts=%p"", sess->rx_lrr, (pj_uint32_t)(sess->rx_lrr_time.u64*65536/ sess->rtcp_session->ts_freq.u64))); } /* Receiving DLRR */ if (rb_dlrr) { pj_uint32_t lrr, now, dlrr; pj_uint64_t eedelay; pjmedia_rtcp_ntp_rec ntp; /* LRR is the middle 32bit of NTP. It has 1/65536 second * resolution */ lrr = pj_ntohl(rb_dlrr->item.lrr); /* DLRR is delay since LRR, also in 1/65536 resolution */ dlrr = pj_ntohl(rb_dlrr->item.dlrr); /* Get current time, and convert to 1/65536 resolution */ pjmedia_rtcp_get_ntp_time(sess->rtcp_session, &ntp); now = ((ntp.hi & 0xFFFF) << 16) + (ntp.lo >> 16); /* End-to-end delay is (now-lrr-dlrr) */ eedelay = now - lrr - dlrr; /* Convert end to end delay to usec (keeping the calculation in * 64bit space):: * sess->ee_delay = (eedelay * 1000) / 65536; */ if (eedelay < 4294) { eedelay = (eedelay * 1000000) >> 16; } else { eedelay = (eedelay * 1000) >> 16; eedelay *= 1000; } TRACE_((sess->name, ""Rx RTCP XR DLRR: lrr=%p, dlrr=%p (%d:%03dms), "" ""now=%p, rtt=%p"", lrr, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, now, (pj_uint32_t)eedelay)); /* Only save calculation if ""now"" is greater than lrr, or * otherwise rtt will be invalid */ if (now-dlrr >= lrr) { unsigned rtt = (pj_uint32_t)eedelay; /* Check that eedelay value really makes sense. * We allow up to 30 seconds RTT! */ if (eedelay <= 30 * 1000 * 1000UL) { /* ""Normalize"" rtt value that is exceptionally high. * For such values, ""normalize"" the rtt to be three times * the average value. */ if (rtt>((unsigned)sess->stat.rtt.mean*3) && sess->stat.rtt.n!=0) { unsigned orig_rtt = rtt; rtt = (unsigned)sess->stat.rtt.mean*3; PJ_LOG(5,(sess->name, ""RTT value %d usec is normalized to %d usec"", orig_rtt, rtt)); } TRACE_((sess->name, ""RTCP RTT is set to %d usec"", rtt)); pj_math_stat_update(&sess->stat.rtt, rtt); } } else { PJ_LOG(5, (sess->name, ""Internal RTCP NTP clock skew detected: "" ""lrr=%p, now=%p, dlrr=%p (%d:%03dms), "" ""diff=%d"", lrr, now, dlrr, dlrr/65536, (dlrr%65536)*1000/65536, dlrr-(now-lrr))); } } /* Receiving Statistics Summary */ if (rb_stats) { pj_uint8_t flags = rb_stats->header.specific; pj_bzero(&sess->stat.tx.stat_sum, sizeof(sess->stat.tx.stat_sum)); /* Range of packets sequence reported in this blocks */ sess->stat.tx.stat_sum.begin_seq = pj_ntohs(rb_stats->begin_seq); sess->stat.tx.stat_sum.end_seq = pj_ntohs(rb_stats->end_seq); /* Get flags of valid fields */ sess->stat.tx.stat_sum.l = (flags & (1 << 7)) != 0; sess->stat.tx.stat_sum.d = (flags & (1 << 6)) != 0; sess->stat.tx.stat_sum.j = (flags & (1 << 5)) != 0; sess->stat.tx.stat_sum.t = (flags & (3 << 3)) != 0; /* Fetch the reports info */ if (sess->stat.tx.stat_sum.l) { sess->stat.tx.stat_sum.lost = pj_ntohl(rb_stats->lost); } if (sess->stat.tx.stat_sum.d) { sess->stat.tx.stat_sum.dup = pj_ntohl(rb_stats->dup); } if (sess->stat.tx.stat_sum.j) { sess->stat.tx.stat_sum.jitter.min = pj_ntohl(rb_stats->jitter_min); sess->stat.tx.stat_sum.jitter.max = pj_ntohl(rb_stats->jitter_max); sess->stat.tx.stat_sum.jitter.mean= pj_ntohl(rb_stats->jitter_mean); pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.jitter, pj_ntohl(rb_stats->jitter_dev)); } if (sess->stat.tx.stat_sum.t) { sess->stat.tx.stat_sum.toh.min = rb_stats->toh_min; sess->stat.tx.stat_sum.toh.max = rb_stats->toh_max; sess->stat.tx.stat_sum.toh.mean= rb_stats->toh_mean; pj_math_stat_set_stddev(&sess->stat.tx.stat_sum.toh, pj_ntohl(rb_stats->toh_dev)); } pj_gettimeofday(&sess->stat.tx.stat_sum.update); } /* Receiving VoIP Metrics */ if (rb_voip_mtc) { sess->stat.tx.voip_mtc.loss_rate = rb_voip_mtc->loss_rate; sess->stat.tx.voip_mtc.discard_rate = rb_voip_mtc->discard_rate; sess->stat.tx.voip_mtc.burst_den = rb_voip_mtc->burst_den; sess->stat.tx.voip_mtc.gap_den = rb_voip_mtc->gap_den; sess->stat.tx.voip_mtc.burst_dur = pj_ntohs(rb_voip_mtc->burst_dur); sess->stat.tx.voip_mtc.gap_dur = pj_ntohs(rb_voip_mtc->gap_dur); sess->stat.tx.voip_mtc.rnd_trip_delay = pj_ntohs(rb_voip_mtc->rnd_trip_delay); sess->stat.tx.voip_mtc.end_sys_delay = pj_ntohs(rb_voip_mtc->end_sys_delay); /* signal & noise level encoded in two's complement form */ sess->stat.tx.voip_mtc.signal_lvl = (pj_int8_t) ((rb_voip_mtc->signal_lvl > 127)? ((int)rb_voip_mtc->signal_lvl - 256) : rb_voip_mtc->signal_lvl); sess->stat.tx.voip_mtc.noise_lvl = (pj_int8_t) ((rb_voip_mtc->noise_lvl > 127)? ((int)rb_voip_mtc->noise_lvl - 256) : rb_voip_mtc->noise_lvl); sess->stat.tx.voip_mtc.rerl = rb_voip_mtc->rerl; sess->stat.tx.voip_mtc.gmin = rb_voip_mtc->gmin; sess->stat.tx.voip_mtc.r_factor = rb_voip_mtc->r_factor; sess->stat.tx.voip_mtc.ext_r_factor = rb_voip_mtc->ext_r_factor; sess->stat.tx.voip_mtc.mos_lq = rb_voip_mtc->mos_lq; sess->stat.tx.voip_mtc.mos_cq = rb_voip_mtc->mos_cq; sess->stat.tx.voip_mtc.rx_config = rb_voip_mtc->rx_config; sess->stat.tx.voip_mtc.jb_nom = pj_ntohs(rb_voip_mtc->jb_nom); sess->stat.tx.voip_mtc.jb_max = pj_ntohs(rb_voip_mtc->jb_max); sess->stat.tx.voip_mtc.jb_abs_max = pj_ntohs(rb_voip_mtc->jb_abs_max); pj_gettimeofday(&sess->stat.tx.voip_mtc.update); } }",CWE-125,1 0," virtual bool cellular_connected() const { return false; } ",none,24 0," void QuotaManager::GetUsageAndQuota( const GURL& origin, StorageType type, GetUsageAndQuotaCallback* callback_ptr) { scoped_ptr callback(callback_ptr); LazyInitialize(); if (type == kStorageTypeUnknown) { callback->Run(kQuotaErrorNotSupported, 0, 0); return; } std::string host = net::GetHostOrSpecFromURL(origin); UsageAndQuotaDispatcherTaskMap::iterator found = usage_and_quota_dispatchers_.find(std::make_pair(host, type)); if (found == usage_and_quota_dispatchers_.end()) { UsageAndQuotaDispatcherTask* dispatcher = UsageAndQuotaDispatcherTask::Create(this, host, type); found = usage_and_quota_dispatchers_.insert( std::make_pair(std::make_pair(host, type), dispatcher)).first; } if (found->second->AddCallback( callback.release(), IsStorageUnlimited(origin))) { found->second->Start(); } } ",none,24 1,"void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &inPen) { #ifdef QT_DEBUG_DRAW qDebug() << ""QPaintEngineEx::stroke()"" << pen; #endif Q_D(QPaintEngineEx); if (path.isEmpty()) return; if (!d->strokeHandler) { d->strokeHandler = new StrokeHandler(path.elementCount()+4); d->stroker.setMoveToHook(qpaintengineex_moveTo); d->stroker.setLineToHook(qpaintengineex_lineTo); d->stroker.setCubicToHook(qpaintengineex_cubicTo); } QRectF clipRect; QPen pen = inPen; if (pen.style() > Qt::SolidLine) { QRectF cpRect = path.controlPointRect(); const QTransform &xf = state()->matrix; if (pen.isCosmetic()) { clipRect = d->exDeviceRect; cpRect.translate(xf.dx(), xf.dy()); } else { clipRect = xf.inverted().mapRect(QRectF(d->exDeviceRect)); } // Check to avoid generating unwieldy amount of dashes that will not be visible anyway QRectF extentRect = cpRect & clipRect; qreal extent = qMax(extentRect.width(), extentRect.height()); qreal patternLength = 0; const QList pattern = pen.dashPattern(); const int patternSize = qMin(pattern.size(), 32); for (int i = 0; i < patternSize; i++) patternLength += qMax(pattern.at(i), qreal(0)); if (pen.widthF()) patternLength *= pen.widthF(); if (qFuzzyIsNull(patternLength)) { pen.setStyle(Qt::NoPen); } else if (extent / patternLength > 10000) { // approximate stream of tiny dashes with semi-transparent solid line pen.setStyle(Qt::SolidLine); QColor color(pen.color()); color.setAlpha(color.alpha() / 2); pen.setColor(color); } } if (!qpen_fast_equals(pen, d->strokerPen)) { d->strokerPen = pen; d->stroker.setJoinStyle(pen.joinStyle()); d->stroker.setCapStyle(pen.capStyle()); d->stroker.setMiterLimit(pen.miterLimit()); qreal penWidth = pen.widthF(); if (penWidth == 0) d->stroker.setStrokeWidth(1); else d->stroker.setStrokeWidth(penWidth); Qt::PenStyle style = pen.style(); if (style == Qt::SolidLine) { d->activeStroker = &d->stroker; } else if (style == Qt::NoPen) { d->activeStroker = nullptr; } else { d->dasher.setDashPattern(pen.dashPattern()); d->dasher.setDashOffset(pen.dashOffset()); d->activeStroker = &d->dasher; } } if (!d->activeStroker) { return; } if (!clipRect.isNull()) d->activeStroker->setClipRect(clipRect); if (d->activeStroker == &d->stroker) d->stroker.setForceOpen(path.hasExplicitOpen()); const QPainterPath::ElementType *types = path.elements(); const qreal *points = path.points(); int pointCount = path.elementCount(); const qreal *lastPoint = points + (pointCount<<1); d->strokeHandler->types.reset(); d->strokeHandler->pts.reset(); // Some engines might decide to optimize for the non-shape hint later on... uint flags = QVectorPath::WindingFill; if (path.elementCount() > 2) flags |= QVectorPath::NonConvexShapeMask; if (d->stroker.capStyle() == Qt::RoundCap || d->stroker.joinStyle() == Qt::RoundJoin) flags |= QVectorPath::CurvedShapeMask; // ### Perspective Xforms are currently not supported... if (!pen.isCosmetic()) { // We include cosmetic pens in this case to avoid having to // change the current transform. Normal transformed, // non-cosmetic pens will be transformed as part of fill // later, so they are also covered here.. d->activeStroker->setCurveThresholdFromTransform(state()->matrix); d->activeStroker->begin(d->strokeHandler); if (types) { while (points < lastPoint) { switch (*types) { case QPainterPath::MoveToElement: d->activeStroker->moveTo(points[0], points[1]); points += 2; ++types; break; case QPainterPath::LineToElement: d->activeStroker->lineTo(points[0], points[1]); points += 2; ++types; break; case QPainterPath::CurveToElement: d->activeStroker->cubicTo(points[0], points[1], points[2], points[3], points[4], points[5]); points += 6; types += 3; flags |= QVectorPath::CurvedShapeMask; break; default: break; } } if (path.hasImplicitClose()) d->activeStroker->lineTo(path.points()[0], path.points()[1]); } else { d->activeStroker->moveTo(points[0], points[1]); points += 2; while (points < lastPoint) { d->activeStroker->lineTo(points[0], points[1]); points += 2; } if (path.hasImplicitClose()) d->activeStroker->lineTo(path.points()[0], path.points()[1]); } d->activeStroker->end(); if (!d->strokeHandler->types.size()) // an empty path... return; QVectorPath strokePath(d->strokeHandler->pts.data(), d->strokeHandler->types.size(), d->strokeHandler->types.data(), flags); fill(strokePath, pen.brush()); } else { // For cosmetic pens we need a bit of trickery... We to process xform the input points if (state()->matrix.type() >= QTransform::TxProject) { QPainterPath painterPath = state()->matrix.map(path.convertToPainterPath()); d->activeStroker->strokePath(painterPath, d->strokeHandler, QTransform()); } else { d->activeStroker->setCurveThresholdFromTransform(QTransform()); d->activeStroker->begin(d->strokeHandler); if (types) { while (points < lastPoint) { switch (*types) { case QPainterPath::MoveToElement: { QPointF pt = (*(const QPointF *) points) * state()->matrix; d->activeStroker->moveTo(pt.x(), pt.y()); points += 2; ++types; break; } case QPainterPath::LineToElement: { QPointF pt = (*(const QPointF *) points) * state()->matrix; d->activeStroker->lineTo(pt.x(), pt.y()); points += 2; ++types; break; } case QPainterPath::CurveToElement: { QPointF c1 = ((const QPointF *) points)[0] * state()->matrix; QPointF c2 = ((const QPointF *) points)[1] * state()->matrix; QPointF e = ((const QPointF *) points)[2] * state()->matrix; d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y()); points += 6; types += 3; flags |= QVectorPath::CurvedShapeMask; break; } default: break; } } if (path.hasImplicitClose()) { QPointF pt = * ((const QPointF *) path.points()) * state()->matrix; d->activeStroker->lineTo(pt.x(), pt.y()); } } else { QPointF p = ((const QPointF *)points)[0] * state()->matrix; d->activeStroker->moveTo(p.x(), p.y()); points += 2; while (points < lastPoint) { QPointF p = ((const QPointF *)points)[0] * state()->matrix; d->activeStroker->lineTo(p.x(), p.y()); points += 2; } if (path.hasImplicitClose()) d->activeStroker->lineTo(p.x(), p.y()); } d->activeStroker->end(); } QVectorPath strokePath(d->strokeHandler->pts.data(), d->strokeHandler->types.size(), d->strokeHandler->types.data(), flags); QTransform xform = state()->matrix; state()->matrix = QTransform(); transformChanged(); QBrush brush = pen.brush(); if (qbrush_style(brush) != Qt::SolidPattern) brush.setTransform(brush.transform() * xform); fill(strokePath, brush); state()->matrix = xform; transformChanged(); } }",CWE-787,16 1,"void nfcmrvl_nci_unregister_dev(struct nfcmrvl_private *priv) { struct nci_dev *ndev = priv->ndev; if (priv->ndev->nfc_dev->fw_download_in_progress) nfcmrvl_fw_dnld_abort(priv); nfcmrvl_fw_dnld_deinit(priv); if (gpio_is_valid(priv->config.reset_n_io)) gpio_free(priv->config.reset_n_io); nci_unregister_device(ndev); nci_free_device(ndev); kfree(priv); }",CWE-416,10 0," virtual const WifiNetworkVector& remembered_wifi_networks() const { return wifi_networks_; } ",none,24 0,"void QuotaManager::SetPersistentHostQuota(const std::string& host, int64 new_quota, HostQuotaCallback* callback_ptr) { scoped_ptr callback(callback_ptr); LazyInitialize(); if (host.empty()) { callback->Run(kQuotaErrorNotSupported, host, kStorageTypePersistent, 0); return; } if (new_quota < 0) { callback->Run(kQuotaErrorInvalidModification, host, kStorageTypePersistent, -1); return; } if (!db_disabled_) { scoped_refptr task( new UpdatePersistentHostQuotaTask( this, host, new_quota, callback.release())); task->Start(); } else { callback->Run(kQuotaErrorInvalidAccess, host, kStorageTypePersistent, -1); } } ",none,24 1,"int kvmppc_rtas_hcall(struct kvm_vcpu *vcpu) { struct rtas_token_definition *d; struct rtas_args args; rtas_arg_t *orig_rets; gpa_t args_phys; int rc; /* * r4 contains the guest physical address of the RTAS args * Mask off the top 4 bits since this is a guest real address */ args_phys = kvmppc_get_gpr(vcpu, 4) & KVM_PAM; vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); rc = kvm_read_guest(vcpu->kvm, args_phys, &args, sizeof(args)); srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx); if (rc) goto fail; /* * args->rets is a pointer into args->args. Now that we've * copied args we need to fix it up to point into our copy, * not the guest args. We also need to save the original * value so we can restore it on the way out. */ orig_rets = args.rets; args.rets = &args.args[be32_to_cpu(args.nargs)]; mutex_lock(&vcpu->kvm->arch.rtas_token_lock); rc = -ENOENT; list_for_each_entry(d, &vcpu->kvm->arch.rtas_tokens, list) { if (d->token == be32_to_cpu(args.token)) { d->handler->handler(vcpu, &args); rc = 0; break; } } mutex_unlock(&vcpu->kvm->arch.rtas_token_lock); if (rc == 0) { args.rets = orig_rets; rc = kvm_write_guest(vcpu->kvm, args_phys, &args, sizeof(args)); if (rc) goto fail; } return rc; fail: /* * We only get here if the guest has called RTAS with a bogus * args pointer. That means we can't get to the args, and so we * can't fail the RTAS call. So fail right out to userspace, * which should kill the guest. */ return rc; }",CWE-787,16 1,"PHP_FUNCTION(openssl_encrypt) { zend_bool raw_output = 0; char *data, *method, *password, *iv = """"; int data_len, method_len, password_len, iv_len = 0, max_iv_len; const EVP_CIPHER *cipher_type; EVP_CIPHER_CTX cipher_ctx; int i, outlen, keylen; unsigned char *outbuf, *key; zend_bool free_iv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""sss|bs"", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) { return; } cipher_type = EVP_get_cipherbyname(method); if (!cipher_type) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unknown cipher algorithm""); RETURN_FALSE; } keylen = EVP_CIPHER_key_length(cipher_type); if (keylen > password_len) { key = emalloc(keylen); memset(key, 0, keylen); memcpy(key, password, password_len); } else { key = (unsigned char*)password; } max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len <= 0 && max_iv_len > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Using an empty Initialization Vector (iv) is potentially insecure and not recommended""); } free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC); outlen = data_len + EVP_CIPHER_block_size(cipher_type); outbuf = emalloc(outlen + 1); EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL); if (password_len > keylen) { EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len); } EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv); EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len); outlen = i; if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) { outlen += i; if (raw_output) { outbuf[outlen] = '\0'; RETVAL_STRINGL((char *)outbuf, outlen, 0); } else { int base64_str_len; char *base64_str; base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len); efree(outbuf); RETVAL_STRINGL(base64_str, base64_str_len, 0); } } else { efree(outbuf); RETVAL_FALSE; } if (key != (unsigned char*)password) { efree(key); } if (free_iv) { efree(iv); } EVP_CIPHER_CTX_cleanup(&cipher_ctx); }",CWE-200,4 1," void Compute(OpKernelContext* context) override { // Here's the basic idea: // Batch and depth dimension are independent from row and col dimension. And // because FractionalAvgPool currently only support pooling along row and // col, we can basically think of this 4D tensor backpropagation as // operation of a series of 2D planes. // // For each element of a 'slice' (2D plane) of output_backprop, we need to // figure out its contributors when doing FractionalAvgPool operation. This // can be done based on row_pooling_sequence, col_pooling_seq and // overlapping. // Once we figure out the original contributors, we just need to evenly // divide the value of this element among these contributors. // // Internally, we divide the out_backprop tensor and store it in a temporary // tensor of double type. And cast it to the corresponding type. typedef Eigen::Map> ConstEigenMatrixMap; typedef Eigen::Map> EigenDoubleMatrixMap; // Grab the inputs. const Tensor& orig_input_tensor_shape = context->input(0); OP_REQUIRES(context, orig_input_tensor_shape.dims() == 1 && orig_input_tensor_shape.NumElements() == 4, errors::InvalidArgument(""original input tensor shape must be"" ""1-dimensional and 4 elements"")); const Tensor& out_backprop = context->input(1); const Tensor& row_seq_tensor = context->input(2); const Tensor& col_seq_tensor = context->input(3); const int64_t out_batch = out_backprop.dim_size(0); const int64_t out_rows = out_backprop.dim_size(1); const int64_t out_cols = out_backprop.dim_size(2); const int64_t out_depth = out_backprop.dim_size(3); OP_REQUIRES(context, row_seq_tensor.NumElements() > out_rows, errors::InvalidArgument(""Given out_backprop shape "", out_backprop.shape().DebugString(), "", row_seq_tensor must have at least "", out_rows + 1, "" elements, but got "", row_seq_tensor.NumElements())); OP_REQUIRES(context, col_seq_tensor.NumElements() > out_cols, errors::InvalidArgument(""Given out_backprop shape "", out_backprop.shape().DebugString(), "", col_seq_tensor must have at least "", out_cols + 1, "" elements, but got "", col_seq_tensor.NumElements())); auto row_seq_tensor_flat = row_seq_tensor.flat(); auto col_seq_tensor_flat = col_seq_tensor.flat(); auto orig_input_tensor_shape_flat = orig_input_tensor_shape.flat(); const int64_t in_batch = orig_input_tensor_shape_flat(0); const int64_t in_rows = orig_input_tensor_shape_flat(1); const int64_t in_cols = orig_input_tensor_shape_flat(2); const int64_t in_depth = orig_input_tensor_shape_flat(3); OP_REQUIRES( context, in_batch != 0, errors::InvalidArgument(""Batch dimension of input must not be 0"")); OP_REQUIRES( context, in_rows != 0, errors::InvalidArgument(""Rows dimension of input must not be 0"")); OP_REQUIRES( context, in_cols != 0, errors::InvalidArgument(""Columns dimension of input must not be 0"")); OP_REQUIRES( context, in_depth != 0, errors::InvalidArgument(""Depth dimension of input must not be 0"")); constexpr int tensor_in_and_out_dims = 4; // Transform orig_input_tensor_shape into TensorShape TensorShape in_shape; for (auto i = 0; i < tensor_in_and_out_dims; ++i) { in_shape.AddDim(orig_input_tensor_shape_flat(i)); } // Create intermediate in_backprop. Tensor in_backprop_tensor_temp; OP_REQUIRES_OK(context, context->forward_input_or_allocate_temp( {0}, DataTypeToEnum::v(), in_shape, &in_backprop_tensor_temp)); in_backprop_tensor_temp.flat().setZero(); // Transform 4D tensor to 2D matrix. EigenDoubleMatrixMap in_backprop_tensor_temp_mat( in_backprop_tensor_temp.flat().data(), in_depth, in_cols * in_rows * in_batch); ConstEigenMatrixMap out_backprop_mat(out_backprop.flat().data(), out_depth, out_cols * out_rows * out_batch); // Loop through each element of out_backprop and evenly distribute the // element to the corresponding pooling cell. const int64_t in_max_row_index = in_rows - 1; const int64_t in_max_col_index = in_cols - 1; for (int64_t b = 0; b < out_batch; ++b) { for (int64_t r = 0; r < out_rows; ++r) { const int64_t in_row_start = row_seq_tensor_flat(r); int64_t in_row_end = overlapping_ ? row_seq_tensor_flat(r + 1) : row_seq_tensor_flat(r + 1) - 1; in_row_end = std::min(in_row_end, in_max_row_index); for (int64_t c = 0; c < out_cols; ++c) { const int64_t in_col_start = col_seq_tensor_flat(c); int64_t in_col_end = overlapping_ ? col_seq_tensor_flat(c + 1) : col_seq_tensor_flat(c + 1) - 1; in_col_end = std::min(in_col_end, in_max_col_index); const int64_t num_elements_in_pooling_cell = (in_row_end - in_row_start + 1) * (in_col_end - in_col_start + 1); const int64_t out_index = (b * out_rows + r) * out_cols + c; // Now we can evenly distribute out_backprop(b, h, w, *) to // in_backprop(b, hs:he, ws:we, *). for (int64_t in_r = in_row_start; in_r <= in_row_end; ++in_r) { for (int64_t in_c = in_col_start; in_c <= in_col_end; ++in_c) { const int64_t in_index = (b * in_rows + in_r) * in_cols + in_c; // Walk through each channel (depth). for (int64_t d = 0; d < out_depth; ++d) { const double out_backprop_element = static_cast( out_backprop_mat.coeffRef(d, out_index)); double& in_backprop_ref = in_backprop_tensor_temp_mat.coeffRef(d, in_index); in_backprop_ref += out_backprop_element / num_elements_in_pooling_cell; } } } } } } // Depending on the type, cast double to type T. Tensor* in_backprop_tensor = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 0, in_shape, &in_backprop_tensor)); auto in_backprop_tensor_flat = in_backprop_tensor->flat(); auto in_backprop_tensor_temp_flat = in_backprop_tensor_temp.flat(); for (int64_t i = 0; i < in_backprop_tensor_flat.size(); ++i) { in_backprop_tensor_flat(i) = static_cast(in_backprop_tensor_temp_flat(i)); } }",CWE-125,1 1,"mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter) { int k; int c1, w, c2; switch (filter->status) { case 0: if (filter->from->no_encoding == mbfl_no_encoding_cp950) { c1 = 0x80; } else { c1 = 0xa0; } if (c >= 0 && c <= 0x80) { /* latin */ CK((*filter->output_function)(c, filter->data)); } else if (c == 0xff) { CK((*filter->output_function)(0xf8f8, filter->data)); } else if (c > c1 && c < 0xff) { /* dbcs lead byte */ filter->status = 1; filter->cache = c; } else { w = c & MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; case 1: /* dbcs second byte */ filter->status = 0; c1 = filter->cache; if ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) { if (c < 0x7f){ w = (c1 - 0xa1)*157 + (c - 0x40); } else { w = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f; } if (w >= 0 && w < big5_ucs_table_size) { w = big5_ucs_table[w]; } else { w = 0; } if (filter->from->no_encoding == mbfl_no_encoding_cp950) { /* PUA for CP950 */ if (w <= 0 && (((c1 >= 0xfa && c1 <= 0xfe) || (c1 >= 0x8e && c1 <= 0xa0) || (c1 >= 0x81 && c1 <= 0x8d) ||(c1 >= 0xc7 && c1 <= 0xc8)) && ((c > 0x39 && c < 0x7f) || (c > 0xa0 && c < 0xff))) || ((c1 == 0xc6) && (c > 0xa0 && c < 0xff))) { c2 = c1 << 8 | c; for (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) { if (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) { break; } } if ((cp950_pua_tbl[k][2] & 0xff) == 0x40) { w = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40) + cp950_pua_tbl[k][0]; } else { w = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0]; } } } if (w <= 0) { w = (c1 << 8) | c; w &= MBFL_WCSPLANE_MASK; w |= MBFL_WCSPLANE_BIG5; } CK((*filter->output_function)(w, filter->data)); } else if ((c >= 0 && c < 0x21) || c == 0x7f) { /* CTLs */ CK((*filter->output_function)(c, filter->data)); } else { w = (c1 << 8) | c; w &= MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; default: filter->status = 0; break; } return c; }",CWE-125,1 1,"int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max) { struct page *page; struct address_space *mapping; __be32 *pptr, *curr, *end; u32 mask, start, len, n; __be32 val; int i; len = *max; if (!len) return size; dprint(DBG_BITMAP, ""block_allocate: %u,%u,%u\n"", size, offset, len); mutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex); mapping = HFSPLUS_SB(sb).alloc_file->i_mapping; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32; i = offset % 32; offset &= ~(PAGE_CACHE_BITS - 1); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; /* scan the first partial u32 for zero bits */ val = *curr; if (~val) { n = be32_to_cpu(val); mask = (1U << 31) >> i; for (; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; /* scan complete u32s for the first zero bit */ while (1) { while (curr < end) { val = *curr; if (~val) { n = be32_to_cpu(val); mask = 1 << 31; for (i = 0; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; } kunmap(page); offset += PAGE_CACHE_BITS; if (offset >= size) break; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); curr = pptr = kmap(page); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; } dprint(DBG_BITMAP, ""bitmap full\n""); start = size; goto out; found: start = offset + (curr - pptr) * 32 + i; if (start >= size) { dprint(DBG_BITMAP, ""bitmap full\n""); goto out; } /* do any partial u32 at the start */ len = min(size - start, len); while (1) { n |= mask; if (++i >= 32) break; mask >>= 1; if (!--len || n & mask) goto done; } if (!--len) goto done; *curr++ = cpu_to_be32(n); /* do full u32s */ while (1) { while (curr < end) { n = be32_to_cpu(*curr); if (len < 32) goto last; if (n) { len = 32; goto last; } *curr++ = cpu_to_be32(0xffffffff); len -= 32; } set_page_dirty(page); kunmap(page); offset += PAGE_CACHE_BITS; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr; end = pptr + PAGE_CACHE_BITS / 32; } last: /* do any partial u32 at end */ mask = 1U << 31; for (i = 0; i < len; i++) { if (n & mask) break; n |= mask; mask >>= 1; } done: *curr = cpu_to_be32(n); set_page_dirty(page); kunmap(page); *max = offset + (curr - pptr) * 32 + i - start; HFSPLUS_SB(sb).free_blocks -= *max; sb->s_dirt = 1; dprint(DBG_BITMAP, ""-> %u,%u\n"", start, *max); out: mutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex); return start; }",CWE-20,3 0,"QuotaManager* QuotaManagerProxy::quota_manager() const { DCHECK(!io_thread_ || io_thread_->BelongsToCurrentThread()); return manager_; } ",none,24 0," virtual void AddCellularDataPlanObserver(CellularDataPlanObserver* observer) { if (!data_plan_observers_.HasObserver(observer)) data_plan_observers_.AddObserver(observer); } ",none,24 1,"int udf_expand_file_adinicb(struct inode *inode) { struct page *page; char *kaddr; struct udf_inode_info *iinfo = UDF_I(inode); int err; struct writeback_control udf_wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, }; WARN_ON_ONCE(!inode_is_locked(inode)); if (!iinfo->i_lenAlloc) { if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; up_write(&iinfo->i_data_sem); mark_inode_dirty(inode); return 0; } /* * Release i_data_sem so that we can lock a page - page lock ranks * above i_data_sem. i_mutex still protects us against file changes. */ up_write(&iinfo->i_data_sem); page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS); if (!page) return -ENOMEM; if (!PageUptodate(page)) { kaddr = kmap_atomic(page); memset(kaddr + iinfo->i_lenAlloc, 0x00, PAGE_SIZE - iinfo->i_lenAlloc); memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr, iinfo->i_lenAlloc); flush_dcache_page(page); SetPageUptodate(page); kunmap_atomic(kaddr); } down_write(&iinfo->i_data_sem); memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00, iinfo->i_lenAlloc); iinfo->i_lenAlloc = 0; if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; up_write(&iinfo->i_data_sem); err = inode->i_data.a_ops->writepage(page, &udf_wbc); if (err) { /* Restore everything back so that we don't lose data... */ lock_page(page); down_write(&iinfo->i_data_sem); kaddr = kmap_atomic(page); memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size); kunmap_atomic(kaddr); unlock_page(page); iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB; inode->i_data.a_ops = &udf_adinicb_aops; up_write(&iinfo->i_data_sem); } put_page(page); mark_inode_dirty(inode); return err; }",CWE-476,12 1," void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in // the step container, and return it as the output. const Tensor* indices; OP_REQUIRES_OK(ctx, ctx->input(""indices"", &indices)); const Tensor* values; OP_REQUIRES_OK(ctx, ctx->input(""values"", &values)); const Tensor* dense_shape; OP_REQUIRES_OK(ctx, ctx->input(""dense_shape"", &dense_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()), errors::InvalidArgument( ""Input indices should be a matrix but received shape "", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()), errors::InvalidArgument( ""Input values should be a vector but received shape "", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()), errors::InvalidArgument( ""Input shape should be a vector but received shape "", dense_shape->shape().DebugString())); // We currently ensure that `sparse_tensor` is ordered in the // batch dimension. // TODO(mrry): Investigate ways to avoid this unconditional check // if we can be sure that the sparse tensor was produced in an // appropriate order (e.g. by `tf.parse_example()` or a Dataset // that batches elements into rows of a SparseTensor). int64_t previous_batch_index = -1; for (int64_t i = 0; i < indices->dim_size(0); ++i) { int64_t next_batch_index = indices->matrix()(i, 0); OP_REQUIRES( ctx, next_batch_index >= previous_batch_index, errors::Unimplemented(""The SparseTensor must be ordered in the batch "" ""dimension; handling arbitrarily ordered input "" ""is not currently supported."")); previous_batch_index = next_batch_index; } gtl::InlinedVector std_order(dense_shape->NumElements(), 0); sparse::SparseTensor tensor; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create( *indices, *values, TensorShape(dense_shape->vec()), std_order, &tensor)); *output = new Dataset(ctx, std::move(tensor)); }",CWE-476,12 0,"void QuotaManagerProxy::NotifyStorageAccessed( QuotaClient::ID client_id, const GURL& origin, StorageType type) { if (!io_thread_->BelongsToCurrentThread()) { io_thread_->PostTask(FROM_HERE, NewRunnableMethod( this, &QuotaManagerProxy::NotifyStorageAccessed, client_id, origin, type)); return; } if (manager_) manager_->NotifyStorageAccessed(client_id, origin, type); } ",none,24 1,"int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, struct xfrm_migrate *m, int num_migrate, struct xfrm_kmaddress *k, struct net *net, struct xfrm_encap_tmpl *encap) { int i, err, nx_cur = 0, nx_new = 0; struct xfrm_policy *pol = NULL; struct xfrm_state *x, *xc; struct xfrm_state *x_cur[XFRM_MAX_DEPTH]; struct xfrm_state *x_new[XFRM_MAX_DEPTH]; struct xfrm_migrate *mp; if ((err = xfrm_migrate_check(m, num_migrate)) < 0) goto out; /* Stage 1 - find policy */ if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) { err = -ENOENT; goto out; } /* Stage 2 - find and update state(s) */ for (i = 0, mp = m; i < num_migrate; i++, mp++) { if ((x = xfrm_migrate_state_find(mp, net))) { x_cur[nx_cur] = x; nx_cur++; xc = xfrm_state_migrate(x, mp, encap); if (xc) { x_new[nx_new] = xc; nx_new++; } else { err = -ENODATA; goto restore_state; } } } /* Stage 3 - update policy */ if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0) goto restore_state; /* Stage 4 - delete old state(s) */ if (nx_cur) { xfrm_states_put(x_cur, nx_cur); xfrm_states_delete(x_cur, nx_cur); } /* Stage 5 - announce */ km_migrate(sel, dir, type, m, num_migrate, k, encap); xfrm_pol_put(pol); return 0; out: return err; restore_state: if (pol) xfrm_pol_put(pol); if (nx_cur) xfrm_states_put(x_cur, nx_cur); if (nx_new) xfrm_states_delete(x_new, nx_new); return err; }",CWE-125,1 1," void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in // the step container, and return it as the output. const Tensor* indices; OP_REQUIRES_OK(ctx, ctx->input(""indices"", &indices)); const Tensor* values; OP_REQUIRES_OK(ctx, ctx->input(""values"", &values)); const Tensor* dense_shape; OP_REQUIRES_OK(ctx, ctx->input(""dense_shape"", &dense_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()), errors::InvalidArgument( ""Input indices should be a matrix but received shape "", indices->shape().DebugString())); const auto num_indices = indices->NumElements(); const auto num_values = values->NumElements(); if (num_indices == 0 || num_values == 0) { OP_REQUIRES(ctx, num_indices == num_values, errors::InvalidArgument( ""If indices or values are empty, the other one must also "" ""be. Got indices of shape "", indices->shape().DebugString(), "" and values of shape "", values->shape().DebugString())); } OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()), errors::InvalidArgument( ""Input values should be a vector but received shape "", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()), errors::InvalidArgument( ""Input shape should be a vector but received shape "", dense_shape->shape().DebugString())); // We currently ensure that `sparse_tensor` is ordered in the // batch dimension. // TODO(mrry): Investigate ways to avoid this unconditional check // if we can be sure that the sparse tensor was produced in an // appropriate order (e.g. by `tf.parse_example()` or a Dataset // that batches elements into rows of a SparseTensor). int64_t previous_batch_index = -1; for (int64_t i = 0; i < indices->dim_size(0); ++i) { int64_t next_batch_index = indices->matrix()(i, 0); OP_REQUIRES( ctx, next_batch_index >= previous_batch_index, errors::Unimplemented(""The SparseTensor must be ordered in the batch "" ""dimension; handling arbitrarily ordered input "" ""is not currently supported."")); previous_batch_index = next_batch_index; } gtl::InlinedVector std_order(dense_shape->NumElements(), 0); sparse::SparseTensor tensor; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create( *indices, *values, TensorShape(dense_shape->vec()), std_order, &tensor)); *output = new Dataset(ctx, std::move(tensor)); }",CWE-476,12 0,"QuotaManagerProxy::~QuotaManagerProxy() { } ",none,24 0," virtual void ForgetWifiNetwork(const std::string& service_path) { if (!EnsureCrosLoaded()) return; if (DeleteRememberedService(service_path.c_str())) { for (WifiNetworkVector::iterator iter = remembered_wifi_networks_.begin(); iter != remembered_wifi_networks_.end(); ++iter) { if ((*iter)->service_path() == service_path) { delete (*iter); remembered_wifi_networks_.erase(iter); break; } } NotifyNetworkManagerChanged(); } } ",none,24 0," UsageAndQuotaDispatcherTask( QuotaManager* manager, const std::string& host, StorageType type) : QuotaTask(manager), host_(host), type_(type), quota_(-1), global_usage_(-1), global_unlimited_usage_(-1), host_usage_(-1), quota_status_(kQuotaStatusUnknown), waiting_callbacks_(1), callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {} ",none,24 1,"find_start_brace(void) // XXX { pos_T cursor_save; pos_T *trypos; pos_T *pos; static pos_T pos_copy; cursor_save = curwin->w_cursor; while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL) { pos_copy = *trypos; // copy pos_T, next findmatch will change it trypos = &pos_copy; curwin->w_cursor = *trypos; pos = NULL; // ignore the { if it's in a // or / * * / comment if ((colnr_T)cin_skip2pos(trypos) == trypos->col && (pos = ind_find_start_CORS(NULL)) == NULL) // XXX break; if (pos != NULL) curwin->w_cursor.lnum = pos->lnum; } curwin->w_cursor = cursor_save; return trypos; }",CWE-787,16 1,"static int qh_help(int sd, char *buf, unsigned int len) { struct query_handler *qh = NULL; if (!*buf || !strcmp(buf, ""help"")) { nsock_printf_nul(sd, "" help show help for handler \n"" "" help list list registered handlers\n""); return 0; } if (!strcmp(buf, ""list"")) { for (qh = qhandlers; qh != NULL; qh = qh->next_qh) { nsock_printf(sd, ""%-10s %s\n"", qh->name, qh->description ? qh->description : ""(No description available)""); } nsock_printf(sd, ""%c"", 0); return 0; } qh = qh_find_handler(buf); if (qh == NULL) { nsock_printf_nul(sd, ""No handler named '%s' is registered\n"", buf); } else if (qh->handler(sd, ""help"", 4) > 200) { nsock_printf_nul(sd, ""The handler %s doesn't have any help yet."", buf); } return 0; }",CWE-476,12 1,"ex_retab(exarg_T *eap) { linenr_T lnum; int got_tab = FALSE; long num_spaces = 0; long num_tabs; long len; long col; long vcol; long start_col = 0; // For start of white-space string long start_vcol = 0; // For start of white-space string long old_len; char_u *ptr; char_u *new_line = (char_u *)1; // init to non-NULL int did_undo; // called u_save for current line #ifdef FEAT_VARTABS int *new_vts_array = NULL; char_u *new_ts_str; // string value of tab argument #else int temp; int new_ts; #endif int save_list; linenr_T first_line = 0; // first changed line linenr_T last_line = 0; // last changed line save_list = curwin->w_p_list; curwin->w_p_list = 0; // don't want list mode here #ifdef FEAT_VARTABS new_ts_str = eap->arg; if (tabstop_set(eap->arg, &new_vts_array) == FAIL) return; while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',') ++(eap->arg); // This ensures that either new_vts_array and new_ts_str are freshly // allocated, or new_vts_array points to an existing array and new_ts_str // is null. if (new_vts_array == NULL) { new_vts_array = curbuf->b_p_vts_array; new_ts_str = NULL; } else new_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str); #else ptr = eap->arg; new_ts = getdigits(&ptr); if (new_ts < 0 && *eap->arg == '-') { emsg(_(e_argument_must_be_positive)); return; } if (new_ts < 0 || new_ts > TABSTOP_MAX) { semsg(_(e_invalid_argument_str), eap->arg); return; } if (new_ts == 0) new_ts = curbuf->b_p_ts; #endif for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum) { ptr = ml_get(lnum); col = 0; vcol = 0; did_undo = FALSE; for (;;) { if (VIM_ISWHITE(ptr[col])) { if (!got_tab && num_spaces == 0) { // First consecutive white-space start_vcol = vcol; start_col = col; } if (ptr[col] == ' ') num_spaces++; else got_tab = TRUE; } else { if (got_tab || (eap->forceit && num_spaces > 1)) { // Retabulate this string of white-space // len is virtual length of white string len = num_spaces = vcol - start_vcol; num_tabs = 0; if (!curbuf->b_p_et) { #ifdef FEAT_VARTABS int t, s; tabstop_fromto(start_vcol, vcol, curbuf->b_p_ts, new_vts_array, &t, &s); num_tabs = t; num_spaces = s; #else temp = new_ts - (start_vcol % new_ts); if (num_spaces >= temp) { num_spaces -= temp; num_tabs++; } num_tabs += num_spaces / new_ts; num_spaces -= (num_spaces / new_ts) * new_ts; #endif } if (curbuf->b_p_et || got_tab || (num_spaces + num_tabs < len)) { if (did_undo == FALSE) { did_undo = TRUE; if (u_save((linenr_T)(lnum - 1), (linenr_T)(lnum + 1)) == FAIL) { new_line = NULL; // flag out-of-memory break; } } // len is actual number of white characters used len = num_spaces + num_tabs; old_len = (long)STRLEN(ptr); new_line = alloc(old_len - col + start_col + len + 1); if (new_line == NULL) break; if (start_col > 0) mch_memmove(new_line, ptr, (size_t)start_col); mch_memmove(new_line + start_col + len, ptr + col, (size_t)(old_len - col + 1)); ptr = new_line + start_col; for (col = 0; col < len; col++) ptr[col] = (col < num_tabs) ? '\t' : ' '; if (ml_replace(lnum, new_line, FALSE) == OK) // ""new_line"" may have been copied new_line = curbuf->b_ml.ml_line_ptr; if (first_line == 0) first_line = lnum; last_line = lnum; ptr = new_line; col = start_col + len; } } got_tab = FALSE; num_spaces = 0; } if (ptr[col] == NUL) break; vcol += chartabsize(ptr + col, (colnr_T)vcol); if (has_mbyte) col += (*mb_ptr2len)(ptr + col); else ++col; } if (new_line == NULL) // out of memory break; line_breakcheck(); } if (got_int) emsg(_(e_interrupted)); #ifdef FEAT_VARTABS // If a single value was given then it can be considered equal to // either the value of 'tabstop' or the value of 'vartabstop'. if (tabstop_count(curbuf->b_p_vts_array) == 0 && tabstop_count(new_vts_array) == 1 && curbuf->b_p_ts == tabstop_first(new_vts_array)) ; // not changed else if (tabstop_count(curbuf->b_p_vts_array) > 0 && tabstop_eq(curbuf->b_p_vts_array, new_vts_array)) ; // not changed else redraw_curbuf_later(NOT_VALID); #else if (curbuf->b_p_ts != new_ts) redraw_curbuf_later(NOT_VALID); #endif if (first_line != 0) changed_lines(first_line, 0, last_line + 1, 0L); curwin->w_p_list = save_list; // restore 'list' #ifdef FEAT_VARTABS if (new_ts_str != NULL) // set the new tabstop { // If 'vartabstop' is in use or if the value given to retab has more // than one tabstop then update 'vartabstop'. int *old_vts_ary = curbuf->b_p_vts_array; if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1) { set_string_option_direct((char_u *)""vts"", -1, new_ts_str, OPT_FREE|OPT_LOCAL, 0); curbuf->b_p_vts_array = new_vts_array; vim_free(old_vts_ary); } else { // 'vartabstop' wasn't in use and a single value was given to // retab then update 'tabstop'. curbuf->b_p_ts = tabstop_first(new_vts_array); vim_free(new_vts_array); } vim_free(new_ts_str); } #else curbuf->b_p_ts = new_ts; #endif coladvance(curwin->w_curswant); u_clearline(); }",CWE-787,16 0," virtual const CellularNetworkVector& cellular_networks() const { return cellular_networks_; } ",none,24 0,"void QuotaManager::GetAvailableSpace(AvailableSpaceCallback* callback) { scoped_refptr task( new AvailableSpaceQueryTask(this, db_thread_, profile_path_, callback)); task->Start(); } ",none,24 0,"void QuotaManager::RegisterClient(QuotaClient* client) { DCHECK(io_thread_->BelongsToCurrentThread()); DCHECK(!database_.get()); clients_.push_back(client); } ",none,24 1,"static void ip6gre_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info) { const struct ipv6hdr *ipv6h = (const struct ipv6hdr *)skb->data; __be16 *p = (__be16 *)(skb->data + offset); int grehlen = offset + 4; struct ip6_tnl *t; __be16 flags; flags = p[0]; if (flags&(GRE_CSUM|GRE_KEY|GRE_SEQ|GRE_ROUTING|GRE_VERSION)) { if (flags&(GRE_VERSION|GRE_ROUTING)) return; if (flags&GRE_KEY) { grehlen += 4; if (flags&GRE_CSUM) grehlen += 4; } } /* If only 8 bytes returned, keyed message will be dropped here */ if (!pskb_may_pull(skb, grehlen)) return; ipv6h = (const struct ipv6hdr *)skb->data; p = (__be16 *)(skb->data + offset); t = ip6gre_tunnel_lookup(skb->dev, &ipv6h->daddr, &ipv6h->saddr, flags & GRE_KEY ? *(((__be32 *)p) + (grehlen / 4) - 1) : 0, p[1]); if (!t) return; switch (type) { __u32 teli; struct ipv6_tlv_tnl_enc_lim *tel; __u32 mtu; case ICMPV6_DEST_UNREACH: net_dbg_ratelimited(""%s: Path to destination invalid or inactive!\n"", t->parms.name); break; case ICMPV6_TIME_EXCEED: if (code == ICMPV6_EXC_HOPLIMIT) { net_dbg_ratelimited(""%s: Too small hop limit or routing loop in tunnel!\n"", t->parms.name); } break; case ICMPV6_PARAMPROB: teli = 0; if (code == ICMPV6_HDR_FIELD) teli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data); if (teli && teli == be32_to_cpu(info) - 2) { tel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli]; if (tel->encap_limit == 0) { net_dbg_ratelimited(""%s: Too small encapsulation limit or routing loop in tunnel!\n"", t->parms.name); } } else { net_dbg_ratelimited(""%s: Recipient unable to parse tunneled packet!\n"", t->parms.name); } break; case ICMPV6_PKT_TOOBIG: mtu = be32_to_cpu(info) - offset; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; t->dev->mtu = mtu; break; } if (time_before(jiffies, t->err_time + IP6TUNNEL_ERR_TIMEO)) t->err_count++; else t->err_count = 1; t->err_time = jiffies; }",CWE-125,1 0," QuotaStatusCode quota_status() const { return quota_status_; } ",none,24