target,func,cwe_id_cleaned,label 1,"GF_Err Media_RewriteODFrame(GF_MediaBox *mdia, GF_ISOSample *sample) { GF_Err e; GF_ODCodec *ODdecode; GF_ODCodec *ODencode; GF_ODCom *com; //the commands we proceed GF_ESDUpdate *esdU, *esdU2; GF_ESDRemove *esdR, *esdR2; GF_ODUpdate *odU, *odU2; //the desc they contain GF_ObjectDescriptor *od; GF_IsomObjectDescriptor *isom_od; GF_ESD *esd; GF_ES_ID_Ref *ref; GF_Descriptor *desc; GF_TrackReferenceTypeBox *mpod; u32 i, j, skipped; if (!mdia || !sample || !sample->data || !sample->dataLength) return GF_BAD_PARAM; mpod = NULL; e = Track_FindRef(mdia->mediaTrack, GF_ISOM_BOX_TYPE_MPOD, &mpod); if (e) return e; //no references, nothing to do... if (!mpod || !mpod->trackIDs) return GF_OK; ODdecode = gf_odf_codec_new(); if (!ODdecode) return GF_OUT_OF_MEM; ODencode = gf_odf_codec_new(); if (!ODencode) { gf_odf_codec_del(ODdecode); return GF_OUT_OF_MEM; } e = gf_odf_codec_set_au(ODdecode, sample->data, sample->dataLength); if (e) goto err_exit; e = gf_odf_codec_decode(ODdecode); if (e) goto err_exit; while (1) { com = gf_odf_codec_get_com(ODdecode); if (!com) break; //we only need to rewrite commands with ESDs inside: ESDUpdate and ODUpdate switch (com->tag) { case GF_ODF_OD_UPDATE_TAG: odU = (GF_ODUpdate *) com; odU2 = (GF_ODUpdate *) gf_odf_com_new(GF_ODF_OD_UPDATE_TAG); i=0; while ((desc = (GF_Descriptor*)gf_list_enum(odU->objectDescriptors, &i))) { switch (desc->tag) { case GF_ODF_OD_TAG: case GF_ODF_ISOM_OD_TAG: //IOD can be used in OD streams case GF_ODF_ISOM_IOD_TAG: break; default: return GF_ISOM_INVALID_FILE; } e = gf_odf_desc_copy(desc, (GF_Descriptor **)&isom_od); if (e) goto err_exit; //create our OD... if (desc->tag == GF_ODF_ISOM_IOD_TAG) { od = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_InitialObjectDescriptor)); } else { od = (GF_ObjectDescriptor *) gf_malloc(sizeof(GF_ObjectDescriptor)); } if (!od) { e = GF_OUT_OF_MEM; goto err_exit; } od->ESDescriptors = gf_list_new(); //and duplicate... od->objectDescriptorID = isom_od->objectDescriptorID; od->tag = GF_ODF_OD_TAG; od->URLString = isom_od->URLString; isom_od->URLString = NULL; od->extensionDescriptors = isom_od->extensionDescriptors; isom_od->extensionDescriptors = NULL; od->IPMP_Descriptors = isom_od->IPMP_Descriptors; isom_od->IPMP_Descriptors = NULL; od->OCIDescriptors = isom_od->OCIDescriptors; isom_od->OCIDescriptors = NULL; //init as IOD if (isom_od->tag == GF_ODF_ISOM_IOD_TAG) { ((GF_InitialObjectDescriptor *)od)->audio_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->audio_profileAndLevel; ((GF_InitialObjectDescriptor *)od)->inlineProfileFlag = ((GF_IsomInitialObjectDescriptor *)isom_od)->inlineProfileFlag; ((GF_InitialObjectDescriptor *)od)->graphics_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->graphics_profileAndLevel; ((GF_InitialObjectDescriptor *)od)->OD_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->OD_profileAndLevel; ((GF_InitialObjectDescriptor *)od)->scene_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->scene_profileAndLevel; ((GF_InitialObjectDescriptor *)od)->visual_profileAndLevel = ((GF_IsomInitialObjectDescriptor *)isom_od)->visual_profileAndLevel; ((GF_InitialObjectDescriptor *)od)->IPMPToolList = ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList; ((GF_IsomInitialObjectDescriptor *)isom_od)->IPMPToolList = NULL; } //then rewrite the ESDesc j=0; while ((ref = (GF_ES_ID_Ref*)gf_list_enum(isom_od->ES_ID_RefDescriptors, &j))) { //if the ref index is not valid, skip this desc... if (!mpod->trackIDs || gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue; //OK, get the esd e = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd); if (!e) e = gf_odf_desc_add_desc((GF_Descriptor *) od, (GF_Descriptor *) esd); if (e) { gf_odf_desc_del((GF_Descriptor *)od); gf_odf_com_del((GF_ODCom **)&odU2); gf_odf_desc_del((GF_Descriptor *)isom_od); gf_odf_com_del((GF_ODCom **)&odU); goto err_exit; } } //delete our desc gf_odf_desc_del((GF_Descriptor *)isom_od); gf_list_add(odU2->objectDescriptors, od); } //clean a bit gf_odf_com_del((GF_ODCom **)&odU); gf_odf_codec_add_com(ODencode, (GF_ODCom *)odU2); break; case GF_ODF_ESD_UPDATE_TAG: esdU = (GF_ESDUpdate *) com; esdU2 = (GF_ESDUpdate *) gf_odf_com_new(GF_ODF_ESD_UPDATE_TAG); esdU2->ODID = esdU->ODID; i=0; while ((ref = (GF_ES_ID_Ref*)gf_list_enum(esdU->ESDescriptors, &i))) { //if the ref index is not valid, skip this desc... if (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1]) == NULL) continue; //OK, get the esd e = GetESDForTime(mdia->mediaTrack->moov, mpod->trackIDs[ref->trackRef - 1], sample->DTS, &esd); if (e) goto err_exit; gf_list_add(esdU2->ESDescriptors, esd); } gf_odf_com_del((GF_ODCom **)&esdU); gf_odf_codec_add_com(ODencode, (GF_ODCom *)esdU2); break; //brand new case: the ESRemove follows the same principle according to the spec... case GF_ODF_ESD_REMOVE_REF_TAG: //both commands have the same structure, only the tags change esdR = (GF_ESDRemove *) com; esdR2 = (GF_ESDRemove *) gf_odf_com_new(GF_ODF_ESD_REMOVE_TAG); esdR2->ODID = esdR->ODID; esdR2->NbESDs = esdR->NbESDs; //alloc our stuff esdR2->ES_ID = (unsigned short*)gf_malloc(sizeof(u32) * esdR->NbESDs); if (!esdR2->ES_ID) { e = GF_OUT_OF_MEM; goto err_exit; } skipped = 0; //get the ES_ID in the mpod indicated in the ES_ID[] for (i = 0; i < esdR->NbESDs; i++) { //if the ref index is not valid, remove this desc... if (gf_isom_get_track_from_id(mdia->mediaTrack->moov, mpod->trackIDs[esdR->ES_ID[i] - 1]) == NULL) { skipped ++; } else { //the command in the file has the ref index of the trackID in the mpod esdR2->ES_ID[i - skipped] = mpod->trackIDs[esdR->ES_ID[i] - 1]; } } //gf_realloc... if (skipped && (skipped != esdR2->NbESDs) ) { esdR2->NbESDs -= skipped; esdR2->ES_ID = (unsigned short*)gf_realloc(esdR2->ES_ID, sizeof(u32) * esdR2->NbESDs); } gf_odf_com_del((GF_ODCom **)&esdR); gf_odf_codec_add_com(ODencode, (GF_ODCom *)esdR2); break; default: e = gf_odf_codec_add_com(ODencode, com); if (e) goto err_exit; } } //encode our new AU e = gf_odf_codec_encode(ODencode, 1); if (e) goto err_exit; //and set the buffer in the sample gf_free(sample->data); sample->data = NULL; sample->dataLength = 0; e = gf_odf_codec_get_au(ODencode, &sample->data, &sample->dataLength); err_exit: gf_odf_codec_del(ODdecode); gf_odf_codec_del(ODencode); return e; }",CWE-476,12 1,"rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; }",CWE-125,1 1,"void stralgoLCS(client *c) { uint32_t i, j; long long minmatchlen = 0; sds a = NULL, b = NULL; int getlen = 0, getidx = 0, withmatchlen = 0; robj *obja = NULL, *objb = NULL; for (j = 2; j < (uint32_t)c->argc; j++) { char *opt = c->argv[j]->ptr; int moreargs = (c->argc-1) - j; if (!strcasecmp(opt,""IDX"")) { getidx = 1; } else if (!strcasecmp(opt,""LEN"")) { getlen = 1; } else if (!strcasecmp(opt,""WITHMATCHLEN"")) { withmatchlen = 1; } else if (!strcasecmp(opt,""MINMATCHLEN"") && moreargs) { if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL) != C_OK) goto cleanup; if (minmatchlen < 0) minmatchlen = 0; j++; } else if (!strcasecmp(opt,""STRINGS"") && moreargs > 1) { if (a != NULL) { addReplyError(c,""Either use STRINGS or KEYS""); goto cleanup; } a = c->argv[j+1]->ptr; b = c->argv[j+2]->ptr; j += 2; } else if (!strcasecmp(opt,""KEYS"") && moreargs > 1) { if (a != NULL) { addReplyError(c,""Either use STRINGS or KEYS""); goto cleanup; } obja = lookupKeyRead(c->db,c->argv[j+1]); objb = lookupKeyRead(c->db,c->argv[j+2]); if ((obja && obja->type != OBJ_STRING) || (objb && objb->type != OBJ_STRING)) { addReplyError(c, ""The specified keys must contain string values""); /* Don't cleanup the objects, we need to do that * only after callign getDecodedObject(). */ obja = NULL; objb = NULL; goto cleanup; } obja = obja ? getDecodedObject(obja) : createStringObject("""",0); objb = objb ? getDecodedObject(objb) : createStringObject("""",0); a = obja->ptr; b = objb->ptr; j += 2; } else { addReply(c,shared.syntaxerr); goto cleanup; } } /* Complain if the user passed ambiguous parameters. */ if (a == NULL) { addReplyError(c,""Please specify two strings: "" ""STRINGS or KEYS options are mandatory""); goto cleanup; } else if (getlen && getidx) { addReplyError(c, ""If you want both the length and indexes, please "" ""just use IDX.""); goto cleanup; } /* Compute the LCS using the vanilla dynamic programming technique of * building a table of LCS(x,y) substrings. */ uint32_t alen = sdslen(a); uint32_t blen = sdslen(b); /* Setup an uint32_t array to store at LCS[i,j] the length of the * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so * we index it as LCS[j+(blen+1)*j] */ uint32_t *lcs = zmalloc((alen+1)*(blen+1)*sizeof(uint32_t)); #define LCS(A,B) lcs[(B)+((A)*(blen+1))] /* Start building the LCS table. */ for (uint32_t i = 0; i <= alen; i++) { for (uint32_t j = 0; j <= blen; j++) { if (i == 0 || j == 0) { /* If one substring has length of zero, the * LCS length is zero. */ LCS(i,j) = 0; } else if (a[i-1] == b[j-1]) { /* The len LCS (and the LCS itself) of two * sequences with the same final character, is the * LCS of the two sequences without the last char * plus that last char. */ LCS(i,j) = LCS(i-1,j-1)+1; } else { /* If the last character is different, take the longest * between the LCS of the first string and the second * minus the last char, and the reverse. */ uint32_t lcs1 = LCS(i-1,j); uint32_t lcs2 = LCS(i,j-1); LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2; } } } /* Store the actual LCS string in ""result"" if needed. We create * it backward, but the length is already known, we store it into idx. */ uint32_t idx = LCS(alen,blen); sds result = NULL; /* Resulting LCS string. */ void *arraylenptr = NULL; /* Deffered length of the array for IDX. */ uint32_t arange_start = alen, /* alen signals that values are not set. */ arange_end = 0, brange_start = 0, brange_end = 0; /* Do we need to compute the actual LCS string? Allocate it in that case. */ int computelcs = getidx || !getlen; if (computelcs) result = sdsnewlen(SDS_NOINIT,idx); /* Start with a deferred array if we have to emit the ranges. */ uint32_t arraylen = 0; /* Number of ranges emitted in the array. */ if (getidx) { addReplyMapLen(c,2); addReplyBulkCString(c,""matches""); arraylenptr = addReplyDeferredLen(c); } i = alen, j = blen; while (computelcs && i > 0 && j > 0) { int emit_range = 0; if (a[i-1] == b[j-1]) { /* If there is a match, store the character and reduce * the indexes to look for a new match. */ result[idx-1] = a[i-1]; /* Track the current range. */ if (arange_start == alen) { arange_start = i-1; arange_end = i-1; brange_start = j-1; brange_end = j-1; } else { /* Let's see if we can extend the range backward since * it is contiguous. */ if (arange_start == i && brange_start == j) { arange_start--; brange_start--; } else { emit_range = 1; } } /* Emit the range if we matched with the first byte of * one of the two strings. We'll exit the loop ASAP. */ if (arange_start == 0 || brange_start == 0) emit_range = 1; idx--; i--; j--; } else { /* Otherwise reduce i and j depending on the largest * LCS between, to understand what direction we need to go. */ uint32_t lcs1 = LCS(i-1,j); uint32_t lcs2 = LCS(i,j-1); if (lcs1 > lcs2) i--; else j--; if (arange_start != alen) emit_range = 1; } /* Emit the current range if needed. */ uint32_t match_len = arange_end - arange_start + 1; if (emit_range) { if (minmatchlen == 0 || match_len >= minmatchlen) { if (arraylenptr) { addReplyArrayLen(c,2+withmatchlen); addReplyArrayLen(c,2); addReplyLongLong(c,arange_start); addReplyLongLong(c,arange_end); addReplyArrayLen(c,2); addReplyLongLong(c,brange_start); addReplyLongLong(c,brange_end); if (withmatchlen) addReplyLongLong(c,match_len); arraylen++; } } arange_start = alen; /* Restart at the next match. */ } } /* Signal modified key, increment dirty, ... */ /* Reply depending on the given options. */ if (arraylenptr) { addReplyBulkCString(c,""len""); addReplyLongLong(c,LCS(alen,blen)); setDeferredArrayLen(c,arraylenptr,arraylen); } else if (getlen) { addReplyLongLong(c,LCS(alen,blen)); } else { addReplyBulkSds(c,result); result = NULL; } /* Cleanup. */ sdsfree(result); zfree(lcs); cleanup: if (obja) decrRefCount(obja); if (objb) decrRefCount(objb); return; }",CWE-190,2 0,"void ContentSettingsStore::SetExtensionState( const std::string& ext_id, bool is_enabled) { bool notify = false; bool notify_incognito = false; { base::AutoLock lock(lock_); ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i == entries_.end()) return; notify = !i->second->settings.empty(); notify_incognito = !i->second->incognito_persistent_settings.empty() || !i->second->incognito_session_only_settings.empty(); i->second->enabled = is_enabled; } if (notify) NotifyOfContentSettingChanged(ext_id, false); if (notify_incognito) NotifyOfContentSettingChanged(ext_id, true); } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::isErrorGeneratedOnOutOfBoundsAccesses() { return false; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::vertexAttribPointer(unsigned long indx, int size, int type, bool normalized, unsigned long stride, unsigned long offset) { makeContextCurrent(); if (m_boundArrayBuffer <= 0) { return; } if (indx < NumTrackedPointerStates) { VertexAttribPointerState& state = m_vertexAttribPointerState[indx]; state.buffer = m_boundArrayBuffer; state.indx = indx; state.size = size; state.type = type; state.normalized = normalized; state.stride = stride; state.offset = offset; } glVertexAttribPointer(indx, size, type, normalized, stride, reinterpret_cast(static_cast(offset))); } ",none,24 1,"int mutt_seqset_iterator_next(struct SeqsetIterator *iter, unsigned int *next) { if (!iter || !next) return -1; if (iter->in_range) { if ((iter->down && (iter->range_cur == (iter->range_end - 1))) || (!iter->down && (iter->range_cur == (iter->range_end + 1)))) { iter->in_range = 0; } } if (!iter->in_range) { iter->substr_cur = iter->substr_end; if (iter->substr_cur == iter->eostr) return 1; while (!*(iter->substr_cur)) iter->substr_cur++; iter->substr_end = strchr(iter->substr_cur, ','); if (!iter->substr_end) iter->substr_end = iter->eostr; else *(iter->substr_end) = '\0'; char *range_sep = strchr(iter->substr_cur, ':'); if (range_sep) *range_sep++ = '\0'; if (mutt_str_atoui(iter->substr_cur, &iter->range_cur) != 0) return -1; if (range_sep) { if (mutt_str_atoui(range_sep, &iter->range_end) != 0) return -1; } else iter->range_end = iter->range_cur; iter->down = (iter->range_end < iter->range_cur); iter->in_range = 1; } *next = iter->range_cur; if (iter->down) iter->range_cur--; else iter->range_cur++; return 0; }",CWE-125,1 1,"int vt_do_kdgkb_ioctl(int cmd, struct kbsentry __user *user_kdgkb, int perm) { struct kbsentry *kbs; char *p; u_char *q; u_char __user *up; int sz, fnw_sz; int delta; char *first_free, *fj, *fnw; int i, j, k; int ret; unsigned long flags; if (!capable(CAP_SYS_TTY_CONFIG)) perm = 0; kbs = kmalloc(sizeof(*kbs), GFP_KERNEL); if (!kbs) { ret = -ENOMEM; goto reterr; } /* we mostly copy too much here (512bytes), but who cares ;) */ if (copy_from_user(kbs, user_kdgkb, sizeof(struct kbsentry))) { ret = -EFAULT; goto reterr; } kbs->kb_string[sizeof(kbs->kb_string)-1] = '\0'; i = array_index_nospec(kbs->kb_func, MAX_NR_FUNC); switch (cmd) { case KDGKBSENT: sz = sizeof(kbs->kb_string) - 1; /* sz should have been a struct member */ up = user_kdgkb->kb_string; p = func_table[i]; if(p) for ( ; *p && sz; p++, sz--) if (put_user(*p, up++)) { ret = -EFAULT; goto reterr; } if (put_user('\0', up)) { ret = -EFAULT; goto reterr; } kfree(kbs); return ((p && *p) ? -EOVERFLOW : 0); case KDSKBSENT: if (!perm) { ret = -EPERM; goto reterr; } fnw = NULL; fnw_sz = 0; /* race aginst other writers */ again: spin_lock_irqsave(&func_buf_lock, flags); q = func_table[i]; /* fj pointer to next entry after 'q' */ first_free = funcbufptr + (funcbufsize - funcbufleft); for (j = i+1; j < MAX_NR_FUNC && !func_table[j]; j++) ; if (j < MAX_NR_FUNC) fj = func_table[j]; else fj = first_free; /* buffer usage increase by new entry */ delta = (q ? -strlen(q) : 1) + strlen(kbs->kb_string); if (delta <= funcbufleft) { /* it fits in current buf */ if (j < MAX_NR_FUNC) { /* make enough space for new entry at 'fj' */ memmove(fj + delta, fj, first_free - fj); for (k = j; k < MAX_NR_FUNC; k++) if (func_table[k]) func_table[k] += delta; } if (!q) func_table[i] = fj; funcbufleft -= delta; } else { /* allocate a larger buffer */ sz = 256; while (sz < funcbufsize - funcbufleft + delta) sz <<= 1; if (fnw_sz != sz) { spin_unlock_irqrestore(&func_buf_lock, flags); kfree(fnw); fnw = kmalloc(sz, GFP_KERNEL); fnw_sz = sz; if (!fnw) { ret = -ENOMEM; goto reterr; } goto again; } if (!q) func_table[i] = fj; /* copy data before insertion point to new location */ if (fj > funcbufptr) memmove(fnw, funcbufptr, fj - funcbufptr); for (k = 0; k < j; k++) if (func_table[k]) func_table[k] = fnw + (func_table[k] - funcbufptr); /* copy data after insertion point to new location */ if (first_free > fj) { memmove(fnw + (fj - funcbufptr) + delta, fj, first_free - fj); for (k = j; k < MAX_NR_FUNC; k++) if (func_table[k]) func_table[k] = fnw + (func_table[k] - funcbufptr) + delta; } if (funcbufptr != func_buf) kfree(funcbufptr); funcbufptr = fnw; funcbufleft = funcbufleft - delta + sz - funcbufsize; funcbufsize = sz; } /* finally insert item itself */ strcpy(func_table[i], kbs->kb_string); spin_unlock_irqrestore(&func_buf_lock, flags); break; } ret = 0; reterr: kfree(kbs); return ret; }",CWE-416,10 1,"static inline void kvm_memslot_delete(struct kvm_memslots *slots, struct kvm_memory_slot *memslot) { struct kvm_memory_slot *mslots = slots->memslots; int i; if (WARN_ON(slots->id_to_index[memslot->id] == -1)) return; slots->used_slots--; for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) { mslots[i] = mslots[i + 1]; slots->id_to_index[mslots[i].id] = i; } mslots[i] = *memslot; slots->id_to_index[memslot->id] = -1; }",CWE-416,10 1,"static void slc_bump(struct slcan *sl) { struct sk_buff *skb; struct can_frame cf; int i, tmp; u32 tmpid; char *cmd = sl->rbuff; cf.can_id = 0; switch (*cmd) { case 'r': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 't': /* store dlc ASCII value and terminate SFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1; break; case 'R': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 'T': cf.can_id |= CAN_EFF_FLAG; /* store dlc ASCII value and terminate EFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1; break; default: return; } if (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid)) return; cf.can_id |= tmpid; /* get can_dlc from sanitized ASCII value */ if (cf.can_dlc >= '0' && cf.can_dlc < '9') cf.can_dlc -= '0'; else return; *(u64 *) (&cf.data) = 0; /* clear payload */ /* RTR frames may have a dlc > 0 but they never have any data bytes */ if (!(cf.can_id & CAN_RTR_FLAG)) { for (i = 0; i < cf.can_dlc; i++) { tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] = (tmp << 4); tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] |= tmp; } } skb = dev_alloc_skb(sizeof(struct can_frame) + sizeof(struct can_skb_priv)); if (!skb) return; skb->dev = sl->dev; skb->protocol = htons(ETH_P_CAN); skb->pkt_type = PACKET_BROADCAST; skb->ip_summed = CHECKSUM_UNNECESSARY; can_skb_reserve(skb); can_skb_prv(skb)->ifindex = sl->dev->ifindex; can_skb_prv(skb)->skbcnt = 0; skb_put_data(skb, &cf, sizeof(struct can_frame)); sl->dev->stats.rx_packets++; sl->dev->stats.rx_bytes += cf.can_dlc; netif_rx_ni(skb); }",CWE-200,4 0,"PassRefPtrWillBeRawPtr SpeechSynthesis::create(ExecutionContext* context) { return adoptRefWillBeRefCountedGarbageCollected(new SpeechSynthesis(context)); } ",none,24 0," virtual void SetUpOnIOThread() {} ",none,24 1,"ImagingLibTiffDecode( Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = ""tempfile.tif""; char *mode = ""r""; TIFF *tiff; uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR int isYCbCr = 0; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE((""in decoder: bytes %d\n"", bytes)); TRACE( (""State: count %d, state %d, x %d, y %d, ystep %d\n"", state->count, state->state, state->x, state->y, state->ystep)); TRACE( (""State: xsize %d, ysize %d, xoff %d, yoff %d \n"", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE((""State: bits %d, bytes %d \n"", state->bits, state->bytes)); TRACE( (""Buffer: %p: %c%c%c%c\n"", buffer, (char)buffer[0], (char)buffer[1], (char)buffer[2], (char)buffer[3])); TRACE( (""State->Buffer: %c%c%c%c\n"", (char)state->buffer[0], (char)state->buffer[1], (char)state->buffer[2], (char)state->buffer[3])); TRACE( (""Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n"", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE( (""Image: image8 %p, image32 %p, image %p, block %p \n"", im->image8, im->image32, im->image, im->block)); TRACE((""Image: pixelsize: %d, linesize %d \n"", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE((""Opening using fd: %d\n"", clientstate->fp)); lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode); } else { TRACE((""Opening from string\n"")); tiff = TIFFClientOpen( filename, mode, (thandle_t)clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff) { TRACE((""Error, didn't get the tiff\n"")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd) { int rv; uint32 ifdoffset = clientstate->ifd; TRACE((""reading tiff ifd %u\n"", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv) { TRACE((""error in TIFFSetSubDirectory"")); goto decode_err; } } TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); isYCbCr = photometric == PHOTOMETRIC_YCBCR; if (TIFFIsTiled(tiff)) { INT32 x, y, tile_y; UINT32 tile_width, tile_length, current_tile_length, current_line, current_tile_width, row_byte_size; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); /* overflow check for row_byte_size calculation */ if ((UINT32)INT_MAX / state->bits < tile_width) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } if (isYCbCr) { row_byte_size = tile_width * 4; /* sanity check, we use this value in shuffle below */ if (im->pixelsize != 4) { state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } else { // We could use TIFFTileSize, but for YCbCr data it returns subsampled data // size row_byte_size = (tile_width * state->bits + 7) / 8; } /* overflow check for realloc */ if (INT_MAX / row_byte_size < tile_length) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } state->bytes = row_byte_size * tile_length; if (TIFFTileSize(tiff) > state->bytes) { // If the strip size as expected by LibTiff isn't what we're expecting, // abort. state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } /* realloc to fit whole tile */ /* malloc check above */ new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } state->buffer = new_data; TRACE((""TIFFTileSize: %d\n"", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { if (isYCbCr) { /* To avoid dealing with YCbCr subsampling, let libtiff handle it */ if (!TIFFReadRGBATile(tiff, x, y, (UINT32 *)state->buffer)) { TRACE((""Decode Error, Tile at %dx%d\n"", x, y)); state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } else { if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, 0) == -1) { TRACE((""Decode Error, Tile at %dx%d\n"", x, y)); state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } TRACE((""Read tile at %dx%d; \n\n"", x, y)); current_tile_width = min((INT32)tile_width, state->xsize - x); current_tile_length = min((INT32)tile_length, state->ysize - y); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < current_tile_length; tile_y++) { TRACE( (""Writing tile data at %dx%d using tile_width: %d; \n"", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE((""chars: %x%x%x%x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], // ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); /* * For some reason the TIFFReadRGBATile() function * chooses the lower left corner as the origin. * Vertically mirror by shuffling the scanlines * backwards */ if (isYCbCr) { current_line = tile_length - tile_y - 1; } else { current_line = tile_y; } state->shuffle( (UINT8 *)im->image[tile_y + y] + x * im->pixelsize, state->buffer + current_line * row_byte_size, current_tile_width); } } } } else { if (!isYCbCr) { _decodeStrip(im, state, tiff); } else { _decodeStripYCbCr(im, state, tiff); } } decode_err: TIFFClose(tiff); TRACE((""Done Decoding, Returning \n"")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }",CWE-125,1 0," void SetUpRegistrationOnIOThread(const std::string& worker_url) { const int64 version_id = 1L; registration_ = new ServiceWorkerRegistration( embedded_test_server()->GetURL(""/*""), embedded_test_server()->GetURL(worker_url), next_registration_id_++); version_ = new ServiceWorkerVersion( registration_, wrapper()->context()->embedded_worker_registry(), version_id); AssociateRendererProcessToWorker(version_->embedded_worker()); } ",none,24 0,"TranslateInfoBarDelegate* TranslateManager::GetTranslateInfoBarDelegate( TabContents* tab) { for (int i = 0; i < tab->infobar_delegate_count(); ++i) { TranslateInfoBarDelegate* delegate = tab->GetInfoBarDelegateAt(i)->AsTranslateInfoBarDelegate(); if (delegate) return delegate; } return NULL; } ",none,24 1,"int LibRaw::ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, ""ljpeg_start()""); return zero_after_ff = 1; }",CWE-125,1 1,"static void hci_extended_inquiry_result_evt(struct hci_dev *hdev, struct sk_buff *skb) { struct inquiry_data data; struct extended_inquiry_info *info = (void *) (skb->data + 1); int num_rsp = *((__u8 *) skb->data); size_t eir_len; BT_DBG(""%s num_rsp %d"", hdev->name, num_rsp); if (!num_rsp) return; if (hci_dev_test_flag(hdev, HCI_PERIODIC_INQ)) return; hci_dev_lock(hdev); for (; num_rsp; num_rsp--, info++) { u32 flags; bool name_known; bacpy(&data.bdaddr, &info->bdaddr); data.pscan_rep_mode = info->pscan_rep_mode; data.pscan_period_mode = info->pscan_period_mode; data.pscan_mode = 0x00; memcpy(data.dev_class, info->dev_class, 3); data.clock_offset = info->clock_offset; data.rssi = info->rssi; data.ssp_mode = 0x01; if (hci_dev_test_flag(hdev, HCI_MGMT)) name_known = eir_get_data(info->data, sizeof(info->data), EIR_NAME_COMPLETE, NULL); else name_known = true; flags = hci_inquiry_cache_update(hdev, &data, name_known); eir_len = eir_get_length(info->data, sizeof(info->data)); mgmt_device_found(hdev, &info->bdaddr, ACL_LINK, 0x00, info->dev_class, info->rssi, flags, info->data, eir_len, NULL, 0); } hci_dev_unlock(hdev); }",CWE-125,1 1,"ares_parse_naptr_reply (const unsigned char *abuf, int alen, struct ares_naptr_reply **naptr_out) { unsigned int qdcount, ancount, i; const unsigned char *aptr, *vptr; int status, rr_type, rr_class, rr_len; long len; char *hostname = NULL, *rr_name = NULL; struct ares_naptr_reply *naptr_head = NULL; struct ares_naptr_reply *naptr_last = NULL; struct ares_naptr_reply *naptr_curr; /* Set *naptr_out to NULL for all failure cases. */ *naptr_out = NULL; /* Give up if abuf doesn't have room for a header. */ if (alen < HFIXEDSZ) return ARES_EBADRESP; /* Fetch the question and answer count from the header. */ qdcount = DNS_HEADER_QDCOUNT (abuf); ancount = DNS_HEADER_ANCOUNT (abuf); if (qdcount != 1) return ARES_EBADRESP; if (ancount == 0) return ARES_ENODATA; /* Expand the name from the question, and skip past the question. */ aptr = abuf + HFIXEDSZ; status = ares_expand_name (aptr, abuf, alen, &hostname, &len); if (status != ARES_SUCCESS) return status; if (aptr + len + QFIXEDSZ > abuf + alen) { ares_free (hostname); return ARES_EBADRESP; } aptr += len + QFIXEDSZ; /* Examine each answer resource record (RR) in turn. */ for (i = 0; i < ancount; i++) { /* Decode the RR up to the data field. */ status = ares_expand_name (aptr, abuf, alen, &rr_name, &len); if (status != ARES_SUCCESS) { break; } aptr += len; if (aptr + RRFIXEDSZ > abuf + alen) { status = ARES_EBADRESP; break; } rr_type = DNS_RR_TYPE (aptr); rr_class = DNS_RR_CLASS (aptr); rr_len = DNS_RR_LEN (aptr); aptr += RRFIXEDSZ; if (aptr + rr_len > abuf + alen) { status = ARES_EBADRESP; break; } /* RR must contain at least 7 bytes = 2 x int16 + 3 x name */ if (rr_len < 7) { status = ARES_EBADRESP; break; } /* Check if we are really looking at a NAPTR record */ if (rr_class == C_IN && rr_type == T_NAPTR) { /* parse the NAPTR record itself */ /* Allocate storage for this NAPTR answer appending it to the list */ naptr_curr = ares_malloc_data(ARES_DATATYPE_NAPTR_REPLY); if (!naptr_curr) { status = ARES_ENOMEM; break; } if (naptr_last) { naptr_last->next = naptr_curr; } else { naptr_head = naptr_curr; } naptr_last = naptr_curr; vptr = aptr; naptr_curr->order = DNS__16BIT(vptr); vptr += sizeof(unsigned short); naptr_curr->preference = DNS__16BIT(vptr); vptr += sizeof(unsigned short); status = ares_expand_string(vptr, abuf, alen, &naptr_curr->flags, &len); if (status != ARES_SUCCESS) break; vptr += len; status = ares_expand_string(vptr, abuf, alen, &naptr_curr->service, &len); if (status != ARES_SUCCESS) break; vptr += len; status = ares_expand_string(vptr, abuf, alen, &naptr_curr->regexp, &len); if (status != ARES_SUCCESS) break; vptr += len; status = ares_expand_name(vptr, abuf, alen, &naptr_curr->replacement, &len); if (status != ARES_SUCCESS) break; } /* Don't lose memory in the next iteration */ ares_free (rr_name); rr_name = NULL; /* Move on to the next record */ aptr += rr_len; } if (hostname) ares_free (hostname); if (rr_name) ares_free (rr_name); /* clean up on error */ if (status != ARES_SUCCESS) { if (naptr_head) ares_free_data (naptr_head); return status; } /* everything looks fine, return the data */ *naptr_out = naptr_head; return ARES_SUCCESS; }",CWE-200,4 1,"static void nhmldump_send_header(GF_NHMLDumpCtx *ctx) { GF_FilterPacket *dst_pck; char nhml[1024]; u32 size; u8 *output; const GF_PropertyValue *p; ctx->szRootName = ""NHNTStream""; if (ctx->dims) { ctx->szRootName = ""DIMSStream""; } if (!ctx->filep) { sprintf(nhml, ""\n""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } /*write header*/ sprintf(nhml, ""<%s version=\""1.0\"" "", ctx->szRootName); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); NHML_PRINT_UINT(GF_PROP_PID_ID, NULL, ""trackID"") NHML_PRINT_UINT(GF_PROP_PID_TIMESCALE, NULL, ""timeScale"") p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_IN_IOD); if (p && p->value.boolean) { sprintf(nhml, ""inRootOD=\""yes\"" ""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } if (ctx->oti && (ctx->otistreamtype, ctx->oti); gf_bs_write_data(ctx->bs_w, nhml, (u32)strlen(nhml)); } else { p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_SUBTYPE); if (p) { sprintf(nhml, ""%s=\""%s\"" "", ""mediaType"", gf_4cc_to_str(p->value.uint)); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); NHML_PRINT_4CC(GF_PROP_PID_ISOM_SUBTYPE, ""mediaSubType"", ""mediaSubType"") } else { NHML_PRINT_4CC(GF_PROP_PID_CODECID, NULL, ""codecID"") } } if (ctx->w && ctx->h) { //compatibility with old arch, we might want to remove this switch (ctx->streamtype) { case GF_STREAM_VISUAL: case GF_STREAM_SCENE: sprintf(nhml, ""width=\""%d\"" height=\""%d\"" "", ctx->w, ctx->h); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); break; default: break; } } else if (ctx->sr && ctx->chan) { sprintf(nhml, ""sampleRate=\""%d\"" numChannels=\""%d\"" "", ctx->sr, ctx->chan); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); sprintf(nhml, ""sampleRate=\""%d\"" numChannels=\""%d\"" "", ctx->sr, ctx->chan); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); p = gf_filter_pid_get_property(ctx->ipid, GF_PROP_PID_AUDIO_FORMAT); sprintf(nhml, ""bitsPerSample=\""%d\"" "", gf_audio_fmt_bit_depth(p->value.uint)); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } NHML_PRINT_4CC(0, ""codec_vendor"", ""codecVendor"") NHML_PRINT_UINT(0, ""codec_version"", ""codecVersion"") NHML_PRINT_UINT(0, ""codec_revision"", ""codecRevision"") NHML_PRINT_STRING(0, ""compressor_name"", ""compressorName"") NHML_PRINT_UINT(0, ""temporal_quality"", ""temporalQuality"") NHML_PRINT_UINT(0, ""spatial_quality"", ""spatialQuality"") NHML_PRINT_UINT(0, ""hres"", ""horizontalResolution"") NHML_PRINT_UINT(0, ""vres"", ""verticalResolution"") NHML_PRINT_UINT(GF_PROP_PID_BIT_DEPTH_Y, NULL, ""bitDepth"") NHML_PRINT_STRING(0, ""meta:xmlns"", ""xml_namespace"") NHML_PRINT_STRING(0, ""meta:schemaloc"", ""xml_schema_location"") NHML_PRINT_STRING(0, ""meta:mime"", ""mime_type"") NHML_PRINT_STRING(0, ""meta:config"", ""config"") NHML_PRINT_STRING(0, ""meta:aux_mimes"", ""aux_mime_type"") if (ctx->codecid == GF_CODECID_DIMS) { if (gf_filter_pid_get_property_str(ctx->ipid, ""meta:xmlns"")==NULL) { sprintf(nhml, ""xmlns=\""http://www.3gpp.org/richmedia\"" ""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } NHML_PRINT_UINT(0, ""dims:profile"", ""profile"") NHML_PRINT_UINT(0, ""dims:level"", ""level"") NHML_PRINT_UINT(0, ""dims:pathComponents"", ""pathComponents"") p = gf_filter_pid_get_property_str(ctx->ipid, ""dims:fullRequestHost""); if (p) { sprintf(nhml, ""useFullRequestHost=\""%s\"" "", p->value.boolean ? ""yes"" : ""no""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } p = gf_filter_pid_get_property_str(ctx->ipid, ""dims:streamType""); if (p) { sprintf(nhml, ""stream_type=\""%s\"" "", p->value.boolean ? ""primary"" : ""secondary""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } p = gf_filter_pid_get_property_str(ctx->ipid, ""dims:redundant""); if (p) { sprintf(nhml, ""contains_redundant=\""%s\"" "", (p->value.uint==1) ? ""main"" : ((p->value.uint==1) ? ""redundant"" : ""main+redundant"") ); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } NHML_PRINT_UINT(0, ""dims:scriptTypes"", ""scriptTypes"") } //send DCD if (ctx->opid_info) { sprintf(nhml, ""specificInfoFile=\""%s\"" "", gf_file_basename(ctx->info_file) ); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); dst_pck = gf_filter_pck_new_shared(ctx->opid_info, ctx->dcfg, ctx->dcfg_size, NULL); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE); gf_filter_pck_set_readonly(dst_pck); gf_filter_pck_send(dst_pck); } NHML_PRINT_STRING(0, ""meta:encoding"", ""encoding"") NHML_PRINT_STRING(0, ""meta:contentEncoding"", ""content_encoding"") ctx->uncompress = GF_FALSE; if (p) { if (!strcmp(p->value.string, ""deflate"")) ctx->uncompress = GF_TRUE; else { GF_LOG(GF_LOG_ERROR, GF_LOG_AUTHOR, (""[NHMLMx] content_encoding %s not supported\n"", p->value.string )); } } if (ctx->opid_mdia) { sprintf(nhml, ""baseMediaFile=\""%s\"" "", gf_file_basename(ctx->media_file) ); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); } sprintf(nhml, "">\n""); gf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml)); gf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size); if (ctx->filep) { gf_fwrite(ctx->nhml_buffer, size, ctx->filep); return; } dst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output); memcpy(output, ctx->nhml_buffer, size); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_FALSE); gf_filter_pck_send(dst_pck); }",CWE-476,12 0," CaptureVideoDecoderTest() { message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO)); message_loop_proxy_ = base::MessageLoopProxy::current().get(); vc_manager_ = new MockVideoCaptureImplManager(); media::VideoCaptureCapability capability; capability.width = kWidth; capability.height = kHeight; capability.frame_rate = kFPS; capability.expected_capture_delay = 0; capability.color = media::VideoCaptureCapability::kI420; capability.interlaced = false; decoder_ = new CaptureVideoDecoder(message_loop_proxy_, kVideoStreamId, vc_manager_, capability); EXPECT_CALL(statistics_cb_object_, OnStatistics(_)) .Times(AnyNumber()); read_cb_ = base::Bind(&CaptureVideoDecoderTest::FrameReady, base::Unretained(this)); vc_impl_.reset(new MockVideoCaptureImpl( kVideoStreamId, message_loop_proxy_, new VideoCaptureMessageFilter())); } ",none,24 1,"static struct socket *get_raw_socket(int fd) { struct { struct sockaddr_ll sa; char buf[MAX_ADDR_LEN]; } uaddr; int r; struct socket *sock = sockfd_lookup(fd, &r); if (!sock) return ERR_PTR(-ENOTSOCK); /* Parameter checking */ if (sock->sk->sk_type != SOCK_RAW) { r = -ESOCKTNOSUPPORT; goto err; } r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa, 0); if (r < 0) goto err; if (uaddr.sa.sll_family != AF_PACKET) { r = -EPFNOSUPPORT; goto err; } return sock; err: sockfd_put(sock); return ERR_PTR(r); }",CWE-787,16 1,"static struct sock *pep_sock_accept(struct sock *sk, int flags, int *errp, bool kern) { struct pep_sock *pn = pep_sk(sk), *newpn; struct sock *newsk = NULL; struct sk_buff *skb; struct pnpipehdr *hdr; struct sockaddr_pn dst, src; int err; u16 peer_type; u8 pipe_handle, enabled, n_sb; u8 aligned = 0; skb = skb_recv_datagram(sk, 0, flags & O_NONBLOCK, errp); if (!skb) return NULL; lock_sock(sk); if (sk->sk_state != TCP_LISTEN) { err = -EINVAL; goto drop; } sk_acceptq_removed(sk); err = -EPROTO; if (!pskb_may_pull(skb, sizeof(*hdr) + 4)) goto drop; hdr = pnp_hdr(skb); pipe_handle = hdr->pipe_handle; switch (hdr->state_after_connect) { case PN_PIPE_DISABLE: enabled = 0; break; case PN_PIPE_ENABLE: enabled = 1; break; default: pep_reject_conn(sk, skb, PN_PIPE_ERR_INVALID_PARAM, GFP_KERNEL); goto drop; } peer_type = hdr->other_pep_type << 8; /* Parse sub-blocks (options) */ n_sb = hdr->data[3]; while (n_sb > 0) { u8 type, buf[1], len = sizeof(buf); const u8 *data = pep_get_sb(skb, &type, &len, buf); if (data == NULL) goto drop; switch (type) { case PN_PIPE_SB_CONNECT_REQ_PEP_SUB_TYPE: if (len < 1) goto drop; peer_type = (peer_type & 0xff00) | data[0]; break; case PN_PIPE_SB_ALIGNED_DATA: aligned = data[0] != 0; break; } n_sb--; } /* Check for duplicate pipe handle */ newsk = pep_find_pipe(&pn->hlist, &dst, pipe_handle); if (unlikely(newsk)) { __sock_put(newsk); newsk = NULL; pep_reject_conn(sk, skb, PN_PIPE_ERR_PEP_IN_USE, GFP_KERNEL); goto drop; } /* Create a new to-be-accepted sock */ newsk = sk_alloc(sock_net(sk), PF_PHONET, GFP_KERNEL, sk->sk_prot, kern); if (!newsk) { pep_reject_conn(sk, skb, PN_PIPE_ERR_OVERLOAD, GFP_KERNEL); err = -ENOBUFS; goto drop; } sock_init_data(NULL, newsk); newsk->sk_state = TCP_SYN_RECV; newsk->sk_backlog_rcv = pipe_do_rcv; newsk->sk_protocol = sk->sk_protocol; newsk->sk_destruct = pipe_destruct; newpn = pep_sk(newsk); pn_skb_get_dst_sockaddr(skb, &dst); pn_skb_get_src_sockaddr(skb, &src); newpn->pn_sk.sobject = pn_sockaddr_get_object(&dst); newpn->pn_sk.dobject = pn_sockaddr_get_object(&src); newpn->pn_sk.resource = pn_sockaddr_get_resource(&dst); sock_hold(sk); newpn->listener = sk; skb_queue_head_init(&newpn->ctrlreq_queue); newpn->pipe_handle = pipe_handle; atomic_set(&newpn->tx_credits, 0); newpn->ifindex = 0; newpn->peer_type = peer_type; newpn->rx_credits = 0; newpn->rx_fc = newpn->tx_fc = PN_LEGACY_FLOW_CONTROL; newpn->init_enable = enabled; newpn->aligned = aligned; err = pep_accept_conn(newsk, skb); if (err) { sock_put(newsk); newsk = NULL; goto drop; } sk_add_node(newsk, &pn->hlist); drop: release_sock(sk); kfree_skb(skb); *errp = err; return newsk; }",CWE-200,4 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; 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) { ldout(s->cct, 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) { ldout(s->cct, 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); 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. */ response_attrs[aiter->second] = iter->second.c_str(); } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type = iter->second.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{ bufferlist::iterator it = iter->second.begin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << ""Error caught buffer::error couldn't decode TagSet "" << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } } } 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 0,"unsigned WebGraphicsContext3DDefaultImpl::createBuffer() { makeContextCurrent(); GLuint o; glGenBuffersARB(1, &o); return o; } ",none,24 1,"static int uvc_scan_chain_forward(struct uvc_video_chain *chain, struct uvc_entity *entity, struct uvc_entity *prev) { struct uvc_entity *forward; int found; /* Forward scan */ forward = NULL; found = 0; while (1) { forward = uvc_entity_by_reference(chain->dev, entity->id, forward); if (forward == NULL) break; if (forward == prev) continue; switch (UVC_ENTITY_TYPE(forward)) { case UVC_VC_EXTENSION_UNIT: if (forward->bNrInPins != 1) { uvc_trace(UVC_TRACE_DESCR, ""Extension unit %d "" ""has more than 1 input pin.\n"", entity->id); return -EINVAL; } list_add_tail(&forward->chain, &chain->entities); if (uvc_trace_param & UVC_TRACE_PROBE) { if (!found) printk(KERN_CONT "" (->""); printk(KERN_CONT "" XU %d"", forward->id); found = 1; } break; case UVC_OTT_VENDOR_SPECIFIC: case UVC_OTT_DISPLAY: case UVC_OTT_MEDIA_TRANSPORT_OUTPUT: case UVC_TT_STREAMING: if (UVC_ENTITY_IS_ITERM(forward)) { uvc_trace(UVC_TRACE_DESCR, ""Unsupported input "" ""terminal %u.\n"", forward->id); return -EINVAL; } list_add_tail(&forward->chain, &chain->entities); if (uvc_trace_param & UVC_TRACE_PROBE) { if (!found) printk(KERN_CONT "" (->""); printk(KERN_CONT "" OT %d"", forward->id); found = 1; } break; } } if (found) printk(KERN_CONT "")""); return 0; }",CWE-269,6 0,"void BlobURLRequestJob::DidResolve(base::PlatformFileError rv, const base::PlatformFileInfo& file_info) { if (rv == base::PLATFORM_FILE_ERROR_NOT_FOUND) { NotifyFailure(net::ERR_FILE_NOT_FOUND); return; } else if (rv != base::PLATFORM_FILE_OK) { NotifyFailure(net::ERR_FAILED); return; } const BlobData::Item& item = blob_data_->items().at(item_index_); DCHECK(item.type() == BlobData::TYPE_FILE); if (!item.expected_modification_time().is_null() && item.expected_modification_time().ToTimeT() != file_info.last_modified.ToTimeT()) { NotifyFailure(net::ERR_FILE_NOT_FOUND); return; } int64 item_length = static_cast(item.length()); if (item_length == -1) item_length = file_info.size; item_length_list_.push_back(item_length); total_size_ += item_length; item_index_++; CountSize(); } ",none,24 1," int lazy_bdecode(char const* start, char const* end, lazy_entry& ret , error_code& ec, int* error_pos, int depth_limit, int item_limit) { char const* const orig_start = start; ret.clear(); if (start == end) return 0; std::vector stack; stack.push_back(&ret); while (start <= end) { if (stack.empty()) break; // done! lazy_entry* top = stack.back(); if (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded); if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); char t = *start; ++start; if (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); switch (top->type()) { case lazy_entry::dict_t: { if (t == 'e') { top->set_end(start); stack.pop_back(); continue; } if (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string); boost::int64_t len = t - '0'; bdecode_errors::error_code_enum e = bdecode_errors::no_error; start = parse_int(start, end, ':', len, e); if (e) TORRENT_FAIL_BDECODE(e); if (start + len + 1 > end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); if (len < 0) TORRENT_FAIL_BDECODE(bdecode_errors::overflow); ++start; if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); lazy_entry* ent = top->dict_append(start); if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory); start += len; if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); stack.push_back(ent); t = *start; ++start; break; } case lazy_entry::list_t: { if (t == 'e') { top->set_end(start); stack.pop_back(); continue; } lazy_entry* ent = top->list_append(); if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory); stack.push_back(ent); break; } default: break; } --item_limit; if (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded); top = stack.back(); switch (t) { case 'd': top->construct_dict(start - 1); continue; case 'l': top->construct_list(start - 1); continue; case 'i': { char const* int_start = start; start = find_char(start, end, 'e'); top->construct_int(int_start, start - int_start); if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); TORRENT_ASSERT(*start == 'e'); ++start; stack.pop_back(); continue; } default: { if (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_value); boost::int64_t len = t - '0'; bdecode_errors::error_code_enum e = bdecode_errors::no_error; start = parse_int(start, end, ':', len, e); if (e) TORRENT_FAIL_BDECODE(e); if (start + len + 1 > end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof); if (len < 0) TORRENT_FAIL_BDECODE(bdecode_errors::overflow); ++start; top->construct_string(start, int(len)); stack.pop_back(); start += len; continue; } } return 0; } return 0; }",CWE-20,3 1,"static const char *GetMagickPropertyLetter(const ImageInfo *image_info, Image *image,const char letter) { char value[MaxTextExtent]; const char *string; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); *value='\0'; string=(char *) NULL; switch (letter) { case 'b': { /* Image size read in - in bytes. */ (void) FormatMagickSize(image->extent,MagickFalse,value); if (image->extent == 0) (void) FormatMagickSize(GetBlobSize(image),MagickFalse,value); break; } case 'c': { /* Image comment property - empty string by default. */ string=GetImageProperty(image,""comment""); if (string == (const char *) NULL) string=""""; break; } case 'd': { /* Directory component of filename. */ GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""""; break; } case 'e': { /* Filename extension (suffix) of image file. */ GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""""; break; } case 'f': { /* Filename without directory component. */ GetPathComponent(image->magick_filename,TailPath,value); if (*value == '\0') string=""""; break; } case 'g': { /* Image geometry, canvas and offset %Wx%H+%X+%Y. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20gx%.20g%+.20g%+.20g"", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); break; } case 'h': { /* Image height (current). */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) (image->rows != 0 ? image->rows : image->magick_rows)); break; } case 'i': { /* Filename last used for image (read or write). */ string=image->filename; break; } case 'k': { /* Number of unique colors. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) GetNumberColors(image,(FILE *) NULL,&image->exception)); break; } case 'l': { /* Image label property - empty string by default. */ string=GetImageProperty(image,""label""); if (string == (const char *) NULL) string=""""; break; } case 'm': { /* Image format (file magick). */ string=image->magick; break; } case 'n': { /* Number of images in the list. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) GetImageListLength(image)); break; } case 'o': { /* Output Filename - for delegate use only */ string=image_info->filename; break; } case 'p': { /* Image index in current image list -- As 'n' OBSOLETE. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) GetImageIndexInList(image)); break; } case 'q': { /* Quantum depth of image in memory. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) MAGICKCORE_QUANTUM_DEPTH); break; } case 'r': { ColorspaceType colorspace; /* Image storage class and colorspace. */ colorspace=image->colorspace; if ((image->columns != 0) && (image->rows != 0) && (SetImageGray(image,&image->exception) != MagickFalse)) colorspace=GRAYColorspace; (void) FormatLocaleString(value,MaxTextExtent,""%s %s %s"", CommandOptionToMnemonic(MagickClassOptions,(ssize_t) image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions, (ssize_t) colorspace),image->matte != MagickFalse ? ""Matte"" : """" ); break; } case 's': { /* Image scene number. */ if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image_info->scene); else (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->scene); break; } case 't': { /* Base filename without directory or extension. */ GetPathComponent(image->magick_filename,BasePath,value); break; } case 'u': { /* Unique filename. */ string=image_info->unique; break; } case 'w': { /* Image width (current). */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) (image->columns != 0 ? image->columns : image->magick_columns)); break; } case 'x': { /* Image horizontal resolution. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"", fabs(image->x_resolution) > MagickEpsilon ? image->x_resolution : 72.0); break; } case 'y': { /* Image vertical resolution. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"", fabs(image->y_resolution) > MagickEpsilon ? image->y_resolution : 72.0); break; } case 'z': { /* Image depth. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->depth); break; } case 'A': { /* Image alpha channel. */ (void) FormatLocaleString(value,MaxTextExtent,""%s"", CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte)); break; } case 'B': { /* Image size read in - in bytes. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->extent); if (image->extent == 0) (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) GetBlobSize(image)); break; } case 'C': { /* Image compression method. */ (void) FormatLocaleString(value,MaxTextExtent,""%s"", CommandOptionToMnemonic(MagickCompressOptions,(ssize_t) image->compression)); break; } case 'D': { /* Image dispose method. */ (void) FormatLocaleString(value,MaxTextExtent,""%s"", CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t) image->dispose)); break; } case 'F': { const char *q; register char *p; static char whitelist[] = ""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "" ""$-_.+!*'(),{}|\\^~[]`\""><#%;/?:@&=""; /* Magick filename (sanitized) - filename given incl. coder & read mods. */ (void) CopyMagickString(value,image->magick_filename,MaxTextExtent); p=value; q=value+strlen(value); for (p+=strspn(p,whitelist); p != q; p+=strspn(p,whitelist)) *p='_'; break; } case 'G': { /* Image size as geometry = ""%wx%h"". */ (void) FormatLocaleString(value,MaxTextExtent,""%.20gx%.20g"",(double) image->magick_columns,(double) image->magick_rows); break; } case 'H': { /* Layer canvas height. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->page.height); break; } case 'M': { /* Magick filename - filename given incl. coder & read mods. */ string=image->magick_filename; break; } case 'O': { /* Layer canvas offset with sign = ""+%X+%Y"". */ (void) FormatLocaleString(value,MaxTextExtent,""%+ld%+ld"",(long) image->page.x,(long) image->page.y); break; } case 'P': { /* Layer canvas page size = ""%Wx%H"". */ (void) FormatLocaleString(value,MaxTextExtent,""%.20gx%.20g"",(double) image->page.width,(double) image->page.height); break; } case 'Q': { /* Image compression quality. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) (image->quality == 0 ? 92 : image->quality)); break; } case 'S': { /* Image scenes. */ if (image_info->number_scenes == 0) string=""2147483647""; else (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image_info->scene+image_info->number_scenes); break; } case 'T': { /* Image time delay for animations. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->delay); break; } case 'U': { /* Image resolution units. */ (void) FormatLocaleString(value,MaxTextExtent,""%s"", CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t) image->units)); break; } case 'W': { /* Layer canvas width. */ (void) FormatLocaleString(value,MaxTextExtent,""%.20g"",(double) image->page.width); break; } case 'X': { /* Layer canvas X offset. */ (void) FormatLocaleString(value,MaxTextExtent,""%+.20g"",(double) image->page.x); break; } case 'Y': { /* Layer canvas Y offset. */ (void) FormatLocaleString(value,MaxTextExtent,""%+.20g"",(double) image->page.y); break; } case 'Z': { /* Zero filename. */ string=image_info->zero; break; } case '@': { RectangleInfo page; /* Image bounding box. */ page=GetImageBoundingBox(image,&image->exception); (void) FormatLocaleString(value,MaxTextExtent,""%.20gx%.20g%+.20g%+.20g"", (double) page.width,(double) page.height,(double) page.x,(double) page.y); break; } case '#': { /* Image signature. */ if ((image->columns != 0) && (image->rows != 0)) (void) SignatureImage(image); string=GetImageProperty(image,""signature""); break; } case '%': { /* Percent escaped. */ string=""%""; break; } } if (*value != '\0') string=value; if (string != (char *) NULL) { (void) SetImageArtifact(image,""get-property"",string); return(GetImageArtifact(image,""get-property"")); } return((char *) NULL); }",CWE-476,12 1,"ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if (strcmp(im->mode, ""1"") == 0 && state->xsize > state->bytes * 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } else if (strcmp(im->mode, ""P"") == 0 && state->xsize > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }",CWE-125,1 0,"void WebGraphicsContext3DDefaultImpl::disableVertexAttribArray(unsigned long index) { makeContextCurrent(); if (index < NumTrackedPointerStates) m_vertexAttribPointerState[index].enabled = false; glDisableVertexAttribArray(index); } ",none,24 1,"void __do_SAK(struct tty_struct *tty) { #ifdef TTY_SOFT_SAK tty_hangup(tty); #else struct task_struct *g, *p; struct pid *session; int i; if (!tty) return; session = tty->session; tty_ldisc_flush(tty); tty_driver_flush_buffer(tty); read_lock(&tasklist_lock); /* Kill the entire session */ do_each_pid_task(session, PIDTYPE_SID, p) { tty_notice(tty, ""SAK: killed process %d (%s): by session\n"", task_pid_nr(p), p->comm); group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID); } while_each_pid_task(session, PIDTYPE_SID, p); /* Now kill any processes that happen to have the tty open */ do_each_thread(g, p) { if (p->signal->tty == tty) { tty_notice(tty, ""SAK: killed process %d (%s): by controlling tty\n"", task_pid_nr(p), p->comm); group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID); continue; } task_lock(p); i = iterate_fd(p->files, 0, this_tty, tty); if (i != 0) { tty_notice(tty, ""SAK: killed process %d (%s): by fd#%d\n"", task_pid_nr(p), p->comm, i - 1); group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID); } task_unlock(p); } while_each_thread(g, p); read_unlock(&tasklist_lock); #endif }",CWE-416,10 1," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const float input_min_float = ctx->input(1).flat()(0); const float input_max_float = ctx->input(2).flat()(0); Tensor* output_min = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min)); Tensor* output_max = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max)); qint32 used_min_quantized; qint32 used_max_quantized; CalculateUsedRange(input, &used_min_quantized, &used_max_quantized); // We want to make sure that the minimum is no larger than zero, so that the // convolution operation can run efficiently. const float used_min_float = std::min( 0.0f, QuantizedToFloat(used_min_quantized, input_min_float, input_max_float)); const float used_max_float = QuantizedToFloat(used_max_quantized, input_min_float, input_max_float); output_min->flat().setConstant(used_min_float); output_max->flat().setConstant(used_max_float); }",CWE-125,1 0,"void BlobURLRequestJob::CountSize() { for (; item_index_ < blob_data_->items().size(); ++item_index_) { const BlobData::Item& item = blob_data_->items().at(item_index_); int64 item_length = static_cast(item.length()); if (item.type() == BlobData::TYPE_FILE) { ResolveFile(item.file_path()); return; } item_length_list_.push_back(item_length); total_size_ += item_length; } item_index_ = 0; if (!byte_range_.ComputeBounds(total_size_)) { NotifyFailure(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE); return; } remaining_bytes_ = byte_range_.last_byte_position() - byte_range_.first_byte_position() + 1; DCHECK_GE(remaining_bytes_, 0); if (byte_range_.first_byte_position()) Seek(byte_range_.first_byte_position()); NotifySuccess(); } ",none,24 1,"CairoFont *CairoFont::create(GfxFont *gfxFont, XRef *xref, FT_Library lib, GBool useCIDs) { Ref embRef; Object refObj, strObj; GooString *tmpFileName, *fileName,*tmpFileName2; DisplayFontParam *dfp; FILE *tmpFile; int c, i, n; GfxFontType fontType; char **enc; char *name; FoFiTrueType *ff; FoFiType1C *ff1c; Ref ref; static cairo_user_data_key_t cairo_font_face_key; cairo_font_face_t *cairo_font_face; FT_Face face; Gushort *codeToGID; int codeToGIDLen; dfp = NULL; codeToGID = NULL; codeToGIDLen = 0; cairo_font_face = NULL; ref = *gfxFont->getID(); fontType = gfxFont->getType(); tmpFileName = NULL; if (gfxFont->getEmbeddedFontID(&embRef)) { if (!openTempFile(&tmpFileName, &tmpFile, ""wb"", NULL)) { error(-1, ""Couldn't create temporary font file""); goto err2; } refObj.initRef(embRef.num, embRef.gen); refObj.fetch(xref, &strObj); refObj.free(); strObj.streamReset(); while ((c = strObj.streamGetChar()) != EOF) { fputc(c, tmpFile); } strObj.streamClose(); strObj.free(); fclose(tmpFile); fileName = tmpFileName; } else if (!(fileName = gfxFont->getExtFontFile())) { // look for a display font mapping or a substitute font dfp = NULL; if (gfxFont->getName()) { dfp = globalParams->getDisplayFont(gfxFont); } if (!dfp) { error(-1, ""Couldn't find a font for '%s'"", gfxFont->getName() ? gfxFont->getName()->getCString() : ""(unnamed)""); goto err2; } switch (dfp->kind) { case displayFontT1: fileName = dfp->t1.fileName; fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1; break; case displayFontTT: fileName = dfp->tt.fileName; fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType; break; } } switch (fontType) { case fontType1: case fontType1C: if (FT_New_Face(lib, fileName->getCString(), 0, &face)) { error(-1, ""could not create type1 face""); goto err2; } enc = ((Gfx8BitFont *)gfxFont)->getEncoding(); codeToGID = (Gushort *)gmallocn(256, sizeof(int)); codeToGIDLen = 256; for (i = 0; i < 256; ++i) { codeToGID[i] = 0; if ((name = enc[i])) { codeToGID[i] = (Gushort)FT_Get_Name_Index(face, name); } } break; case fontCIDType2: codeToGID = NULL; n = 0; if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); if (n) { codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort)); memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), n * sizeof(Gushort)); } } else { ff = FoFiTrueType::load(fileName->getCString()); if (! ff) goto err2; codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n); delete ff; } codeToGIDLen = n; /* Fall through */ case fontTrueType: if (!(ff = FoFiTrueType::load(fileName->getCString()))) { error(-1, ""failed to load truetype font\n""); goto err2; } /* This might be set already for the CIDType2 case */ if (fontType == fontTrueType) { codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff); codeToGIDLen = 256; } if (!openTempFile(&tmpFileName2, &tmpFile, ""wb"", NULL)) { delete ff; error(-1, ""failed to open truetype tempfile\n""); goto err2; } ff->writeTTF(&fileWrite, tmpFile); fclose(tmpFile); delete ff; if (FT_New_Face(lib, tmpFileName2->getCString(), 0, &face)) { error(-1, ""could not create truetype face\n""); goto err2; } unlink (tmpFileName2->getCString()); delete tmpFileName2; break; case fontCIDType0: case fontCIDType0C: codeToGID = NULL; codeToGIDLen = 0; if (!useCIDs) { if ((ff1c = FoFiType1C::load(fileName->getCString()))) { codeToGID = ff1c->getCIDToGIDMap(&codeToGIDLen); delete ff1c; } } if (FT_New_Face(lib, fileName->getCString(), 0, &face)) { gfree(codeToGID); codeToGID = NULL; error(-1, ""could not create cid face\n""); goto err2; } break; default: printf (""font type not handled\n""); goto err2; break; } // delete the (temporary) font file -- with Unix hard link // semantics, this will remove the last link; otherwise it will // return an error, leaving the file to be deleted later if (fileName == tmpFileName) { unlink (fileName->getCString()); delete tmpFileName; } cairo_font_face = cairo_ft_font_face_create_for_ft_face (face, FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP); if (cairo_font_face == NULL) { error(-1, ""could not create cairo font\n""); goto err2; /* this doesn't do anything, but it looks like we're * handling the error */ } { CairoFont *ret = new CairoFont(ref, cairo_font_face, face, codeToGID, codeToGIDLen); cairo_font_face_set_user_data (cairo_font_face, &cairo_font_face_key, ret, cairo_font_face_destroy); return ret; } err2: /* hmm? */ printf (""some font thing failed\n""); return NULL; }",CWE-20,3 0,"bool SpeechSynthesis::paused() const { return m_isPaused; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::deleteBuffer(unsigned buffer) { makeContextCurrent(); glDeleteBuffersARB(1, &buffer); } ",none,24 0,"ContentSettingsStore::ContentSettingsStore() { DCHECK(OnCorrectThread()); } ",none,24 1,"GF_Err tenc_box_read(GF_Box *s, GF_BitStream *bs) { u8 iv_size; GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*)s; ISOM_DECREASE_SIZE(ptr, 3); gf_bs_read_u8(bs); //reserved if (!ptr->version) { gf_bs_read_u8(bs); //reserved } else { ptr->crypt_byte_block = gf_bs_read_int(bs, 4); ptr->skip_byte_block = gf_bs_read_int(bs, 4); } ptr->isProtected = gf_bs_read_u8(bs); ISOM_DECREASE_SIZE(ptr, 17); ptr->key_info[0] = 0; ptr->key_info[1] = 0; ptr->key_info[2] = 0; ptr->key_info[3] = iv_size = gf_bs_read_u8(bs); gf_bs_read_data(bs, ptr->key_info+4, 16); if (!iv_size && ptr->isProtected) { ISOM_DECREASE_SIZE(ptr, 1); iv_size = ptr->key_info[20] = gf_bs_read_u8(bs); ISOM_DECREASE_SIZE(ptr, ptr->key_info[20]); gf_bs_read_data(bs, ptr->key_info+21, iv_size); } return GF_OK; }",CWE-787,16 1,"static apr_status_t session_identity_decode(request_rec * r, session_rec * z) { char *last = NULL; char *encoded, *pair; const char *sep = ""&""; /* sanity check - anything to decode? */ if (!z->encoded) { return OK; } /* decode what we have */ encoded = apr_pstrdup(r->pool, z->encoded); pair = apr_strtok(encoded, sep, &last); while (pair && pair[0]) { char *plast = NULL; const char *psep = ""=""; char *key = apr_strtok(pair, psep, &plast); char *val = apr_strtok(NULL, psep, &plast); if (key && *key) { if (!val || !*val) { apr_table_unset(z->entries, key); } else if (!ap_unescape_urlencoded(key) && !ap_unescape_urlencoded(val)) { if (!strcmp(SESSION_EXPIRY, key)) { z->expiry = (apr_time_t) apr_atoi64(val); } else { apr_table_set(z->entries, key, val); } } } pair = apr_strtok(NULL, sep, &last); } z->encoded = NULL; return OK; }",CWE-476,12 1,"#ifndef GPAC_DISABLE_ISOM_HINTING void dump_isom_sdp(GF_ISOFile *file, char *inName, Bool is_final_name) { const char *sdp; u32 size, i; FILE *dump; if (inName) { char szBuf[1024]; strcpy(szBuf, inName); if (!is_final_name) { char *ext = strchr(szBuf, '.'); if (ext) ext[0] = 0; strcat(szBuf, ""_sdp.txt""); } dump = gf_fopen(szBuf, ""wt""); if (!dump) { fprintf(stderr, ""Failed to open %s for dumping\n"", szBuf); return; } } else { dump = stdout; fprintf(dump, ""* File SDP content *\n\n""); } //get the movie SDP gf_isom_sdp_get(file, &sdp, &size); fprintf(dump, ""%s"", sdp); fprintf(dump, ""\r\n""); //then tracks for (i=0; i utterance) { if (utterance->client()) handleSpeakingCompleted(static_cast(utterance->client()), false); } ",none,24 1,"static inline void tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked) { if (sk->sk_send_head == skb_unlinked) sk->sk_send_head = NULL; }",CWE-269,6 1," static void bfq_idle_slice_timer_body(struct bfq_queue *bfqq) { struct bfq_data *bfqd = bfqq->bfqd; enum bfqq_expiration reason; unsigned long flags; spin_lock_irqsave(&bfqd->lock, flags); bfq_clear_bfqq_wait_request(bfqq); if (bfqq != bfqd->in_service_queue) { spin_unlock_irqrestore(&bfqd->lock, flags); return; } if (bfq_bfqq_budget_timeout(bfqq)) /* * Also here the queue can be safely expired * for budget timeout without wasting * guarantees */ reason = BFQQE_BUDGET_TIMEOUT; else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0) /* * The queue may not be empty upon timer expiration, * because we may not disable the timer when the * first request of the in-service queue arrives * during disk idling. */ reason = BFQQE_TOO_IDLE; else goto schedule_dispatch; bfq_bfqq_expire(bfqd, bfqq, true, reason); schedule_dispatch: spin_unlock_irqrestore(&bfqd->lock, flags); bfq_schedule_dispatch(bfqd);",CWE-416,10 0,"bool BlobURLRequestJob::GetMimeType(std::string* mime_type) const { if (!response_info_.get()) return false; return response_info_->headers->GetMimeType(mime_type); } ",none,24 1,"static inline Status ParseAndCheckBoxSizes(const Tensor& boxes, const Tensor& box_index, int* num_boxes) { if (boxes.NumElements() == 0 && box_index.NumElements() == 0) { *num_boxes = 0; return Status::OK(); } // The shape of 'boxes' is [num_boxes, 4]. if (boxes.dims() != 2) { return errors::InvalidArgument(""boxes must be 2-D"", boxes.shape().DebugString()); } *num_boxes = boxes.dim_size(0); if (boxes.dim_size(1) != 4) { return errors::InvalidArgument(""boxes must have 4 columns""); } // The shape of 'box_index' is [num_boxes]. if (box_index.dims() != 1) { return errors::InvalidArgument(""box_index must be 1-D"", box_index.shape().DebugString()); } if (box_index.dim_size(0) != *num_boxes) { return errors::InvalidArgument(""box_index has incompatible shape""); } return Status::OK(); }",CWE-787,16 1,"int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n, curr_rec, num_recs, read_bytes; SSL3_RECORD *rr; SSL3_BUFFER *rbuf; void (*cb) (const SSL *ssl, int type2, int val) = NULL; rbuf = &s->rlayer.rbuf; if (!SSL3_BUFFER_is_initialised(rbuf)) { /* Not initialized yet */ if (!ssl3_setup_read_buffer(s)) return (-1); } if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0)) /* (partially) satisfy request from storage */ { unsigned char *src = s->rlayer.handshake_fragment; unsigned char *dst = buf; unsigned int k; /* peek == 0 */ n = 0; while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) { *dst++ = *src++; len--; s->rlayer.handshake_fragment_len--; n++; } /* move any remaining fragment bytes: */ for (k = 0; k < s->rlayer.handshake_fragment_len; k++) s->rlayer.handshake_fragment[k] = *src++; if (recvd_type != NULL) *recvd_type = SSL3_RT_HANDSHAKE; return n; } /* * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * For each record 'i' up to |num_recs] * rr[i].type - is the type of record * rr[i].data, - data * rr[i].off, - offset into 'data' for next read * rr[i].length, - number of bytes. */ rr = s->rlayer.rrec; num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer); do { /* get new records if necessary */ if (num_recs == 0) { ret = ssl3_get_record(s); if (ret <= 0) return (ret); num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer); if (num_recs == 0) { /* Shouldn't happen */ al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; } } /* Skip over any records we have already read */ for (curr_rec = 0; curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]); curr_rec++) ; if (curr_rec == num_recs) { RECORD_LAYER_set_numrpipes(&s->rlayer, 0); num_recs = 0; curr_rec = 0; } } while (num_recs == 0); rr = &rr[curr_rec]; /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT && SSL3_RECORD_get_length(rr) != 0) s->rlayer.alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); goto f_err; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { SSL3_RECORD_set_length(rr, 0); s->rwstate = SSL_NOTHING; return (0); } if (type == SSL3_RECORD_get_type(rr) || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) { /* * SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE or * SSL3_RT_CHANGE_CIPHER_SPEC */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (type == SSL3_RT_HANDSHAKE && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC && s->rlayer.handshake_fragment_len > 0) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } if (recvd_type != NULL) *recvd_type = SSL3_RECORD_get_type(rr); if (len <= 0) return (len); read_bytes = 0; do { if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr)) n = SSL3_RECORD_get_length(rr); else n = (unsigned int)len - read_bytes; memcpy(buf, &(rr->data[rr->off]), n); buf += n; if (!peek) { SSL3_RECORD_sub_length(rr, n); SSL3_RECORD_add_off(rr, n); if (SSL3_RECORD_get_length(rr) == 0) { s->rlayer.rstate = SSL_ST_READ_HEADER; SSL3_RECORD_set_off(rr, 0); SSL3_RECORD_set_read(rr); } } if (SSL3_RECORD_get_length(rr) == 0 || (peek && n == SSL3_RECORD_get_length(rr))) { curr_rec++; rr++; } read_bytes += n; } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs && read_bytes < (unsigned int)len); if (read_bytes == 0) { /* We must have read empty records. Get more data */ goto start; } if (!peek && curr_rec == num_recs && (s->mode & SSL_MODE_RELEASE_BUFFERS) && SSL3_BUFFER_get_left(rbuf) == 0) ssl3_release_read_buffer(s); return read_bytes; } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello) or invalid (we * were actually expecting a CCS). */ /* * Lets just double check that we've not got an SSLv2 record */ if (rr->rec_version == SSL2_VERSION) { /* * Should never happen. ssl3_get_record() should only give us an SSLv2 * record back if this is the first packet and we are looking for an * initial ClientHello. Therefore |type| should always be equal to * |rr->type|. If not then something has gone horribly wrong */ al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; } if (s->method->version == TLS_ANY_VERSION && (s->server || rr->type != SSL3_RT_ALERT)) { /* * If we've got this far and still haven't decided on what version * we're using then this must be a client side alert we're dealing with * (we don't allow heartbeats yet). We shouldn't be receiving anything * other than a ClientHello if we are a server. */ s->version = rr->rec_version; al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE); goto f_err; } /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->rlayer.handshake_fragment; dest = s->rlayer.handshake_fragment; dest_len = &s->rlayer.handshake_fragment_len; } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) { dest_maxlen = sizeof s->rlayer.alert_fragment; dest = s->rlayer.alert_fragment; dest_len = &s->rlayer.alert_fragment_len; } if (dest_maxlen > 0) { n = dest_maxlen - *dest_len; /* available space in 'dest' */ if (SSL3_RECORD_get_length(rr) < n) n = SSL3_RECORD_get_length(rr); /* available bytes */ /* now move 'n' bytes: */ while (n-- > 0) { dest[(*dest_len)++] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]; SSL3_RECORD_add_off(rr, 1); SSL3_RECORD_add_length(rr, -1); } if (*dest_len < dest_maxlen) { SSL3_RECORD_set_read(rr); goto start; /* fragment was too small */ } } } /*- * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->rlayer.handshake_fragment_len >= 4) && (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->rlayer.handshake_fragment_len = 0; if ((s->rlayer.handshake_fragment[1] != 0) || (s->rlayer.handshake_fragment[2] != 0) || (s->rlayer.handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->rlayer.handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(rbuf) == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } /* * If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. WARNING: * experimental code, needs reviewing (steve) */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && (s->version > SSL3_VERSION) && (s->rlayer.handshake_fragment_len >= 4) && (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) && (s->session != NULL) && (s->session->cipher != NULL) && !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->rlayer.alert_fragment_len >= 2) { int alert_level = s->rlayer.alert_fragment[0]; int alert_descr = s->rlayer.alert_fragment[1]; s->rlayer.alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->rlayer.alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; SSL3_RECORD_set_read(rr); s->rlayer.alert_count++; if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); goto f_err; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } /* * This is a warning but we receive it if we requested * renegotiation and the peer denied it. Terminate with a fatal * alert because if application tried to renegotiate it * presumably had a good reason and expects it to succeed. In * future we might have a renegotiation where we don't care if * the peer refused it where we carry on. */ else if (alert_descr == SSL_AD_NO_RENEGOTIATION) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION); goto f_err; } #ifdef SSL_AD_MISSING_SRP_USERNAME else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME) return (0); #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof tmp, ""%d"", alert_descr); ERR_add_error_data(2, ""SSL alert number "", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL3_RECORD_set_read(rr); SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); return (0); } if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->rlayer.handshake_fragment_len >= 4) && !ossl_statem_get_in_handshake(s)) { if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { ossl_statem_set_in_init(s, 1); s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(rbuf) == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (SSL3_RECORD_get_type(rr)) { default: /* * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give * an unexpected message alert. */ if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) { SSL3_RECORD_set_length(rr, 0); SSL3_RECORD_set_read(rr); goto start; } al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but * that should not happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (ossl_statem_app_data_allowed(s)) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return (-1); }",CWE-20,3 0,"void VideoRendererBase::Initialize(const scoped_refptr& decoder, const PipelineStatusCB& status_cb, const StatisticsCB& statistics_cb, const TimeCB& time_cb) { base::AutoLock auto_lock(lock_); DCHECK(decoder); DCHECK(!status_cb.is_null()); DCHECK(!statistics_cb.is_null()); DCHECK(!time_cb.is_null()); DCHECK_EQ(kUninitialized, state_); decoder_ = decoder; statistics_cb_ = statistics_cb; time_cb_ = time_cb; host()->SetNaturalVideoSize(decoder_->natural_size()); state_ = kFlushed; set_opaque_cb_.Run(!decoder->HasAlpha()); set_opaque_cb_.Reset(); if (!base::PlatformThread::Create(0, this, &thread_)) { NOTREACHED() << ""Video thread creation failed""; state_ = kError; status_cb.Run(PIPELINE_ERROR_INITIALIZATION_FAILED); return; } #if defined(OS_WIN) ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL); #endif // defined(OS_WIN) status_cb.Run(PIPELINE_OK); } ",none,24 1,"void LibRaw::identify_process_dng_fields() { if (!dng_version) return; int c; { /* copy DNG data from per-IFD field to color.dng */ int iifd = find_ifd_by_offset(data_offset); int pifd = find_ifd_by_offset(thumb_offset); #define CFAROUND(value, filters) \ filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) \ : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) \ ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) \ ? ifd \ : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < (int)tiff_nifds && iifd >= 0) { int sidx; // Per field, not per structure if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DONT_CHECK_DNG_ILLUMINANT)) { int illidx[2], cmidx[2], calidx[2], abidx; for (int i = 0; i < 2; i++) { illidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_ILLUMINANT); cmidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_COLORMATRIX); calidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_CALIBRATION); } abidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); // Data found, all in same ifd, illuminants are inited if (illidx[0] >= 0 && illidx[0] < (int)tiff_nifds && illidx[0] == illidx[1] && illidx[0] == cmidx[0] && illidx[0] == cmidx[1] && tiff_ifd[illidx[0]].dng_color[0].illuminant > 0 && tiff_ifd[illidx[0]].dng_color[1].illuminant > 0) { sidx = illidx[0]; // => selected IFD double cc[4][4], cm[4][3], cam_xyz[4][3]; // CM -> Color Matrix // CC -> Camera calibration for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) cc[j][i] = i == j; int colidx = -1; // IS D65 here? for (int i = 0; i < 2; i++) { if (tiff_ifd[sidx].dng_color[i].illuminant == LIBRAW_WBI_D65) { colidx = i; break; } } // Other daylight-type ill if (colidx < 0) for (int i = 0; i < 2; i++) { int ill = tiff_ifd[sidx].dng_color[i].illuminant; if (ill == LIBRAW_WBI_Daylight || ill == LIBRAW_WBI_D55 || ill == LIBRAW_WBI_D75 || ill == LIBRAW_WBI_D50 || ill == LIBRAW_WBI_Flash) { colidx = i; break; } } if (colidx >= 0) // Selected { // Init camera matrix from DNG FORCC for (int j = 0; j < 3; j++) cm[c][j] = tiff_ifd[sidx].dng_color[colidx].colormatrix[c][j]; if (calidx[colidx] == sidx) { for (int i = 0; i < colors; i++) FORCC cc[i][c] = tiff_ifd[sidx].dng_color[colidx].calibration[i][c]; } if (abidx == sidx) for (int i = 0; i < colors; i++) FORCC cc[i][c] *= tiff_ifd[sidx].dng_levels.analogbalance[i]; int j; FORCC for (int i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i]; // add AsShotXY later * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } } } bool noFujiDNGCrop = makeIs(LIBRAW_CAMERAMAKER_Fujifilm) && (!strcmp(normalized_model, ""S3Pro"") || !strcmp(normalized_model, ""S5Pro"") || !strcmp(normalized_model, ""S2Pro"")); if (!noFujiDNGCrop && (imgdata.params.raw_processing_options &LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 && tiff_ifd[sidx].dng_levels.default_crop[3] > 0) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BASELINEEXPOSURE); if (sidx >= 0) imgdata.color.dng_levels.baseline_exposure = tiff_ifd[sidx].dng_levels.baseline_exposure; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0 && tiff_ifd[sidx].dng_levels.dng_whitelevel[0]) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); else if (tiff_ifd[iifd].sample_format <= 2 && tiff_ifd[iifd].bps > 0 && tiff_ifd[iifd].bps < 32) FORC4 imgdata.color.dng_levels.dng_whitelevel[c] = (1 << tiff_ifd[iifd].bps) - 1; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ASSHOTNEUTRAL); if (sidx >= 0) { COPYARR(imgdata.color.dng_levels.asshotneutral, tiff_ifd[sidx].dng_levels.asshotneutral); if (imgdata.color.dng_levels.asshotneutral[0]) { cam_mul[3] = 0; FORCC if (fabs(imgdata.color.dng_levels.asshotneutral[c]) > 0.0001) cam_mul[c] = 1 / imgdata.color.dng_levels.asshotneutral[c]; } } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_fblack = tiff_ifd[sidx].dng_levels.dng_fblack; imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); COPYARR(imgdata.color.dng_levels.dng_fcblack, tiff_ifd[sidx].dng_levels.dng_fcblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ if (load_raw == &LibRaw::lossy_dng_load_raw) { maximum = 0xffff; FORC4 imgdata.color.linear_max[c] = imgdata.color.dng_levels.dng_whitelevel[c] = 0xffff; } else { maximum = imgdata.color.dng_levels.dng_whitelevel[0]; } black = imgdata.color.dng_levels.dng_black; if (tiff_samples == 2 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples == imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1]) { unsigned ff = filters; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; /* Special case, Fuji SuperCCD dng */ int csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 }; int i = 6 + shot_select; for (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++) for (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++) { csum[FC(row, col)] += imgdata.color.dng_levels.dng_cblack[i]; ccount[FC(row, col)]++; i += tiff_samples; } for (int c = 0; c < 4; c++) if (ccount[c]) imgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c]; imgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0; filters = ff; } else if (tiff_samples > 2 && tiff_samples <= 4 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples == imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE - 1]) { /* Special case, per_channel blacks in RepeatDim, average for per-channel */ int csum[4] = { 0,0,0,0 }, ccount[4] = { 0,0,0,0 }; int i = 6; for (unsigned row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++) for (unsigned col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++) for (unsigned c = 0; c < tiff_samples; c++) { csum[c] += imgdata.color.dng_levels.dng_cblack[i]; ccount[c]++; i++; } for (int c = 0; c < 4; c++) if (ccount[c]) imgdata.color.dng_levels.dng_cblack[c] += csum[c] / ccount[c]; imgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0; } memmove(cblack, imgdata.color.dng_levels.dng_cblack, sizeof(cblack)); if (iifd < (int)tiff_nifds && iifd >= 0) { int sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINEARRESPONSELIMIT); if (sidx >= 0) { imgdata.color.dng_levels.LinearResponseLimit = tiff_ifd[sidx].dng_levels.LinearResponseLimit; if (imgdata.color.dng_levels.LinearResponseLimit > 0.1 && imgdata.color.dng_levels.LinearResponseLimit <= 1.0) { // And approx promote it to linear_max: int bl4 = 0, bl64 = 0; for (int chan = 0; chan < colors && chan < 4; chan++) bl4 += cblack[chan]; bl4 /= LIM(colors, 1, 4); if (cblack[4] * cblack[5] > 0) { unsigned cnt = 0; for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) { bl64 += cblack[c + 6]; cnt++; } bl64 /= LIM(cnt, 1, 4096); } int rblack = black + bl4 + bl64; for (int chan = 0; chan < colors && chan < 4; chan++) imgdata.color.linear_max[chan] = (maximum - rblack) * imgdata.color.dng_levels.LinearResponseLimit + rblack; } } } } }",CWE-787,16 1,"void CLASS kodak_65000_load_raw() { short buf[256]; int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) if ((RAW(row,col+i) = curve[ret ? buf[i] : (pred[i & 1] += buf[i])]) >> 12) derror(); } } }",CWE-787,16 0,"SoftwareFrame::~SoftwareFrame() { if (frame_manager_client_) { frame_manager_client_->SoftwareFrameWasFreed( output_surface_id_, frame_id_); } } ",none,24 1,"Pl_AES_PDF::flush(bool strip_padding) { assert(this->offset == this->buf_size); if (first) { first = false; bool return_after_init = false; if (this->cbc_mode) { if (encrypt) { // Set cbc_block to the initialization vector, and if // not zero, write it to the output stream. initializeVector(); if (! (this->use_zero_iv || this->use_specified_iv)) { getNext()->write(this->cbc_block, this->buf_size); } } else if (this->use_zero_iv || this->use_specified_iv) { // Initialize vector with zeroes; zero vector was not // written to the beginning of the input file. initializeVector(); } else { // Take the first block of input as the initialization // vector. There's nothing to write at this time. memcpy(this->cbc_block, this->inbuf, this->buf_size); this->offset = 0; return_after_init = true; } } this->crypto->rijndael_init( encrypt, this->key.get(), key_bytes, this->cbc_mode, this->cbc_block); if (return_after_init) { return; } } if (this->encrypt) { this->crypto->rijndael_process(this->inbuf, this->outbuf); } else { this->crypto->rijndael_process(this->inbuf, this->outbuf); } unsigned int bytes = this->buf_size; if (strip_padding) { unsigned char last = this->outbuf[this->buf_size - 1]; if (last <= this->buf_size) { bool strip = true; for (unsigned int i = 1; i <= last; ++i) { if (this->outbuf[this->buf_size - i] != last) { strip = false; break; } } if (strip) { bytes -= last; } } } getNext()->write(this->outbuf, bytes); this->offset = 0; }",CWE-787,16 1,"long uv__idna_toascii(const char* s, const char* se, char* d, char* de) { const char* si; const char* st; unsigned c; char* ds; int rc; ds = d; for (si = s; si < se; /* empty */) { st = si; c = uv__utf8_decode1(&si, se); if (c != '.') if (c != 0x3002) /* 。 */ if (c != 0xFF0E) /* . */ if (c != 0xFF61) /* 。 */ continue; rc = uv__idna_toascii_label(s, st, &d, de); if (rc < 0) return rc; if (d < de) *d++ = '.'; s = si; } if (s < se) { rc = uv__idna_toascii_label(s, se, &d, de); if (rc < 0) return rc; } if (d < de) *d++ = '\0'; return d - ds; /* Number of bytes written. */ }",CWE-125,1 1,"static int llcp_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct nfc_llcp_sock *llcp_sock = nfc_llcp_sock(sk); struct nfc_llcp_local *local; struct nfc_dev *dev; struct sockaddr_nfc_llcp llcp_addr; int len, ret = 0; if (!addr || alen < offsetofend(struct sockaddr, sa_family) || addr->sa_family != AF_NFC) return -EINVAL; pr_debug(""sk %p addr %p family %d\n"", sk, addr, addr->sa_family); memset(&llcp_addr, 0, sizeof(llcp_addr)); len = min_t(unsigned int, sizeof(llcp_addr), alen); memcpy(&llcp_addr, addr, len); /* This is going to be a listening socket, dsap must be 0 */ if (llcp_addr.dsap != 0) return -EINVAL; lock_sock(sk); if (sk->sk_state != LLCP_CLOSED) { ret = -EBADFD; goto error; } dev = nfc_get_device(llcp_addr.dev_idx); if (dev == NULL) { ret = -ENODEV; goto error; } local = nfc_llcp_find_local(dev); if (local == NULL) { ret = -ENODEV; goto put_dev; } llcp_sock->dev = dev; llcp_sock->local = nfc_llcp_local_get(local); llcp_sock->nfc_protocol = llcp_addr.nfc_protocol; llcp_sock->service_name_len = min_t(unsigned int, llcp_addr.service_name_len, NFC_LLCP_MAX_SERVICE_NAME); llcp_sock->service_name = kmemdup(llcp_addr.service_name, llcp_sock->service_name_len, GFP_KERNEL); if (!llcp_sock->service_name) { nfc_llcp_local_put(llcp_sock->local); llcp_sock->local = NULL; ret = -ENOMEM; goto put_dev; } llcp_sock->ssap = nfc_llcp_get_sdp_ssap(local, llcp_sock); if (llcp_sock->ssap == LLCP_SAP_MAX) { nfc_llcp_local_put(llcp_sock->local); llcp_sock->local = NULL; kfree(llcp_sock->service_name); llcp_sock->service_name = NULL; ret = -EADDRINUSE; goto put_dev; } llcp_sock->reserved_ssap = llcp_sock->ssap; nfc_llcp_sock_link(&local->sockets, sk); pr_debug(""Socket bound to SAP %d\n"", llcp_sock->ssap); sk->sk_state = LLCP_BOUND; put_dev: nfc_put_device(dev); error: release_sock(sk); return ret; }",CWE-476,12 0,"AudioContext::AudioContext(Document* document, unsigned numberOfChannels, size_t numberOfFrames, float sampleRate) : ActiveDOMObject(document) , m_isStopScheduled(false) , m_isCleared(false) , m_isInitialized(false) , m_destinationNode(nullptr) , m_isResolvingResumePromises(false) , m_automaticPullNodesNeedUpdating(false) , m_connectionCount(0) , m_didInitializeContextGraphMutex(false) , m_audioThread(0) , m_isOfflineContext(true) , m_contextState(Suspended) , m_cachedSampleFrame(0) { m_didInitializeContextGraphMutex = true; m_renderTarget = AudioBuffer::create(numberOfChannels, numberOfFrames, sampleRate); if (m_renderTarget.get()) m_destinationNode = OfflineAudioDestinationNode::create(this, m_renderTarget.get()); initialize(); } ",none,24 1,"ngx_http_auth_spnego_handler( ngx_http_request_t * r) { ngx_int_t ret = NGX_DECLINED; ngx_http_auth_spnego_ctx_t *ctx; ngx_http_auth_spnego_loc_conf_t *alcf; alcf = ngx_http_get_module_loc_conf(r, ngx_http_auth_spnego_module); if (alcf->protect == 0) { return NGX_DECLINED; } ctx = ngx_http_get_module_ctx(r, ngx_http_auth_spnego_module); if (NULL == ctx) { ctx = ngx_palloc(r->pool, sizeof(ngx_http_auth_spnego_ctx_t)); if (NULL == ctx) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } ctx->token.len = 0; ctx->token.data = NULL; ctx->head = 0; ctx->ret = NGX_HTTP_UNAUTHORIZED; ngx_http_set_ctx(r, ctx, ngx_http_auth_spnego_module); } spnego_debug3(""SSO auth handling IN: token.len=%d, head=%d, ret=%d"", ctx->token.len, ctx->head, ctx->ret); if (ctx->token.len && ctx->head) { spnego_debug1(""Found token and head, returning %d"", ctx->ret); return ctx->ret; } if (NULL != r->headers_in.user.data) { spnego_debug0(""User header set""); return NGX_OK; } spnego_debug0(""Begin auth""); if (alcf->allow_basic) { spnego_debug0(""Detect basic auth""); ret = ngx_http_auth_basic_user(r); if (NGX_OK == ret) { spnego_debug0(""Basic auth credentials supplied by client""); /* If basic auth is enabled and basic creds are supplied * attempt basic auth. If we attempt basic auth, we do * not fall through to real SPNEGO */ if (NGX_DECLINED == ngx_http_auth_spnego_basic(r, ctx, alcf)) { spnego_debug0(""Basic auth failed""); if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) { spnego_debug0(""Error setting headers""); return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR); } return (ctx->ret = NGX_HTTP_UNAUTHORIZED); } if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) { spnego_debug0(""User not authorized""); return (ctx->ret = NGX_HTTP_FORBIDDEN); } spnego_debug0(""Basic auth succeeded""); return (ctx->ret = NGX_OK); } } /* Basic auth either disabled or not supplied by client */ spnego_debug0(""Detect SPNEGO token""); ret = ngx_http_auth_spnego_token(r, ctx); if (NGX_OK == ret) { spnego_debug0(""Client sent a reasonable Negotiate header""); ret = ngx_http_auth_spnego_auth_user_gss(r, ctx, alcf); if (NGX_ERROR == ret) { spnego_debug0(""GSSAPI failed""); return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR); } /* There are chances that client knows about Negotiate * but doesn't support GSSAPI. We could attempt to fall * back to basic here... */ if (NGX_DECLINED == ret) { spnego_debug0(""GSSAPI failed""); if(!alcf->allow_basic) { return (ctx->ret = NGX_HTTP_FORBIDDEN); } if (NGX_ERROR == ngx_http_auth_spnego_headers_basic_only(r, ctx, alcf)) { spnego_debug0(""Error setting headers""); return (ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR); } return (ctx->ret = NGX_HTTP_UNAUTHORIZED); } if (!ngx_spnego_authorized_principal(r, &r->headers_in.user, alcf)) { spnego_debug0(""User not authorized""); return (ctx->ret = NGX_HTTP_FORBIDDEN); } spnego_debug0(""GSSAPI auth succeeded""); } ngx_str_t *token_out_b64 = NULL; switch(ret) { case NGX_DECLINED: /* DECLINED, but not yet FORBIDDEN */ ctx->ret = NGX_HTTP_UNAUTHORIZED; break; case NGX_OK: ctx->ret = NGX_OK; token_out_b64 = &ctx->token_out_b64; break; case NGX_ERROR: default: ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR; break; } if (NGX_ERROR == ngx_http_auth_spnego_headers(r, ctx, token_out_b64, alcf)) { spnego_debug0(""Error setting headers""); ctx->ret = NGX_HTTP_INTERNAL_SERVER_ERROR; } spnego_debug3(""SSO auth handling OUT: token.len=%d, head=%d, ret=%d"", ctx->token.len, ctx->head, ctx->ret); return ctx->ret; }",CWE-287,7 1,"void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, ""search H323\n""); /* The TPKT protocol is used by ISO 8072 (on port 102) and H.323. So this check below is to avoid ambiguities */ if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) { NDPI_LOG_DBG2(ndpi_struct, ""calculated dport over tcp\n""); /* H323 */ if(packet->payload_packet_len >= 4 && (packet->payload[0] == 0x03) && (packet->payload[1] == 0x00)) { struct tpkt *t = (struct tpkt*)packet->payload; u_int16_t len = ntohs(t->len); if(packet->payload_packet_len == len) { /* We need to check if this packet is in reality a RDP (Remote Desktop) packet encapsulated on TPTK */ if(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) { /* ISO 8073/X.224 */ if((packet->payload[5] == 0xE0 /* CC Connect Request */) || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) { NDPI_LOG_INFO(ndpi_struct, ""found RDP\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN); return; } } flow->l4.tcp.h323_valid_packets++; if(flow->l4.tcp.h323_valid_packets >= 2) { NDPI_LOG_INFO(ndpi_struct, ""found H323 broadcast\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); } } else { /* This is not H.323 */ NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return; } } } else if(packet->udp != NULL) { sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest); NDPI_LOG_DBG2(ndpi_struct, ""calculated dport over udp\n""); if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 && (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) && packet->payload[4] == 0x00 && packet->payload[5] == 0x00) { NDPI_LOG_INFO(ndpi_struct, ""found H323 broadcast\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } /* H323 */ if(sport == 1719 || dport == 1719) { if(packet->payload[0] == 0x16 && packet->payload[1] == 0x80 && packet->payload[4] == 0x06 && packet->payload[5] == 0x00) { NDPI_LOG_INFO(ndpi_struct, ""found H323 broadcast\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117) { NDPI_LOG_INFO(ndpi_struct, ""found H323 broadcast\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return; } } } }",CWE-125,1 0,"int WebGraphicsContext3DDefaultImpl::width() { return m_cachedWidth; } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::readBackFramebuffer(unsigned char* pixels, size_t bufferSize) { if (bufferSize != static_cast(4 * width() * height())) return false; makeContextCurrent(); resolveMultisampledFramebuffer(0, 0, m_cachedWidth, m_cachedHeight); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); GLint packAlignment = 4; bool mustRestorePackAlignment = false; glGetIntegerv(GL_PACK_ALIGNMENT, &packAlignment); if (packAlignment > 4) { glPixelStorei(GL_PACK_ALIGNMENT, 4); mustRestorePackAlignment = true; } glReadPixels(0, 0, m_cachedWidth, m_cachedHeight, GL_BGRA, GL_UNSIGNED_BYTE, pixels); if (mustRestorePackAlignment) glPixelStorei(GL_PACK_ALIGNMENT, packAlignment); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); #ifdef FLIP_FRAMEBUFFER_VERTICALLY if (pixels) flipVertically(pixels, m_cachedWidth, m_cachedHeight); #endif return true; } ",none,24 1,"static void sm501_2d_operation(SM501State *s) { int cmd = (s->twoD_control >> 16) & 0x1F; int rtl = s->twoD_control & BIT(27); int format = (s->twoD_stretch >> 20) & 0x3; int rop_mode = (s->twoD_control >> 15) & 0x1; /* 1 for rop2, else rop3 */ /* 1 if rop2 source is the pattern, otherwise the source is the bitmap */ int rop2_source_is_pattern = (s->twoD_control >> 14) & 0x1; int rop = s->twoD_control & 0xFF; int dst_x = (s->twoD_destination >> 16) & 0x01FFF; int dst_y = s->twoD_destination & 0xFFFF; int width = (s->twoD_dimension >> 16) & 0x1FFF; int height = s->twoD_dimension & 0xFFFF; uint32_t dst_base = s->twoD_destination_base & 0x03FFFFFF; uint8_t *dst = s->local_mem + dst_base; int dst_pitch = (s->twoD_pitch >> 16) & 0x1FFF; int crt = (s->dc_crt_control & SM501_DC_CRT_CONTROL_SEL) ? 1 : 0; int fb_len = get_width(s, crt) * get_height(s, crt) * get_bpp(s, crt); if ((s->twoD_stretch >> 16) & 0xF) { qemu_log_mask(LOG_UNIMP, ""sm501: only XY addressing is supported.\n""); return; } if (rop_mode == 0) { if (rop != 0xcc) { /* Anything other than plain copies are not supported */ qemu_log_mask(LOG_UNIMP, ""sm501: rop3 mode with rop %x is not "" ""supported.\n"", rop); } } else { if (rop2_source_is_pattern && rop != 0x5) { /* For pattern source, we support only inverse dest */ qemu_log_mask(LOG_UNIMP, ""sm501: rop2 source being the pattern and "" ""rop %x is not supported.\n"", rop); } else { if (rop != 0x5 && rop != 0xc) { /* Anything other than plain copies or inverse dest is not * supported */ qemu_log_mask(LOG_UNIMP, ""sm501: rop mode %x is not "" ""supported.\n"", rop); } } } if (s->twoD_source_base & BIT(27) || s->twoD_destination_base & BIT(27)) { qemu_log_mask(LOG_UNIMP, ""sm501: only local memory is supported.\n""); return; } switch (cmd) { case 0x00: /* copy area */ { int src_x = (s->twoD_source >> 16) & 0x01FFF; int src_y = s->twoD_source & 0xFFFF; uint32_t src_base = s->twoD_source_base & 0x03FFFFFF; uint8_t *src = s->local_mem + src_base; int src_pitch = s->twoD_pitch & 0x1FFF; #define COPY_AREA(_bpp, _pixel_type, rtl) { \ int y, x, index_d, index_s; \ for (y = 0; y < height; y++) { \ for (x = 0; x < width; x++) { \ _pixel_type val; \ \ if (rtl) { \ index_s = ((src_y - y) * src_pitch + src_x - x) * _bpp; \ index_d = ((dst_y - y) * dst_pitch + dst_x - x) * _bpp; \ } else { \ index_s = ((src_y + y) * src_pitch + src_x + x) * _bpp; \ index_d = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \ } \ if (rop_mode == 1 && rop == 5) { \ /* Invert dest */ \ val = ~*(_pixel_type *)&dst[index_d]; \ } else { \ val = *(_pixel_type *)&src[index_s]; \ } \ *(_pixel_type *)&dst[index_d] = val; \ } \ } \ } switch (format) { case 0: COPY_AREA(1, uint8_t, rtl); break; case 1: COPY_AREA(2, uint16_t, rtl); break; case 2: COPY_AREA(4, uint32_t, rtl); break; } break; } case 0x01: /* fill rectangle */ { uint32_t color = s->twoD_foreground; #define FILL_RECT(_bpp, _pixel_type) { \ int y, x; \ for (y = 0; y < height; y++) { \ for (x = 0; x < width; x++) { \ int index = ((dst_y + y) * dst_pitch + dst_x + x) * _bpp; \ *(_pixel_type *)&dst[index] = (_pixel_type)color; \ } \ } \ } switch (format) { case 0: FILL_RECT(1, uint8_t); break; case 1: color = cpu_to_le16(color); FILL_RECT(2, uint16_t); break; case 2: color = cpu_to_le32(color); FILL_RECT(4, uint32_t); break; } break; } default: qemu_log_mask(LOG_UNIMP, ""sm501: not implemented 2D operation: %d\n"", cmd); return; } if (dst_base >= get_fb_addr(s, crt) && dst_base <= get_fb_addr(s, crt) + fb_len) { int dst_len = MIN(fb_len, ((dst_y + height - 1) * dst_pitch + dst_x + width) * (1 << format)); if (dst_len) { memory_region_set_dirty(&s->local_mem_region, dst_base, dst_len); } } }",CWE-190,2 0,"void SpeechSynthesis::pause() { if (!m_isPaused) m_platformSpeechSynthesizer->pause(); } ",none,24 1,"ldns_rr_new_frm_str_internal(ldns_rr **newrr, const char *str, uint32_t default_ttl, const ldns_rdf *origin, ldns_rdf **prev, bool question) { ldns_rr *new; const ldns_rr_descriptor *desc; ldns_rr_type rr_type; ldns_buffer *rr_buf = NULL; ldns_buffer *rd_buf = NULL; uint32_t ttl_val; char *owner = NULL; char *ttl = NULL; ldns_rr_class clas_val; char *clas = NULL; char *type = NULL; size_t type_sz; char *rdata = NULL; char *rd = NULL; char *xtok = NULL; /* For RDF types with spaces (i.e. extra tokens) */ size_t rd_strlen; const char *delimiters; ssize_t c; ldns_rdf *owner_dname; const char* endptr; int was_unknown_rr_format = 0; ldns_status status = LDNS_STATUS_OK; /* used for types with unknown number of rdatas */ bool done; bool quoted; ldns_rdf *r = NULL; uint16_t r_cnt; uint16_t r_min; uint16_t r_max; size_t pre_data_pos; uint16_t hex_data_size; char *hex_data_str = NULL; uint16_t cur_hex_data_size; size_t hex_pos = 0; uint8_t *hex_data = NULL; new = ldns_rr_new(); owner = LDNS_XMALLOC(char, LDNS_MAX_DOMAINLEN + 1); ttl = LDNS_XMALLOC(char, LDNS_TTL_DATALEN); clas = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN); rdata = LDNS_XMALLOC(char, LDNS_MAX_PACKETLEN + 1); rr_buf = LDNS_MALLOC(ldns_buffer); rd_buf = LDNS_MALLOC(ldns_buffer); rd = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN); xtok = LDNS_XMALLOC(char, LDNS_MAX_RDFLEN); if (rr_buf) { rr_buf->_data = NULL; } if (rd_buf) { rd_buf->_data = NULL; } if (!new || !owner || !ttl || !clas || !rdata || !rr_buf || !rd_buf || !rd || !xtok) { goto memerror; } ldns_buffer_new_frm_data(rr_buf, (char*)str, strlen(str)); /* split the rr in its parts -1 signals trouble */ if (ldns_bget_token(rr_buf, owner, ""\t\n "", LDNS_MAX_DOMAINLEN) == -1){ status = LDNS_STATUS_SYNTAX_ERR; goto error; } if (ldns_bget_token(rr_buf, ttl, ""\t\n "", LDNS_TTL_DATALEN) == -1) { status = LDNS_STATUS_SYNTAX_TTL_ERR; goto error; } ttl_val = (uint32_t) ldns_str2period(ttl, &endptr); if (strlen(ttl) > 0 && !isdigit((int) ttl[0])) { /* ah, it's not there or something */ if (default_ttl == 0) { ttl_val = LDNS_DEFAULT_TTL; } else { ttl_val = default_ttl; } /* we not ASSUMING the TTL is missing and that * the rest of the RR is still there. That is * CLASS TYPE RDATA * so ttl value we read is actually the class */ clas_val = ldns_get_rr_class_by_name(ttl); /* class can be left out too, assume IN, current * token must be type */ if (clas_val == 0) { clas_val = LDNS_RR_CLASS_IN; type_sz = strlen(ttl) + 1; type = LDNS_XMALLOC(char, type_sz); if (!type) { goto memerror; } strlcpy(type, ttl, type_sz); } } else { if (-1 == ldns_bget_token( rr_buf, clas, ""\t\n "", LDNS_SYNTAX_DATALEN)) { status = LDNS_STATUS_SYNTAX_CLASS_ERR; goto error; } clas_val = ldns_get_rr_class_by_name(clas); /* class can be left out too, assume IN, current * token must be type */ if (clas_val == 0) { clas_val = LDNS_RR_CLASS_IN; type_sz = strlen(clas) + 1; type = LDNS_XMALLOC(char, type_sz); if (!type) { goto memerror; } strlcpy(type, clas, type_sz); } } /* the rest should still be waiting for us */ if (!type) { type = LDNS_XMALLOC(char, LDNS_SYNTAX_DATALEN); if (!type) { goto memerror; } if (-1 == ldns_bget_token( rr_buf, type, ""\t\n "", LDNS_SYNTAX_DATALEN)) { status = LDNS_STATUS_SYNTAX_TYPE_ERR; goto error; } } if (ldns_bget_token(rr_buf, rdata, ""\0"", LDNS_MAX_PACKETLEN) == -1) { /* apparently we are done, and it's only a question RR * so do not set status and go to ldnserror here */ } ldns_buffer_new_frm_data(rd_buf, rdata, strlen(rdata)); if (strlen(owner) <= 1 && strncmp(owner, ""@"", 1) == 0) { if (origin) { ldns_rr_set_owner(new, ldns_rdf_clone(origin)); } else if (prev && *prev) { ldns_rr_set_owner(new, ldns_rdf_clone(*prev)); } else { /* default to root */ ldns_rr_set_owner(new, ldns_dname_new_frm_str(""."")); } /* @ also overrides prev */ if (prev) { ldns_rdf_deep_free(*prev); *prev = ldns_rdf_clone(ldns_rr_owner(new)); if (!*prev) { goto memerror; } } } else { if (strlen(owner) == 0) { /* no ownername was given, try prev, if that fails * origin, else default to root */ if (prev && *prev) { ldns_rr_set_owner(new, ldns_rdf_clone(*prev)); } else if (origin) { ldns_rr_set_owner(new, ldns_rdf_clone(origin)); } else { ldns_rr_set_owner(new, ldns_dname_new_frm_str(""."")); } if(!ldns_rr_owner(new)) { goto memerror; } } else { owner_dname = ldns_dname_new_frm_str(owner); if (!owner_dname) { status = LDNS_STATUS_SYNTAX_ERR; goto error; } ldns_rr_set_owner(new, owner_dname); if (!ldns_dname_str_absolute(owner) && origin) { if(ldns_dname_cat(ldns_rr_owner(new), origin) != LDNS_STATUS_OK) { status = LDNS_STATUS_SYNTAX_ERR; goto error; } } if (prev) { ldns_rdf_deep_free(*prev); *prev = ldns_rdf_clone(ldns_rr_owner(new)); if (!*prev) { goto error; } } } } LDNS_FREE(owner); ldns_rr_set_question(new, question); ldns_rr_set_ttl(new, ttl_val); LDNS_FREE(ttl); ldns_rr_set_class(new, clas_val); LDNS_FREE(clas); rr_type = ldns_get_rr_type_by_name(type); LDNS_FREE(type); desc = ldns_rr_descript((uint16_t)rr_type); ldns_rr_set_type(new, rr_type); if (desc) { /* only the rdata remains */ r_max = ldns_rr_descriptor_maximum(desc); r_min = ldns_rr_descriptor_minimum(desc); } else { r_min = 0; r_max = 1; } for (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) { quoted = false; switch (ldns_rr_descriptor_field_type(desc, r_cnt)) { case LDNS_RDF_TYPE_B64 : case LDNS_RDF_TYPE_HEX : /* These rdf types may con- */ case LDNS_RDF_TYPE_LOC : /* tain whitespace, only if */ case LDNS_RDF_TYPE_WKS : /* it is the last rd field. */ case LDNS_RDF_TYPE_IPSECKEY : case LDNS_RDF_TYPE_AMTRELAY : case LDNS_RDF_TYPE_NSEC : if (r_cnt == r_max - 1) { delimiters = ""\n""; break; } /* fallthrough */ default : delimiters = ""\n\t ""; } if (ldns_rdf_type_maybe_quoted( ldns_rr_descriptor_field_type( desc, r_cnt)) && ldns_buffer_remaining(rd_buf) > 0){ /* skip spaces */ while (*(ldns_buffer_current(rd_buf)) == ' ') { ldns_buffer_skip(rd_buf, 1); } if (*(ldns_buffer_current(rd_buf)) == '\""') { delimiters = ""\""\0""; ldns_buffer_skip(rd_buf, 1); quoted = true; } else if (ldns_rr_descriptor_field_type(desc, r_cnt) == LDNS_RDF_TYPE_LONG_STR) { status = LDNS_STATUS_SYNTAX_RDATA_ERR; goto error; } } /* because number of fields can be variable, we can't rely on * _maximum() only */ /* skip spaces */ while (ldns_buffer_position(rd_buf) < ldns_buffer_limit(rd_buf) && *(ldns_buffer_current(rd_buf)) == ' ' && !quoted) { ldns_buffer_skip(rd_buf, 1); } pre_data_pos = ldns_buffer_position(rd_buf); if (-1 == (c = ldns_bget_token( rd_buf, rd, delimiters, LDNS_MAX_RDFLEN))) { done = true; (void)done; /* we're breaking, so done not read anymore */ break; } /* hmmz, rfc3597 specifies that any type can be represented * with \# method, which can contain spaces... * it does specify size though... */ rd_strlen = strlen(rd); /* unknown RR data */ if (strncmp(rd, ""\\#"", 2) == 0 && !quoted && (rd_strlen == 2 || rd[2]==' ')) { was_unknown_rr_format = 1; /* go back to before \# * and skip it while setting delimiters better */ ldns_buffer_set_position(rd_buf, pre_data_pos); delimiters = ""\n\t ""; (void)ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN); /* read rdata octet length */ c = ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN); if (c == -1) { /* something goes very wrong here */ status = LDNS_STATUS_SYNTAX_RDATA_ERR; goto error; } hex_data_size = (uint16_t) atoi(rd); /* copy hex chars into hex str (2 chars per byte) */ hex_data_str = LDNS_XMALLOC(char, 2*hex_data_size + 1); if (!hex_data_str) { /* malloc error */ goto memerror; } cur_hex_data_size = 0; while(cur_hex_data_size < 2 * hex_data_size) { c = ldns_bget_token(rd_buf, rd, delimiters, LDNS_MAX_RDFLEN); if (c == -1) { status = LDNS_STATUS_SYNTAX_RDATA_ERR; goto error; } rd_strlen = strlen(rd); if ((size_t)cur_hex_data_size + rd_strlen > 2 * (size_t)hex_data_size) { status = LDNS_STATUS_SYNTAX_RDATA_ERR; goto error; } strlcpy(hex_data_str + cur_hex_data_size, rd, rd_strlen + 1); cur_hex_data_size += rd_strlen; } hex_data_str[cur_hex_data_size] = '\0'; /* correct the rdf type */ /* if *we* know the type, interpret it as wireformat */ if (desc) { hex_pos = 0; hex_data = LDNS_XMALLOC(uint8_t, hex_data_size+2); if (!hex_data) { goto memerror; } ldns_write_uint16(hex_data, hex_data_size); ldns_hexstring_to_data( hex_data + 2, hex_data_str); status = ldns_wire2rdf(new, hex_data, hex_data_size + 2, &hex_pos); if (status != LDNS_STATUS_OK) { goto error; } LDNS_FREE(hex_data); } else { r = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_HEX, hex_data_str); if (!r) { goto memerror; } ldns_rdf_set_type(r, LDNS_RDF_TYPE_UNKNOWN); if (!ldns_rr_push_rdf(new, r)) { goto memerror; } } LDNS_FREE(hex_data_str); } else if(rd_strlen > 0 || quoted) { /* Normal RR */ switch(ldns_rr_descriptor_field_type(desc, r_cnt)) { case LDNS_RDF_TYPE_HEX: case LDNS_RDF_TYPE_B64: /* When this is the last rdata field, then the * rest should be read in (cause then these * rdf types may contain spaces). */ if (r_cnt == r_max - 1) { c = ldns_bget_token(rd_buf, xtok, ""\n"", LDNS_MAX_RDFLEN); if (c != -1) { (void) strncat(rd, xtok, LDNS_MAX_RDFLEN - strlen(rd) - 1); } } r = ldns_rdf_new_frm_str( ldns_rr_descriptor_field_type( desc, r_cnt), rd); break; case LDNS_RDF_TYPE_HIP: /* * In presentation format this RDATA type has * three tokens: An algorithm byte, then a * variable length HIT (in hexbytes) and then * a variable length Public Key (in base64). * * We have just read the algorithm, so we need * two more tokens: HIT and Public Key. */ do { /* Read and append HIT */ if (ldns_bget_token(rd_buf, xtok, delimiters, LDNS_MAX_RDFLEN) == -1) break; (void) strncat(rd, "" "", LDNS_MAX_RDFLEN - strlen(rd) - 1); (void) strncat(rd, xtok, LDNS_MAX_RDFLEN - strlen(rd) - 1); /* Read and append Public Key*/ if (ldns_bget_token(rd_buf, xtok, delimiters, LDNS_MAX_RDFLEN) == -1) break; (void) strncat(rd, "" "", LDNS_MAX_RDFLEN - strlen(rd) - 1); (void) strncat(rd, xtok, LDNS_MAX_RDFLEN - strlen(rd) - 1); } while (false); r = ldns_rdf_new_frm_str( ldns_rr_descriptor_field_type( desc, r_cnt), rd); break; case LDNS_RDF_TYPE_DNAME: r = ldns_rdf_new_frm_str( ldns_rr_descriptor_field_type( desc, r_cnt), rd); /* check if the origin should be used * or concatenated */ if (r && ldns_rdf_size(r) > 1 && ldns_rdf_data(r)[0] == 1 && ldns_rdf_data(r)[1] == '@') { ldns_rdf_deep_free(r); r = origin ? ldns_rdf_clone(origin) : ( rr_type == LDNS_RR_TYPE_SOA ? ldns_rdf_clone( ldns_rr_owner(new)) : ldns_rdf_new_frm_str( LDNS_RDF_TYPE_DNAME, ""."") ); } else if (r && rd_strlen >= 1 && origin && !ldns_dname_str_absolute(rd)) { status = ldns_dname_cat(r, origin); if (status != LDNS_STATUS_OK) { goto error; } } break; default: r = ldns_rdf_new_frm_str( ldns_rr_descriptor_field_type( desc, r_cnt), rd); break; } if (!r) { status = LDNS_STATUS_SYNTAX_RDATA_ERR; goto error; } ldns_rr_push_rdf(new, r); } if (quoted) { if (ldns_buffer_available(rd_buf, 1)) { ldns_buffer_skip(rd_buf, 1); } else { done = true; } } } /* for (done = false, r_cnt = 0; !done && r_cnt < r_max; r_cnt++) */ LDNS_FREE(rd); LDNS_FREE(xtok); ldns_buffer_free(rr_buf); LDNS_FREE(rdata); if (ldns_buffer_remaining(rd_buf) > 0) { ldns_buffer_free(rd_buf); ldns_rr_free(new); return LDNS_STATUS_SYNTAX_SUPERFLUOUS_TEXT_ERR; } ldns_buffer_free(rd_buf); if (!question && desc && !was_unknown_rr_format && ldns_rr_rd_count(new) < r_min) { ldns_rr_free(new); return LDNS_STATUS_SYNTAX_MISSING_VALUE_ERR; } if (newrr) { *newrr = new; } else { /* Maybe the caller just wanted to see if it would parse? */ ldns_rr_free(new); } return LDNS_STATUS_OK; memerror: status = LDNS_STATUS_MEM_ERR; error: if (rd_buf && rd_buf->_data) { ldns_buffer_free(rd_buf); } else { LDNS_FREE(rd_buf); } if (rr_buf && rr_buf->_data) { ldns_buffer_free(rr_buf); } else { LDNS_FREE(rr_buf); } LDNS_FREE(type); LDNS_FREE(owner); LDNS_FREE(ttl); LDNS_FREE(clas); LDNS_FREE(hex_data); LDNS_FREE(hex_data_str); LDNS_FREE(xtok); LDNS_FREE(rd); LDNS_FREE(rdata); ldns_rr_free(new); return status; }",CWE-125,1 1,"GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex) { GF_DataEntryURLBox *entry; GF_DataMap *map; GF_Err e; if (!mdia || !dataEntryIndex || dataEntryIndex > gf_list_count(mdia->information->dataInformation->dref->child_boxes)) return GF_BAD_PARAM; entry = (GF_DataEntryURLBox*)gf_list_get(mdia->information->dataInformation->dref->child_boxes, dataEntryIndex - 1); if (!entry) return GF_ISOM_INVALID_FILE; if (entry->flags == 1) return GF_OK; //ok, not self contained, let's go for it... //we don't know what's a URN yet if (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED; if (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) { e = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map); } else { e = gf_isom_datamap_new(entry->location, mdia->mediaTrack->moov->mov->fileName, GF_ISOM_DATA_MAP_READ, &map); } if (e) return e; gf_isom_datamap_del(map); return GF_OK; }",CWE-787,16 1,"Pl_ASCIIHexDecoder::flush() { if (this->pos == 0) { QTC::TC(""libtests"", ""Pl_ASCIIHexDecoder no-op flush""); return; } int b[2]; for (int i = 0; i < 2; ++i) { if (this->inbuf[i] >= 'A') { b[i] = this->inbuf[i] - 'A' + 10; } else { b[i] = this->inbuf[i] - '0'; } } unsigned char ch = static_cast((b[0] << 4) + b[1]); QTC::TC(""libtests"", ""Pl_ASCIIHexDecoder partial flush"", (this->pos == 2) ? 0 : 1); getNext()->write(&ch, 1); this->pos = 0; this->inbuf[0] = '0'; this->inbuf[1] = '0'; this->inbuf[2] = '\0'; }",CWE-787,16 1,"BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s) { UINT32 os_major; UINT32 os_minor; UINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo; wStream* licenseStream = NULL; BOOL ret = FALSE; BYTE computedMac[16]; LICENSE_BLOB* calBlob; DEBUG_LICENSE(""Receiving Server New/Upgrade License Packet""); calBlob = license_new_binary_blob(BB_DATA_BLOB); if (!calBlob) return FALSE; /* EncryptedLicenseInfo */ if (!license_read_encrypted_blob(license, s, calBlob)) goto out_free_blob; /* compute MAC and check it */ if (Stream_GetRemainingLength(s) < 16) goto out_free_blob; if (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac)) goto out_free_blob; if (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0) { WLog_ERR(TAG, ""new or upgrade license MAC mismatch""); goto out_free_blob; } if (!Stream_SafeSeek(s, 16)) goto out_free_blob; licenseStream = Stream_New(calBlob->data, calBlob->length); if (!licenseStream) goto out_free_blob; Stream_Read_UINT16(licenseStream, os_minor); Stream_Read_UINT16(licenseStream, os_major); /* Scope */ Stream_Read_UINT32(licenseStream, cbScope); if (Stream_GetRemainingLength(licenseStream) < cbScope) goto out_free_stream; #ifdef WITH_DEBUG_LICENSE WLog_DBG(TAG, ""Scope:""); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope); #endif Stream_Seek(licenseStream, cbScope); /* CompanyName */ Stream_Read_UINT32(licenseStream, cbCompanyName); if (Stream_GetRemainingLength(licenseStream) < cbCompanyName) goto out_free_stream; #ifdef WITH_DEBUG_LICENSE WLog_DBG(TAG, ""Company name:""); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName); #endif Stream_Seek(licenseStream, cbCompanyName); /* productId */ Stream_Read_UINT32(licenseStream, cbProductId); if (Stream_GetRemainingLength(licenseStream) < cbProductId) goto out_free_stream; #ifdef WITH_DEBUG_LICENSE WLog_DBG(TAG, ""Product id:""); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId); #endif Stream_Seek(licenseStream, cbProductId); /* licenseInfo */ Stream_Read_UINT32(licenseStream, cbLicenseInfo); if (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo) goto out_free_stream; license->state = LICENSE_STATE_COMPLETED; ret = TRUE; if (!license->rdp->settings->OldLicenseBehaviour) ret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo, license->rdp->settings->ClientHostname); out_free_stream: Stream_Free(licenseStream, FALSE); out_free_blob: license_free_binary_blob(calBlob); return ret; }",CWE-125,1 1,"_decodeStripYCbCr(Imaging im, ImagingCodecState state, TIFF *tiff) { // To avoid dealing with YCbCr subsampling, let libtiff handle it // Use a TIFFRGBAImage wrapping the tiff image, and let libtiff handle // all of the conversion. Metadata read from the TIFFRGBAImage could // be different from the metadata that the base tiff returns. INT32 strip_row; UINT8 *new_data; UINT32 rows_per_strip, row_byte_size, rows_to_read; int ret; TIFFRGBAImage img; char emsg[1024] = """"; ret = TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { rows_per_strip = state->ysize; } TRACE((""RowsPerStrip: %u \n"", rows_per_strip)); if (!(TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg))) { TRACE((""Decode error, msg: %s"", emsg)); state->errcode = IMAGING_CODEC_BROKEN; // nothing to clean up, just return return -1; } img.req_orientation = ORIENTATION_TOPLEFT; img.col_offset = 0; if (state->xsize != img.width || state->ysize != img.height) { TRACE( (""Inconsistent Image Error: %d =? %d, %d =? %d"", state->xsize, img.width, state->ysize, img.height)); state->errcode = IMAGING_CODEC_BROKEN; goto decodeycbcr_err; } /* overflow check for row byte size */ if (INT_MAX / 4 < img.width) { state->errcode = IMAGING_CODEC_MEMORY; goto decodeycbcr_err; } // TiffRGBAImages are 32bits/pixel. row_byte_size = img.width * 4; /* overflow check for realloc */ if (INT_MAX / row_byte_size < rows_per_strip) { state->errcode = IMAGING_CODEC_MEMORY; goto decodeycbcr_err; } state->bytes = rows_per_strip * row_byte_size; TRACE((""StripSize: %d \n"", state->bytes)); /* realloc to fit whole strip */ /* malloc check above */ new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; goto decodeycbcr_err; } state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { img.row_offset = state->y; rows_to_read = min(rows_per_strip, img.height - state->y); if (TIFFRGBAImageGet(&img, (UINT32 *)state->buffer, img.width, rows_to_read) == -1) { TRACE((""Decode Error, y: %d\n"", state->y)); state->errcode = IMAGING_CODEC_BROKEN; goto decodeycbcr_err; } TRACE((""Decoded strip for row %d \n"", state->y)); // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < min((INT32)rows_per_strip, state->ysize - state->y); strip_row++) { TRACE((""Writing data into line %d ; \n"", state->y + strip_row)); // UINT8 * bbb = state->buffer + strip_row * (state->bytes / // rows_per_strip); TRACE((""chars: %x %x %x %x\n"", ((UINT8 *)bbb)[0], // ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle( (UINT8 *)im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize); } } decodeycbcr_err: TIFFRGBAImageEnd(&img); if (state->errcode != 0) { return -1; } return 0; }",CWE-787,16 0,"void WebGraphicsContext3DDefaultImpl::enableVertexAttribArray(unsigned long index) { makeContextCurrent(); if (index < NumTrackedPointerStates) m_vertexAttribPointerState[index].enabled = true; glEnableVertexAttribArray(index); } ",none,24 0,"void SpeechSynthesis::speakingErrorOccurred(PassRefPtr utterance) { if (utterance->client()) handleSpeakingCompleted(static_cast(utterance->client()), true); } ",none,24 1,"static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct sock *sk; struct packet_sock *po; struct sockaddr_ll *sll; union tpacket_uhdr h; u8 *skb_head = skb->data; int skb_len = skb->len; unsigned int snaplen, res; unsigned long status = TP_STATUS_USER; unsigned short macoff, netoff, hdrlen; struct sk_buff *copy_skb = NULL; struct timespec64 ts; __u32 ts_status; bool is_drop_n_account = false; unsigned int slot_id = 0; bool do_vnet = false; /* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT. * We may add members to them until current aligned size without forcing * userspace to call getsockopt(..., PACKET_HDRLEN, ...). */ BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32); BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48); if (skb->pkt_type == PACKET_LOOPBACK) goto drop; sk = pt->af_packet_priv; po = pkt_sk(sk); if (!net_eq(dev_net(dev), sock_net(sk))) goto drop; if (dev->header_ops) { if (sk->sk_type != SOCK_DGRAM) skb_push(skb, skb->data - skb_mac_header(skb)); else if (skb->pkt_type == PACKET_OUTGOING) { /* Special case: outgoing packets have ll header at head */ skb_pull(skb, skb_network_offset(skb)); } } snaplen = skb->len; res = run_filter(skb, sk, snaplen); if (!res) goto drop_n_restore; /* If we are flooded, just give up */ if (__packet_rcv_has_room(po, skb) == ROOM_NONE) { atomic_inc(&po->tp_drops); goto drop_n_restore; } if (skb->ip_summed == CHECKSUM_PARTIAL) status |= TP_STATUS_CSUMNOTREADY; else if (skb->pkt_type != PACKET_OUTGOING && (skb->ip_summed == CHECKSUM_COMPLETE || skb_csum_unnecessary(skb))) status |= TP_STATUS_CSUM_VALID; if (snaplen > res) snaplen = res; if (sk->sk_type == SOCK_DGRAM) { macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 + po->tp_reserve; } else { unsigned int maclen = skb_network_offset(skb); netoff = TPACKET_ALIGN(po->tp_hdrlen + (maclen < 16 ? 16 : maclen)) + po->tp_reserve; if (po->has_vnet_hdr) { netoff += sizeof(struct virtio_net_hdr); do_vnet = true; } macoff = netoff - maclen; } if (po->tp_version <= TPACKET_V2) { if (macoff + snaplen > po->rx_ring.frame_size) { if (po->copy_thresh && atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) { if (skb_shared(skb)) { copy_skb = skb_clone(skb, GFP_ATOMIC); } else { copy_skb = skb_get(skb); skb_head = skb->data; } if (copy_skb) skb_set_owner_r(copy_skb, sk); } snaplen = po->rx_ring.frame_size - macoff; if ((int)snaplen < 0) { snaplen = 0; do_vnet = false; } } } else if (unlikely(macoff + snaplen > GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) { u32 nval; nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff; pr_err_once(""tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n"", snaplen, nval, macoff); snaplen = nval; if (unlikely((int)snaplen < 0)) { snaplen = 0; macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len; do_vnet = false; } } spin_lock(&sk->sk_receive_queue.lock); h.raw = packet_current_rx_frame(po, skb, TP_STATUS_KERNEL, (macoff+snaplen)); if (!h.raw) goto drop_n_account; if (po->tp_version <= TPACKET_V2) { slot_id = po->rx_ring.head; if (test_bit(slot_id, po->rx_ring.rx_owner_map)) goto drop_n_account; __set_bit(slot_id, po->rx_ring.rx_owner_map); } if (do_vnet && virtio_net_hdr_from_skb(skb, h.raw + macoff - sizeof(struct virtio_net_hdr), vio_le(), true, 0)) { if (po->tp_version == TPACKET_V3) prb_clear_blk_fill_status(&po->rx_ring); goto drop_n_account; } if (po->tp_version <= TPACKET_V2) { packet_increment_rx_head(po, &po->rx_ring); /* * LOSING will be reported till you read the stats, * because it's COR - Clear On Read. * Anyways, moving it for V1/V2 only as V3 doesn't need this * at packet level. */ if (atomic_read(&po->tp_drops)) status |= TP_STATUS_LOSING; } po->stats.stats1.tp_packets++; if (copy_skb) { status |= TP_STATUS_COPY; __skb_queue_tail(&sk->sk_receive_queue, copy_skb); } spin_unlock(&sk->sk_receive_queue.lock); skb_copy_bits(skb, 0, h.raw + macoff, snaplen); if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp))) ktime_get_real_ts64(&ts); status |= ts_status; switch (po->tp_version) { case TPACKET_V1: h.h1->tp_len = skb->len; h.h1->tp_snaplen = snaplen; h.h1->tp_mac = macoff; h.h1->tp_net = netoff; h.h1->tp_sec = ts.tv_sec; h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC; hdrlen = sizeof(*h.h1); break; case TPACKET_V2: h.h2->tp_len = skb->len; h.h2->tp_snaplen = snaplen; h.h2->tp_mac = macoff; h.h2->tp_net = netoff; h.h2->tp_sec = ts.tv_sec; h.h2->tp_nsec = ts.tv_nsec; if (skb_vlan_tag_present(skb)) { h.h2->tp_vlan_tci = skb_vlan_tag_get(skb); h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto); status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID; } else { h.h2->tp_vlan_tci = 0; h.h2->tp_vlan_tpid = 0; } memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding)); hdrlen = sizeof(*h.h2); break; case TPACKET_V3: /* tp_nxt_offset,vlan are already populated above. * So DONT clear those fields here */ h.h3->tp_status |= status; h.h3->tp_len = skb->len; h.h3->tp_snaplen = snaplen; h.h3->tp_mac = macoff; h.h3->tp_net = netoff; h.h3->tp_sec = ts.tv_sec; h.h3->tp_nsec = ts.tv_nsec; memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding)); hdrlen = sizeof(*h.h3); break; default: BUG(); } sll = h.raw + TPACKET_ALIGN(hdrlen); sll->sll_halen = dev_parse_header(skb, sll->sll_addr); sll->sll_family = AF_PACKET; sll->sll_hatype = dev->type; sll->sll_protocol = skb->protocol; sll->sll_pkttype = skb->pkt_type; if (unlikely(po->origdev)) sll->sll_ifindex = orig_dev->ifindex; else sll->sll_ifindex = dev->ifindex; smp_mb(); #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1 if (po->tp_version <= TPACKET_V2) { u8 *start, *end; end = (u8 *) PAGE_ALIGN((unsigned long) h.raw + macoff + snaplen); for (start = h.raw; start < end; start += PAGE_SIZE) flush_dcache_page(pgv_to_page(start)); } smp_wmb(); #endif if (po->tp_version <= TPACKET_V2) { spin_lock(&sk->sk_receive_queue.lock); __packet_set_status(po, h.raw, status); __clear_bit(slot_id, po->rx_ring.rx_owner_map); spin_unlock(&sk->sk_receive_queue.lock); sk->sk_data_ready(sk); } else if (po->tp_version == TPACKET_V3) { prb_clear_blk_fill_status(&po->rx_ring); } drop_n_restore: if (skb_head != skb->data && skb_shared(skb)) { skb->data = skb_head; skb->len = skb_len; } drop: if (!is_drop_n_account) consume_skb(skb); else kfree_skb(skb); return 0; drop_n_account: spin_unlock(&sk->sk_receive_queue.lock); atomic_inc(&po->tp_drops); is_drop_n_account = true; sk->sk_data_ready(sk); kfree_skb(copy_skb); goto drop_n_restore; }",CWE-787,16 1,"GF_Err gf_isom_set_extraction_slc(GF_ISOFile *the_file, u32 trackNumber, u32 StreamDescriptionIndex, const GF_SLConfig *slConfig) { GF_TrackBox *trak; GF_SampleEntryBox *entry; GF_Err e; GF_SLConfig **slc; trak = gf_isom_get_track_from_file(the_file, trackNumber); if (!trak) return GF_BAD_PARAM; e = Media_GetSampleDesc(trak->Media, StreamDescriptionIndex, &entry, NULL); if (e) return e; //we must be sure we are not using a remote ESD switch (entry->type) { case GF_ISOM_BOX_TYPE_MP4S: if (((GF_MPEGSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGSampleEntryBox *)entry)->slc; break; case GF_ISOM_BOX_TYPE_MP4A: if (((GF_MPEGAudioSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGAudioSampleEntryBox *)entry)->slc; break; case GF_ISOM_BOX_TYPE_MP4V: if (((GF_MPEGVisualSampleEntryBox *)entry)->esd->desc->slConfig->predefined != SLPredef_MP4) return GF_BAD_PARAM; slc = & ((GF_MPEGVisualSampleEntryBox *)entry)->slc; break; default: return GF_BAD_PARAM; } if (*slc) { gf_odf_desc_del((GF_Descriptor *)*slc); *slc = NULL; } if (!slConfig) return GF_OK; //finally duplicate the SL return gf_odf_desc_copy((GF_Descriptor *) slConfig, (GF_Descriptor **) slc); }",CWE-476,12 1,"void CleanWriters(GF_List *writers) { while (gf_list_count(writers)) { TrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0); gf_isom_box_del(writer->stco); gf_isom_box_del((GF_Box *)writer->stsc); gf_free(writer); gf_list_rem(writers, 0); } }",CWE-416,10 0,"bool BlobURLRequestJob::ReadLoop(int* bytes_read) { while (remaining_bytes_ > 0 && read_buf_remaining_bytes_ > 0) { if (!ReadItem()) return false; } *bytes_read = ReadCompleted(); return true; } ",none,24 1,"service_info *FindServiceEventURLPath( service_table *table, const char *eventURLPath) { service_info *finger = NULL; uri_type parsed_url; uri_type parsed_url_in; if (table && parse_uri(eventURLPath, strlen(eventURLPath), &parsed_url_in) == HTTP_SUCCESS) { finger = table->serviceList; while (finger) { if (finger->eventURL) { if (parse_uri(finger->eventURL, strlen(finger->eventURL), &parsed_url) == HTTP_SUCCESS) { if (!token_cmp(&parsed_url.pathquery, &parsed_url_in.pathquery)) { return finger; } } } finger = finger->next; } } return NULL; }",CWE-476,12 0,"unsigned WebGraphicsContext3DDefaultImpl::createFramebuffer() { makeContextCurrent(); GLuint o = 0; glGenFramebuffersEXT(1, &o); return o; } ",none,24 1,"static struct ip *ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp) { register struct mbuf *m = dtom(slirp, ip); register struct ipasfrag *q; int hlen = ip->ip_hl << 2; int i, next; DEBUG_CALL(""ip_reass""); DEBUG_ARG(""ip = %p"", ip); DEBUG_ARG(""fp = %p"", fp); DEBUG_ARG(""m = %p"", m); /* * Presence of header sizes in mbufs * would confuse code below. * Fragment m_data is concatenated. */ m->m_data += hlen; m->m_len -= hlen; /* * If first fragment to arrive, create a reassembly queue. */ if (fp == NULL) { struct mbuf *t = m_get(slirp); if (t == NULL) { goto dropfrag; } fp = mtod(t, struct ipq *); insque(&fp->ip_link, &slirp->ipq.ip_link); fp->ipq_ttl = IPFRAGTTL; fp->ipq_p = ip->ip_p; fp->ipq_id = ip->ip_id; fp->frag_link.next = fp->frag_link.prev = &fp->frag_link; fp->ipq_src = ip->ip_src; fp->ipq_dst = ip->ip_dst; q = (struct ipasfrag *)fp; goto insert; } /* * Find a segment which begins after this one does. */ for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link; q = q->ipf_next) if (q->ipf_off > ip->ip_off) break; /* * If there is a preceding segment, it may provide some of * our data already. If so, drop the data from the incoming * segment. If it provides all of our data, drop us. */ if (q->ipf_prev != &fp->frag_link) { struct ipasfrag *pq = q->ipf_prev; i = pq->ipf_off + pq->ipf_len - ip->ip_off; if (i > 0) { if (i >= ip->ip_len) goto dropfrag; m_adj(dtom(slirp, ip), i); ip->ip_off += i; ip->ip_len -= i; } } /* * While we overlap succeeding segments trim them or, * if they are completely covered, dequeue them. */ while (q != (struct ipasfrag *)&fp->frag_link && ip->ip_off + ip->ip_len > q->ipf_off) { i = (ip->ip_off + ip->ip_len) - q->ipf_off; if (i < q->ipf_len) { q->ipf_len -= i; q->ipf_off += i; m_adj(dtom(slirp, q), i); break; } q = q->ipf_next; m_free(dtom(slirp, q->ipf_prev)); ip_deq(q->ipf_prev); } insert: /* * Stick new segment in its place; * check for complete reassembly. */ ip_enq(iptofrag(ip), q->ipf_prev); next = 0; for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link; q = q->ipf_next) { if (q->ipf_off != next) return NULL; next += q->ipf_len; } if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1) return NULL; /* * Reassembly is complete; concatenate fragments. */ q = fp->frag_link.next; m = dtom(slirp, q); q = (struct ipasfrag *)q->ipf_next; while (q != (struct ipasfrag *)&fp->frag_link) { struct mbuf *t = dtom(slirp, q); q = (struct ipasfrag *)q->ipf_next; m_cat(m, t); } /* * Create header for new ip packet by * modifying header of first packet; * dequeue and discard fragment reassembly header. * Make header visible. */ q = fp->frag_link.next; /* * If the fragments concatenated to an mbuf that's * bigger than the total size of the fragment, then and * m_ext buffer was alloced. But fp->ipq_next points to * the old buffer (in the mbuf), so we must point ip * into the new buffer. */ if (m->m_flags & M_EXT) { int delta = (char *)q - m->m_dat; q = (struct ipasfrag *)(m->m_ext + delta); } ip = fragtoip(q); ip->ip_len = next; ip->ip_tos &= ~1; ip->ip_src = fp->ipq_src; ip->ip_dst = fp->ipq_dst; remque(&fp->ip_link); (void)m_free(dtom(slirp, fp)); m->m_len += (ip->ip_hl << 2); m->m_data -= (ip->ip_hl << 2); return ip; dropfrag: m_free(m); return NULL; }",CWE-787,16 1,"archive_string_append_from_wcs(struct archive_string *as, const wchar_t *w, size_t len) { /* We cannot use the standard wcstombs() here because it * cannot tell us how big the output buffer should be. So * I've built a loop around wcrtomb() or wctomb() that * converts a character at a time and resizes the string as * needed. We prefer wcrtomb() when it's available because * it's thread-safe. */ int n, ret_val = 0; char *p; char *end; #if HAVE_WCRTOMB mbstate_t shift_state; memset(&shift_state, 0, sizeof(shift_state)); #else /* Clear the shift state before starting. */ wctomb(NULL, L'\0'); #endif /* * Allocate buffer for MBS. * We need this allocation here since it is possible that * as->s is still NULL. */ if (archive_string_ensure(as, as->length + len + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; while (*w != L'\0' && len > 0) { if (p >= end) { as->length = p - as->s; as->s[as->length] = '\0'; /* Re-allocate buffer for MBS. */ if (archive_string_ensure(as, as->length + len * 2 + 1) == NULL) return (-1); p = as->s + as->length; end = as->s + as->buffer_length - MB_CUR_MAX -1; } #if HAVE_WCRTOMB n = wcrtomb(p, *w++, &shift_state); #else n = wctomb(p, *w++); #endif if (n == -1) { if (errno == EILSEQ) { /* Skip an illegal wide char. */ *p++ = '?'; ret_val = -1; } else { ret_val = -1; break; } } else p += n; len--; } as->length = p - as->s; as->s[as->length] = '\0'; return (ret_val); }",CWE-787,16 1," yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[32]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, ""inode: %"" PRIuINUM ""\n"", inum); tsk_fprintf(hFile, ""%sAllocated\n"", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? """" : ""Not ""); if (fs_meta->link) tsk_fprintf(hFile, ""symbolic link to: %s\n"", fs_meta->link); tsk_fprintf(hFile, ""uid / gid: %"" PRIuUID "" / %"" PRIuGID ""\n"", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, ""mode: %s\n"", ls); tsk_fprintf(hFile, ""size: %"" PRIdOFF ""\n"", fs_meta->size); tsk_fprintf(hFile, ""num of links: %d\n"", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, ""Name: %s\n"", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, ""\nAdjusted Inode Times:\n""); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, ""\nOriginal Inode Times:\n""); } else { tsk_fprintf(hFile, ""\nInode Times:\n""); } tsk_fprintf(hFile, ""Accessed:\t%s\n"", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, ""File Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, ""Inode Modified:\t%s\n"", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, ""\nHeader Chunk:\n""); tsk_fprintf(hFile, ""%"" PRIuDADDR ""\n"", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, ""\nData Chunks:\n""); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, ""\nError creating run lists ""); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, ""\nError reading file: ""); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, ""\n""); } } tsk_fs_file_close(fs_file); return 0; }",CWE-125,1 0," void AssociateRendererProcessToWorker(EmbeddedWorkerInstance* worker) { worker->AddProcessReference( shell()->web_contents()->GetRenderProcessHost()->GetID()); } ",none,24 0," void InitializeWithConfigAndStatus(const VideoDecoderConfig& config, PipelineStatus status) { EXPECT_CALL(*demuxer_, video_decoder_config()) .WillOnce(ReturnRef(config)); decoder_->Initialize(demuxer_, NewExpectedStatusCB(status), base::Bind(&MockStatisticsCB::OnStatistics, base::Unretained(&statistics_cb_))); message_loop_.RunAllPending(); } ",none,24 0,"void VideoRendererBase::OnDecoderFlushDone() { base::AutoLock auto_lock(lock_); DCHECK_EQ(kFlushingDecoder, state_); DCHECK(!pending_read_); state_ = kFlushing; AttemptFlush_Locked(); } ",none,24 1,"bool SFD_GetFontMetaData( FILE *sfd, char *tok, SplineFont *sf, SFD_GetFontMetaDataData* d ) { int ch; int i; KernClass* kc = 0; int old; char val[2000]; // This allows us to assume we can dereference d // at all times static SFD_GetFontMetaDataData my_static_d; static int my_static_d_is_virgin = 1; if( !d ) { if( my_static_d_is_virgin ) { my_static_d_is_virgin = 0; SFD_GetFontMetaDataData_Init( &my_static_d ); } d = &my_static_d; } if ( strmatch(tok,""FontName:"")==0 ) { geteol(sfd,val); sf->fontname = copy(val); } else if ( strmatch(tok,""FullName:"")==0 ) { geteol(sfd,val); sf->fullname = copy(val); } else if ( strmatch(tok,""FamilyName:"")==0 ) { geteol(sfd,val); sf->familyname = copy(val); } else if ( strmatch(tok,""DefaultBaseFilename:"")==0 ) { geteol(sfd,val); sf->defbasefilename = copy(val); } else if ( strmatch(tok,""Weight:"")==0 ) { getprotectedname(sfd,val); sf->weight = copy(val); } else if ( strmatch(tok,""Copyright:"")==0 ) { sf->copyright = getquotedeol(sfd); } else if ( strmatch(tok,""Comments:"")==0 ) { char *temp = getquotedeol(sfd); sf->comments = latin1_2_utf8_copy(temp); free(temp); } else if ( strmatch(tok,""UComments:"")==0 ) { sf->comments = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,""FontLog:"")==0 ) { sf->fontlog = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,""Version:"")==0 ) { geteol(sfd,val); sf->version = copy(val); } else if ( strmatch(tok,""StyleMapFamilyName:"")==0 ) { sf->styleMapFamilyName = SFDReadUTF7Str(sfd); } /* Legacy attribute for StyleMapFamilyName. Deprecated. */ else if ( strmatch(tok,""OS2FamilyName:"")==0 ) { if (sf->styleMapFamilyName == NULL) sf->styleMapFamilyName = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,""FONDName:"")==0 ) { geteol(sfd,val); sf->fondname = copy(val); } else if ( strmatch(tok,""ItalicAngle:"")==0 ) { getreal(sfd,&sf->italicangle); } else if ( strmatch(tok,""StrokeWidth:"")==0 ) { getreal(sfd,&sf->strokewidth); } else if ( strmatch(tok,""UnderlinePosition:"")==0 ) { getreal(sfd,&sf->upos); } else if ( strmatch(tok,""UnderlineWidth:"")==0 ) { getreal(sfd,&sf->uwidth); } else if ( strmatch(tok,""ModificationTime:"")==0 ) { getlonglong(sfd,&sf->modificationtime); } else if ( strmatch(tok,""CreationTime:"")==0 ) { getlonglong(sfd,&sf->creationtime); d->hadtimes = true; } else if ( strmatch(tok,""PfmFamily:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.pfmfamily = temp; sf->pfminfo.pfmset = true; } else if ( strmatch(tok,""LangName:"")==0 ) { sf->names = SFDGetLangName(sfd,sf->names); } else if ( strmatch(tok,""GaspTable:"")==0 ) { SFDGetGasp(sfd,sf); } else if ( strmatch(tok,""DesignSize:"")==0 ) { SFDGetDesignSize(sfd,sf); } else if ( strmatch(tok,""OtfFeatName:"")==0 ) { SFDGetOtfFeatName(sfd,sf); } else if ( strmatch(tok,""PfmWeight:"")==0 || strmatch(tok,""TTFWeight:"")==0 ) { getsint(sfd,&sf->pfminfo.weight); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,""TTFWidth:"")==0 ) { getsint(sfd,&sf->pfminfo.width); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,""Panose:"")==0 ) { int temp,i; for ( i=0; i<10; ++i ) { getint(sfd,&temp); sf->pfminfo.panose[i] = temp; } sf->pfminfo.panose_set = true; } else if ( strmatch(tok,""LineGap:"")==0 ) { getsint(sfd,&sf->pfminfo.linegap); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,""VLineGap:"")==0 ) { getsint(sfd,&sf->pfminfo.vlinegap); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,""HheadAscent:"")==0 ) { getsint(sfd,&sf->pfminfo.hhead_ascent); } else if ( strmatch(tok,""HheadAOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.hheadascent_add = temp; } else if ( strmatch(tok,""HheadDescent:"")==0 ) { getsint(sfd,&sf->pfminfo.hhead_descent); } else if ( strmatch(tok,""HheadDOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp; } else if ( strmatch(tok,""OS2TypoLinegap:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_typolinegap); } else if ( strmatch(tok,""OS2TypoAscent:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_typoascent); } else if ( strmatch(tok,""OS2TypoAOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.typoascent_add = temp; } else if ( strmatch(tok,""OS2TypoDescent:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_typodescent); } else if ( strmatch(tok,""OS2TypoDOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.typodescent_add = temp; } else if ( strmatch(tok,""OS2WinAscent:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_winascent); } else if ( strmatch(tok,""OS2WinDescent:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_windescent); } else if ( strmatch(tok,""OS2WinAOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.winascent_add = temp; } else if ( strmatch(tok,""OS2WinDOffset:"")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.windescent_add = temp; } else if ( strmatch(tok,""HHeadAscent:"")==0 ) { // DUPLICATE OF ABOVE getsint(sfd,&sf->pfminfo.hhead_ascent); } else if ( strmatch(tok,""HHeadDescent:"")==0 ) { // DUPLICATE OF ABOVE getsint(sfd,&sf->pfminfo.hhead_descent); } else if ( strmatch(tok,""HHeadAOffset:"")==0 ) { // DUPLICATE OF ABOVE int temp; getint(sfd,&temp); sf->pfminfo.hheadascent_add = temp; } else if ( strmatch(tok,""HHeadDOffset:"")==0 ) { // DUPLICATE OF ABOVE int temp; getint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp; } else if ( strmatch(tok,""MacStyle:"")==0 ) { getsint(sfd,&sf->macstyle); } else if ( strmatch(tok,""OS2SubXSize:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_subxsize); sf->pfminfo.subsuper_set = true; } else if ( strmatch(tok,""OS2SubYSize:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_subysize); } else if ( strmatch(tok,""OS2SubXOff:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_subxoff); } else if ( strmatch(tok,""OS2SubYOff:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_subyoff); } else if ( strmatch(tok,""OS2SupXSize:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_supxsize); } else if ( strmatch(tok,""OS2SupYSize:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_supysize); } else if ( strmatch(tok,""OS2SupXOff:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_supxoff); } else if ( strmatch(tok,""OS2SupYOff:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_supyoff); } else if ( strmatch(tok,""OS2StrikeYSize:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_strikeysize); } else if ( strmatch(tok,""OS2StrikeYPos:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_strikeypos); } else if ( strmatch(tok,""OS2CapHeight:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_capheight); } else if ( strmatch(tok,""OS2XHeight:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_xheight); } else if ( strmatch(tok,""OS2FamilyClass:"")==0 ) { getsint(sfd,&sf->pfminfo.os2_family_class); } else if ( strmatch(tok,""OS2Vendor:"")==0 ) { while ( isspace(nlgetc(sfd))); sf->pfminfo.os2_vendor[0] = nlgetc(sfd); sf->pfminfo.os2_vendor[1] = nlgetc(sfd); sf->pfminfo.os2_vendor[2] = nlgetc(sfd); sf->pfminfo.os2_vendor[3] = nlgetc(sfd); (void) nlgetc(sfd); } else if ( strmatch(tok,""OS2CodePages:"")==0 ) { gethexints(sfd,sf->pfminfo.codepages,2); sf->pfminfo.hascodepages = true; } else if ( strmatch(tok,""OS2UnicodeRanges:"")==0 ) { gethexints(sfd,sf->pfminfo.unicoderanges,4); sf->pfminfo.hasunicoderanges = true; } else if ( strmatch(tok,""TopEncoding:"")==0 ) { /* Obsolete */ getint(sfd,&sf->top_enc); } else if ( strmatch(tok,""Ascent:"")==0 ) { getint(sfd,&sf->ascent); } else if ( strmatch(tok,""Descent:"")==0 ) { getint(sfd,&sf->descent); } else if ( strmatch(tok,""InvalidEm:"")==0 ) { getint(sfd,&sf->invalidem); } else if ( strmatch(tok,""woffMajor:"")==0 ) { getint(sfd,&sf->woffMajor); } else if ( strmatch(tok,""woffMinor:"")==0 ) { getint(sfd,&sf->woffMinor); } else if ( strmatch(tok,""woffMetadata:"")==0 ) { sf->woffMetadata = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,""UFOAscent:"")==0 ) { getreal(sfd,&sf->ufo_ascent); } else if ( strmatch(tok,""UFODescent:"")==0 ) { getreal(sfd,&sf->ufo_descent); } else if ( strmatch(tok,""sfntRevision:"")==0 ) { gethex(sfd,(uint32 *)&sf->sfntRevision); } else if ( strmatch(tok,""LayerCount:"")==0 ) { d->had_layer_cnt = true; getint(sfd,&sf->layer_cnt); if ( sf->layer_cnt>2 ) { sf->layers = realloc(sf->layers,sf->layer_cnt*sizeof(LayerInfo)); memset(sf->layers+2,0,(sf->layer_cnt-2)*sizeof(LayerInfo)); } } else if ( strmatch(tok,""Layer:"")==0 ) { // TODO: Read the U. F. O. path. int layer, o2, bk; getint(sfd,&layer); if ( layer>=sf->layer_cnt ) { sf->layers = realloc(sf->layers,(layer+1)*sizeof(LayerInfo)); memset(sf->layers+sf->layer_cnt,0,((layer+1)-sf->layer_cnt)*sizeof(LayerInfo)); sf->layer_cnt = layer+1; } getint(sfd,&o2); sf->layers[layer].order2 = o2; sf->layers[layer].background = layer==ly_back; /* Used briefly, now background is after layer name */ while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='""' ) { getint(sfd,&bk); sf->layers[layer].background = bk; } /* end of section for obsolete format */ sf->layers[layer].name = SFDReadUTF7Str(sfd); while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='\n' ) { getint(sfd,&bk); sf->layers[layer].background = bk; } while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='\n' ) { sf->layers[layer].ufo_path = SFDReadUTF7Str(sfd); } } else if ( strmatch(tok,""PreferredKerning:"")==0 ) { int temp; getint(sfd,&temp); sf->preferred_kerning = temp; } else if ( strmatch(tok,""StrokedFont:"")==0 ) { int temp; getint(sfd,&temp); sf->strokedfont = temp; } else if ( strmatch(tok,""MultiLayer:"")==0 ) { int temp; getint(sfd,&temp); sf->multilayer = temp; } else if ( strmatch(tok,""NeedsXUIDChange:"")==0 ) { int temp; getint(sfd,&temp); sf->changed_since_xuidchanged = temp; } else if ( strmatch(tok,""VerticalOrigin:"")==0 ) { // this doesn't seem to be written ever. int temp; getint(sfd,&temp); sf->hasvmetrics = true; } else if ( strmatch(tok,""HasVMetrics:"")==0 ) { int temp; getint(sfd,&temp); sf->hasvmetrics = temp; } else if ( strmatch(tok,""Justify:"")==0 ) { SFDParseJustify(sfd,sf,tok); } else if ( strmatch(tok,""BaseHoriz:"")==0 ) { sf->horiz_base = SFDParseBase(sfd); d->last_base = sf->horiz_base; d->last_base_script = NULL; } else if ( strmatch(tok,""BaseVert:"")==0 ) { sf->vert_base = SFDParseBase(sfd); d->last_base = sf->vert_base; d->last_base_script = NULL; } else if ( strmatch(tok,""BaseScript:"")==0 ) { struct basescript *bs = SFDParseBaseScript(sfd,d->last_base); if ( d->last_base==NULL ) { BaseScriptFree(bs); bs = NULL; } else if ( d->last_base_script!=NULL ) d->last_base_script->next = bs; else d->last_base->scripts = bs; d->last_base_script = bs; } else if ( strmatch(tok,""StyleMap:"")==0 ) { gethex(sfd,(uint32 *)&sf->pfminfo.stylemap); } /* Legacy attribute for StyleMap. Deprecated. */ else if ( strmatch(tok,""OS2StyleName:"")==0 ) { char* sname = SFDReadUTF7Str(sfd); if (sf->pfminfo.stylemap == -1) { if (strcmp(sname,""bold italic"")==0) sf->pfminfo.stylemap = 0x21; else if (strcmp(sname,""bold"")==0) sf->pfminfo.stylemap = 0x20; else if (strcmp(sname,""italic"")==0) sf->pfminfo.stylemap = 0x01; else if (strcmp(sname,""regular"")==0) sf->pfminfo.stylemap = 0x40; } free(sname); } else if ( strmatch(tok,""FSType:"")==0 ) { getsint(sfd,&sf->pfminfo.fstype); } else if ( strmatch(tok,""OS2Version:"")==0 ) { getsint(sfd,&sf->os2_version); } else if ( strmatch(tok,""OS2_WeightWidthSlopeOnly:"")==0 ) { int temp; getint(sfd,&temp); sf->weight_width_slope_only = temp; } else if ( strmatch(tok,""OS2_UseTypoMetrics:"")==0 ) { int temp; getint(sfd,&temp); sf->use_typo_metrics = temp; } else if ( strmatch(tok,""UseUniqueID:"")==0 ) { int temp; getint(sfd,&temp); sf->use_uniqueid = temp; } else if ( strmatch(tok,""UseXUID:"")==0 ) { int temp; getint(sfd,&temp); sf->use_xuid = temp; } else if ( strmatch(tok,""UniqueID:"")==0 ) { getint(sfd,&sf->uniqueid); } else if ( strmatch(tok,""XUID:"")==0 ) { geteol(sfd,tok); sf->xuid = copy(tok); } else if ( strmatch(tok,""Lookup:"")==0 ) { OTLookup *otl; int temp; if ( sf->sfd_version<2 ) { IError( ""Lookups should not happen in version 1 sfd files."" ); exit(1); } otl = chunkalloc(sizeof(OTLookup)); getint(sfd,&temp); otl->lookup_type = temp; getint(sfd,&temp); otl->lookup_flags = temp; getint(sfd,&temp); otl->store_in_afm = temp; otl->lookup_name = SFDReadUTF7Str(sfd); if ( otl->lookup_typelastsotl==NULL ) sf->gsub_lookups = otl; else d->lastsotl->next = otl; d->lastsotl = otl; } else { if ( d->lastpotl==NULL ) sf->gpos_lookups = otl; else d->lastpotl->next = otl; d->lastpotl = otl; } SFDParseLookup(sfd,otl); } else if ( strmatch(tok,""MarkAttachClasses:"")==0 ) { getint(sfd,&sf->mark_class_cnt); sf->mark_classes = malloc(sf->mark_class_cnt*sizeof(char *)); sf->mark_class_names = malloc(sf->mark_class_cnt*sizeof(char *)); sf->mark_classes[0] = NULL; sf->mark_class_names[0] = NULL; for ( i=1; imark_class_cnt; ++i ) { /* Class 0 is unused */ int temp; while ( (temp=nlgetc(sfd))=='\n' || temp=='\r' ); ungetc(temp,sfd); sf->mark_class_names[i] = SFDReadUTF7Str(sfd); getint(sfd,&temp); sf->mark_classes[i] = malloc(temp+1); sf->mark_classes[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(sf->mark_classes[i],1,temp,sfd); } } else if ( strmatch(tok,""MarkAttachSets:"")==0 ) { getint(sfd,&sf->mark_set_cnt); sf->mark_sets = malloc(sf->mark_set_cnt*sizeof(char *)); sf->mark_set_names = malloc(sf->mark_set_cnt*sizeof(char *)); for ( i=0; imark_set_cnt; ++i ) { /* Set 0 is used */ int temp; while ( (temp=nlgetc(sfd))=='\n' || temp=='\r' ); ungetc(temp,sfd); sf->mark_set_names[i] = SFDReadUTF7Str(sfd); getint(sfd,&temp); sf->mark_sets[i] = malloc(temp+1); sf->mark_sets[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(sf->mark_sets[i],1,temp,sfd); } } else if ( strmatch(tok,""KernClass2:"")==0 || strmatch(tok,""VKernClass2:"")==0 || strmatch(tok,""KernClass:"")==0 || strmatch(tok,""VKernClass:"")==0 || strmatch(tok,""KernClass3:"")==0 || strmatch(tok,""VKernClass3:"")==0 ) { int kernclassversion = 0; int isv = tok[0]=='V'; int kcvoffset = (isv ? 10 : 9); //Offset to read kerning class version if (isdigit(tok[kcvoffset])) kernclassversion = tok[kcvoffset] - '0'; int temp, classstart=1; int old = (kernclassversion == 0); if ( (sf->sfd_version<2)!=old ) { IError( ""Version mixup in Kerning Classes of sfd file."" ); exit(1); } kc = chunkalloc(old ? sizeof(KernClass1) : sizeof(KernClass)); getint(sfd,&kc->first_cnt); ch=nlgetc(sfd); if ( ch=='+' ) classstart = 0; else ungetc(ch,sfd); getint(sfd,&kc->second_cnt); if ( old ) { getint(sfd,&temp); ((KernClass1 *) kc)->sli = temp; getint(sfd,&temp); ((KernClass1 *) kc)->flags = temp; } else { kc->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd)); if ( kc->subtable!=NULL && kc->subtable->kc==NULL ) kc->subtable->kc = kc; else { if ( kc->subtable==NULL ) LogError(_(""Bad SFD file, missing subtable in kernclass defn.\n"") ); else LogError(_(""Bad SFD file, two kerning classes assigned to the same subtable: %s\n""), kc->subtable->subtable_name ); kc->subtable = NULL; } } kc->firsts = calloc(kc->first_cnt,sizeof(char *)); kc->seconds = calloc(kc->second_cnt,sizeof(char *)); kc->offsets = calloc(kc->first_cnt*kc->second_cnt,sizeof(int16)); kc->adjusts = calloc(kc->first_cnt*kc->second_cnt,sizeof(DeviceTable)); if (kernclassversion >= 3) { kc->firsts_flags = calloc(kc->first_cnt, sizeof(int)); kc->seconds_flags = calloc(kc->second_cnt, sizeof(int)); kc->offsets_flags = calloc(kc->first_cnt*kc->second_cnt, sizeof(int)); kc->firsts_names = calloc(kc->first_cnt, sizeof(char*)); kc->seconds_names = calloc(kc->second_cnt, sizeof(char*)); } kc->firsts[0] = NULL; for ( i=classstart; ifirst_cnt; ++i ) { if (kernclassversion < 3) { getint(sfd,&temp); kc->firsts[i] = malloc(temp+1); kc->firsts[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(kc->firsts[i],1,temp,sfd); } else { getint(sfd,&kc->firsts_flags[i]); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->firsts_names[i] = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->firsts[i] = SFDReadUTF7Str(sfd); if (kc->firsts[i] == NULL) kc->firsts[i] = copy(""""); // In certain places, this must be defined. while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); } } kc->seconds[0] = NULL; for ( i=1; isecond_cnt; ++i ) { if (kernclassversion < 3) { getint(sfd,&temp); kc->seconds[i] = malloc(temp+1); kc->seconds[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(kc->seconds[i],1,temp,sfd); } else { getint(sfd,&temp); kc->seconds_flags[i] = temp; while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->seconds_names[i] = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->seconds[i] = SFDReadUTF7Str(sfd); if (kc->seconds[i] == NULL) kc->seconds[i] = copy(""""); // In certain places, this must be defined. while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); } } for ( i=0; ifirst_cnt*kc->second_cnt; ++i ) { if (kernclassversion >= 3) { getint(sfd,&temp); kc->offsets_flags[i] = temp; } getint(sfd,&temp); kc->offsets[i] = temp; SFDReadDeviceTable(sfd,&kc->adjusts[i]); } if ( !old && kc->subtable == NULL ) { /* Error. Ignore it. Free it. Whatever */; } else if ( !isv ) { if ( d->lastkc==NULL ) sf->kerns = kc; else d->lastkc->next = kc; d->lastkc = kc; } else { if ( d->lastvkc==NULL ) sf->vkerns = kc; else d->lastvkc->next = kc; d->lastvkc = kc; } } else if ( strmatch(tok,""ContextPos2:"")==0 || strmatch(tok,""ContextSub2:"")==0 || strmatch(tok,""ChainPos2:"")==0 || strmatch(tok,""ChainSub2:"")==0 || strmatch(tok,""ReverseChain2:"")==0 || strmatch(tok,""ContextPos:"")==0 || strmatch(tok,""ContextSub:"")==0 || strmatch(tok,""ChainPos:"")==0 || strmatch(tok,""ChainSub:"")==0 || strmatch(tok,""ReverseChain:"")==0 ) { FPST *fpst; int old; if ( strchr(tok,'2')!=NULL ) { old = false; fpst = chunkalloc(sizeof(FPST)); } else { old = true; fpst = chunkalloc(sizeof(FPST1)); } if ( (sf->sfd_version<2)!=old ) { IError( ""Version mixup in FPST of sfd file."" ); exit(1); } if ( d->lastfp==NULL ) sf->possub = fpst; else d->lastfp->next = fpst; d->lastfp = fpst; SFDParseChainContext(sfd,sf,fpst,tok,old); } else if ( strmatch(tok,""Group:"")==0 ) { struct ff_glyphclasses *grouptmp = calloc(1, sizeof(struct ff_glyphclasses)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); grouptmp->classname = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); grouptmp->glyphs = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroup != NULL) d->lastgroup->next = grouptmp; else sf->groups = grouptmp; d->lastgroup = grouptmp; } else if ( strmatch(tok,""GroupKern:"")==0 ) { int temp = 0; struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->left = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->right = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); getint(sfd,&temp); kerntmp->offset = temp; while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroupkern != NULL) d->lastgroupkern->next = kerntmp; else sf->groupkerns = kerntmp; d->lastgroupkern = kerntmp; } else if ( strmatch(tok,""GroupVKern:"")==0 ) { int temp = 0; struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->left = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->right = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); getint(sfd,&temp); kerntmp->offset = temp; while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroupvkern != NULL) d->lastgroupvkern->next = kerntmp; else sf->groupvkerns = kerntmp; d->lastgroupvkern = kerntmp; } else if ( strmatch(tok,""MacIndic2:"")==0 || strmatch(tok,""MacContext2:"")==0 || strmatch(tok,""MacLigature2:"")==0 || strmatch(tok,""MacSimple2:"")==0 || strmatch(tok,""MacKern2:"")==0 || strmatch(tok,""MacInsert2:"")==0 || strmatch(tok,""MacIndic:"")==0 || strmatch(tok,""MacContext:"")==0 || strmatch(tok,""MacLigature:"")==0 || strmatch(tok,""MacSimple:"")==0 || strmatch(tok,""MacKern:"")==0 || strmatch(tok,""MacInsert:"")==0 ) { ASM *sm; if ( strchr(tok,'2')!=NULL ) { old = false; sm = chunkalloc(sizeof(ASM)); } else { old = true; sm = chunkalloc(sizeof(ASM1)); } if ( (sf->sfd_version<2)!=old ) { IError( ""Version mixup in state machine of sfd file."" ); exit(1); } if ( d->lastsm==NULL ) sf->sm = sm; else d->lastsm->next = sm; d->lastsm = sm; SFDParseStateMachine(sfd,sf,sm,tok,old); } else if ( strmatch(tok,""MacFeat:"")==0 ) { sf->features = SFDParseMacFeatures(sfd,tok); } else if ( strmatch(tok,""TtfTable:"")==0 ) { /* Old, binary format */ /* still used for maxp and unknown tables */ SFDGetTtfTable(sfd,sf,d->lastttf); } else if ( strmatch(tok,""TtTable:"")==0 ) { /* text instruction format */ SFDGetTtTable(sfd,sf,d->lastttf); } /////////////////// else if ( strmatch(tok,""ShortTable:"")==0 ) { // only read, not written. /* text number format */ SFDGetShortTable(sfd,sf,d->lastttf); } else { // // We didn't have a match ourselves. // return false; } return true; }",CWE-416,10 0," media::StatisticsCB NewStatisticsCB() { return base::Bind(&media::MockStatisticsCB::OnStatistics, base::Unretained(&statistics_cb_object_)); } ",none,24 1,"ExecAlterObjectDependsStmt(AlterObjectDependsStmt *stmt, ObjectAddress *refAddress) { ObjectAddress address; ObjectAddress refAddr; Relation rel; address = get_object_address_rv(stmt->objectType, stmt->relation, (List *) stmt->object, &rel, AccessExclusiveLock, false); /* * If a relation was involved, it would have been opened and locked. We * don't need the relation here, but we'll retain the lock until commit. */ if (rel) table_close(rel, NoLock); refAddr = get_object_address(OBJECT_EXTENSION, (Node *) stmt->extname, &rel, AccessExclusiveLock, false); Assert(rel == NULL); if (refAddress) *refAddress = refAddr; recordDependencyOn(&address, &refAddr, DEPENDENCY_AUTO_EXTENSION); return address; }",CWE-862,19 1,"static MagickBooleanType ReadHEICImageByID(const ImageInfo *image_info, Image *image,struct heif_context *heif_context,heif_item_id image_id, ExceptionInfo *exception) { const char *option; int stride_y, stride_cb, stride_cr; MagickBooleanType status; ssize_t y; struct heif_decoding_options *decode_options; struct heif_error error; struct heif_image *heif_image; struct heif_image_handle *image_handle; const uint8_t *p_y, *p_cb, *p_cr; error=heif_context_get_image_handle(heif_context,image_id,&image_handle); if (IsHeifSuccess(&error,image,exception) == MagickFalse) return(MagickFalse); if (ReadHEICColorProfile(image,image_handle,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } if (ReadHEICExifProfile(image,image_handle,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } /* Set image size. */ image->depth=8; image->columns=(size_t) heif_image_handle_get_width(image_handle); image->rows=(size_t) heif_image_handle_get_height(image_handle); if (image_info->ping != MagickFalse) { image->colorspace=YCbCrColorspace; heif_image_handle_release(image_handle); return(MagickTrue); } if (HEICSkipImage(image_info,image) != MagickFalse) { heif_image_handle_release(image_handle); return(MagickTrue); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } /* Copy HEIF image into ImageMagick data structures. */ (void) SetImageColorspace(image,YCbCrColorspace,exception); decode_options=(struct heif_decoding_options *) NULL; option=GetImageOption(image_info,""heic:preserve-orientation""); if (IsStringTrue(option) == MagickTrue) { decode_options=heif_decoding_options_alloc(); decode_options->ignore_transformations=1; } else (void) SetImageProperty(image,""exif:Orientation"",""1"",exception); error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr, heif_chroma_420,decode_options); if (IsHeifSuccess(&error,image,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } if (decode_options != (struct heif_decoding_options *) NULL) { /* Correct the width and height of the image. */ image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y); image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y); status=SetImageExtent(image,image->columns,image->rows,exception); heif_decoding_options_free(decode_options); if (status == MagickFalse) { heif_image_release(heif_image); heif_image_handle_release(image_handle); return(MagickFalse); } } p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y); p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb); p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) p_y[y* stride_y+x]),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) p_cb[(y/2)* stride_cb+x/2]),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) p_cr[(y/2)* stride_cr+x/2]),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } heif_image_release(heif_image); heif_image_handle_release(image_handle); return(MagickTrue); }",CWE-125,1 1,"gst_matroska_demux_add_wvpk_header (GstElement * element, GstMatroskaTrackContext * stream, GstBuffer ** buf) { GstMatroskaTrackAudioContext *audiocontext = (GstMatroskaTrackAudioContext *) stream; GstBuffer *newbuf = NULL; GstMapInfo map, outmap; guint8 *buf_data, *data; Wavpack4Header wvh; wvh.ck_id[0] = 'w'; wvh.ck_id[1] = 'v'; wvh.ck_id[2] = 'p'; wvh.ck_id[3] = 'k'; wvh.version = GST_READ_UINT16_LE (stream->codec_priv); wvh.track_no = 0; wvh.index_no = 0; wvh.total_samples = -1; wvh.block_index = audiocontext->wvpk_block_index; if (audiocontext->channels <= 2) { guint32 block_samples, tmp; gsize size = gst_buffer_get_size (*buf); gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32)); block_samples = GUINT32_FROM_LE (tmp); /* we need to reconstruct the header of the wavpack block */ /* -20 because ck_size is the size of the wavpack block -8 * and lace_size is the size of the wavpack block + 12 * (the three guint32 of the header that already are in the buffer) */ wvh.ck_size = size + sizeof (Wavpack4Header) - 20; /* block_samples, flags and crc are already in the buffer */ newbuf = gst_buffer_new_allocate (NULL, sizeof (Wavpack4Header) - 12, NULL); gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE); data = outmap.data; data[0] = 'w'; data[1] = 'v'; data[2] = 'p'; data[3] = 'k'; GST_WRITE_UINT32_LE (data + 4, wvh.ck_size); GST_WRITE_UINT16_LE (data + 8, wvh.version); GST_WRITE_UINT8 (data + 10, wvh.track_no); GST_WRITE_UINT8 (data + 11, wvh.index_no); GST_WRITE_UINT32_LE (data + 12, wvh.total_samples); GST_WRITE_UINT32_LE (data + 16, wvh.block_index); gst_buffer_unmap (newbuf, &outmap); /* Append data from buf: */ gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size); gst_buffer_unref (*buf); *buf = newbuf; audiocontext->wvpk_block_index += block_samples; } else { guint8 *outdata = NULL; guint outpos = 0; gsize buf_size, size, out_size = 0; guint32 block_samples, flags, crc, blocksize; gst_buffer_map (*buf, &map, GST_MAP_READ); buf_data = map.data; buf_size = map.size; if (buf_size < 4) { GST_ERROR_OBJECT (element, ""Too small wavpack buffer""); gst_buffer_unmap (*buf, &map); return GST_FLOW_ERROR; } data = buf_data; size = buf_size; block_samples = GST_READ_UINT32_LE (data); data += 4; size -= 4; while (size > 12) { flags = GST_READ_UINT32_LE (data); data += 4; size -= 4; crc = GST_READ_UINT32_LE (data); data += 4; size -= 4; blocksize = GST_READ_UINT32_LE (data); data += 4; size -= 4; if (blocksize == 0 || size < blocksize) break; g_assert ((newbuf == NULL) == (outdata == NULL)); if (newbuf == NULL) { out_size = sizeof (Wavpack4Header) + blocksize; newbuf = gst_buffer_new_allocate (NULL, out_size, NULL); gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1); outpos = 0; gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE); outdata = outmap.data; } else { gst_buffer_unmap (newbuf, &outmap); out_size += sizeof (Wavpack4Header) + blocksize; gst_buffer_set_size (newbuf, out_size); gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE); outdata = outmap.data; } outdata[outpos] = 'w'; outdata[outpos + 1] = 'v'; outdata[outpos + 2] = 'p'; outdata[outpos + 3] = 'k'; outpos += 4; GST_WRITE_UINT32_LE (outdata + outpos, blocksize + sizeof (Wavpack4Header) - 8); GST_WRITE_UINT16_LE (outdata + outpos + 4, wvh.version); GST_WRITE_UINT8 (outdata + outpos + 6, wvh.track_no); GST_WRITE_UINT8 (outdata + outpos + 7, wvh.index_no); GST_WRITE_UINT32_LE (outdata + outpos + 8, wvh.total_samples); GST_WRITE_UINT32_LE (outdata + outpos + 12, wvh.block_index); GST_WRITE_UINT32_LE (outdata + outpos + 16, block_samples); GST_WRITE_UINT32_LE (outdata + outpos + 20, flags); GST_WRITE_UINT32_LE (outdata + outpos + 24, crc); outpos += 28; memmove (outdata + outpos, data, blocksize); outpos += blocksize; data += blocksize; size -= blocksize; } gst_buffer_unmap (*buf, &map); gst_buffer_unref (*buf); if (newbuf) gst_buffer_unmap (newbuf, &outmap); *buf = newbuf; audiocontext->wvpk_block_index += block_samples; } return GST_FLOW_OK; }",CWE-416,10 1,"ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if (strcmp(im->mode, ""1"") == 0 && state->xsize > state->bytes * 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }",CWE-787,16 1,"bool do_notify_parent(struct task_struct *tsk, int sig) { struct kernel_siginfo info; unsigned long flags; struct sighand_struct *psig; bool autoreap = false; u64 utime, stime; BUG_ON(sig == -1); /* do_notify_parent_cldstop should have been called instead. */ BUG_ON(task_is_stopped_or_traced(tsk)); BUG_ON(!tsk->ptrace && (tsk->group_leader != tsk || !thread_group_empty(tsk))); /* Wake up all pidfd waiters */ do_notify_pidfd(tsk); if (sig != SIGCHLD) { /* * This is only possible if parent == real_parent. * Check if it has changed security domain. */ if (tsk->parent_exec_id != tsk->parent->self_exec_id) sig = SIGCHLD; } clear_siginfo(&info); info.si_signo = sig; info.si_errno = 0; /* * We are under tasklist_lock here so our parent is tied to * us and cannot change. * * task_active_pid_ns will always return the same pid namespace * until a task passes through release_task. * * write_lock() currently calls preempt_disable() which is the * same as rcu_read_lock(), but according to Oleg, this is not * correct to rely on this */ rcu_read_lock(); info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent)); info.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns), task_uid(tsk)); rcu_read_unlock(); task_cputime(tsk, &utime, &stime); info.si_utime = nsec_to_clock_t(utime + tsk->signal->utime); info.si_stime = nsec_to_clock_t(stime + tsk->signal->stime); info.si_status = tsk->exit_code & 0x7f; if (tsk->exit_code & 0x80) info.si_code = CLD_DUMPED; else if (tsk->exit_code & 0x7f) info.si_code = CLD_KILLED; else { info.si_code = CLD_EXITED; info.si_status = tsk->exit_code >> 8; } psig = tsk->parent->sighand; spin_lock_irqsave(&psig->siglock, flags); if (!tsk->ptrace && sig == SIGCHLD && (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN || (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) { /* * We are exiting and our parent doesn't care. POSIX.1 * defines special semantics for setting SIGCHLD to SIG_IGN * or setting the SA_NOCLDWAIT flag: we should be reaped * automatically and not left for our parent's wait4 call. * Rather than having the parent do it as a magic kind of * signal handler, we just set this to tell do_exit that we * can be cleaned up without becoming a zombie. Note that * we still call __wake_up_parent in this case, because a * blocked sys_wait4 might now return -ECHILD. * * Whether we send SIGCHLD or not for SA_NOCLDWAIT * is implementation-defined: we do (if you don't want * it, just use SIG_IGN instead). */ autoreap = true; if (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN) sig = 0; } if (valid_signal(sig) && sig) __group_send_sig_info(sig, &info, tsk->parent); __wake_up_parent(tsk, tsk->parent); spin_unlock_irqrestore(&psig->siglock, flags); return autoreap; }",CWE-190,2 0,"bool WebGraphicsContext3DDefaultImpl::angleValidateShaderSource(ShaderSourceEntry& entry) { entry.isValid = false; if (entry.translatedSource) { fastFree(entry.translatedSource); entry.translatedSource = 0; } if (entry.log) { fastFree(entry.log); entry.log = 0; } ShHandle compiler = 0; switch (entry.type) { case GL_FRAGMENT_SHADER: compiler = m_fragmentCompiler; break; case GL_VERTEX_SHADER: compiler = m_vertexCompiler; break; } if (!compiler) return false; if (!ShCompile(compiler, &entry.source, 1, SH_OBJECT_CODE)) { int logSize = 0; ShGetInfo(compiler, SH_INFO_LOG_LENGTH, &logSize); if (logSize > 1 && tryFastMalloc(logSize * sizeof(char)).getValue(entry.log)) ShGetInfoLog(compiler, entry.log); return false; } int length = 0; ShGetInfo(compiler, SH_OBJECT_CODE_LENGTH, &length); if (length > 1) { if (!tryFastMalloc(length * sizeof(char)).getValue(entry.translatedSource)) return false; ShGetObjectCode(compiler, entry.translatedSource); } entry.isValid = true; return true; } ",none,24 1,"static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head) { struct io_buffer *buf; u64 addr = pbuf->addr; int i, bid = pbuf->bid; for (i = 0; i < pbuf->nbufs; i++) { buf = kmalloc(sizeof(*buf), GFP_KERNEL); if (!buf) break; buf->addr = addr; buf->len = pbuf->len; buf->bid = bid; addr += pbuf->len; bid++; if (!*head) { INIT_LIST_HEAD(&buf->list); *head = buf; } else { list_add_tail(&buf->list, &(*head)->list); } } return i ? i : -ENOMEM; }",CWE-787,16 1,"void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream, uint16_t* data, unsigned data_length) { while (data_length != 0) { unsigned cursor = 0; uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor); // There's a total lack of bounds checking for stream // as it was already done in Reset. stream += cursor; if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) { *data++ = Utf16::LeadSurrogate(character); *data++ = Utf16::TrailSurrogate(character); DCHECK(data_length > 1); data_length -= 2; } else { *data++ = character; data_length -= 1; } } }",CWE-119,0 1,"main(int argc, char **argv) { const char *safepath = ""/bin:/sbin:/usr/bin:/usr/sbin:"" ""/usr/local/bin:/usr/local/sbin""; const char *confpath = NULL; char *shargv[] = { NULL, NULL }; char *sh; const char *p; const char *cmd; char cmdline[LINE_MAX]; struct passwd mypwstore, targpwstore; struct passwd *mypw, *targpw; const struct rule *rule; uid_t uid; uid_t target = 0; gid_t groups[NGROUPS_MAX + 1]; int ngroups; int i, ch, rv; int sflag = 0; int nflag = 0; char cwdpath[PATH_MAX]; const char *cwd; char **envp; setprogname(""doas""); closefrom(STDERR_FILENO + 1); uid = getuid(); while ((ch = getopt(argc, argv, ""+C:Lnsu:"")) != -1) { switch (ch) { case 'C': confpath = optarg; break; case 'L': #if defined(USE_TIMESTAMP) exit(timestamp_clear() == -1); #else exit(0); #endif case 'u': if (parseuid(optarg, &target) != 0) errx(1, ""unknown user""); break; case 'n': nflag = 1; break; case 's': sflag = 1; break; default: usage(); break; } } argv += optind; argc -= optind; if (confpath) { if (sflag) usage(); } else if ((!sflag && !argc) || (sflag && argc)) usage(); rv = mygetpwuid_r(uid, &mypwstore, &mypw); if (rv != 0) err(1, ""getpwuid_r failed""); if (mypw == NULL) errx(1, ""no passwd entry for self""); ngroups = getgroups(NGROUPS_MAX, groups); if (ngroups == -1) err(1, ""can't get groups""); groups[ngroups++] = getgid(); if (sflag) { sh = getenv(""SHELL""); if (sh == NULL || *sh == '\0') { shargv[0] = mypw->pw_shell; } else shargv[0] = sh; argv = shargv; argc = 1; } if (confpath) { checkconfig(confpath, argc, argv, uid, groups, ngroups, target); exit(1); /* fail safe */ } if (geteuid()) errx(1, ""not installed setuid""); parseconfig(DOAS_CONF, 1); /* cmdline is used only for logging, no need to abort on truncate */ (void)strlcpy(cmdline, argv[0], sizeof(cmdline)); for (i = 1; i < argc; i++) { if (strlcat(cmdline, "" "", sizeof(cmdline)) >= sizeof(cmdline)) break; if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline)) break; } cmd = argv[0]; if (!permit(uid, groups, ngroups, &rule, target, cmd, (const char **)argv + 1)) { syslog(LOG_AUTHPRIV | LOG_NOTICE, ""command not permitted for %s: %s"", mypw->pw_name, cmdline); errc(1, EPERM, NULL); } #if defined(USE_SHADOW) if (!(rule->options & NOPASS)) { if (nflag) errx(1, ""Authorization required""); shadowauth(mypw->pw_name, rule->options & PERSIST); } #elif !defined(USE_PAM) /* no authentication provider, only allow NOPASS rules */ (void) nflag; if (!(rule->options & NOPASS)) errx(1, ""Authorization required""); #endif if ((p = getenv(""PATH"")) != NULL) formerpath = strdup(p); if (formerpath == NULL) formerpath = """"; if (rule->cmd) { if (setenv(""PATH"", safepath, 1) == -1) err(1, ""failed to set PATH '%s'"", safepath); } rv = mygetpwuid_r(target, &targpwstore, &targpw); if (rv != 0) err(1, ""getpwuid_r failed""); if (targpw == NULL) errx(1, ""no passwd entry for target""); #if defined(USE_PAM) pamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS, rule->options & PERSIST); #endif #ifdef HAVE_LOGIN_CAP_H if (setusercontext(NULL, targpw, target, LOGIN_SETGROUP | LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK | LOGIN_SETUSER) != 0) errx(1, ""failed to set user context for target""); #else if (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0) err(1, ""setresgid""); if (initgroups(targpw->pw_name, targpw->pw_gid) != 0) err(1, ""initgroups""); if (setresuid(target, target, target) != 0) err(1, ""setresuid""); #endif if (getcwd(cwdpath, sizeof(cwdpath)) == NULL) cwd = ""(failed)""; else cwd = cwdpath; if (!(rule->options & NOLOG)) { syslog(LOG_AUTHPRIV | LOG_INFO, ""%s ran command %s as %s from %s"", mypw->pw_name, cmdline, targpw->pw_name, cwd); } envp = prepenv(rule, mypw, targpw); /* setusercontext set path for the next process, so reset it for us */ if (rule->cmd) { if (setenv(""PATH"", safepath, 1) == -1) err(1, ""failed to set PATH '%s'"", safepath); } else { if (setenv(""PATH"", formerpath, 1) == -1) err(1, ""failed to set PATH '%s'"", formerpath); } execvpe(cmd, argv, envp); if (errno == ENOENT) errx(1, ""%s: command not found"", cmd); err(1, ""%s"", cmd); }",CWE-200,4 0,"void BlobURLRequestJob::DidRead(int result) { if (result < 0) { NotifyFailure(net::ERR_FAILED); return; } SetStatus(net::URLRequestStatus()); // Clear the IO_PENDING status AdvanceBytesRead(result); if (!read_buf_remaining_bytes_) { int bytes_read = ReadCompleted(); NotifyReadComplete(bytes_read); return; } int bytes_read = 0; if (ReadLoop(&bytes_read)) NotifyReadComplete(bytes_read); } ",none,24 1," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); Tensor input_min_tensor; Tensor input_max_tensor; Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); if (axis_ == -1) { auto min_val = input_min_tensor.scalar()(); auto max_val = input_max_tensor.scalar()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument(""Invalid range: input_min "", min_val, "" > input_max "", max_val)); } else { OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_min_tensor has incorrect size, was "", input_min_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_min_tensor.shape())); OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_max_tensor has incorrect size, was "", input_max_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_max_tensor.shape())); } } else { auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth}); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_max_tensor)); } if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleFunctor f; f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->flat()); } else { functor::QuantizeAndDequantizePerChannelFunctor f; f(ctx->eigen_device(), input.template flat_inner_outer_dims(axis_ - 1), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->template flat_inner_outer_dims(axis_ - 1)); } }",CWE-787,16 1,"sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie) { int rc; BerElement *ber; struct berval *bvp; char *uuid; Slapi_Attr *attr; Slapi_Value *val; if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) { return (LDAP_OPERATIONS_ERROR); } *ctrlp = NULL; slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr); slapi_attr_first_value(attr, &val); uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val)); if ((rc = ber_printf(ber, ""{eo"", type, uuid, 16)) != -1) { if (cookie) { char *cookiestr = sync_cookie2str(cookie); rc = ber_printf(ber, ""s}"", cookiestr); slapi_ch_free((void **)&cookiestr); } else { rc = ber_printf(ber, ""}""); } } if (rc != -1) { rc = ber_flatten(ber, &bvp); } ber_free(ber, 1); slapi_ch_free((void **)&uuid); if (rc == -1) { return (LDAP_OPERATIONS_ERROR); } *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl)); (*ctrlp)->ldctl_iscritical = 0; (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE); (*ctrlp)->ldctl_value = *bvp; /* struct copy */ bvp->bv_val = NULL; ber_bvfree(bvp); return (LDAP_SUCCESS); }",CWE-476,12 1,"void gf_isom_cenc_get_default_info_internal(GF_TrackBox *trak, u32 sampleDescriptionIndex, u32 *container_type, Bool *default_IsEncrypted, u8 *crypt_byte_block, u8 *skip_byte_block, const u8 **key_info, u32 *key_info_size) { GF_ProtectionSchemeInfoBox *sinf; //setup all default as not encrypted if (default_IsEncrypted) *default_IsEncrypted = GF_FALSE; if (crypt_byte_block) *crypt_byte_block = 0; if (skip_byte_block) *skip_byte_block = 0; if (container_type) *container_type = 0; if (key_info) *key_info = NULL; if (key_info_size) *key_info_size = 0; sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENC_SCHEME, NULL); if (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBC_SCHEME, NULL); if (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CENS_SCHEME, NULL); if (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_CBCS_SCHEME, NULL); if (!sinf) sinf = isom_get_sinf_entry(trak, sampleDescriptionIndex, GF_ISOM_PIFF_SCHEME, NULL); if (!sinf) { u32 i, nb_stsd = gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes); for (i=0; iMedia->information->sampleTable->SampleDescription->child_boxes, i); a_sinf = (GF_ProtectionSchemeInfoBox *) gf_isom_box_find_child(sentry->child_boxes, GF_ISOM_BOX_TYPE_SINF); if (!a_sinf) continue; //signal default (not encrypted) return; } } if (sinf && sinf->info && sinf->info->tenc) { if (default_IsEncrypted) *default_IsEncrypted = sinf->info->tenc->isProtected; if (crypt_byte_block) *crypt_byte_block = sinf->info->tenc->crypt_byte_block; if (skip_byte_block) *skip_byte_block = sinf->info->tenc->skip_byte_block; if (key_info) *key_info = sinf->info->tenc->key_info; if (key_info_size) { *key_info_size = 20; if (!sinf->info->tenc->key_info[3]) *key_info_size += 1 + sinf->info->tenc->key_info[20]; } //set default value, overwritten below if (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC; } else if (sinf && sinf->info && sinf->info->piff_tenc) { if (default_IsEncrypted) *default_IsEncrypted = GF_TRUE; if (key_info) *key_info = sinf->info->piff_tenc->key_info; if (key_info_size) *key_info_size = 19; //set default value, overwritten below if (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC; } else { u32 i, count = 0; GF_CENCSampleEncryptionGroupEntry *seig_entry = NULL; if (!trak->moov->mov->is_smooth) count = gf_list_count(trak->Media->information->sampleTable->sampleGroupsDescription); for (i=0; iMedia->information->sampleTable->sampleGroupsDescription, i); if (sgdesc->grouping_type!=GF_ISOM_SAMPLE_GROUP_SEIG) continue; if (sgdesc->default_description_index) seig_entry = gf_list_get(sgdesc->group_descriptions, sgdesc->default_description_index-1); else seig_entry = gf_list_get(sgdesc->group_descriptions, 0); if (!seig_entry->key_info[0]) seig_entry = NULL; break; } if (seig_entry) { if (default_IsEncrypted) *default_IsEncrypted = seig_entry->IsProtected; if (crypt_byte_block) *crypt_byte_block = seig_entry->crypt_byte_block; if (skip_byte_block) *skip_byte_block = seig_entry->skip_byte_block; if (key_info) *key_info = seig_entry->key_info; if (key_info_size) *key_info_size = seig_entry->key_info_size; if (container_type) *container_type = GF_ISOM_BOX_TYPE_SENC; } else { if (! trak->moov->mov->is_smooth ) { trak->moov->mov->is_smooth = GF_TRUE; GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] senc box without tenc, assuming MS smooth+piff\n"")); } if (default_IsEncrypted) *default_IsEncrypted = GF_TRUE; //set default value, overwritten below if (container_type) *container_type = GF_ISOM_BOX_UUID_PSEC; } } if (container_type && trak->sample_encryption) { if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_SENC) *container_type = GF_ISOM_BOX_TYPE_SENC; else if (trak->sample_encryption->type == GF_ISOM_BOX_TYPE_UUID) *container_type = ((GF_UUIDBox*)trak->sample_encryption)->internal_4cc; } }",CWE-476,12 1,"TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input, const TfLiteTensor* axis, TfLiteTensor* output) { int axis_value; // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss. if (axis->type == kTfLiteInt64) { axis_value = static_cast(*GetTensorData(axis)); } else { axis_value = *GetTensorData(axis); } if (axis_value < 0) { axis_value += NumDimensions(input); } // Copy the input dimensions to output except the axis dimension. TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1); int j = 0; for (int i = 0; i < NumDimensions(input); ++i) { if (i != axis_value) { output_dims->data[j] = SizeOfDimension(input, i); ++j; } } return context->ResizeTensor(context, output, output_dims); }",CWE-787,16 0," RTCVideoDecoderTest() { decoder_ = new RTCVideoDecoder(&message_loop_, kUrl); renderer_ = new MockVideoRenderer(); read_cb_ = base::Bind(&RTCVideoDecoderTest::FrameReady, base::Unretained(this)); DCHECK(decoder_); EXPECT_CALL(statistics_cb_, OnStatistics(_)) .Times(AnyNumber()); } ",none,24 1,"handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) { #define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; } #define MAX_DATA_SZ (4u * 100000000u) has_add_respose = false; bool existing, init_img = true; Image *img = NULL; unsigned char tt = g->transmission_type ? g->transmission_type : 'd'; enum FORMATS { RGB=24, RGBA=32, PNG=100 }; uint32_t fmt = g->format ? g->format : RGBA; if (tt == 'd' && self->loading_image) init_img = false; if (init_img) { self->last_init_graphics_command = *g; self->last_init_graphics_command.id = iid; self->loading_image = 0; if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, ""Image too large""); remove_images(self, add_trim_predicate, 0); img = find_or_create_image(self, iid, &existing); if (existing) { free_load_data(&img->load_data); img->data_loaded = false; free_refs_data(img); *is_dirty = true; self->layers_dirty = true; } else { img->internal_id = internal_id_counter++; img->client_id = iid; } img->atime = monotonic(); img->used_storage = 0; img->width = g->data_width; img->height = g->data_height; switch(fmt) { case PNG: if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, ""PNG data size too large""); img->load_data.is_4byte_aligned = true; img->load_data.is_opaque = false; img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100; break; case RGB: case RGBA: img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8); if (!img->load_data.data_sz) ABRT(EINVAL, ""Zero width/height not allowed""); img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0); img->load_data.is_opaque = fmt == RGB; break; default: ABRT(EINVAL, ""Unknown image format: %u"", fmt); } if (tt == 'd') { if (g->more) self->loading_image = img->internal_id; img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header img->load_data.buf = malloc(img->load_data.buf_capacity); img->load_data.buf_used = 0; if (img->load_data.buf == NULL) { ABRT(ENOMEM, ""Out of memory""); img->load_data.buf_capacity = 0; img->load_data.buf_used = 0; } } } else { self->last_init_graphics_command.more = g->more; self->last_init_graphics_command.payload_sz = g->payload_sz; g = &self->last_init_graphics_command; tt = g->transmission_type ? g->transmission_type : 'd'; fmt = g->format ? g->format : RGBA; img = img_by_internal_id(self, self->loading_image); if (img == NULL) { self->loading_image = 0; ABRT(EILSEQ, ""More payload loading refers to non-existent image""); } } int fd; static char fname[2056] = {0}; switch(tt) { case 'd': // direct if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) { if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, ""Too much data""); img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ); img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity); if (img->load_data.buf == NULL) { ABRT(ENOMEM, ""Out of memory""); img->load_data.buf_capacity = 0; img->load_data.buf_used = 0; } } memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz); img->load_data.buf_used += g->payload_sz; if (!g->more) { img->data_loaded = true; self->loading_image = 0; } break; case 'f': // file case 't': // temporary file case 's': // POSIX shared memory if (g->payload_sz > 2048) ABRT(EINVAL, ""Filename too long""); snprintf(fname, sizeof(fname)/sizeof(fname[0]), ""%.*s"", (int)g->payload_sz, payload); if (tt == 's') fd = shm_open(fname, O_RDONLY, 0); else fd = open(fname, O_CLOEXEC | O_RDONLY); if (fd == -1) ABRT(EBADF, ""Failed to open file %s for graphics transmission with error: [%d] %s"", fname, errno, strerror(errno)); img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset); safe_close(fd, __FILE__, __LINE__); if (tt == 't') { if (global_state.boss) { call_boss(safe_delete_temp_file, ""s"", fname); } else unlink(fname); } else if (tt == 's') shm_unlink(fname); break; default: ABRT(EINVAL, ""Unknown transmission type: %c"", g->transmission_type); } if (!img->data_loaded) return NULL; self->loading_image = 0; bool needs_processing = g->compressed || fmt == PNG; if (needs_processing) { uint8_t *buf; size_t bufsz; #define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } } switch(g->compressed) { case 'z': IB; if (!inflate_zlib(self, img, buf, bufsz)) { img->data_loaded = false; return NULL; } break; case 0: break; default: ABRT(EINVAL, ""Unknown image compression: %c"", g->compressed); } switch(fmt) { case PNG: IB; if (!inflate_png(self, img, buf, bufsz)) { img->data_loaded = false; return NULL; } break; default: break; } #undef IB img->load_data.data = img->load_data.buf; if (img->load_data.buf_used < img->load_data.data_sz) { ABRT(ENODATA, ""Insufficient image data: %zu < %zu"", img->load_data.buf_used, img->load_data.data_sz); } if (img->load_data.mapped_file) { munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz); img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0; } } else { if (tt == 'd') { if (img->load_data.buf_used < img->load_data.data_sz) { ABRT(ENODATA, ""Insufficient image data: %zu < %zu"", img->load_data.buf_used, img->load_data.data_sz); } else img->load_data.data = img->load_data.buf; } else { if (img->load_data.mapped_file_sz < img->load_data.data_sz) { ABRT(ENODATA, ""Insufficient image data: %zu < %zu"", img->load_data.mapped_file_sz, img->load_data.data_sz); } else img->load_data.data = img->load_data.mapped_file; } } size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height; if (img->load_data.data_sz != required_sz) ABRT(EINVAL, ""Image dimensions: %ux%u do not match data size: %zu, expected size: %zu"", img->width, img->height, img->load_data.data_sz, required_sz); if (LIKELY(img->data_loaded && send_to_gpu)) { send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP); free_load_data(&img->load_data); self->used_storage += required_sz; img->used_storage = required_sz; } return img; #undef MAX_DATA_SZ #undef ABRT }",CWE-787,16 1,"REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv(""PERL_DUMP_RE_MAX_LEN""); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Assembling pattern from %d elements%s\n"", pat_count, orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Precompiled pattern%s\n"", orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ ""%sCompiling REx%s %s\n"", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL(""Regexp out of space""); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ ""Eval-group in insecure regular expression""); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Starting parse and generation\n""); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL(""Regexp out of space""); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, ""foo""); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ ""panic: reg returned failure to re_op_compile, flags=%#"" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse after upgrade\n"")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse\n"")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Required size %"" IVdf "" nodes\n"", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ ""%s %"" UVuf "" bytes for offset annotations.\n"", RExC_offsets ? ""Got"" : ""Couldn't get"", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ ""Offsets: [%"" UVuf ""]\n\t"", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ ""%"" UVuf "":%"" UVuf ""[%"" UVuf ""] "", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ ""\n""); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ ""Starting post parse optimization\n""); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ ""Restudying\n"")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is ""must appear"" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP(""first:"", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""""); data.substrs[1].str = newSVpvs(""""); data.last_found = newSVpvs(""""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name(""study_chunk""); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name(""study_chunk"")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name(""study_chunk""); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""\nMulti Top Level\n"")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the ""real"" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ ""minlen: %"" IVdf "" RExC_rx->minlen:%"" IVdf "" maxlen:%"" IVdf ""\n"", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify ""special"" patterns that might result * in Perl NOT calling the regex engine and instead doing the match ""itself"", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN(""a"")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ ""study_chunk_recursed_count: %lu\n"", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ ""Final program:\n""); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx;",CWE-190,2 1,"p11_rpc_buffer_get_attribute (p11_buffer *buffer, size_t *offset, CK_ATTRIBUTE *attr) { uint32_t type, length; unsigned char validity; p11_rpc_attribute_serializer *serializer; p11_rpc_value_type value_type; /* The attribute type */ if (!p11_rpc_buffer_get_uint32 (buffer, offset, &type)) return false; /* Attribute validity */ if (!p11_rpc_buffer_get_byte (buffer, offset, &validity)) return false; /* Not a valid attribute */ if (!validity) { attr->ulValueLen = ((CK_ULONG)-1); attr->type = type; return true; } if (!p11_rpc_buffer_get_uint32 (buffer, offset, &length)) return false; /* Decode the attribute value */ value_type = map_attribute_to_value_type (type); assert (value_type < ELEMS (p11_rpc_attribute_serializers)); serializer = &p11_rpc_attribute_serializers[value_type]; assert (serializer != NULL); if (!serializer->decode (buffer, offset, attr->pValue, &attr->ulValueLen)) return false; if (!attr->pValue) attr->ulValueLen = length; attr->type = type; return true; }",CWE-787,16 1,"Status CompressElement(const std::vector& element, CompressedElement* out) { // Step 1: Determine the total uncompressed size. This requires serializing // non-memcopyable tensors, which we save to use again later. std::vector non_memcpy_components; int64 total_size = 0; for (auto& component : element) { if (DataTypeCanUseMemcpy(component.dtype())) { // Some datatypes can be memcopied, allowing us to save two copies // (AsProtoTensorContent and SerializeToArray). total_size += DMAHelper::buffer(&component)->size(); } else { non_memcpy_components.emplace_back(); component.AsProtoTensorContent(&non_memcpy_components.back()); total_size += non_memcpy_components.back().ByteSizeLong(); } } // Step 2: Write the tensor data to a buffer, and compress that buffer. // We use tstring for access to resize_uninitialized. tstring uncompressed; uncompressed.resize_uninitialized(total_size); // Position in `uncompressed` to write the next component. char* position = uncompressed.mdata(); int non_memcpy_component_index = 0; for (auto& component : element) { CompressedComponentMetadata* metadata = out->mutable_component_metadata()->Add(); metadata->set_dtype(component.dtype()); component.shape().AsProto(metadata->mutable_tensor_shape()); if (DataTypeCanUseMemcpy(component.dtype())) { const TensorBuffer* buffer = DMAHelper::buffer(&component); memcpy(position, buffer->data(), buffer->size()); metadata->set_tensor_size_bytes(buffer->size()); } else { TensorProto& proto = non_memcpy_components[non_memcpy_component_index++]; proto.SerializeToArray(position, proto.ByteSizeLong()); metadata->set_tensor_size_bytes(proto.ByteSizeLong()); } position += metadata->tensor_size_bytes(); } DCHECK_EQ(position, uncompressed.mdata() + total_size); if (!port::Snappy_Compress(uncompressed.mdata(), total_size, out->mutable_data())) { return errors::Internal(""Failed to compress using snappy.""); } VLOG(3) << ""Compressed element from "" << total_size << "" bytes to "" << out->data().size() << "" bytes""; return Status::OK(); }",CWE-125,1 1,"static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs) { u8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len; u32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc = 0; u8 dimension_id_len[16], dim_bit_offset[16]; u8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx; u8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS]; u8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS + 1]; u8 ols_highest_output_layer_id[MAX_LHVC_LAYERS + 1]; u32 k, d, r, p, iNuhLId, jNuhLId; u8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS]; u8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS]; // u8 num_ref_layers[64]; // u8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS]; // u8 id_ref_layers[64][MAX_LHVC_LAYERS]; // u8 id_direct_ref_layers[64][MAX_LHVC_LAYERS]; u8 layer_id_in_list_flag[64]; Bool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS]; vps->vps_extension_found = 1; if ((vps->max_layers > 1) && vps->base_layer_internal_flag) hevc_profile_tier_level(bs, 0, vps->max_sub_layers - 1, &vps->ext_ptl[0], 0); splitting_flag = gf_bs_read_int_log(bs, 1, ""splitting_flag""); num_scalability_types = 0; for (i = 0; i < 16; i++) { vps->scalability_mask[i] = gf_bs_read_int_log_idx(bs, 1, ""scalability_mask"", i); num_scalability_types += vps->scalability_mask[i]; } if (num_scalability_types >= 16) { num_scalability_types = 16; } dimension_id_len[0] = 0; for (i = 0; i < (num_scalability_types - splitting_flag); i++) { dimension_id_len[i] = 1 + gf_bs_read_int_log_idx(bs, 3, ""dimension_id_len_minus1"", i); } if (splitting_flag) { for (i = 0; i < num_scalability_types; i++) { dim_bit_offset[i] = 0; for (j = 0; j < i; j++) dim_bit_offset[i] += dimension_id_len[j]; } dimension_id_len[num_scalability_types - 1] = 1 + (5 - dim_bit_offset[num_scalability_types - 1]); dim_bit_offset[num_scalability_types] = 6; } vps_nuh_layer_id_present_flag = gf_bs_read_int_log(bs, 1, ""vps_nuh_layer_id_present_flag""); vps->layer_id_in_nuh[0] = 0; vps->layer_id_in_vps[0] = 0; for (i = 1; i < vps->max_layers; i++) { if (vps_nuh_layer_id_present_flag) { vps->layer_id_in_nuh[i] = gf_bs_read_int_log_idx(bs, 6, ""layer_id_in_nuh"", i); } else { vps->layer_id_in_nuh[i] = i; } vps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i; if (!splitting_flag) { for (j = 0; j < num_scalability_types; j++) { vps->dimension_id[i][j] = gf_bs_read_int_log_idx2(bs, dimension_id_len[j], ""dimension_id"", i, j); } } } if (splitting_flag) { for (i = 0; i < vps->max_layers; i++) for (j = 0; j < num_scalability_types; j++) vps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j + 1]) - 1)) >> dim_bit_offset[j]); } else { for (j = 0; j < num_scalability_types; j++) vps->dimension_id[0][j] = 0; } view_id_len = gf_bs_read_int_log(bs, 4, ""view_id_len""); if (view_id_len > 0) { for (i = 0; i < lhvc_get_num_views(vps); i++) { gf_bs_read_int_log_idx(bs, view_id_len, ""view_id_val"", i); } } for (i = 1; i < vps->max_layers; i++) { for (j = 0; j < i; j++) { vps->direct_dependency_flag[i][j] = gf_bs_read_int_log_idx(bs, 1, ""direct_dependency_flag"", i); } } //we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds for (i = 0; i < MAX_LHVC_LAYERS; i++) { if (i >= vps->max_layers) break; for (j = 0; j < vps->max_layers; j++) { dependency_flag[i][j] = vps->direct_dependency_flag[i][j]; for (k = 0; k < i; k++) if (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j]) dependency_flag[i][j] = 1; } } for (i = 0; i < vps->max_layers; i++) { iNuhLId = vps->layer_id_in_nuh[i]; d = r = p = 0; for (j = 0; j < vps->max_layers; j++) { jNuhLId = vps->layer_id_in_nuh[j]; if (vps->direct_dependency_flag[i][j]) { // id_direct_ref_layers[iNuhLId][d] = jNuhLId; d++; } if (dependency_flag[i][j]) { // id_ref_layers[iNuhLId][r] = jNuhLId; r++; } if (dependency_flag[j][i]) id_pred_layers[iNuhLId][p++] = jNuhLId; } num_direct_ref_layers[iNuhLId] = d; // num_ref_layers[iNuhLId] = r; num_pred_layers[iNuhLId] = p; } memset(layer_id_in_list_flag, 0, 64 * sizeof(u8)); k = 0; //num_indepentdent_layers for (i = 0; i < vps->max_layers; i++) { iNuhLId = vps->layer_id_in_nuh[i]; if (!num_direct_ref_layers[iNuhLId]) { u32 h = 1; //tree_partition_layer_id[k][0] = iNuhLId; for (j = 0; j < num_pred_layers[iNuhLId]; j++) { u32 predLId = id_pred_layers[iNuhLId][j]; if (!layer_id_in_list_flag[predLId]) { //tree_partition_layer_id[k][h++] = predLId; layer_id_in_list_flag[predLId] = 1; } } num_layers_in_tree_partition[k++] = h; } } num_indepentdent_layers = k; num_add_layer_set = 0; if (num_indepentdent_layers > 1) num_add_layer_set = gf_bs_read_ue_log(bs, ""num_add_layer_set""); for (i = 0; i < num_add_layer_set; i++) for (j = 1; j < num_indepentdent_layers; j++) { nb_bits = 1; while ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1)) nb_bits++; gf_bs_read_int_log_idx2(bs, nb_bits, ""highest_layer_idx_plus1"", i, j); } if (gf_bs_read_int_log(bs, 1, ""vps_sub_layers_max_minus1_present_flag"")) { for (i = 0; i < vps->max_layers; i++) { gf_bs_read_int_log_idx(bs, 3, ""sub_layers_vps_max_minus1"", i); } } if (gf_bs_read_int_log(bs, 1, ""max_tid_ref_present_flag"")) { for (i = 0; i < (vps->max_layers - 1); i++) { for (j = i + 1; j < vps->max_layers; j++) { if (vps->direct_dependency_flag[j][i]) gf_bs_read_int_log_idx2(bs, 3, ""max_tid_il_ref_pics_plus1"", i, j); } } } gf_bs_read_int_log(bs, 1, ""default_ref_layers_active_flag""); vps->num_profile_tier_level = 1 + gf_bs_read_ue_log(bs, ""num_profile_tier_level""); if (vps->num_profile_tier_level > MAX_LHVC_LAYERS) { GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (""[HEVC] Wrong number of PTLs in VPS %d\n"", vps->num_profile_tier_level)); vps->num_profile_tier_level = 1; return GF_FALSE; } for (i = vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) { Bool vps_profile_present_flag = gf_bs_read_int_log_idx(bs, 1, ""vps_profile_present_flag"", i); hevc_profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers - 1, &vps->ext_ptl[i - 1], i-1); } NumLayerSets = vps->num_layer_sets + num_add_layer_set; num_add_olss = 0; if (NumLayerSets > 1) { num_add_olss = gf_bs_read_ue_log(bs, ""num_add_olss""); default_output_layer_idc = gf_bs_read_int_log(bs, 2, ""default_output_layer_idc""); default_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2; } vps->num_output_layer_sets = num_add_olss + NumLayerSets; layer_set_idx_for_ols_minus1[0] = 1; vps->output_layer_flag[0][0] = 1; for (i = 0; i < vps->num_output_layer_sets; i++) { if ((NumLayerSets > 2) && (i >= NumLayerSets)) { nb_bits = 1; while ((1 << nb_bits) < (NumLayerSets - 1)) nb_bits++; layer_set_idx_for_ols_minus1[i] = gf_bs_read_int_log_idx(bs, nb_bits, ""layer_set_idx_for_ols_minus1"", i); } else layer_set_idx_for_ols_minus1[i] = 0; ols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1; if ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) { for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) vps->output_layer_flag[i][j] = gf_bs_read_int_log_idx2(bs, 1, ""output_layer_flag"", i, j); } if ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) { for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i])) OutputLayerFlag[i][j] = GF_TRUE; else OutputLayerFlag[i][j] = GF_FALSE; } } for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if (OutputLayerFlag[i][j]) { u32 curLayerID; vps->necessary_layers_flag[i][j] = GF_TRUE; curLayerID = vps->LayerSetLayerIdList[i][j]; for (k = 0; k < j; k++) { u32 refLayerId = vps->LayerSetLayerIdList[i][k]; if (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]]) vps->necessary_layers_flag[i][k] = GF_TRUE; } } } vps->num_necessary_layers[i] = 0; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { if (vps->necessary_layers_flag[i][j]) vps->num_necessary_layers[i] += 1; } if (i == 0) { if (vps->base_layer_internal_flag) { if (vps->max_layers > 1) vps->profile_tier_level_idx[0][0] = 1; else vps->profile_tier_level_idx[0][0] = 0; } continue; } nb_bits = 1; while ((u32)(1 << nb_bits) < vps->num_profile_tier_level) nb_bits++; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) if (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level) vps->profile_tier_level_idx[i][j] = gf_bs_read_int_log_idx2(bs, nb_bits, ""profile_tier_level_idx"", i, j); else vps->profile_tier_level_idx[i][j] = 0; nb_output_layers_in_output_layer_set[i] = 0; for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) { nb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j]; if (OutputLayerFlag[i][j]) { ols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j]; } } if (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0) vps->alt_output_layer_flag[i] = gf_bs_read_int_log_idx(bs, 1, ""alt_output_layer_flag"", i); } vps->num_rep_formats = 1 + gf_bs_read_ue_log(bs, ""num_rep_formats_minus1""); if (vps->num_rep_formats > 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (""[HEVC] Wrong number of rep formats in VPS %d\n"", vps->num_rep_formats)); vps->num_rep_formats = 0; return GF_FALSE; } for (i = 0; i < vps->num_rep_formats; i++) { lhvc_parse_rep_format(&vps->rep_formats[i], bs, i); } if (vps->num_rep_formats > 1) rep_format_idx_present_flag = gf_bs_read_int_log(bs, 1, ""rep_format_idx_present_flag""); else rep_format_idx_present_flag = 0; vps->rep_format_idx[0] = 0; nb_bits = 1; while ((u32)(1 << nb_bits) < vps->num_rep_formats) nb_bits++; for (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) { if (rep_format_idx_present_flag) { vps->rep_format_idx[i] = gf_bs_read_int_log_idx(bs, nb_bits, ""rep_format_idx"", i); } else { vps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1; } } //TODO - we don't use the rest ... return GF_TRUE; }",CWE-787,16 0,"VideoRendererBase::~VideoRendererBase() { base::AutoLock auto_lock(lock_); DCHECK(state_ == kUninitialized || state_ == kStopped) << state_; } ",none,24 1,"nosy_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct client *client = file->private_data; spinlock_t *client_list_lock = &client->lynx->client_list_lock; struct nosy_stats stats; switch (cmd) { case NOSY_IOC_GET_STATS: spin_lock_irq(client_list_lock); stats.total_packet_count = client->buffer.total_packet_count; stats.lost_packet_count = client->buffer.lost_packet_count; spin_unlock_irq(client_list_lock); if (copy_to_user((void __user *) arg, &stats, sizeof stats)) return -EFAULT; else return 0; case NOSY_IOC_START: spin_lock_irq(client_list_lock); list_add_tail(&client->link, &client->lynx->client_list); spin_unlock_irq(client_list_lock); return 0; case NOSY_IOC_STOP: spin_lock_irq(client_list_lock); list_del_init(&client->link); spin_unlock_irq(client_list_lock); return 0; case NOSY_IOC_FILTER: spin_lock_irq(client_list_lock); client->tcode_mask = arg; spin_unlock_irq(client_list_lock); return 0; default: return -EINVAL; /* Flush buffer, configure filter. */ } }",CWE-416,10 0,"void SearchEngineTabHelper::DidNavigateMainFrame( const content::LoadCommittedDetails& /*details*/, const content::FrameNavigateParams& params) { GenerateKeywordIfNecessary(params); } ",none,24 0," void EnterEndOfStreamState() { scoped_refptr video_frame; VideoDecoder::DecoderStatus status; Read(&status, &video_frame); EXPECT_EQ(status, VideoDecoder::kOk); ASSERT_TRUE(video_frame); EXPECT_TRUE(video_frame->IsEndOfStream()); } ",none,24 0,"void SpeechSynthesis::setPlatformSynthesizer(PassOwnPtr synthesizer) { m_platformSpeechSynthesizer = synthesizer; } ",none,24 1,"GF_Err gf_hinter_track_process(GF_RTPHinter *tkHint) { GF_Err e; u32 i, descIndex, duration; u64 ts; u8 PadBits; GF_Fraction ft; GF_ISOSample *samp; tkHint->HintSample = tkHint->RTPTime = 0; tkHint->TotalSample = gf_isom_get_sample_count(tkHint->file, tkHint->TrackNum); ft.num = tkHint->rtp_p->sl_config.timestampResolution; ft.den = tkHint->OrigTimeScale; e = GF_OK; for (i=0; iTotalSample; i++) { samp = gf_isom_get_sample(tkHint->file, tkHint->TrackNum, i+1, &descIndex); if (!samp) return gf_isom_last_error(tkHint->file); //setup SL tkHint->CurrentSample = i + 1; /*keep same AU indicator if sync shadow - TODO FIXME: this assumes shadows are placed interleaved with the track content which is the case for GPAC scene carousel generation, but may not always be true*/ if (samp->IsRAP==RAP_REDUNDANT) { tkHint->rtp_p->sl_header.AU_sequenceNumber -= 1; samp->IsRAP = RAP; } ts = ft.num * (samp->DTS+samp->CTS_Offset) / ft.den; tkHint->rtp_p->sl_header.compositionTimeStamp = ts; ts = ft.num * samp->DTS / ft.den; tkHint->rtp_p->sl_header.decodingTimeStamp = ts; tkHint->rtp_p->sl_header.randomAccessPointFlag = samp->IsRAP; tkHint->base_offset_in_sample = 0; /*crypted*/ if (tkHint->rtp_p->slMap.IV_length) { GF_ISMASample *s = gf_isom_get_ismacryp_sample(tkHint->file, tkHint->TrackNum, samp, descIndex); /*one byte take for selective_enc flag*/ if (s->flags & GF_ISOM_ISMA_USE_SEL_ENC) tkHint->base_offset_in_sample += 1; if (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) tkHint->base_offset_in_sample += s->IV_length + s->KI_length; gf_free(samp->data); samp->data = s->data; samp->dataLength = s->dataLength; gf_rtp_builder_set_cryp_info(tkHint->rtp_p, s->IV, (char*)s->key_indicator, (s->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? 1 : 0); s->data = NULL; s->dataLength = 0; gf_isom_ismacryp_delete_sample(s); } if (tkHint->rtp_p->sl_config.usePaddingFlag) { gf_isom_get_sample_padding_bits(tkHint->file, tkHint->TrackNum, i+1, &PadBits); tkHint->rtp_p->sl_header.paddingBits = PadBits; } else { tkHint->rtp_p->sl_header.paddingBits = 0; } duration = gf_isom_get_sample_duration(tkHint->file, tkHint->TrackNum, i+1); // ts = (u32) (ft * (s64) (duration)); /*unpack nal units*/ if (tkHint->avc_nalu_size) { u32 v, size; u32 remain = samp->dataLength; char *ptr = samp->data; tkHint->rtp_p->sl_header.accessUnitStartFlag = 1; tkHint->rtp_p->sl_header.accessUnitEndFlag = 0; while (remain) { size = 0; v = tkHint->avc_nalu_size; if (v>remain) { GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (""[rtp hinter] Broken AVC nalu encapsulation: NALU size length is %d but only %d bytes left in sample %d\n"", v, remain, tkHint->CurrentSample)); break; } while (v) { size |= (u8) *ptr; ptr++; remain--; v-=1; if (v) size<<=8; } tkHint->base_offset_in_sample = samp->dataLength-remain; if (remain < size) { GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (""[rtp hinter] Broken AVC nalu encapsulation: NALU size is %d but only %d bytes left in sample %d\n"", size, remain, tkHint->CurrentSample)); break; } remain -= size; tkHint->rtp_p->sl_header.accessUnitEndFlag = remain ? 0 : 1; e = gf_rtp_builder_process(tkHint->rtp_p, ptr, size, (u8) !remain, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) ); ptr += size; tkHint->rtp_p->sl_header.accessUnitStartFlag = 0; } } else { e = gf_rtp_builder_process(tkHint->rtp_p, samp->data, samp->dataLength, 1, samp->dataLength, duration, (u8) (descIndex + GF_RTP_TX3G_SIDX_OFFSET) ); } tkHint->rtp_p->sl_header.packetSequenceNumber += 1; //signal some progress gf_set_progress(""Hinting"", tkHint->CurrentSample, tkHint->TotalSample); tkHint->rtp_p->sl_header.AU_sequenceNumber += 1; gf_isom_sample_del(&samp); if (e) return e; } //flush gf_rtp_builder_process(tkHint->rtp_p, NULL, 0, 1, 0, 0, 0); gf_isom_end_hint_sample(tkHint->file, tkHint->HintTrack, (u8) tkHint->SampleIsRAP); return GF_OK; }",CWE-787,16 1,"static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, ""Discarding %d bytes at "" ""beginning of image.\n"", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no SOI marker found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: first "" ""marker is %02x, should be SOI.\n"", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no image content found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker.\n"", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker segment.\n"", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) { if (!data_ref) av_freep(&data); return err; } if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; }",CWE-787,16 0,"void WebGraphicsContext3DDefaultImpl::texImage2D(unsigned target, unsigned level, unsigned internalFormat, unsigned width, unsigned height, unsigned border, unsigned format, unsigned type, const void* pixels) { OwnArrayPtr zero; if (!pixels) { size_t size = imageSizeInBytes(width, height, format, type); zero.set(new uint8[size]); memset(zero.get(), 0, size); pixels = zero.get(); } glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } ",none,24 0,"bool BlobURLRequestJob::ReadBytes(const BlobData::Item& item) { DCHECK(read_buf_remaining_bytes_ >= bytes_to_read_); memcpy(read_buf_->data() + read_buf_offset_, &item.data().at(0) + item.offset() + current_item_offset_, bytes_to_read_); AdvanceBytesRead(bytes_to_read_); return true; } ",none,24 0,"bool SoftwareFrameManager::HasCurrentFrame() const { return current_frame_.get() ? true : false; } ",none,24 1,"UINT rdpgfx_read_rect16(wStream* s, RECTANGLE_16* rect16) { if (Stream_GetRemainingLength(s) < 8) { WLog_ERR(TAG, ""not enough data!""); return ERROR_INVALID_DATA; } Stream_Read_UINT16(s, rect16->left); /* left (2 bytes) */ Stream_Read_UINT16(s, rect16->top); /* top (2 bytes) */ Stream_Read_UINT16(s, rect16->right); /* right (2 bytes) */ Stream_Read_UINT16(s, rect16->bottom); /* bottom (2 bytes) */ return CHANNEL_RC_OK; }",CWE-190,2 1," void Compute(OpKernelContext* context) override { const Tensor& x = context->input(0); const Tensor& y = context->input(1); const float min_x = context->input(2).flat()(0); const float max_x = context->input(3).flat()(0); const float min_y = context->input(4).flat()(0); const float max_y = context->input(5).flat()(0); BCast bcast(BCast::FromShape(x.shape()), BCast::FromShape(y.shape())); if (!bcast.IsValid()) { context->SetStatus(errors::InvalidArgument( ""Incompatible shapes: "", x.shape().DebugString(), "" vs. "", y.shape().DebugString())); return; } Tensor* z; OP_REQUIRES_OK(context, context->allocate_output( 0, BCast::ToShape(bcast.output_shape()), &z)); // Make sure that we have valid quantization ranges for the input buffers. // If the difference between the min and max is negative or zero, it makes // it hard to do meaningful intermediate operations on the values. OP_REQUIRES(context, (max_x > min_x), errors::InvalidArgument(""max_x must be larger than min_a."")); OP_REQUIRES(context, (max_y > min_y), errors::InvalidArgument(""max_x must be larger than min_b."")); const int32 offset_x = FloatToQuantizedUnclamped(0.0f, min_x, max_x); const int32 offset_y = FloatToQuantizedUnclamped(0.0f, min_y, max_y); const T* x_data = x.flat().data(); const T* y_data = y.flat().data(); Toutput* z_data = z->flat().data(); const int ndims = bcast.x_reshape().size(); if (ndims <= 1) { if (x.NumElements() == 1) { ScalarMultiply(context, y_data, offset_y, y.NumElements(), x_data[0], offset_x, z_data); } else if (y.NumElements() == 1) { ScalarMultiply(context, x_data, offset_x, x.NumElements(), y_data[0], offset_y, z_data); } else { VectorMultiply(context, x_data, offset_x, y_data, offset_y, x.NumElements(), z_data); } } else if (ndims == 2) { const T* vector_data; int64 vector_num_elements; int32 vector_offset; const T* tensor_data; int64 tensor_num_elements; int32 tensor_offset; if (x.NumElements() < y.NumElements()) { vector_data = x_data; vector_num_elements = x.NumElements(); vector_offset = offset_x; tensor_data = y_data; tensor_num_elements = y.NumElements(); tensor_offset = offset_y; } else { vector_data = y_data; vector_num_elements = y.NumElements(); vector_offset = offset_y; tensor_data = x_data; tensor_num_elements = x.NumElements(); tensor_offset = offset_x; } if (vector_num_elements == 0) { context->SetStatus( errors::InvalidArgument(""vector must have at least 1 element"")); return; } VectorTensorMultiply( vector_data, vector_offset, vector_num_elements, tensor_data, tensor_offset, tensor_num_elements, z_data); } else { LOG(INFO) << ""ndims="" << ndims; LOG(INFO) << ""bcast.x_reshape()="" << TensorShape(bcast.x_reshape()).DebugString(); LOG(INFO) << ""bcast.y_reshape()="" << TensorShape(bcast.y_reshape()).DebugString(); LOG(INFO) << ""bcast.x_bcast()="" << TensorShape(bcast.x_bcast()).DebugString(); LOG(INFO) << ""bcast.y_bcast()="" << TensorShape(bcast.y_bcast()).DebugString(); context->SetStatus(errors::Unimplemented( ""Broadcast between "", context->input(0).shape().DebugString(), "" and "", context->input(1).shape().DebugString(), "" is not supported yet."")); return; } float min_z_value; float max_z_value; QuantizationRangeForMultiplication( min_x, max_x, min_y, max_y, &min_z_value, &max_z_value); Tensor* z_min = nullptr; OP_REQUIRES_OK(context, context->allocate_output(1, {}, &z_min)); z_min->flat()(0) = min_z_value; Tensor* z_max = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, {}, &z_max)); z_max->flat()(0) = max_z_value; }",CWE-787,16 1,"static void vgacon_scrolldelta(struct vc_data *c, int lines) { int start, end, count, soff; if (!lines) { vgacon_restore_screen(c); return; } if (!vgacon_scrollback_cur->data) return; if (!vgacon_scrollback_cur->save) { vgacon_cursor(c, CM_ERASE); vgacon_save_screen(c); c->vc_origin = (unsigned long)c->vc_screenbuf; vgacon_scrollback_cur->save = 1; } vgacon_scrollback_cur->restore = 0; start = vgacon_scrollback_cur->cur + lines; end = start + abs(lines); if (start < 0) start = 0; if (start > vgacon_scrollback_cur->cnt) start = vgacon_scrollback_cur->cnt; if (end < 0) end = 0; if (end > vgacon_scrollback_cur->cnt) end = vgacon_scrollback_cur->cnt; vgacon_scrollback_cur->cur = start; count = end - start; soff = vgacon_scrollback_cur->tail - ((vgacon_scrollback_cur->cnt - end) * c->vc_size_row); soff -= count * c->vc_size_row; if (soff < 0) soff += vgacon_scrollback_cur->size; count = vgacon_scrollback_cur->cnt - start; if (count > c->vc_rows) count = c->vc_rows; if (count) { int copysize; int diff = c->vc_rows - count; void *d = (void *) c->vc_visible_origin; void *s = (void *) c->vc_screenbuf; count *= c->vc_size_row; /* how much memory to end of buffer left? */ copysize = min(count, vgacon_scrollback_cur->size - soff); scr_memcpyw(d, vgacon_scrollback_cur->data + soff, copysize); d += copysize; count -= copysize; if (count) { scr_memcpyw(d, vgacon_scrollback_cur->data, count); d += count; } if (diff) scr_memcpyw(d, s, diff * c->vc_size_row); } else vgacon_cursor(c, CM_MOVE); }",CWE-125,1 1,"isdn_net_setcfg(isdn_net_ioctl_cfg * cfg) { isdn_net_dev *p = isdn_net_findif(cfg->name); ulong features; int i; int drvidx; int chidx; char drvid[25]; if (p) { isdn_net_local *lp = p->local; /* See if any registered driver supports the features we want */ features = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) | ((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT); for (i = 0; i < ISDN_MAX_DRIVERS; i++) if (dev->drv[i]) if ((dev->drv[i]->interface->features & features) == features) break; if (i == ISDN_MAX_DRIVERS) { printk(KERN_WARNING ""isdn_net: No driver with selected features\n""); return -ENODEV; } if (lp->p_encap != cfg->p_encap){ #ifdef CONFIG_ISDN_X25 struct concap_proto * cprot = p -> cprot; #endif if (isdn_net_device_started(p)) { printk(KERN_WARNING ""%s: cannot change encap when if is up\n"", p->dev->name); return -EBUSY; } #ifdef CONFIG_ISDN_X25 if( cprot && cprot -> pops ) cprot -> pops -> proto_del ( cprot ); p -> cprot = NULL; lp -> dops = NULL; /* ... , prepare for configuration of new one ... */ switch ( cfg -> p_encap ){ case ISDN_NET_ENCAP_X25IFACE: lp -> dops = &isdn_concap_reliable_dl_dops; } /* ... and allocate new one ... */ p -> cprot = isdn_concap_new( cfg -> p_encap ); /* p -> cprot == NULL now if p_encap is not supported by means of the concap_proto mechanism */ /* the protocol is not configured yet; this will happen later when isdn_net_reset() is called */ #endif } switch ( cfg->p_encap ) { case ISDN_NET_ENCAP_SYNCPPP: #ifndef CONFIG_ISDN_PPP printk(KERN_WARNING ""%s: SyncPPP support not configured\n"", p->dev->name); return -EINVAL; #else p->dev->type = ARPHRD_PPP; /* change ARP type */ p->dev->addr_len = 0; p->dev->do_ioctl = isdn_ppp_dev_ioctl; #endif break; case ISDN_NET_ENCAP_X25IFACE: #ifndef CONFIG_ISDN_X25 printk(KERN_WARNING ""%s: isdn-x25 support not configured\n"", p->dev->name); return -EINVAL; #else p->dev->type = ARPHRD_X25; /* change ARP type */ p->dev->addr_len = 0; #endif break; case ISDN_NET_ENCAP_CISCOHDLCK: p->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl; break; default: if( cfg->p_encap >= 0 && cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP ) break; printk(KERN_WARNING ""%s: encapsulation protocol %d not supported\n"", p->dev->name, cfg->p_encap); return -EINVAL; } if (strlen(cfg->drvid)) { /* A bind has been requested ... */ char *c, *e; drvidx = -1; chidx = -1; strcpy(drvid, cfg->drvid); if ((c = strchr(drvid, ','))) { /* The channel-number is appended to the driver-Id with a comma */ chidx = (int) simple_strtoul(c + 1, &e, 10); if (e == c) chidx = -1; *c = '\0'; } for (i = 0; i < ISDN_MAX_DRIVERS; i++) /* Lookup driver-Id in array */ if (!(strcmp(dev->drvid[i], drvid))) { drvidx = i; break; } if ((drvidx == -1) || (chidx == -1)) /* Either driver-Id or channel-number invalid */ return -ENODEV; } else { /* Parameters are valid, so get them */ drvidx = lp->pre_device; chidx = lp->pre_channel; } if (cfg->exclusive > 0) { unsigned long flags; /* If binding is exclusive, try to grab the channel */ spin_lock_irqsave(&dev->lock, flags); if ((i = isdn_get_free_channel(ISDN_USAGE_NET, lp->l2_proto, lp->l3_proto, drvidx, chidx, lp->msn)) < 0) { /* Grab failed, because desired channel is in use */ lp->exclusive = -1; spin_unlock_irqrestore(&dev->lock, flags); return -EBUSY; } /* All went ok, so update isdninfo */ dev->usage[i] = ISDN_USAGE_EXCLUSIVE; isdn_info_update(); spin_unlock_irqrestore(&dev->lock, flags); lp->exclusive = i; } else { /* Non-exclusive binding or unbind. */ lp->exclusive = -1; if ((lp->pre_device != -1) && (cfg->exclusive == -1)) { isdn_unexclusive_channel(lp->pre_device, lp->pre_channel); isdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET); drvidx = -1; chidx = -1; } } strcpy(lp->msn, cfg->eaz); lp->pre_device = drvidx; lp->pre_channel = chidx; lp->onhtime = cfg->onhtime; lp->charge = cfg->charge; lp->l2_proto = cfg->l2_proto; lp->l3_proto = cfg->l3_proto; lp->cbdelay = cfg->cbdelay; lp->dialmax = cfg->dialmax; lp->triggercps = cfg->triggercps; lp->slavedelay = cfg->slavedelay * HZ; lp->pppbind = cfg->pppbind; lp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1; lp->dialwait = cfg->dialwait * HZ; if (cfg->secure) lp->flags |= ISDN_NET_SECURE; else lp->flags &= ~ISDN_NET_SECURE; if (cfg->cbhup) lp->flags |= ISDN_NET_CBHUP; else lp->flags &= ~ISDN_NET_CBHUP; switch (cfg->callback) { case 0: lp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT); break; case 1: lp->flags |= ISDN_NET_CALLBACK; lp->flags &= ~ISDN_NET_CBOUT; break; case 2: lp->flags |= ISDN_NET_CBOUT; lp->flags &= ~ISDN_NET_CALLBACK; break; } lp->flags &= ~ISDN_NET_DIALMODE_MASK; /* first all bits off */ if (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) { /* old isdnctrl version, where only 0 or 1 is given */ printk(KERN_WARNING ""Old isdnctrl version detected! Please update.\n""); lp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */ } else { lp->flags |= cfg->dialmode; /* turn on selected bits */ } if (cfg->chargehup) lp->hupflags |= ISDN_CHARGEHUP; else lp->hupflags &= ~ISDN_CHARGEHUP; if (cfg->ihup) lp->hupflags |= ISDN_INHUP; else lp->hupflags &= ~ISDN_INHUP; if (cfg->chargeint > 10) { lp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE; lp->chargeint = cfg->chargeint * HZ; } if (cfg->p_encap != lp->p_encap) { if (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) { p->dev->header_ops = NULL; p->dev->flags = IFF_NOARP|IFF_POINTOPOINT; } else { p->dev->header_ops = &isdn_header_ops; if (cfg->p_encap == ISDN_NET_ENCAP_ETHER) p->dev->flags = IFF_BROADCAST | IFF_MULTICAST; else p->dev->flags = IFF_NOARP|IFF_POINTOPOINT; } } lp->p_encap = cfg->p_encap; return 0; } return -ENODEV; }",CWE-119,0 0,"void BlobURLRequestJob::Seek(int64 offset) { for (item_index_ = 0; item_index_ < blob_data_->items().size() && offset >= item_length_list_[item_index_]; ++item_index_) { offset -= item_length_list_[item_index_]; } current_item_offset_ = offset; } ",none,24 1,"wsrep_cb_status_t wsrep_sst_donate_cb (void* app_ctx, void* recv_ctx, const void* msg, size_t msg_len, const wsrep_gtid_t* current_gtid, const char* state, size_t state_len, bool bypass) { /* This will be reset when sync callback is called. * Should we set wsrep_ready to FALSE here too? */ local_status.set(WSREP_MEMBER_DONOR); const char* method = (char*)msg; size_t method_len = strlen (method); const char* data = method + method_len + 1; char uuid_str[37]; wsrep_uuid_print (¤t_gtid->uuid, uuid_str, sizeof(uuid_str)); wsp::env env(NULL); if (env.error()) { WSREP_ERROR(""wsrep_sst_donate_cb(): env var ctor failed: %d"", -env.error()); return WSREP_CB_FAILURE; } int ret; if ((ret= sst_append_auth_env(env, sst_auth_real))) { WSREP_ERROR(""wsrep_sst_donate_cb(): appending auth env failed: %d"", ret); return WSREP_CB_FAILURE; } if (!strcmp (WSREP_SST_MYSQLDUMP, method)) { ret = sst_donate_mysqldump(data, ¤t_gtid->uuid, uuid_str, current_gtid->seqno, bypass, env()); } else { ret = sst_donate_other(method, data, uuid_str, current_gtid->seqno, bypass, env()); } return (ret >= 0 ? WSREP_CB_SUCCESS : WSREP_CB_FAILURE); }",CWE-77,14 1,"static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; const char *option; FILE *file; Image *image, *next; int status, unique_file; ssize_t n; SVGInfo *svg_info; unsigned char message[MagickPathExtent]; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); 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); } if ((fabs(image->resolution.x) < MagickEpsilon) || (fabs(image->resolution.y) < MagickEpsilon)) { GeometryInfo geometry_info; int flags; flags=ParseGeometry(SVGDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (LocaleCompare(image_info->magick,""MSVG"") != 0) { Image *svg_image; svg_image=RenderSVGImage(image_info,image,exception); if (svg_image != (Image *) NULL) { image=DestroyImageList(image); return(svg_image); } { #if defined(MAGICKCORE_RSVG_DELEGATE) #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface_t *cairo_surface; cairo_t *cairo_image; MagickBooleanType apply_density; MemoryInfo *pixel_info; register unsigned char *p; RsvgDimensionData dimension_info; unsigned char *pixels; #else GdkPixbuf *pixel_buffer; register const guchar *p; #endif GError *error; PixelInfo fill_color; register ssize_t x; register Quantum *q; RsvgHandle *svg_handle; ssize_t y; unsigned char *buffer; buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); #if LIBRSVG_CHECK_VERSION(2,40,3) option=GetImageOption(image_info,""svg:xml-parse-huge""); if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse)) svg_handle=rsvg_handle_new_with_flags(RSVG_HANDLE_FLAG_UNLIMITED); else #endif svg_handle=rsvg_handle_new(); if (svg_handle == (RsvgHandle *) NULL) { buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } rsvg_handle_set_base_uri(svg_handle,image_info->filename); if ((fabs(image->resolution.x) > MagickEpsilon) && (fabs(image->resolution.y) > MagickEpsilon)) rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x, image->resolution.y); while ((n=ReadBlob(image,MagickMaxBufferExtent-1,buffer)) != 0) { buffer[n]='\0'; error=(GError *) NULL; (void) rsvg_handle_write(svg_handle,buffer,n,&error); if (error != (GError *) NULL) g_error_free(error); } buffer=(unsigned char *) RelinquishMagickMemory(buffer); error=(GError *) NULL; rsvg_handle_close(svg_handle,&error); if (error != (GError *) NULL) g_error_free(error); #if defined(MAGICKCORE_CAIRO_DELEGATE) apply_density=MagickTrue; rsvg_handle_get_dimensions(svg_handle,&dimension_info); if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0)) { RsvgDimensionData dpi_dimension_info; /* We should not apply the density when the internal 'factor' is 'i'. This can be checked by using the trick below. */ rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256, image->resolution.y*256); rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info); if ((dpi_dimension_info.width != dimension_info.width) || (dpi_dimension_info.height != dimension_info.height)) apply_density=MagickFalse; rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x, image->resolution.y); } if (image_info->size != (char *) NULL) { (void) GetGeometry(image_info->size,(ssize_t *) NULL, (ssize_t *) NULL,&image->columns,&image->rows); if ((image->columns != 0) || (image->rows != 0)) { image->resolution.x=DefaultSVGDensity*image->columns/ dimension_info.width; image->resolution.y=DefaultSVGDensity*image->rows/ dimension_info.height; if (fabs(image->resolution.x) < MagickEpsilon) image->resolution.x=image->resolution.y; else if (fabs(image->resolution.y) < MagickEpsilon) image->resolution.y=image->resolution.x; else image->resolution.x=image->resolution.y=MagickMin( image->resolution.x,image->resolution.y); apply_density=MagickTrue; } } if (apply_density != MagickFalse) { image->columns=image->resolution.x*dimension_info.width/ DefaultSVGDensity; image->rows=image->resolution.y*dimension_info.height/ DefaultSVGDensity; } else { image->columns=dimension_info.width; image->rows=dimension_info.height; } pixel_info=(MemoryInfo *) NULL; #else pixel_buffer=rsvg_handle_get_pixbuf(svg_handle); rsvg_handle_free(svg_handle); image->columns=gdk_pixbuf_get_width(pixel_buffer); image->rows=gdk_pixbuf_get_height(pixel_buffer); #endif image->alpha_trait=BlendPixelTrait; if (image_info->ping == MagickFalse) { #if defined(MAGICKCORE_CAIRO_DELEGATE) size_t stride; #endif status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { #if !defined(MAGICKCORE_CAIRO_DELEGATE) g_object_unref(G_OBJECT(pixel_buffer)); #endif g_object_unref(svg_handle); ThrowReaderException(MissingDelegateError, ""NoDecodeDelegateForThisImageFormat""); } #if defined(MAGICKCORE_CAIRO_DELEGATE) stride=4*image->columns; #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int) image->columns); #endif pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); #endif (void) SetImageBackgroundColor(image,exception); #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface=cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int) stride); if ((cairo_surface == (cairo_surface_t *) NULL) || (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS)) { if (cairo_surface != (cairo_surface_t *) NULL) cairo_surface_destroy(cairo_surface); pixel_info=RelinquishVirtualMemory(pixel_info); g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } cairo_image=cairo_create(cairo_surface); cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR); cairo_paint(cairo_image); cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER); if (apply_density != MagickFalse) cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity, image->resolution.y/DefaultSVGDensity); rsvg_handle_render_cairo(svg_handle,cairo_image); cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); g_object_unref(svg_handle); p=pixels; #else p=gdk_pixbuf_get_pixels(pixel_buffer); #endif GetPixelInfo(image,&fill_color); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { #if defined(MAGICKCORE_CAIRO_DELEGATE) fill_color.blue=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.red=ScaleCharToQuantum(*p++); #else fill_color.red=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.blue=ScaleCharToQuantum(*p++); #endif fill_color.alpha=ScaleCharToQuantum(*p++); #if defined(MAGICKCORE_CAIRO_DELEGATE) { double gamma; gamma=QuantumScale*fill_color.alpha; gamma=PerceptibleReciprocal(gamma); fill_color.blue*=gamma; fill_color.green*=gamma; fill_color.red*=gamma; } #endif CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } #if defined(MAGICKCORE_CAIRO_DELEGATE) if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); #else g_object_unref(G_OBJECT(pixel_buffer)); #endif (void) CloseBlob(image); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); #endif } } /* Open draw file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,""w""); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) CopyMagickString(image->filename,filename,MagickPathExtent); ThrowFileException(exception,FileOpenError,""UnableToCreateTemporaryFile"", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Parse SVG file. */ svg_info=AcquireSVGInfo(); if (svg_info == (SVGInfo *) NULL) { (void) fclose(file); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } svg_info->file=file; svg_info->exception=exception; svg_info->image=image; svg_info->image_info=image_info; svg_info->bounds.width=image->columns; svg_info->bounds.height=image->rows; svg_info->svgDepth=0; if (image_info->size != (char *) NULL) (void) CloneString(&svg_info->size,image_info->size); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),""begin SAX""); xmlInitParser(); (void) xmlSubstituteEntitiesDefault(1); (void) memset(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=SVGInternalSubset; sax_modules.isStandalone=SVGIsStandalone; sax_modules.hasInternalSubset=SVGHasInternalSubset; sax_modules.hasExternalSubset=SVGHasExternalSubset; sax_modules.resolveEntity=SVGResolveEntity; sax_modules.getEntity=SVGGetEntity; sax_modules.entityDecl=SVGEntityDeclaration; sax_modules.notationDecl=SVGNotationDeclaration; sax_modules.attributeDecl=SVGAttributeDeclaration; sax_modules.elementDecl=SVGElementDeclaration; sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration; sax_modules.setDocumentLocator=SVGSetDocumentLocator; sax_modules.startDocument=SVGStartDocument; sax_modules.endDocument=SVGEndDocument; sax_modules.startElement=SVGStartElement; sax_modules.endElement=SVGEndElement; sax_modules.reference=SVGReference; sax_modules.characters=SVGCharacters; sax_modules.ignorableWhitespace=SVGIgnorableWhitespace; sax_modules.processingInstruction=SVGProcessingInstructions; sax_modules.comment=SVGComment; sax_modules.warning=SVGWarning; sax_modules.error=SVGError; sax_modules.fatalError=SVGError; sax_modules.getParameterEntity=SVGGetParameterEntity; sax_modules.cdataBlock=SVGCDataBlock; sax_modules.externalSubset=SVGExternalSubset; sax_handler=(&sax_modules); n=ReadBlob(image,MagickPathExtent-1,message); message[n]='\0'; if (n > 0) { svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *) message,n,image->filename); option=GetImageOption(image_info,""svg:xml-parse-huge""); if ((option != (char *) NULL) && (IsStringTrue(option) != MagickFalse)) (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE); while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0) { message[n]='\0'; status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0); if (status != 0) break; } } (void) xmlParseChunk(svg_info->parser,(char *) message,0,1); SVGEndDocument(svg_info); if (svg_info->parser->myDoc != (xmlDocPtr) NULL) xmlFreeDoc(svg_info->parser->myDoc); xmlFreeParserCtxt(svg_info->parser); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),""end SAX""); (void) fclose(file); (void) CloseBlob(image); image->columns=svg_info->width; image->rows=svg_info->height; if (exception->severity >= ErrorException) { svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); image=DestroyImage(image); return((Image *) NULL); } if (image_info->ping == MagickFalse) { ImageInfo *read_info; /* Draw image. */ image=DestroyImage(image); image=(Image *) NULL; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MagickPathExtent,""mvg:%s"", filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); } /* Relinquish resources. */ if (image != (Image *) NULL) { if (svg_info->title != (char *) NULL) (void) SetImageProperty(image,""svg:title"",svg_info->title,exception); if (svg_info->comment != (char *) NULL) (void) SetImageProperty(image,""svg:comment"",svg_info->comment, exception); } for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); return(GetFirstImageInList(image)); }",CWE-476,12 1,"enhanced_recursion( const char *p, TBOOLEAN brace, char *fontname, double fontsize, double base, TBOOLEAN widthflag, TBOOLEAN showflag, int overprint) { TBOOLEAN wasitalic, wasbold; /* Keep track of the style of the font passed in at this recursion level */ wasitalic = (strstr(fontname, "":Italic"") != NULL); wasbold = (strstr(fontname, "":Bold"") != NULL); FPRINTF((stderr, ""RECURSE WITH \""%s\"", %d %s %.1f %.1f %d %d %d"", p, brace, fontname, fontsize, base, widthflag, showflag, overprint)); /* Start each recursion with a clean string */ (term->enhanced_flush)(); if (base + fontsize > enhanced_max_height) { enhanced_max_height = base + fontsize; ENH_DEBUG((""Setting max height to %.1f\n"", enhanced_max_height)); } if (base < enhanced_min_height) { enhanced_min_height = base; ENH_DEBUG((""Setting min height to %.1f\n"", enhanced_min_height)); } while (*p) { double shift; /* * EAM Jun 2009 - treating bytes one at a time does not work for multibyte * encodings, including utf-8. If we hit a byte with the high bit set, test * whether it starts a legal UTF-8 sequence and if so copy the whole thing. * Other multibyte encodings are still a problem. * Gnuplot's other defined encodings are all single-byte; for those we * really do want to treat one byte at a time. */ if ((*p & 0x80) && (encoding == S_ENC_DEFAULT || encoding == S_ENC_UTF8)) { unsigned long utf8char; const char *nextchar = p; (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); if (utf8toulong(&utf8char, &nextchar)) { /* Legal UTF8 sequence */ while (p < nextchar) (term->enhanced_writec)(*p++); p--; } else { /* Some other multibyte encoding? */ (term->enhanced_writec)(*p); } /* shige : for Shift_JIS */ } else if ((*p & 0x80) && (encoding == S_ENC_SJIS)) { (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_writec)(*(p++)); (term->enhanced_writec)(*p); } else switch (*p) { case '}' : /*{{{ deal with it*/ if (brace) return (p); int_warn(NO_CARET, ""enhanced text parser - spurious }""); break; /*}}}*/ case '_' : case '^' : /*{{{ deal with super/sub script*/ shift = (*p == '^') ? 0.5 : -0.3; (term->enhanced_flush)(); p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8, base + shift * fontsize, widthflag, showflag, overprint); break; /*}}}*/ case '{' : { TBOOLEAN isitalic = FALSE, isbold = FALSE, isnormal = FALSE; const char *start_of_fontname = NULL; const char *end_of_fontname = NULL; char *localfontname = NULL; char ch; double f = fontsize, ovp; /* Mar 2014 - this will hold ""fontfamily{:Italic}{:Bold}"" */ char *styledfontname = NULL; /*{{{ recurse (possibly with a new font) */ ENH_DEBUG((""Dealing with {\n"")); /* 30 Sep 2016: Remove incorrect whitespace-eating loop going */ /* waaay back to 31-May-2000 */ /* while (*++p == ' '); */ ++p; /* get vertical offset (if present) for overprinted text */ if (overprint == 2) { char *end; ovp = strtod(p,&end); p = end; if (term->flags & TERM_IS_POSTSCRIPT) base = ovp*f; else base += ovp*f; } --p; if (*++p == '/') { /* then parse a fontname, optional fontsize */ while (*++p == ' ') ; /* do nothing */ if (*p=='-') { while (*++p == ' ') ; /* do nothing */ } start_of_fontname = p; /* Allow font name to be in quotes. * This makes it possible to handle font names containing spaces. */ if (*p == '\'' || *p == '""') { ++p; while (*p != '\0' && *p != '}' && *p != *start_of_fontname) ++p; if (*p != *start_of_fontname) { int_warn(NO_CARET, ""cannot interpret font name %s"", start_of_fontname); p = start_of_fontname; } start_of_fontname++; end_of_fontname = p++; ch = *p; } else { /* Normal unquoted font name */ while ((ch = *p) > ' ' && ch != '=' && ch != '*' && ch != '}' && ch != ':') ++p; end_of_fontname = p; } do { if (ch == '=') { /* get optional font size */ char *end; p++; ENH_DEBUG((""Calling strtod(\""%s\"") ..."", p)); f = strtod(p, &end); p = end; ENH_DEBUG((""Returned %.1f and \""%s\""\n"", f, p)); if (f == 0) f = fontsize; else f *= enhanced_fontscale; /* remember the scaling */ ENH_DEBUG((""Font size %.1f\n"", f)); } else if (ch == '*') { /* get optional font size scale factor */ char *end; p++; ENH_DEBUG((""Calling strtod(\""%s\"") ..."", p)); f = strtod(p, &end); p = end; ENH_DEBUG((""Returned %.1f and \""%s\""\n"", f, p)); if (f) f *= fontsize; /* apply the scale factor */ else f = fontsize; ENH_DEBUG((""Font size %.1f\n"", f)); } else if (ch == ':') { /* get optional style markup attributes */ p++; if (!strncmp(p,""Bold"",4)) isbold = TRUE; if (!strncmp(p,""Italic"",6)) isitalic = TRUE; if (!strncmp(p,""Normal"",6)) isnormal = TRUE; while (isalpha((unsigned char)*p)) {p++;} } } while (((ch = *p) == '=') || (ch == ':') || (ch == '*')); if (ch == '}') int_warn(NO_CARET,""bad syntax in enhanced text string""); if (*p == ' ') /* Eat up a single space following a font spec */ ++p; if (!start_of_fontname || (start_of_fontname == end_of_fontname)) { /* Use the font name passed in to us */ localfontname = gp_strdup(fontname); } else { /* We found a new font name {/Font ...} */ int len = end_of_fontname - start_of_fontname; localfontname = gp_alloc(len+1,""localfontname""); strncpy(localfontname, start_of_fontname, len); localfontname[len] = '\0'; } } /*}}}*/ /* Collect cumulative style markup before passing it in the font name */ isitalic = (wasitalic || isitalic) && !isnormal; isbold = (wasbold || isbold) && !isnormal; styledfontname = stylefont(localfontname ? localfontname : fontname, isbold, isitalic); p = enhanced_recursion(p, TRUE, styledfontname, f, base, widthflag, showflag, overprint); (term->enhanced_flush)(); free(styledfontname); free(localfontname); break; } /* case '{' */ case '@' : /*{{{ phantom box - prints next 'char', then restores currentpoint */ (term->enhanced_flush)(); (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4); break; /*}}}*/ case '&' : /*{{{ character skip - skips space equal to length of character(s) */ (term->enhanced_flush)(); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, FALSE, overprint); break; /*}}}*/ case '~' : /*{{{ overprinted text */ /* the second string is overwritten on the first, centered * horizontally on the first and (optionally) vertically * shifted by an amount specified (as a fraction of the * current fontsize) at the beginning of the second string * Note that in this implementation neither the under- nor * overprinted string can contain syntax that would result * in additional recursions -- no subscripts, * superscripts, or anything else, with the exception of a * font definition at the beginning of the text */ (term->enhanced_flush)(); p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, widthflag, showflag, 1); (term->enhanced_flush)(); if (!*p) break; p = enhanced_recursion(++p, FALSE, fontname, fontsize, base, FALSE, showflag, 2); overprint = 0; /* may not be necessary, but just in case . . . */ break; /*}}}*/ case '(' : case ')' : /*{{{ an escape and print it */ /* special cases */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); if (term->flags & TERM_IS_POSTSCRIPT) (term->enhanced_writec)('\\'); (term->enhanced_writec)(*p); break; /*}}}*/ case '\\' : /*{{{ various types of escape sequences, some context-dependent */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); /* Unicode represented as \U+hhhhh where hhhhh is hexadecimal code point. * For UTF-8 encoding we translate hhhhh to a UTF-8 byte sequence and * output the bytes one by one. */ if (p[1] == 'U' && p[2] == '+') { if (encoding == S_ENC_UTF8) { uint32_t codepoint; unsigned char utf8char[8]; int i, length; sscanf(&(p[3]), ""%5x"", &codepoint); length = ucs4toutf8(codepoint, utf8char); p += (codepoint > 0xFFFF) ? 7 : 6; for (i=0; ienhanced_writec)(utf8char[i]); break; } /* FIXME: non-utf8 environments not yet supported. * Note that some terminals may have an alternative way to handle unicode * escape sequences that is not dependent on encoding. * E.g. svg and html output could convert to xml sequences &#xhhhh; * For these cases we must retain the leading backslash so that the * unicode escape sequence can be recognized by the terminal driver. */ (term->enhanced_writec)(p[0]); break; } /* Enhanced mode always uses \xyz as an octal character representation * but each terminal type must give us the actual output format wanted. * pdf.trm wants the raw character code, which is why we use strtol(); * most other terminal types want some variant of ""\\%o"". */ if (p[1] >= '0' && p[1] <= '7') { char *e, escape[16], octal[4] = {'\0','\0','\0','\0'}; octal[0] = *(++p); if (p[1] >= '0' && p[1] <= '7') { octal[1] = *(++p); if (p[1] >= '0' && p[1] <= '7') octal[2] = *(++p); } sprintf(escape, enhanced_escape_format, strtol(octal,NULL,8)); for (e=escape; *e; e++) { (term->enhanced_writec)(*e); } break; } /* This was the original (prior to version 4) enhanced text code specific * to the reserved characters of PostScript. */ if (term->flags & TERM_IS_POSTSCRIPT) { if (p[1]=='\\' || p[1]=='(' || p[1]==')') { (term->enhanced_writec)('\\'); } else if (strchr(""^_@&~{}"",p[1]) == NULL) { (term->enhanced_writec)('\\'); (term->enhanced_writec)('\\'); break; } } /* Step past the backslash character in the input stream */ ++p; /* HBB: Avoid broken output if there's a \ exactly at the end of the line */ if (*p == '\0') { int_warn(NO_CARET, ""enhanced text parser -- spurious backslash""); break; } /* SVG requires an escaped '&' to be passed as something else */ /* FIXME: terminal-dependent code does not belong here */ if (*p == '&' && encoding == S_ENC_DEFAULT && !strcmp(term->name, ""svg"")) { (term->enhanced_writec)('\376'); break; } /* print the character following the backslash */ (term->enhanced_writec)(*p); break; /*}}}*/ default: /*{{{ print it */ (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint); (term->enhanced_writec)(*p); /*}}}*/ } /* switch (*p) */ /* like TeX, we only do one character in a recursion, unless it's * in braces */ if (!brace) { (term->enhanced_flush)(); return(p); /* the ++p in the outer copy will increment us */ } if (*p) /* only not true if { not terminated, I think */ ++p; } /* while (*p) */ (term->enhanced_flush)(); return p; }",CWE-787,16 0,"int BlobURLRequestJob::ComputeBytesToRead() const { int64 current_item_remaining_bytes = item_length_list_[item_index_] - current_item_offset_; int bytes_to_read = (read_buf_remaining_bytes_ > current_item_remaining_bytes) ? static_cast(current_item_remaining_bytes) : read_buf_remaining_bytes_; if (bytes_to_read > remaining_bytes_) bytes_to_read = static_cast(remaining_bytes_); return bytes_to_read; } ",none,24 0,"void SpeechSynthesis::speak(SpeechSynthesisUtterance* utterance, ExceptionState& exceptionState) { if (!utterance) { exceptionState.throwTypeError(""Invalid utterance argument""); return; } m_utteranceQueue.append(utterance); if (m_utteranceQueue.size() == 1) startSpeakingImmediately(); } ",none,24 0,"WebGraphicsContext3DDefaultImpl::~WebGraphicsContext3DDefaultImpl() { if (m_initialized) { makeContextCurrent(); if (m_attributes.antialias) { glDeleteRenderbuffersEXT(1, &m_multisampleColorBuffer); if (m_attributes.depth || m_attributes.stencil) glDeleteRenderbuffersEXT(1, &m_multisampleDepthStencilBuffer); glDeleteFramebuffersEXT(1, &m_multisampleFBO); } else { if (m_attributes.depth || m_attributes.stencil) glDeleteRenderbuffersEXT(1, &m_depthStencilBuffer); } glDeleteTextures(1, &m_texture); #ifdef FLIP_FRAMEBUFFER_VERTICALLY if (m_scanline) delete[] m_scanline; #endif glDeleteFramebuffersEXT(1, &m_fbo); m_glContext->Destroy(); for (ShaderSourceMap::iterator ii = m_shaderSourceMap.begin(); ii != m_shaderSourceMap.end(); ++ii) { if (ii->second) delete ii->second; } angleDestroyCompilers(); } } ",none,24 1,"gdImagePtr gdImageCreateFromXpm (char *filename) { XpmInfo info; XpmImage image; int i, j, k, number; char buf[5]; gdImagePtr im = 0; int *pointer; int red = 0, green = 0, blue = 0; int *colors; int ret; ret = XpmReadFileToXpmImage(filename, &image, &info); if (ret != XpmSuccess) { return 0; } if (!(im = gdImageCreate(image.width, image.height))) { goto done; } number = image.ncolors; colors = (int *) safe_emalloc(number, sizeof(int), 0); for (i = 0; i < number; i++) { switch (strlen (image.colorTable[i].c_color)) { case 4: buf[1] = '\0'; buf[0] = image.colorTable[i].c_color[1]; red = strtol(buf, NULL, 16); buf[0] = image.colorTable[i].c_color[2]; green = strtol(buf, NULL, 16); buf[0] = image.colorTable[i].c_color[3]; blue = strtol(buf, NULL, 16); break; case 7: buf[2] = '\0'; buf[0] = image.colorTable[i].c_color[1]; buf[1] = image.colorTable[i].c_color[2]; red = strtol(buf, NULL, 16); buf[0] = image.colorTable[i].c_color[3]; buf[1] = image.colorTable[i].c_color[4]; green = strtol(buf, NULL, 16); buf[0] = image.colorTable[i].c_color[5]; buf[1] = image.colorTable[i].c_color[6]; blue = strtol(buf, NULL, 16); break; case 10: buf[3] = '\0'; buf[0] = image.colorTable[i].c_color[1]; buf[1] = image.colorTable[i].c_color[2]; buf[2] = image.colorTable[i].c_color[3]; red = strtol(buf, NULL, 16); red /= 64; buf[0] = image.colorTable[i].c_color[4]; buf[1] = image.colorTable[i].c_color[5]; buf[2] = image.colorTable[i].c_color[6]; green = strtol(buf, NULL, 16); green /= 64; buf[0] = image.colorTable[i].c_color[7]; buf[1] = image.colorTable[i].c_color[8]; buf[2] = image.colorTable[i].c_color[9]; blue = strtol(buf, NULL, 16); blue /= 64; break; case 13: buf[4] = '\0'; buf[0] = image.colorTable[i].c_color[1]; buf[1] = image.colorTable[i].c_color[2]; buf[2] = image.colorTable[i].c_color[3]; buf[3] = image.colorTable[i].c_color[4]; red = strtol(buf, NULL, 16); red /= 256; buf[0] = image.colorTable[i].c_color[5]; buf[1] = image.colorTable[i].c_color[6]; buf[2] = image.colorTable[i].c_color[7]; buf[3] = image.colorTable[i].c_color[8]; green = strtol(buf, NULL, 16); green /= 256; buf[0] = image.colorTable[i].c_color[9]; buf[1] = image.colorTable[i].c_color[10]; buf[2] = image.colorTable[i].c_color[11]; buf[3] = image.colorTable[i].c_color[12]; blue = strtol(buf, NULL, 16); blue /= 256; break; } colors[i] = gdImageColorResolve(im, red, green, blue); } pointer = (int *) image.data; for (i = 0; i < image.height; i++) { for (j = 0; j < image.width; j++) { k = *pointer++; gdImageSetPixel(im, j, i, colors[k]); } } gdFree(colors); done: XpmFreeXpmImage(&image); XpmFreeXpmInfo(&info); return im; }",CWE-476,12 1,"GF_Descriptor *gf_isom_get_root_od(GF_ISOFile *movie) { GF_Descriptor *desc; GF_ObjectDescriptor *od; GF_InitialObjectDescriptor *iod; GF_IsomObjectDescriptor *isom_od; GF_IsomInitialObjectDescriptor *isom_iod; GF_ESD *esd; GF_ES_ID_Inc *inc; u32 i; u8 useIOD; if (!movie || !movie->moov) return NULL; if (!movie->moov->iods) return NULL; if (movie->disable_odf_translate) { //duplicate our descriptor movie->LastError = gf_odf_desc_copy((GF_Descriptor *) movie->moov->iods->descriptor, &desc); if (movie->LastError) return NULL; return desc; } od = NULL; iod = NULL; switch (movie->moov->iods->descriptor->tag) { case GF_ODF_ISOM_OD_TAG: od = (GF_ObjectDescriptor*)gf_malloc(sizeof(GF_ObjectDescriptor)); if (!od) return NULL; memset(od, 0, sizeof(GF_ObjectDescriptor)); od->ESDescriptors = gf_list_new(); useIOD = 0; break; case GF_ODF_ISOM_IOD_TAG: iod = (GF_InitialObjectDescriptor*)gf_malloc(sizeof(GF_InitialObjectDescriptor)); if (!iod) return NULL; memset(iod, 0, sizeof(GF_InitialObjectDescriptor)); iod->ESDescriptors = gf_list_new(); useIOD = 1; break; default: return NULL; } //duplicate our descriptor movie->LastError = gf_odf_desc_copy((GF_Descriptor *) movie->moov->iods->descriptor, &desc); if (movie->LastError) return NULL; if (!useIOD) { isom_od = (GF_IsomObjectDescriptor *)desc; od->objectDescriptorID = isom_od->objectDescriptorID; od->extensionDescriptors = isom_od->extensionDescriptors; isom_od->extensionDescriptors = NULL; od->IPMP_Descriptors = isom_od->IPMP_Descriptors; isom_od->IPMP_Descriptors = NULL; od->OCIDescriptors = isom_od->OCIDescriptors; isom_od->OCIDescriptors = NULL; od->URLString = isom_od->URLString; isom_od->URLString = NULL; od->tag = GF_ODF_OD_TAG; //then recreate the desc in Inc i=0; while ((inc = (GF_ES_ID_Inc*)gf_list_enum(isom_od->ES_ID_IncDescriptors, &i))) { movie->LastError = GetESDForTime(movie->moov, inc->trackID, 0, &esd); if (!movie->LastError) movie->LastError = gf_list_add(od->ESDescriptors, esd); if (movie->LastError) { gf_odf_desc_del(desc); gf_odf_desc_del((GF_Descriptor *) od); return NULL; } } gf_odf_desc_del(desc); return (GF_Descriptor *)od; } else { isom_iod = (GF_IsomInitialObjectDescriptor *)desc; iod->objectDescriptorID = isom_iod->objectDescriptorID; iod->extensionDescriptors = isom_iod->extensionDescriptors; isom_iod->extensionDescriptors = NULL; iod->IPMP_Descriptors = isom_iod->IPMP_Descriptors; isom_iod->IPMP_Descriptors = NULL; iod->OCIDescriptors = isom_iod->OCIDescriptors; isom_iod->OCIDescriptors = NULL; iod->URLString = isom_iod->URLString; isom_iod->URLString = NULL; iod->tag = GF_ODF_IOD_TAG; iod->audio_profileAndLevel = isom_iod->audio_profileAndLevel; iod->graphics_profileAndLevel = isom_iod->graphics_profileAndLevel; iod->inlineProfileFlag = isom_iod->inlineProfileFlag; iod->OD_profileAndLevel = isom_iod->OD_profileAndLevel; iod->scene_profileAndLevel = isom_iod->scene_profileAndLevel; iod->visual_profileAndLevel = isom_iod->visual_profileAndLevel; iod->IPMPToolList = isom_iod->IPMPToolList; isom_iod->IPMPToolList = NULL; //then recreate the desc in Inc i=0; while ((inc = (GF_ES_ID_Inc*)gf_list_enum(isom_iod->ES_ID_IncDescriptors, &i))) { movie->LastError = GetESDForTime(movie->moov, inc->trackID, 0, &esd); if (!movie->LastError) movie->LastError = gf_list_add(iod->ESDescriptors, esd); if (movie->LastError) { gf_odf_desc_del(desc); gf_odf_desc_del((GF_Descriptor *) iod); return NULL; } } gf_odf_desc_del(desc); return (GF_Descriptor *)iod; } }",CWE-787,16 1,"GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs) { GF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s; int i; u32 tmp_strsize; char *tmp_str; GF_Err e; ISOM_DECREASE_SIZE(ptr, 25) ptr->bootstrapinfo_version = gf_bs_read_u32(bs); ptr->profile = gf_bs_read_int(bs, 2); ptr->live = gf_bs_read_int(bs, 1); ptr->update = gf_bs_read_int(bs, 1); ptr->reserved = gf_bs_read_int(bs, 4); ptr->time_scale = gf_bs_read_u32(bs); ptr->current_media_time = gf_bs_read_u64(bs); ptr->smpte_time_code_offset = gf_bs_read_u64(bs); i=0; if (ptr->size<8) return GF_ISOM_INVALID_FILE; tmp_strsize =(u32)ptr->size; tmp_str = gf_malloc(sizeof(char)*tmp_strsize); if (!tmp_str) return GF_OUT_OF_MEM; memset(tmp_str, 0, sizeof(char)*tmp_strsize); while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) break; i++; } if (i) { ptr->movie_identifier = gf_strdup(tmp_str); } ISOM_DECREASE_SIZE(ptr, 1) ptr->server_entry_count = gf_bs_read_u8(bs); for (i=0; iserver_entry_count; i++) { int j=0; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[j] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[j]) break; j++; } if (j) { gf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i); } } ISOM_DECREASE_SIZE(ptr, 1) ptr->quality_entry_count = gf_bs_read_u8(bs); for (i=0; iquality_entry_count; i++) { int j=0; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[j] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[j]) break; j++; } if (j) { gf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i); } } i=0; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) break; i++; } if (i) { ptr->drm_data = gf_strdup(tmp_str); } i=0; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) break; i++; } if (i) { ptr->meta_data = gf_strdup(tmp_str); } ISOM_DECREASE_SIZE(ptr, 1) ptr->segment_run_table_count = gf_bs_read_u8(bs); for (i=0; isegment_run_table_count; i++) { GF_AdobeSegmentRunTableBox *asrt = NULL; e = gf_isom_box_parse((GF_Box **)&asrt, bs); if (e) { if (asrt) gf_isom_box_del((GF_Box*)asrt); gf_free(tmp_str); return e; } gf_list_add(ptr->segment_run_table_entries, asrt); } ISOM_DECREASE_SIZE(ptr, 1) ptr->fragment_run_table_count = gf_bs_read_u8(bs); for (i=0; ifragment_run_table_count; i++) { GF_AdobeFragmentRunTableBox *afrt = NULL; e = gf_isom_box_parse((GF_Box **)&afrt, bs); if (e) { if (afrt) gf_isom_box_del((GF_Box*)afrt); gf_free(tmp_str); return e; } gf_list_add(ptr->fragment_run_table_entries, afrt); } gf_free(tmp_str); return GF_OK; }",CWE-787,16 1,"GF_Err gf_hinter_track_finalize(GF_RTPHinter *tkHint, Bool AddSystemInfo) { u32 Width, Height; GF_ESD *esd; char sdpLine[20000]; char mediaName[30], payloadName[30]; u32 mtype; Width = Height = 0; gf_isom_sdp_clean_track(tkHint->file, tkHint->TrackNum); mtype = gf_isom_get_media_type(tkHint->file, tkHint->TrackNum); if (gf_isom_is_video_handler_type(mtype)) gf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height); gf_rtp_builder_get_payload_name(tkHint->rtp_p, payloadName, mediaName); /*TODO- extract out of rtp_p for future live tools*/ sprintf(sdpLine, ""m=%s 0 RTP/%s %d"", mediaName, tkHint->rtp_p->slMap.IV_length ? ""SAVP"" : ""AVP"", tkHint->rtp_p->PayloadType); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); if (tkHint->bandwidth) { sprintf(sdpLine, ""b=AS:%d"", tkHint->bandwidth); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } if (tkHint->nb_chan) { sprintf(sdpLine, ""a=rtpmap:%d %s/%d/%d"", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution, tkHint->nb_chan); } else { sprintf(sdpLine, ""a=rtpmap:%d %s/%d"", tkHint->rtp_p->PayloadType, payloadName, tkHint->rtp_p->sl_config.timestampResolution); } gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); /*control for MPEG-4*/ if (AddSystemInfo) { sprintf(sdpLine, ""a=mpeg4-esid:%d"", gf_isom_get_track_id(tkHint->file, tkHint->TrackNum)); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*control for QTSS/DSS*/ sprintf(sdpLine, ""a=control:trackID=%d"", gf_isom_get_track_id(tkHint->file, tkHint->HintTrack)); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); /*H263 extensions*/ if (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H263) { sprintf(sdpLine, ""a=cliprect:0,0,%d,%d"", Height, Width); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*AMR*/ else if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_AMR_WB)) { sprintf(sdpLine, ""a=fmtp:%d octet-align=1"", tkHint->rtp_p->PayloadType); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*Text*/ else if (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_3GPP_TEXT) { u32 w, h, i, m_w, m_h; s32 tx, ty; s16 l; gf_isom_get_track_layout_info(tkHint->file, tkHint->TrackNum, &w, &h, &tx, &ty, &l); m_w = w; m_h = h; for (i=0; ifile); i++) { switch (gf_isom_get_media_type(tkHint->file, i+1)) { case GF_ISOM_MEDIA_SCENE: case GF_ISOM_MEDIA_VISUAL: case GF_ISOM_MEDIA_AUXV: case GF_ISOM_MEDIA_PICT: gf_isom_get_track_layout_info(tkHint->file, i+1, &w, &h, &tx, &ty, &l); if (w>m_w) m_w = w; if (h>m_h) m_h = h; break; default: break; } } gf_media_format_ttxt_sdp(tkHint->rtp_p, payloadName, sdpLine, w, h, tx, ty, l, m_w, m_h, NULL); strcat(sdpLine, ""; tx3g=""); for (i=0; ifile, tkHint->TrackNum); i++) { u8 *tx3g; char buffer[2000]; u32 tx3g_len, len; gf_isom_text_get_encoded_tx3g(tkHint->file, tkHint->TrackNum, i+1, GF_RTP_TX3G_SIDX_OFFSET, &tx3g, &tx3g_len); len = gf_base64_encode(tx3g, tx3g_len, buffer, 2000); gf_free(tx3g); buffer[len] = 0; if (i) strcat(sdpLine, "", ""); strcat(sdpLine, buffer); } gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*EVRC/SMV in non header-free mode*/ else if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_EVRC_SMV) && (tkHint->rtp_p->auh_size>1)) { sprintf(sdpLine, ""a=fmtp:%d maxptime=%d"", tkHint->rtp_p->PayloadType, tkHint->rtp_p->auh_size*20); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*H264/AVC*/ else if ((tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_AVC) || (tkHint->rtp_p->rtp_payt == GF_RTP_PAYT_H264_SVC)) { GF_AVCConfig *avcc = gf_isom_avc_config_get(tkHint->file, tkHint->TrackNum, 1); GF_AVCConfig *svcc = gf_isom_svc_config_get(tkHint->file, tkHint->TrackNum, 1); /*TODO - check syntax for SVC (might be some extra signaling)*/ if (avcc) { sprintf(sdpLine, ""a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1"", tkHint->rtp_p->PayloadType, avcc->AVCProfileIndication, avcc->profile_compatibility, avcc->AVCLevelIndication); } else { sprintf(sdpLine, ""a=fmtp:%d profile-level-id=%02X%02X%02X; packetization-mode=1"", tkHint->rtp_p->PayloadType, svcc->AVCProfileIndication, svcc->profile_compatibility, svcc->AVCLevelIndication); } write_avc_config(sdpLine, avcc, svcc); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); gf_odf_avc_cfg_del(avcc); gf_odf_avc_cfg_del(svcc); } /*MPEG-4 decoder config*/ else if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_MPEG4) { esd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1); if (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) { gf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength); } else { gf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, NULL, 0); } if (esd) gf_odf_desc_del((GF_Descriptor *)esd); if (tkHint->rtp_p->slMap.IV_length) { const char *kms; gf_isom_get_ismacryp_info(tkHint->file, tkHint->TrackNum, 1, NULL, NULL, NULL, NULL, &kms, NULL, NULL, NULL); if (!strnicmp(kms, ""(key)"", 5) || !strnicmp(kms, ""(ipmp)"", 6) || !strnicmp(kms, ""(uri)"", 5)) { strcat(sdpLine, ""; ISMACrypKey=""); } else { strcat(sdpLine, ""; ISMACrypKey=(uri)""); } strcat(sdpLine, kms); } gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } /*MPEG-4 Audio LATM*/ else if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_LATM) { GF_BitStream *bs; u8 *config_bytes; u32 config_size; /* form config string */ bs = gf_bs_new(NULL, 32, GF_BITSTREAM_WRITE); gf_bs_write_int(bs, 0, 1); /* AudioMuxVersion */ gf_bs_write_int(bs, 1, 1); /* all streams same time */ gf_bs_write_int(bs, 0, 6); /* numSubFrames */ gf_bs_write_int(bs, 0, 4); /* numPrograms */ gf_bs_write_int(bs, 0, 3); /* numLayer */ /* audio-specific config */ esd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1); if (esd && esd->decoderConfig && esd->decoderConfig->decoderSpecificInfo) { /*PacketVideo patch: don't signal SBR and PS stuff, not allowed in LATM with audioMuxVersion=0*/ gf_bs_write_data(bs, esd->decoderConfig->decoderSpecificInfo->data, MIN(esd->decoderConfig->decoderSpecificInfo->dataLength, 2) ); } if (esd) gf_odf_desc_del((GF_Descriptor *)esd); /* other data */ gf_bs_write_int(bs, 0, 3); /* frameLengthType */ gf_bs_write_int(bs, 0xff, 8); /* latmBufferFullness */ gf_bs_write_int(bs, 0, 1); /* otherDataPresent */ gf_bs_write_int(bs, 0, 1); /* crcCheckPresent */ gf_bs_get_content(bs, &config_bytes, &config_size); gf_bs_del(bs); gf_rtp_builder_format_sdp(tkHint->rtp_p, payloadName, sdpLine, config_bytes, config_size); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); gf_free(config_bytes); } #if GPAC_ENABLE_3GPP_DIMS_RTP /*3GPP DIMS*/ else if (tkHint->rtp_p->rtp_payt==GF_RTP_PAYT_3GPP_DIMS) { GF_DIMSDescription dims; gf_isom_get_visual_info(tkHint->file, tkHint->TrackNum, 1, &Width, &Height); gf_isom_get_dims_description(tkHint->file, tkHint->TrackNum, 1, &dims); sprintf(sdpLine, ""a=fmtp:%d Version-profile=%d"", tkHint->rtp_p->PayloadType, dims.profile); if (! dims.fullRequestHost) { char fmt[200]; strcat(sdpLine, "";useFullRequestHost=0""); sprintf(fmt, "";pathComponents=%d"", dims.pathComponents); strcat(sdpLine, fmt); } if (!dims.streamType) strcat(sdpLine, "";stream-type=secondary""); if (dims.containsRedundant == 1) strcat(sdpLine, "";contains-redundant=main""); else if (dims.containsRedundant == 2) strcat(sdpLine, "";contains-redundant=redundant""); if (dims.textEncoding && strlen(dims.textEncoding)) { strcat(sdpLine, "";text-encoding=""); strcat(sdpLine, dims.textEncoding); } if (dims.contentEncoding && strlen(dims.contentEncoding)) { strcat(sdpLine, "";content-coding=""); strcat(sdpLine, dims.contentEncoding); } if (dims.contentEncoding && dims.content_script_types && strlen(dims.content_script_types) ) { strcat(sdpLine, "";content-script-types=""); strcat(sdpLine, dims.contentEncoding); } gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } #endif /*extensions for some mobile phones*/ if (Width && Height) { sprintf(sdpLine, ""a=framesize:%d %d-%d"", tkHint->rtp_p->PayloadType, Width, Height); gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } esd = gf_isom_get_esd(tkHint->file, tkHint->TrackNum, 1); if (esd && esd->decoderConfig && (esd->decoderConfig->rvc_config || esd->decoderConfig->predefined_rvc_config)) { if (esd->decoderConfig->predefined_rvc_config) { sprintf(sdpLine, ""a=rvc-config-predef:%d"", esd->decoderConfig->predefined_rvc_config); } else { /*temporary ...*/ if ((esd->decoderConfig->objectTypeIndication==GF_CODECID_AVC) || (esd->decoderConfig->objectTypeIndication==GF_CODECID_SVC)) { sprintf(sdpLine, ""a=rvc-config:%s"", ""http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_avc.xml""); } else { sprintf(sdpLine, ""a=rvc-config:%s"", ""http://download.tsi.telecom-paristech.fr/gpac/RVC/rvc_config_sp.xml""); } } gf_isom_sdp_add_track_line(tkHint->file, tkHint->HintTrack, sdpLine); } if (esd) gf_odf_desc_del((GF_Descriptor *)esd); gf_isom_set_track_enabled(tkHint->file, tkHint->HintTrack, GF_TRUE); return GF_OK; }",CWE-476,12 0," void Initialize() { EXPECT_CALL(*this, FrameReady(media::VideoDecoder::kOk, _)); decoder_->Read(read_cb_); EXPECT_CALL(*vc_manager_, AddDevice(_, _)) .WillOnce(Return(vc_impl_.get())); int buffer_count = 1; EXPECT_CALL(*vc_impl_, StartCapture(capture_client(), _)) .Times(1) .WillOnce(CreateDataBufferFromCapture(capture_client(), vc_impl_.get(), buffer_count)); EXPECT_CALL(*vc_impl_, FeedBuffer(_)) .Times(buffer_count) .WillRepeatedly(DeleteDataBuffer()); decoder_->Initialize(NULL, media::NewExpectedStatusCB(media::PIPELINE_OK), NewStatisticsCB()); message_loop_->RunAllPending(); } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::supportsMapSubCHROMIUM() { return false; } ",none,24 1,"BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, ""Stream_GetRemainingLength(s) < 2""); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, ""%s Update Data PDU"", UPDATE_TYPE_STRINGS[updateType]); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, ""UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed""); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, ""UPDATE_TYPE_PALETTE - update_read_palette() failed""); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, ""UPDATE_TYPE %s [%"" PRIu16 ""] failed"", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; }",CWE-125,1 1,"int nested_svm_vmrun(struct vcpu_svm *svm) { int ret; struct vmcb *vmcb12; struct vmcb *hsave = svm->nested.hsave; struct vmcb *vmcb = svm->vmcb; struct kvm_host_map map; u64 vmcb12_gpa; if (is_smm(&svm->vcpu)) { kvm_queue_exception(&svm->vcpu, UD_VECTOR); return 1; } vmcb12_gpa = svm->vmcb->save.rax; ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb12_gpa), &map); if (ret == -EINVAL) { kvm_inject_gp(&svm->vcpu, 0); return 1; } else if (ret) { return kvm_skip_emulated_instruction(&svm->vcpu); } ret = kvm_skip_emulated_instruction(&svm->vcpu); vmcb12 = map.hva; if (WARN_ON_ONCE(!svm->nested.initialized)) return -EINVAL; if (!nested_vmcb_checks(svm, vmcb12)) { vmcb12->control.exit_code = SVM_EXIT_ERR; vmcb12->control.exit_code_hi = 0; vmcb12->control.exit_info_1 = 0; vmcb12->control.exit_info_2 = 0; goto out; } trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb12_gpa, vmcb12->save.rip, vmcb12->control.int_ctl, vmcb12->control.event_inj, vmcb12->control.nested_ctl); trace_kvm_nested_intercepts(vmcb12->control.intercepts[INTERCEPT_CR] & 0xffff, vmcb12->control.intercepts[INTERCEPT_CR] >> 16, vmcb12->control.intercepts[INTERCEPT_EXCEPTION], vmcb12->control.intercepts[INTERCEPT_WORD3], vmcb12->control.intercepts[INTERCEPT_WORD4], vmcb12->control.intercepts[INTERCEPT_WORD5]); /* Clear internal status */ kvm_clear_exception_queue(&svm->vcpu); kvm_clear_interrupt_queue(&svm->vcpu); /* * Save the old vmcb, so we don't need to pick what we save, but can * restore everything when a VMEXIT occurs */ hsave->save.es = vmcb->save.es; hsave->save.cs = vmcb->save.cs; hsave->save.ss = vmcb->save.ss; hsave->save.ds = vmcb->save.ds; hsave->save.gdtr = vmcb->save.gdtr; hsave->save.idtr = vmcb->save.idtr; hsave->save.efer = svm->vcpu.arch.efer; hsave->save.cr0 = kvm_read_cr0(&svm->vcpu); hsave->save.cr4 = svm->vcpu.arch.cr4; hsave->save.rflags = kvm_get_rflags(&svm->vcpu); hsave->save.rip = kvm_rip_read(&svm->vcpu); hsave->save.rsp = vmcb->save.rsp; hsave->save.rax = vmcb->save.rax; if (npt_enabled) hsave->save.cr3 = vmcb->save.cr3; else hsave->save.cr3 = kvm_read_cr3(&svm->vcpu); copy_vmcb_control_area(&hsave->control, &vmcb->control); svm->nested.nested_run_pending = 1; if (enter_svm_guest_mode(svm, vmcb12_gpa, vmcb12)) goto out_exit_err; if (nested_svm_vmrun_msrpm(svm)) goto out; out_exit_err: svm->nested.nested_run_pending = 0; svm->vmcb->control.exit_code = SVM_EXIT_ERR; svm->vmcb->control.exit_code_hi = 0; svm->vmcb->control.exit_info_1 = 0; svm->vmcb->control.exit_info_2 = 0; nested_svm_vmexit(svm); out: kvm_vcpu_unmap(&svm->vcpu, &map, true); return ret; }",CWE-416,10 0,"void BlobURLRequestJob::DidOpen(base::PlatformFileError rv, base::PassPlatformFile file, bool created) { if (rv != base::PLATFORM_FILE_OK) { NotifyFailure(net::ERR_FAILED); return; } DCHECK(!stream_.get()); stream_.reset(new net::FileStream(file.ReleaseValue(), kFileOpenFlags)); const BlobData::Item& item = blob_data_->items().at(item_index_); { base::ThreadRestrictions::ScopedAllowIO allow_io; int64 offset = current_item_offset_ + static_cast(item.offset()); if (offset > 0 && offset != stream_->Seek(net::FROM_BEGIN, offset)) { NotifyFailure(net::ERR_FAILED); return; } } ReadFile(item); } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::copyTexImage2D(unsigned long target, long level, unsigned long internalformat, long x, long y, unsigned long width, unsigned long height, long border) { makeContextCurrent(); bool needsResolve = (m_attributes.antialias && m_boundFBO == m_multisampleFBO); if (needsResolve) { resolveMultisampledFramebuffer(x, y, width, height); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); } glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); if (needsResolve) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); } ",none,24 0,"void BlobURLRequestJob::AdvanceBytesRead(int result) { DCHECK_GT(result, 0); current_item_offset_ += result; if (current_item_offset_ == item_length_list_[item_index_]) AdvanceItem(); remaining_bytes_ -= result; DCHECK_GE(remaining_bytes_, 0); read_buf_offset_ += result; read_buf_remaining_bytes_ -= result; DCHECK_GE(read_buf_remaining_bytes_, 0); } ",none,24 0,"bool BlobURLRequestJob::DispatchReadFile(const BlobData::Item& item) { if (stream_ != NULL) return ReadFile(item); base::FileUtilProxy::CreateOrOpen( file_thread_proxy_, item.file_path(), kFileOpenFlags, callback_factory_.NewCallback(&BlobURLRequestJob::DidOpen)); SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); return false; } ",none,24 1," void Compute(OpKernelContext* ctx) override { const Tensor& shape_tensor = ctx->input(0); const Tensor& means_tensor = ctx->input(1); const Tensor& stddevs_tensor = ctx->input(2); const Tensor& minvals_tensor = ctx->input(3); const Tensor& maxvals_tensor = ctx->input(4); OP_REQUIRES( ctx, TensorShapeUtils::IsVector(shape_tensor.shape()), errors::InvalidArgument(""Input shape should be a vector, got shape: "", shape_tensor.shape().DebugString())); int32 num_batches = shape_tensor.flat()(0); int32 samples_per_batch = 1; const int32 num_dims = shape_tensor.dim_size(0); for (int32 i = 1; i < num_dims; i++) { samples_per_batch *= shape_tensor.flat()(i); } const int32 num_elements = num_batches * samples_per_batch; // Allocate the output before fudging num_batches and samples_per_batch. auto shape_vec = shape_tensor.flat(); TensorShape tensor_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( shape_vec.data(), shape_vec.size(), &tensor_shape)); Tensor* samples_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor)); // Parameters must be 0-d or 1-d. OP_REQUIRES(ctx, means_tensor.dims() <= 1, errors::InvalidArgument( ""Input means should be a scalar or vector, got shape: "", means_tensor.shape().DebugString())); OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1, errors::InvalidArgument( ""Input stddevs should be a scalar or vector, got shape: "", stddevs_tensor.shape().DebugString())); OP_REQUIRES(ctx, minvals_tensor.dims() <= 1, errors::InvalidArgument( ""Input minvals should be a scalar or vector, got shape: "", minvals_tensor.shape().DebugString())); OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1, errors::InvalidArgument( ""Input maxvals should be a scalar or vector, got shape: "", maxvals_tensor.shape().DebugString())); if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) && (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) && minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) { // All batches have the same parameters, so we can update the batch size // to a reasonable value to improve parallelism (ensure enough batches, // and no very small batches which have high overhead). int32 size = num_batches * samples_per_batch; int32 adjusted_samples = kDesiredBatchSize; // Ensure adjusted_batches * adjusted_samples >= size. int32 adjusted_batches = Eigen::divup(size, adjusted_samples); num_batches = adjusted_batches; samples_per_batch = adjusted_samples; } else { // Parameters must be broadcastable to the shape [num_batches]. OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(means_tensor.shape()) || means_tensor.dim_size(0) == 1 || means_tensor.dim_size(0) == num_batches, errors::InvalidArgument( ""Input means should have length 1 or shape[0], got shape: "", means_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(stddevs_tensor.shape()) || stddevs_tensor.dim_size(0) == 1 || stddevs_tensor.dim_size(0) == num_batches, errors::InvalidArgument( ""Input stddevs should have length 1 or shape[0], got shape: "", stddevs_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(minvals_tensor.shape()) || minvals_tensor.dim_size(0) == 1 || minvals_tensor.dim_size(0) == num_batches, errors::InvalidArgument( ""Input minvals should have length 1 or shape[0], got shape: "", minvals_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(maxvals_tensor.shape()) || maxvals_tensor.dim_size(0) == 1 || maxvals_tensor.dim_size(0) == num_batches, errors::InvalidArgument( ""Input maxvals should have length 1 or shape[0], got shape: "", maxvals_tensor.shape().DebugString())); } auto truncFunctor = functor::TruncatedNormalFunctor(); // Each worker has the fudge factor for samples_per_batch, so use it here. random::PhiloxRandom rng = generator_.ReserveSamples128(num_batches * 2 * functor::kMaxIterations * (samples_per_batch + 3) / 4); truncFunctor(ctx, ctx->eigen_device(), num_batches, samples_per_batch, num_elements, means_tensor.flat(), stddevs_tensor.flat(), minvals_tensor.flat(), maxvals_tensor.flat(), rng, samples_tensor->flat()); }",CWE-125,1 0,"DataObjectItem* DataObjectItem::CreateFromFileWithFileSystemId( File* file, const String& file_system_id) { DataObjectItem* item = MakeGarbageCollected(kFileKind, file->type()); item->file_ = file; item->file_system_id_ = file_system_id; return item; } ",none,24 0,"void SearchEngineTabHelper::OnDownloadedOSDD( scoped_ptr template_url) { Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); delegate_->ConfirmAddSearchProvider(template_url.release(), profile); } ",none,24 1,"static int process_base_block(struct archive_read* a, struct archive_entry* entry) { struct rar5* rar = get_context(a); uint32_t hdr_crc, computed_crc; size_t raw_hdr_size = 0, hdr_size_len, hdr_size; size_t header_id = 0; size_t header_flags = 0; const uint8_t* p; int ret; enum HEADER_TYPE { HEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02, HEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05, HEAD_UNKNOWN = 0xff, }; /* Skip any unprocessed data for this file. */ ret = skip_unprocessed_bytes(a); if(ret != ARCHIVE_OK) return ret; /* Read the expected CRC32 checksum. */ if(!read_u32(a, &hdr_crc)) { return ARCHIVE_EOF; } /* Read header size. */ if(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) { return ARCHIVE_EOF; } /* Sanity check, maximum header size for RAR5 is 2MB. */ if(raw_hdr_size > (2 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Base block header is too large""); return ARCHIVE_FATAL; } hdr_size = raw_hdr_size + hdr_size_len; /* Read the whole header data into memory, maximum memory use here is * 2MB. */ if(!read_ahead(a, hdr_size, &p)) { return ARCHIVE_EOF; } /* Verify the CRC32 of the header data. */ computed_crc = (uint32_t) crc32(0, p, (int) hdr_size); if(computed_crc != hdr_crc) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Header CRC error""); return ARCHIVE_FATAL; } /* If the checksum is OK, we proceed with parsing. */ if(ARCHIVE_OK != consume(a, hdr_size_len)) { return ARCHIVE_EOF; } if(!read_var_sized(a, &header_id, NULL)) return ARCHIVE_EOF; if(!read_var_sized(a, &header_flags, NULL)) return ARCHIVE_EOF; rar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0; rar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0; rar->generic.size = (int)hdr_size; rar->generic.last_header_id = (int)header_id; rar->main.endarc = 0; /* Those are possible header ids in RARv5. */ switch(header_id) { case HEAD_MAIN: ret = process_head_main(a, rar, entry, header_flags); /* Main header doesn't have any files in it, so it's * pointless to return to the caller. Retry to next * header, which should be HEAD_FILE/HEAD_SERVICE. */ if(ret == ARCHIVE_OK) return ARCHIVE_RETRY; return ret; case HEAD_SERVICE: ret = process_head_service(a, rar, entry, header_flags); return ret; case HEAD_FILE: ret = process_head_file(a, rar, entry, header_flags); return ret; case HEAD_CRYPT: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Encryption is not supported""); return ARCHIVE_FATAL; case HEAD_ENDARC: rar->main.endarc = 1; /* After encountering an end of file marker, we need * to take into consideration if this archive is * continued in another file (i.e. is it part01.rar: * is there a part02.rar?) */ if(rar->main.volume) { /* In case there is part02.rar, position the * read pointer in a proper place, so we can * resume parsing. */ ret = scan_for_signature(a); if(ret == ARCHIVE_FATAL) { return ARCHIVE_EOF; } else { if(rar->vol.expected_vol_no == UINT_MAX) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Header error""); return ARCHIVE_FATAL; } rar->vol.expected_vol_no = rar->main.vol_no + 1; return ARCHIVE_OK; } } else { return ARCHIVE_EOF; } case HEAD_MARK: return ARCHIVE_EOF; default: if((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Header type error""); return ARCHIVE_FATAL; } else { /* If the block is marked as 'skip if unknown', * do as the flag says: skip the block * instead on failing on it. */ return ARCHIVE_RETRY; } } #if !defined WIN32 // Not reached. archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER, ""Internal unpacker error""); return ARCHIVE_FATAL; #endif }",CWE-125,1 0,"bool BlobURLRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size, int* bytes_read) { DCHECK_NE(dest_size, 0); DCHECK(bytes_read); DCHECK_GE(remaining_bytes_, 0); if (error_) { *bytes_read = 0; return true; } if (remaining_bytes_ < dest_size) dest_size = static_cast(remaining_bytes_); if (!dest_size) { *bytes_read = 0; return true; } DCHECK(!read_buf_); read_buf_ = dest; read_buf_offset_ = 0; read_buf_size_ = dest_size; read_buf_remaining_bytes_ = dest_size; return ReadLoop(bytes_read); } ",none,24 1,"bool FromkLinuxSockAddr(const struct klinux_sockaddr *input, socklen_t input_len, struct sockaddr *output, socklen_t *output_len, void (*abort_handler)(const char *)) { if (!input || !output || !output_len || input_len == 0) { output = nullptr; return false; } int16_t klinux_family = input->klinux_sa_family; if (klinux_family == kLinux_AF_UNIX) { struct klinux_sockaddr_un *klinux_sockaddr_un_in = const_cast( reinterpret_cast(input)); struct sockaddr_un sockaddr_un_out; sockaddr_un_out.sun_family = AF_UNIX; InitializeToZeroArray(sockaddr_un_out.sun_path); ReinterpretCopyArray( sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path, std::min(sizeof(sockaddr_un_out.sun_path), sizeof(klinux_sockaddr_un_in->klinux_sun_path))); CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len); } else if (klinux_family == kLinux_AF_INET) { struct klinux_sockaddr_in *klinux_sockaddr_in_in = const_cast( reinterpret_cast(input)); struct sockaddr_in sockaddr_in_out; sockaddr_in_out.sin_family = AF_INET; sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port; InitializeToZeroSingle(&sockaddr_in_out.sin_addr); ReinterpretCopySingle(&sockaddr_in_out.sin_addr, &klinux_sockaddr_in_in->klinux_sin_addr); InitializeToZeroArray(sockaddr_in_out.sin_zero); ReinterpretCopyArray(sockaddr_in_out.sin_zero, klinux_sockaddr_in_in->klinux_sin_zero); CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len); } else if (klinux_family == kLinux_AF_INET6) { struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in = const_cast( reinterpret_cast(input)); struct sockaddr_in6 sockaddr_in6_out; sockaddr_in6_out.sin6_family = AF_INET6; sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port; sockaddr_in6_out.sin6_flowinfo = klinux_sockaddr_in6_in->klinux_sin6_flowinfo; sockaddr_in6_out.sin6_scope_id = klinux_sockaddr_in6_in->klinux_sin6_scope_id; InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr); ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr, &klinux_sockaddr_in6_in->klinux_sin6_addr); CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output, output_len); } else if (klinux_family == kLinux_AF_UNSPEC) { output = nullptr; *output_len = 0; } else { if (abort_handler != nullptr) { std::string message = absl::StrCat( ""Type conversion error - Unsupported AF family: "", klinux_family); abort_handler(message.c_str()); } else { abort(); } } return true; }",CWE-787,16 0,"void EmbeddedWorkerContextClient::SendWorkerStarted() { DCHECK(worker_task_runner_->RunsTasksOnCurrentThread()); sender_->Send(new EmbeddedWorkerHostMsg_WorkerStarted( WorkerTaskRunner::Instance()->CurrentWorkerId(), embedded_worker_id_)); } ",none,24 0,"ContentSettingsStore::~ContentSettingsStore() { STLDeleteValues(&entries_); } ",none,24 1,"Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( ""\n [%d: huff+mtf "", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( ""rt+rld"" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; }",CWE-787,16 1,"static ssize_t acpi_table_aml_write(struct config_item *cfg, const void *data, size_t size) { const struct acpi_table_header *header = data; struct acpi_table *table; int ret; table = container_of(cfg, struct acpi_table, cfg); if (table->header) { pr_err(""table already loaded\n""); return -EBUSY; } if (header->length != size) { pr_err(""invalid table length\n""); return -EINVAL; } if (memcmp(header->signature, ACPI_SIG_SSDT, 4)) { pr_err(""invalid table signature\n""); return -EINVAL; } table = container_of(cfg, struct acpi_table, cfg); table->header = kmemdup(header, header->length, GFP_KERNEL); if (!table->header) return -ENOMEM; ret = acpi_load_table(table->header, &table->index); if (ret) { kfree(table->header); table->header = NULL; } return ret; }",CWE-862,19 1,"String preg_quote(const String& str, const String& delimiter /* = null_string */) { const char* in_str = str.data(); const char* in_str_end = in_str + str.size(); /* Nothing to do if we got an empty string */ if (in_str == in_str_end) { return str; } char delim_char = 0; /* Delimiter character to be quoted */ bool quote_delim = false; /* Whether to quote additional delim char */ if (!delimiter.empty()) { delim_char = delimiter.charAt(0); quote_delim = true; } /* Allocate enough memory so that even if each character is quoted, we won't run out of room */ String ret(4 * str.size() + 1, ReserveString); char* out_str = ret.mutableData(); /* Go through the string and quote necessary characters */ const char* p; char* q; for (p = in_str, q = out_str; p != in_str_end; p++) { char c = *p; switch (c) { case '.': case '\\': case '+': case '*': case '?': case '[': case '^': case ']': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '>': case '<': case '|': case ':': case '-': case '#': *q++ = '\\'; *q++ = c; break; case '\0': *q++ = '\\'; *q++ = '0'; *q++ = '0'; *q++ = '0'; break; default: if (quote_delim && c == delim_char) *q++ = '\\'; *q++ = c; break; } } *q = '\0'; return ret.setSize(q - out_str); }",CWE-190,2 1,"sftp_client_message sftp_get_client_message(sftp_session sftp) { ssh_session session = sftp->session; sftp_packet packet; sftp_client_message msg; ssh_buffer payload; int rc; msg = malloc(sizeof (struct sftp_client_message_struct)); if (msg == NULL) { ssh_set_error_oom(session); return NULL; } ZERO_STRUCTP(msg); packet = sftp_packet_read(sftp); if (packet == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } payload = packet->payload; msg->type = packet->type; msg->sftp = sftp; /* take a copy of the whole packet */ msg->complete_message = ssh_buffer_new(); if (msg->complete_message == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } ssh_buffer_add_data(msg->complete_message, ssh_buffer_get(payload), ssh_buffer_get_len(payload)); ssh_buffer_get_u32(payload, &msg->id); switch(msg->type) { case SSH_FXP_CLOSE: case SSH_FXP_READDIR: msg->handle = ssh_buffer_get_ssh_string(payload); if (msg->handle == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_READ: rc = ssh_buffer_unpack(payload, ""Sqd"", &msg->handle, &msg->offset, &msg->len); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_WRITE: rc = ssh_buffer_unpack(payload, ""SqS"", &msg->handle, &msg->offset, &msg->data); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_REMOVE: case SSH_FXP_RMDIR: case SSH_FXP_OPENDIR: case SSH_FXP_READLINK: case SSH_FXP_REALPATH: rc = ssh_buffer_unpack(payload, ""s"", &msg->filename); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_RENAME: case SSH_FXP_SYMLINK: rc = ssh_buffer_unpack(payload, ""sS"", &msg->filename, &msg->data); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_MKDIR: case SSH_FXP_SETSTAT: rc = ssh_buffer_unpack(payload, ""s"", &msg->filename); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } msg->attr = sftp_parse_attr(sftp, payload, 0); if (msg->attr == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_FSETSTAT: msg->handle = ssh_buffer_get_ssh_string(payload); if (msg->handle == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } msg->attr = sftp_parse_attr(sftp, payload, 0); if (msg->attr == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_LSTAT: case SSH_FXP_STAT: rc = ssh_buffer_unpack(payload, ""s"", &msg->filename); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } if(sftp->version > 3) { ssh_buffer_unpack(payload, ""d"", &msg->flags); } break; case SSH_FXP_OPEN: rc = ssh_buffer_unpack(payload, ""sd"", &msg->filename, &msg->flags); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } msg->attr = sftp_parse_attr(sftp, payload, 0); if (msg->attr == NULL) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_FSTAT: rc = ssh_buffer_unpack(payload, ""S"", &msg->handle); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } break; case SSH_FXP_EXTENDED: rc = ssh_buffer_unpack(payload, ""s"", &msg->submessage); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } if (strcmp(msg->submessage, ""hardlink@openssh.com"") == 0 || strcmp(msg->submessage, ""posix-rename@openssh.com"") == 0) { rc = ssh_buffer_unpack(payload, ""sS"", &msg->filename, &msg->data); if (rc != SSH_OK) { ssh_set_error_oom(session); sftp_client_message_free(msg); return NULL; } } break; default: ssh_set_error(sftp->session, SSH_FATAL, ""Received unhandled sftp message %d"", msg->type); sftp_client_message_free(msg); return NULL; } return msg; }",CWE-476,12 0,"void AudioManagerBase::ShowAudioInputSettings() { } ",none,24 1,"rpmRC hdrblobInit(const void *uh, size_t uc, rpmTagVal regionTag, int exact_size, struct hdrblob_s *blob, char **emsg) { rpmRC rc = RPMRC_FAIL; memset(blob, 0, sizeof(*blob)); blob->ei = (int32_t *) uh; /* discards const */ blob->il = ntohl(blob->ei[0]); blob->dl = ntohl(blob->ei[1]); blob->pe = (entryInfo) &(blob->ei[2]); blob->pvlen = sizeof(blob->il) + sizeof(blob->dl) + (blob->il * sizeof(*blob->pe)) + blob->dl; blob->dataStart = (uint8_t *) (blob->pe + blob->il); blob->dataEnd = blob->dataStart + blob->dl; /* Is the blob the right size? */ if (blob->pvlen >= headerMaxbytes || (uc && blob->pvlen != uc)) { rasprintf(emsg, _(""blob size(%d): BAD, 8 + 16 * il(%d) + dl(%d)""), blob->pvlen, blob->il, blob->dl); goto exit; } if (hdrblobVerifyRegion(regionTag, exact_size, blob, emsg) == RPMRC_FAIL) goto exit; /* Sanity check the rest of the header structure. */ if (hdrblobVerifyInfo(blob, emsg)) goto exit; rc = RPMRC_OK; exit: return rc; }",CWE-125,1 1,"static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* exponent, int exponent_size, BYTE* output) { BN_CTX* ctx; int output_length = -1; BYTE* input_reverse; BYTE* modulus_reverse; BYTE* exponent_reverse; BIGNUM *mod, *exp, *x, *y; input_reverse = (BYTE*)malloc(2 * key_length + exponent_size); if (!input_reverse) return -1; modulus_reverse = input_reverse + key_length; exponent_reverse = modulus_reverse + key_length; memcpy(modulus_reverse, modulus, key_length); crypto_reverse(modulus_reverse, key_length); memcpy(exponent_reverse, exponent, exponent_size); crypto_reverse(exponent_reverse, exponent_size); memcpy(input_reverse, input, length); crypto_reverse(input_reverse, length); if (!(ctx = BN_CTX_new())) goto fail_bn_ctx; if (!(mod = BN_new())) goto fail_bn_mod; if (!(exp = BN_new())) goto fail_bn_exp; if (!(x = BN_new())) goto fail_bn_x; if (!(y = BN_new())) goto fail_bn_y; BN_bin2bn(modulus_reverse, key_length, mod); BN_bin2bn(exponent_reverse, exponent_size, exp); BN_bin2bn(input_reverse, length, x); BN_mod_exp(y, x, exp, mod, ctx); output_length = BN_bn2bin(y, output); crypto_reverse(output, output_length); if (output_length < (int)key_length) memset(output + output_length, 0, key_length - output_length); BN_free(y); fail_bn_y: BN_clear_free(x); fail_bn_x: BN_free(exp); fail_bn_exp: BN_free(mod); fail_bn_mod: BN_CTX_free(ctx); fail_bn_ctx: free(input_reverse); return output_length; }",CWE-787,16 1,"static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg /* True if outer SELECT uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or ""subquery"" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int iNewParent = -1;/* Replacement table for iParent */ int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFromnSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); #ifndef SQLITE_OMIT_WINDOWFUNC if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ #endif pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } if( pSub->selFlags & (SF_Recursive) ){ return 0; /* Restrictions (22) */ } /* ** If the subquery is the right operand of a LEFT JOIN, then the ** subquery may not be a join itself (3a). Example of why this is not ** allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** If the subquery is the right operand of a LEFT JOIN, then the outer ** query cannot be an aggregate. (3c) This is an artifact of the way ** aggregates are processed - there is no mechanism to determine if ** the LEFT JOIN table should be all-NULL. ** ** See also tickets #306, #350, and #3300. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ isLeftJoin = 1; if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ /* (3a) (3c) (3b) */ return 0; } } #ifdef SQLITE_EXTRA_IFNULLROW else if( iFrom>0 && !isAgg ){ /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for ** every reference to any result column from subquery in a join, even ** though they are not necessary. This will stress-test the OP_IfNullRow ** opcode. */ isLeftJoin = -1; } #endif /* Restriction (17): If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction (20) */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; /* (17d1), (17d2), or (17d3) */ } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ || pSub1->pSrc->nSrc<1 /* (17c) */ ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction (18). */ if( p->pOrderBy ){ int ii; for(ii=0; iipOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /* Ex-restriction (23): ** The only way that the recursive part of a CTE can contain a compound ** subquery is for the subquery to be one term of a join. But if the ** subquery is a join, then the flattening has already been stopped by ** restriction (17d3) */ assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,(""flatten %u.%p from term %d\n"", pSub->selId, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT FROM () ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the ""compound-subquery flattening"". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; pNew = sqlite3SelectDup(db, p, 0); p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p,(""compound-subquery flattener"" "" creates %u as peer\n"",pNew->selId)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nTabRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nTabRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; ia[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; iNewParent = pSubSrc->a[i].iCursor; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** ""a"" we substitute ""x*3"" and every place we see ""b"" we substitute ""y+10"". */ if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; inExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = pSub->pWhere; pSub->pWhere = 0; if( isLeftJoin>0 ){ sqlite3SetJoinExpr(pWhere, iNewParent); } pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); if( db->mallocFailed==0 ){ SubstContext x; x.pParse = pParse; x.iTable = iParent; x.iNewTable = iNewParent; x.isLeftJoin = isLeftJoin; x.pEList = pSub->pEList; substSelect(&x, pParent, 0); } /* The flattened query is a compound if either the inner or the ** outer query is a compound. */ pParent->selFlags |= pSub->selFlags & SF_Compound; assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,(""After flattening:\n"")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; }",CWE-476,12 1,"static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int16_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4 + len; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf(""[SSH] %s\n"", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf(""[SSH] Invalid packet payload\n""); #endif return(0); }",CWE-787,16 1,"static int oidc_request_post_preserved_restore(request_rec *r, const char *original_url) { oidc_debug(r, ""enter: original_url=%s"", original_url); const char *method = ""postOnLoad""; const char *script = apr_psprintf(r->pool, "" \n"", method, original_url); const char *body = ""

Restoring...

\n"" ""
\n""; return oidc_util_html_send(r, ""Restoring..."", script, method, body, OK); }",CWE-79,17 1,"static void mcba_usb_disconnect(struct usb_interface *intf) { struct mcba_priv *priv = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); netdev_info(priv->netdev, ""device disconnected\n""); unregister_candev(priv->netdev); free_candev(priv->netdev); mcba_urb_unlink(priv); }",CWE-416,10 1,"ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { int klinux_flags = TokLinuxRecvSendFlag(flags); if (klinux_flags == 0 && flags != 0) { errno = EINVAL; return -1; } MessageWriter input; input.Push(sockfd); input.Push(len); input.Push(klinux_flags); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kRecvFromHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_recvfrom"", 4); int result = output.next(); int klinux_errno = output.next(); // recvfrom() returns -1 on failure, with errno set to indicate the cause // of the error. if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return result; } auto buffer_received = output.next(); memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size())); // If |src_addr| is not NULL, and the underlying protocol provides the source // address, this source address is filled in. When |src_addr| is NULL, nothing // is filled in; in this case, |addrlen| is not used, and should also be NULL. if (src_addr != nullptr && addrlen != nullptr) { auto klinux_sockaddr_buf = output.next(); const struct klinux_sockaddr *klinux_addr = klinux_sockaddr_buf.As(); FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr, addrlen, TrustedPrimitives::BestEffortAbort); } return result; }",CWE-125,1 1,"GF_Err latm_dmx_process(GF_Filter *filter) { GF_LATMDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u32 pos; u8 *data, *output; u32 pck_size, prev_pck_size; u64 cts = GF_FILTER_NO_TS; if (ctx->in_error) return ctx->in_error; //always reparse duration if (!ctx->duration.num) latm_dmx_check_dur(filter, ctx); if (ctx->opid && !ctx->is_playing) return GF_OK; pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { if (!ctx->latm_buffer_size) { 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; } } else { return GF_OK; } } data = (char *) gf_filter_pck_get_data(pck, &pck_size); //input pid sets some timescale - we flushed pending data , update cts if (ctx->timescale && pck) { cts = gf_filter_pck_get_cts(pck); } prev_pck_size = ctx->latm_buffer_size; if (pck && !ctx->resume_from) { if (ctx->latm_buffer_size + pck_size > ctx->latm_buffer_alloc) { ctx->latm_buffer_alloc = ctx->latm_buffer_size + pck_size; ctx->latm_buffer = gf_realloc(ctx->latm_buffer, ctx->latm_buffer_alloc); } memcpy(ctx->latm_buffer + ctx->latm_buffer_size, data, pck_size); ctx->latm_buffer_size += pck_size; } if (!ctx->bs) ctx->bs = gf_bs_new(ctx->latm_buffer, ctx->latm_buffer_size, GF_BITSTREAM_READ); else gf_bs_reassign_buffer(ctx->bs, ctx->latm_buffer, ctx->latm_buffer_size); if (ctx->resume_from) { gf_bs_seek(ctx->bs, ctx->resume_from-1); ctx->resume_from = 0; } if (cts == GF_FILTER_NO_TS) prev_pck_size = 0; while (1) { pos = (u32) gf_bs_get_position(ctx->bs); u8 latm_buffer[4096]; u32 latm_frame_size = 4096; if (!latm_dmx_sync_frame_bs(ctx->bs,&ctx->acfg, &latm_frame_size, latm_buffer, NULL)) break; if (ctx->in_seek) { u64 nb_samples_at_seek = (u64) (ctx->start_range * GF_M4ASampleRates[ctx->sr_idx]); if (ctx->cts + ctx->dts_inc >= nb_samples_at_seek) { //u32 samples_to_discard = (ctx->cts + ctx->dts_inc) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } latm_dmx_check_pid(filter, ctx); if (!ctx->is_playing) { ctx->resume_from = pos+1; return GF_OK; } if (!ctx->in_seek) { GF_FilterSAPType sap = GF_FILTER_SAP_1; dst_pck = gf_filter_pck_new_alloc(ctx->opid, latm_frame_size, &output); if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, dst_pck); memcpy(output, latm_buffer, latm_frame_size); gf_filter_pck_set_cts(dst_pck, ctx->cts); gf_filter_pck_set_duration(dst_pck, ctx->dts_inc); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE); /*xHE-AAC, check RAP*/ if (ctx->acfg.base_object_type==GF_CODECID_USAC) { if (latm_frame_size && (output[0] & 0x80) && !ctx->prev_sap) { sap = GF_FILTER_SAP_1; ctx->prev_sap = GF_TRUE; } else { sap = GF_FILTER_SAP_NONE; ctx->prev_sap = GF_FALSE; } } gf_filter_pck_set_sap(dst_pck, sap); gf_filter_pck_send(dst_pck); } latm_dmx_update_cts(ctx); if (prev_pck_size) { pos = (u32) gf_bs_get_position(ctx->bs); if (prev_pck_size<=pos) { prev_pck_size=0; if (ctx->src_pck) gf_filter_pck_unref(ctx->src_pck); ctx->src_pck = pck; if (pck) gf_filter_pck_ref_props(&ctx->src_pck); } } } if (pck) { pos = (u32) gf_bs_get_position(ctx->bs); assert(ctx->latm_buffer_size >= pos); memmove(ctx->latm_buffer, ctx->latm_buffer+pos, ctx->latm_buffer_size - pos); ctx->latm_buffer_size -= pos; gf_filter_pid_drop_packet(ctx->ipid); assert(!ctx->resume_from); } else { ctx->latm_buffer_size = 0; return latm_dmx_process(filter); } return GF_OK; }",CWE-476,12 1,"load_image (const gchar *filename, GError **error) { FILE *f; struct stat st; char buf[32]; PSPimage ia; guint32 block_init_len, block_total_len; long block_start; PSPBlockID id = -1; gint block_number; gint32 image_ID = -1; if (g_stat (filename, &st) == -1) return -1; f = g_fopen (filename, ""rb""); if (f == NULL) { 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; } /* Read the PSP File Header and determine file version */ if (fread (buf, 32, 1, f) < 1 || fread (&psp_ver_major, 2, 1, f) < 1 || fread (&psp_ver_minor, 2, 1, f) < 1) { g_message (""Error reading file header""); goto error; } if (memcmp (buf, ""Paint Shop Pro Image File\n\032\0\0\0\0\0"", 32) != 0) { g_message (""Incorrect file signature""); goto error; } psp_ver_major = GUINT16_FROM_LE (psp_ver_major); psp_ver_minor = GUINT16_FROM_LE (psp_ver_minor); /* I only have the documentation for file format version 3.0, * but PSP 6 writes version 4.0. Let's hope it's backwards compatible. * Earlier versions probably don't have all the fields I expect * so don't accept those. */ if (psp_ver_major < 3) { g_message (""Unsupported PSP file format version "" ""%d.%d, only knows 3.0 (and later?)"", psp_ver_major, psp_ver_minor); goto error; } else if ((psp_ver_major == 3) || (psp_ver_major == 4) || (psp_ver_major == 5) || (psp_ver_major == 6)) ; /* OK */ else { g_message (""Unsupported PSP file format version %d.%d"", psp_ver_major, psp_ver_minor); goto error; } /* Read all the blocks */ block_number = 0; IFDBG(3) g_message (""size = %d"", (int)st.st_size); while (ftell (f) != st.st_size && (id = read_block_header (f, &block_init_len, &block_total_len)) != -1) { block_start = ftell (f); if (id == PSP_IMAGE_BLOCK) { if (block_number != 0) { g_message (""Duplicate General Image Attributes block""); goto error; } if (read_general_image_attribute_block (f, block_init_len, block_total_len, &ia) == -1) { goto error; } IFDBG(2) g_message (""%d dpi %dx%d %s"", (int) ia.resolution, ia.width, ia.height, compression_name (ia.compression)); image_ID = gimp_image_new (ia.width, ia.height, ia.greyscale ? GIMP_GRAY : GIMP_RGB); if (image_ID == -1) { goto error; } gimp_image_set_filename (image_ID, filename); gimp_image_set_resolution (image_ID, ia.resolution, ia.resolution); } else { if (block_number == 0) { g_message (""Missing General Image Attributes block""); goto error; } switch (id) { case PSP_CREATOR_BLOCK: if (read_creator_block (f, image_ID, block_total_len, &ia) == -1) goto error; break; case PSP_COLOR_BLOCK: break; /* Not yet implemented */ case PSP_LAYER_START_BLOCK: if (read_layer_block (f, image_ID, block_total_len, &ia) == -1) goto error; break; case PSP_SELECTION_BLOCK: break; /* Not yet implemented */ case PSP_ALPHA_BANK_BLOCK: break; /* Not yet implemented */ case PSP_THUMBNAIL_BLOCK: break; /* No use for it */ case PSP_EXTENDED_DATA_BLOCK: break; /* Not yet implemented */ case PSP_TUBE_BLOCK: if (read_tube_block (f, image_ID, block_total_len, &ia) == -1) goto error; break; case PSP_COMPOSITE_IMAGE_BANK_BLOCK: break; /* Not yet implemented */ case PSP_LAYER_BLOCK: case PSP_CHANNEL_BLOCK: case PSP_ALPHA_CHANNEL_BLOCK: case PSP_ADJUSTMENT_EXTENSION_BLOCK: case PSP_VECTOR_EXTENSION_BLOCK: case PSP_SHAPE_BLOCK: case PSP_PAINTSTYLE_BLOCK: case PSP_COMPOSITE_ATTRIBUTES_BLOCK: case PSP_JPEG_BLOCK: g_message (""Sub-block %s should not occur "" ""at main level of file"", block_name (id)); break; default: g_message (""Unrecognized block id %d"", id); break; } } if (block_start + block_total_len >= st.st_size) break; if (try_fseek (f, block_start + block_total_len, SEEK_SET) < 0) goto error; block_number++; } if (id == -1) { error: fclose (f); if (image_ID != -1) gimp_image_delete (image_ID); return -1; } fclose (f); return image_ID; }",CWE-787,16 1,"static void cil_reset_classperms_set(struct cil_classperms_set *cp_set) { cil_reset_classpermission(cp_set->set); }",CWE-416,10 1,"export_desktop_file (const char *app, const char *branch, const char *arch, GKeyFile *metadata, const char * const *previous_ids, int parent_fd, const char *name, struct stat *stat_buf, char **target, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; glnx_autofd int desktop_fd = -1; g_autofree char *tmpfile_name = g_strdup_printf (""export-desktop-XXXXXX""); g_autoptr(GOutputStream) out_stream = NULL; g_autofree gchar *data = NULL; gsize data_len; g_autofree gchar *new_data = NULL; gsize new_data_len; g_autoptr(GKeyFile) keyfile = NULL; g_autofree gchar *old_exec = NULL; gint old_argc; g_auto(GStrv) old_argv = NULL; g_auto(GStrv) groups = NULL; GString *new_exec = NULL; g_autofree char *escaped_app = maybe_quote (app); g_autofree char *escaped_branch = maybe_quote (branch); g_autofree char *escaped_arch = maybe_quote (arch); int i; if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error)) goto out; if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error)) goto out; keyfile = g_key_file_new (); if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error)) goto out; if (g_str_has_suffix (name, "".service"")) { g_autofree gchar *dbus_name = NULL; g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen ("".service"")); dbus_name = g_key_file_get_string (keyfile, ""D-BUS Service"", ""Name"", NULL); if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0) { return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED, _(""D-Bus service file '%s' has wrong name""), name); } } if (g_str_has_suffix (name, "".desktop"")) { gsize length; g_auto(GStrv) tags = g_key_file_get_string_list (metadata, ""Application"", ""tags"", &length, NULL); if (tags != NULL) { g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, ""X-Flatpak-Tags"", (const char * const *) tags, length); } /* Add a marker so consumers can easily find out that this launches a sandbox */ g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, ""X-Flatpak"", app); /* If the app has been renamed, add its old .desktop filename to * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to * introduce duplicates. */ if (previous_ids != NULL) { const char *X_FLATPAK_RENAMED_FROM = ""X-Flatpak-RenamedFrom""; g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, NULL, NULL); g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free); g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal); const char *new_suffix; for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++) { if (!g_hash_table_contains (seen, renamed_from[i])) { gchar *copy = g_strdup (renamed_from[i]); g_hash_table_insert (seen, copy, copy); g_ptr_array_add (merged, g_steal_pointer (©)); } } /* If an app was renamed from com.example.Foo to net.example.Bar, and * the new version exports net.example.Bar-suffix.desktop, we assume the * old version exported com.example.Foo-suffix.desktop. * * This assertion is true because * flatpak_name_matches_one_wildcard_prefix() is called on all * exported files before we get here. */ g_assert (g_str_has_prefix (name, app)); /* "".desktop"" for the ""main"" desktop file; something like * ""-suffix.desktop"" for extra ones. */ new_suffix = name + strlen (app); for (i = 0; previous_ids[i] != NULL; i++) { g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL); if (!g_hash_table_contains (seen, previous_desktop)) { g_hash_table_insert (seen, previous_desktop, previous_desktop); g_ptr_array_add (merged, g_steal_pointer (&previous_desktop)); } } if (merged->len > 0) { g_ptr_array_add (merged, NULL); g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, (const char * const *) merged->pdata, merged->len - 1); } } } groups = g_key_file_get_groups (keyfile, NULL); for (i = 0; groups[i] != NULL; i++) { g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], ""X-Flatpak-RunOptions"", NULL, NULL); g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts); g_key_file_remove_key (keyfile, groups[i], ""X-Flatpak-RunOptions"", NULL); g_key_file_remove_key (keyfile, groups[i], ""TryExec"", NULL); /* Remove this to make sure nothing tries to execute it outside the sandbox*/ g_key_file_remove_key (keyfile, groups[i], ""X-GNOME-Bugzilla-ExtraInfoScript"", NULL); new_exec = g_string_new (""""); g_string_append_printf (new_exec, FLATPAK_BINDIR ""/flatpak run --branch=%s --arch=%s"", escaped_branch, escaped_arch); if (flatpak_run_args != NULL) g_string_append_printf (new_exec, ""%s"", flatpak_run_args); old_exec = g_key_file_get_string (keyfile, groups[i], ""Exec"", NULL); if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1) { int j; g_autofree char *command = maybe_quote (old_argv[0]); g_string_append_printf (new_exec, "" --command=%s"", command); for (j = 1; j < old_argc; j++) { if (strcasecmp (old_argv[j], ""%f"") == 0 || strcasecmp (old_argv[j], ""%u"") == 0) { g_string_append (new_exec, "" --file-forwarding""); break; } } g_string_append (new_exec, "" ""); g_string_append (new_exec, escaped_app); for (j = 1; j < old_argc; j++) { g_autofree char *arg = maybe_quote (old_argv[j]); if (strcasecmp (arg, ""%f"") == 0) g_string_append_printf (new_exec, "" @@ %s @@"", arg); else if (strcasecmp (arg, ""%u"") == 0) g_string_append_printf (new_exec, "" @@u %s @@"", arg); else if (strcmp (arg, ""@@"") == 0 || strcmp (arg, ""@@u"") == 0) g_print (_(""Skipping invalid Exec argument %s\n""), arg); else g_string_append_printf (new_exec, "" %s"", arg); } } else { g_string_append (new_exec, "" ""); g_string_append (new_exec, escaped_app); } g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str); } new_data = g_key_file_to_data (keyfile, &new_data_len, error); if (new_data == NULL) goto out; if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error)) goto out; if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error)) goto out; if (!g_output_stream_close (out_stream, cancellable, error)) goto out; if (target) *target = g_steal_pointer (&tmpfile_name); ret = TRUE; out: if (new_exec != NULL) g_string_free (new_exec, TRUE); return ret; }",CWE-94,23 1,"static int usb_host_handle_control(USBHostDevice *s, USBPacket *p) { struct usbdevfs_urb *urb; AsyncURB *aurb; int ret, value, index; /* * Process certain standard device requests. * These are infrequent and are processed synchronously. */ value = le16_to_cpu(s->ctrl.req.wValue); index = le16_to_cpu(s->ctrl.req.wIndex); dprintf(""husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n"", s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, s->ctrl.len); if (s->ctrl.req.bRequestType == 0) { switch (s->ctrl.req.bRequest) { case USB_REQ_SET_ADDRESS: return usb_host_set_address(s, value); case USB_REQ_SET_CONFIGURATION: return usb_host_set_config(s, value & 0xff); } } if (s->ctrl.req.bRequestType == 1 && s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) return usb_host_set_interface(s, index, value); /* The rest are asynchronous */ aurb = async_alloc(); aurb->hdev = s; aurb->packet = p; /* * Setup ctrl transfer. * * s->ctrl is layed out such that data buffer immediately follows * 'req' struct which is exactly what usbdevfs expects. */ urb = &aurb->urb; urb->type = USBDEVFS_URB_TYPE_CONTROL; urb->endpoint = p->devep; urb->buffer = &s->ctrl.req; urb->buffer_length = 8 + s->ctrl.len; urb->usercontext = s; ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb); dprintf(""husb: submit ctrl. len %u aurb %p\n"", urb->buffer_length, aurb); if (ret < 0) { dprintf(""husb: submit failed. errno %d\n"", errno); async_free(aurb); switch(errno) { case ETIMEDOUT: return USB_RET_NAK; case EPIPE: default: return USB_RET_STALL; } } usb_defer_packet(p, async_cancel, aurb); return USB_RET_ASYNC; }",CWE-119,0 1,"static int kvm_s390_get_cmma(struct kvm *kvm, struct kvm_s390_cmma_log *args, u8 *res, unsigned long bufsize) { unsigned long mem_end, cur_gfn, next_gfn, hva, pgstev; struct kvm_memslots *slots = kvm_memslots(kvm); struct kvm_memory_slot *ms; cur_gfn = kvm_s390_next_dirty_cmma(slots, args->start_gfn); ms = gfn_to_memslot(kvm, cur_gfn); args->count = 0; args->start_gfn = cur_gfn; if (!ms) return 0; next_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1); mem_end = slots->memslots[0].base_gfn + slots->memslots[0].npages; while (args->count < bufsize) { hva = gfn_to_hva(kvm, cur_gfn); if (kvm_is_error_hva(hva)) return 0; /* Decrement only if we actually flipped the bit to 0 */ if (test_and_clear_bit(cur_gfn - ms->base_gfn, kvm_second_dirty_bitmap(ms))) atomic64_dec(&kvm->arch.cmma_dirty_pages); if (get_pgste(kvm->mm, hva, &pgstev) < 0) pgstev = 0; /* Save the value */ res[args->count++] = (pgstev >> 24) & 0x43; /* If the next bit is too far away, stop. */ if (next_gfn > cur_gfn + KVM_S390_MAX_BIT_DISTANCE) return 0; /* If we reached the previous ""next"", find the next one */ if (cur_gfn == next_gfn) next_gfn = kvm_s390_next_dirty_cmma(slots, cur_gfn + 1); /* Reached the end of memory or of the buffer, stop */ if ((next_gfn >= mem_end) || (next_gfn - args->start_gfn >= bufsize)) return 0; cur_gfn++; /* Reached the end of the current memslot, take the next one. */ if (cur_gfn - ms->base_gfn >= ms->npages) { ms = gfn_to_memslot(kvm, cur_gfn); if (!ms) return 0; } } return 0; }",CWE-416,10 0,"void AudioManagerBase::ShutdownOnAudioThread() { AudioOutputDispatchersMap::iterator it = output_dispatchers_.begin(); for (; it != output_dispatchers_.end(); ++it) { scoped_refptr& dispatcher = (*it).second; if (dispatcher) { dispatcher->Shutdown(); DCHECK(dispatcher->HasOneRef()) << ""AudioOutputProxies are still alive""; dispatcher = NULL; } } output_dispatchers_.clear(); } ",none,24 0," void EnterDecodingState() { VideoDecoder::DecoderStatus status; scoped_refptr video_frame; DecodeSingleFrame(i_frame_buffer_, &status, &video_frame); EXPECT_EQ(status, VideoDecoder::kOk); ASSERT_TRUE(video_frame); EXPECT_FALSE(video_frame->IsEndOfStream()); } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::flipVertically(unsigned char* framebuffer, unsigned int width, unsigned int height) { unsigned char* scanline = m_scanline; if (!scanline) return; unsigned int rowBytes = width * 4; unsigned int count = height / 2; for (unsigned int i = 0; i < count; i++) { unsigned char* rowA = framebuffer + i * rowBytes; unsigned char* rowB = framebuffer + (height - i - 1) * rowBytes; memcpy(scanline, rowB, rowBytes); memcpy(rowB, rowA, rowBytes); memcpy(rowA, scanline, rowBytes); } } ",none,24 0," virtual ~FFmpegVideoDecoderTest() {} ",none,24 1," void Compute(OpKernelContext* context) override { const float in_min = context->input(2).flat()(0); const float in_max = context->input(3).flat()(0); ImageResizerState st(align_corners_, false); st.ValidateAndCreateOutput(context); if (!context->status().ok()) return; // Return if the output is empty. if (st.output->NumElements() == 0) return; typename TTypes::ConstTensor image_data( context->input(0).tensor()); typename TTypes::Tensor output_data(st.output->tensor()); ResizeBilinear(image_data, st.height_scale, st.width_scale, in_min, in_max, half_pixel_centers_, &output_data); Tensor* out_min = nullptr; OP_REQUIRES_OK(context, context->allocate_output(1, {}, &out_min)); out_min->flat()(0) = in_min; Tensor* out_max = nullptr; OP_REQUIRES_OK(context, context->allocate_output(2, {}, &out_max)); out_max->flat()(0) = in_max; }",CWE-787,16 1,"static int xar_hash_check(int hash, const void * result, const void * expected) { int len; if (!result || !expected) return 1; switch (hash) { case XAR_CKSUM_SHA1: len = SHA1_HASH_SIZE; break; case XAR_CKSUM_MD5: len = CLI_HASH_MD5; break; case XAR_CKSUM_OTHER: case XAR_CKSUM_NONE: default: return 1; } return memcmp(result, expected, len); }",CWE-125,1 1," int MemIo::seek(int64 offset, Position pos ) { int64 newIdx = 0; switch (pos) { case BasicIo::cur: newIdx = p_->idx_ + offset; break; case BasicIo::beg: newIdx = offset; break; case BasicIo::end: newIdx = p_->size_ + offset; break; } if (newIdx < 0) return 1; p_->idx_ = static_cast(newIdx); //not very sure about this. need more test!! - note by Shawn fly2xj@gmail.com //TODO p_->eof_ = false; return 0; }",CWE-125,1 1,"static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); 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) { 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); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } 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)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,""tiff:exif-properties""); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { 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) { 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; 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) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* 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) { 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) { TIFFClose(tiff); ThrowReaderException(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) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(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; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); 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,DisassociatedQuantumAlpha); (void) SetImageProperty(image,""tiff:alpha"",""associated""); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,""tiff:alpha"",""unassociated""); } } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,""%u"",(unsigned int) rows_per_strip); (void) SetImageProperty(image,""tiff:rows-per-strip"",value); } if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; tiff_pixels=(unsigned char *) AcquireMagickMemory(MagickMax( TIFFScanlineSize(tiff),(image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0)))))); if (tiff_pixels == (unsigned char *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) tiff_pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tiff_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: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; 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,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; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,""ImageIsNotTiled""); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register 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) 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; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); 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; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); }",CWE-400,9 0,"void VideoRendererBase::AttemptRead_Locked() { lock_.AssertAcquired(); DCHECK_NE(kEnded, state_); if (pending_read_ || NumFrames_Locked() == limits::kMaxVideoFrames || (!ready_frames_.empty() && ready_frames_.back()->IsEndOfStream()) || state_ == kFlushingDecoder || state_ == kFlushing) { return; } pending_read_ = true; decoder_->Read(base::Bind(&VideoRendererBase::FrameReady, this)); } ",none,24 1,"slap_modrdn2mods( Operation *op, SlapReply *rs ) { int a_cnt, d_cnt; LDAPRDN old_rdn = NULL; LDAPRDN new_rdn = NULL; assert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) ); /* if requestDN is empty, silently reset deleteOldRDN */ if ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0; if ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn, (char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: can't figure out "" ""type(s)/value(s) of newrdn\n"", op->o_log_prefix ); rs->sr_err = LDAP_INVALID_DN_SYNTAX; rs->sr_text = ""unknown type(s)/value(s) used in RDN""; goto done; } if ( op->oq_modrdn.rs_deleteoldrdn ) { if ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn, (char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: can't figure out "" ""type(s)/value(s) of oldrdn\n"", op->o_log_prefix ); rs->sr_err = LDAP_OTHER; rs->sr_text = ""cannot parse RDN from old DN""; goto done; } } rs->sr_text = NULL; /* Add new attribute values to the entry */ for ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) { AttributeDescription *desc = NULL; Modifications *mod_tmp; rs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text ); if ( rs->sr_err != LDAP_SUCCESS ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (new)\n"", op->o_log_prefix, rs->sr_text, new_rdn[ a_cnt ]->la_attr.bv_val ); goto done; } if ( !desc->ad_type->sat_equality ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (new)\n"", op->o_log_prefix, rs->sr_text, new_rdn[ a_cnt ]->la_attr.bv_val ); rs->sr_text = ""naming attribute has no equality matching rule""; rs->sr_err = LDAP_NAMING_VIOLATION; goto done; } /* Apply modification */ mod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) ); mod_tmp->sml_desc = desc; BER_BVZERO( &mod_tmp->sml_type ); mod_tmp->sml_numvals = 1; mod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); ber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value ); mod_tmp->sml_values[1].bv_val = NULL; if( desc->ad_type->sat_equality->smr_normalize) { mod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); rs->sr_err = desc->ad_type->sat_equality->smr_normalize( SLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, desc->ad_type->sat_syntax, desc->ad_type->sat_equality, &mod_tmp->sml_values[0], &mod_tmp->sml_nvalues[0], NULL ); if (rs->sr_err != LDAP_SUCCESS) { ch_free(mod_tmp->sml_nvalues); ch_free(mod_tmp->sml_values[0].bv_val); ch_free(mod_tmp->sml_values); ch_free(mod_tmp); goto done; } mod_tmp->sml_nvalues[1].bv_val = NULL; } else { mod_tmp->sml_nvalues = NULL; } mod_tmp->sml_op = SLAP_MOD_SOFTADD; mod_tmp->sml_flags = 0; mod_tmp->sml_next = op->orr_modlist; op->orr_modlist = mod_tmp; } /* Remove old rdn value if required */ if ( op->orr_deleteoldrdn ) { for ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) { AttributeDescription *desc = NULL; Modifications *mod_tmp; rs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text ); if ( rs->sr_err != LDAP_SUCCESS ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (old)\n"", op->o_log_prefix, rs->sr_text, old_rdn[d_cnt]->la_attr.bv_val ); goto done; } /* Apply modification */ mod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) ); mod_tmp->sml_desc = desc; BER_BVZERO( &mod_tmp->sml_type ); mod_tmp->sml_numvals = 1; mod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); ber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value ); mod_tmp->sml_values[1].bv_val = NULL; if( desc->ad_type->sat_equality->smr_normalize) { mod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); (void) (*desc->ad_type->sat_equality->smr_normalize)( SLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, desc->ad_type->sat_syntax, desc->ad_type->sat_equality, &mod_tmp->sml_values[0], &mod_tmp->sml_nvalues[0], NULL ); mod_tmp->sml_nvalues[1].bv_val = NULL; } else { mod_tmp->sml_nvalues = NULL; } mod_tmp->sml_op = LDAP_MOD_DELETE; mod_tmp->sml_flags = 0; mod_tmp->sml_next = op->orr_modlist; op->orr_modlist = mod_tmp; } } done: /* LDAP v2 supporting correct attribute handling. */ if ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) { Modifications *tmp; for ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) { tmp = op->orr_modlist->sml_next; ch_free( op->orr_modlist ); } } if ( new_rdn != NULL ) { ldap_rdnfree_x( new_rdn, op->o_tmpmemctx ); } if ( old_rdn != NULL ) { ldap_rdnfree_x( old_rdn, op->o_tmpmemctx ); } return rs->sr_err; }",CWE-476,12 1,"LJ_NOINLINE void lj_err_run(lua_State *L) { ptrdiff_t ef = finderrfunc(L); if (ef) { TValue *errfunc = restorestack(L, ef); TValue *top = L->top; lj_trace_abort(G(L)); if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) { setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR)); lj_err_throw(L, LUA_ERRERR); } L->status = LUA_ERRERR; copyTV(L, top, top-1); copyTV(L, top-1, errfunc); L->top = top+1; lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */ } lj_err_throw(L, LUA_ERRRUN); }",CWE-125,1 1,"FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], uint32_t nvals, uint32_t parameter) { /* try and get br->consumed_words and br->consumed_bits into register; * must remember to flush them back to *br before calling other * bitreader functions that use them, and before returning */ uint32_t cwords, words, lsbs, msbs, x, y; uint32_t ucbits; /* keep track of the number of unconsumed bits in word */ brword b; int *val, *end; FLAC__ASSERT(0 != br); FLAC__ASSERT(0 != br->buffer); /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */ FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32); FLAC__ASSERT(parameter < 32); /* the above two asserts also guarantee that the binary part never straddles more than 2 words, so we don't have to loop to read it */ val = vals; end = vals + nvals; if(parameter == 0) { while(val < end) { /* read the unary MSBs and end bit */ if(!FLAC__bitreader_read_unary_unsigned(br, &msbs)) return false; *val++ = (int)(msbs >> 1) ^ -(int)(msbs & 1); } return true; } FLAC__ASSERT(parameter > 0); cwords = br->consumed_words; words = br->words; /* if we've not consumed up to a partial tail word... */ if(cwords >= words) { x = 0; goto process_tail; } ucbits = FLAC__BITS_PER_WORD - br->consumed_bits; b = br->buffer[cwords] << br->consumed_bits; /* keep unconsumed bits aligned to left */ while(val < end) { /* read the unary MSBs and end bit */ x = y = COUNT_ZERO_MSBS2(b); if(x == FLAC__BITS_PER_WORD) { x = ucbits; do { /* didn't find stop bit yet, have to keep going... */ cwords++; if (cwords >= words) goto incomplete_msbs; b = br->buffer[cwords]; y = COUNT_ZERO_MSBS2(b); x += y; } while(y == FLAC__BITS_PER_WORD); } b <<= y; b <<= 1; /* account for stop bit */ ucbits = (ucbits - x - 1) % FLAC__BITS_PER_WORD; msbs = x; /* read the binary LSBs */ x = (FLAC__uint32)(b >> (FLAC__BITS_PER_WORD - parameter)); /* parameter < 32, so we can cast to 32-bit uint32_t */ if(parameter <= ucbits) { ucbits -= parameter; b <<= parameter; } else { /* there are still bits left to read, they will all be in the next word */ cwords++; if (cwords >= words) goto incomplete_lsbs; b = br->buffer[cwords]; ucbits += FLAC__BITS_PER_WORD - parameter; x |= (FLAC__uint32)(b >> ucbits); b <<= FLAC__BITS_PER_WORD - ucbits; } lsbs = x; /* compose the value */ x = (msbs << parameter) | lsbs; *val++ = (int)(x >> 1) ^ -(int)(x & 1); continue; /* at this point we've eaten up all the whole words */ process_tail: do { if(0) { incomplete_msbs: br->consumed_bits = 0; br->consumed_words = cwords; } /* read the unary MSBs and end bit */ if(!FLAC__bitreader_read_unary_unsigned(br, &msbs)) return false; msbs += x; x = ucbits = 0; if(0) { incomplete_lsbs: br->consumed_bits = 0; br->consumed_words = cwords; } /* read the binary LSBs */ if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter - ucbits)) return false; lsbs = x | lsbs; /* compose the value */ x = (msbs << parameter) | lsbs; *val++ = (int)(x >> 1) ^ -(int)(x & 1); x = 0; cwords = br->consumed_words; words = br->words; ucbits = FLAC__BITS_PER_WORD - br->consumed_bits; b = br->buffer[cwords] << br->consumed_bits; } while(cwords >= words && val < end); } if(ucbits == 0 && cwords < words) { /* don't leave the head word with no unconsumed bits */ cwords++; ucbits = FLAC__BITS_PER_WORD; } br->consumed_bits = FLAC__BITS_PER_WORD - ucbits; br->consumed_words = cwords; return true; }",CWE-125,1 0,"long WebGraphicsContext3DDefaultImpl::getVertexAttribOffset(unsigned long index, unsigned long pname) { makeContextCurrent(); void* pointer; glGetVertexAttribPointerv(index, pname, &pointer); return reinterpret_cast(pointer); } ",none,24 0,"gfx::Size SoftwareFrameManager::GetCurrentFrameSizeInPixels() const { DCHECK(HasCurrentFrame()); return current_frame_->frame_size_pixels_; } ",none,24 1,"static void ov518_mode_init_regs(struct sd *sd) { struct gspca_dev *gspca_dev = (struct gspca_dev *)sd; int hsegs, vsegs, packet_size; struct usb_host_interface *alt; struct usb_interface *intf; intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface); alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt); if (!alt) { gspca_err(gspca_dev, ""Couldn't get altsetting\n""); sd->gspca_dev.usb_err = -EIO; return; } packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); ov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2); /******** Set the mode ********/ reg_w(sd, 0x2b, 0); reg_w(sd, 0x2c, 0); reg_w(sd, 0x2d, 0); reg_w(sd, 0x2e, 0); reg_w(sd, 0x3b, 0); reg_w(sd, 0x3c, 0); reg_w(sd, 0x3d, 0); reg_w(sd, 0x3e, 0); if (sd->bridge == BRIDGE_OV518) { /* Set 8-bit (YVYU) input format */ reg_w_mask(sd, 0x20, 0x08, 0x08); /* Set 12-bit (4:2:0) output format */ reg_w_mask(sd, 0x28, 0x80, 0xf0); reg_w_mask(sd, 0x38, 0x80, 0xf0); } else { reg_w(sd, 0x28, 0x80); reg_w(sd, 0x38, 0x80); } hsegs = sd->gspca_dev.pixfmt.width / 16; vsegs = sd->gspca_dev.pixfmt.height / 4; reg_w(sd, 0x29, hsegs); reg_w(sd, 0x2a, vsegs); reg_w(sd, 0x39, hsegs); reg_w(sd, 0x3a, vsegs); /* Windows driver does this here; who knows why */ reg_w(sd, 0x2f, 0x80); /******** Set the framerate ********/ if (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 && sd->sensor == SEN_OV7620AE) sd->clockdiv = 0; else sd->clockdiv = 1; /* Mode independent, but framerate dependent, regs */ /* 0x51: Clock divider; Only works on some cams which use 2 crystals */ reg_w(sd, 0x51, 0x04); reg_w(sd, 0x22, 0x18); reg_w(sd, 0x23, 0xff); if (sd->bridge == BRIDGE_OV518PLUS) { switch (sd->sensor) { case SEN_OV7620AE: /* * HdG: 640x480 needs special handling on device * revision 2, we check for device revision > 0 to * avoid regressions, as we don't know the correct * thing todo for revision 1. * * Also this likely means we don't need to * differentiate between the OV7620 and OV7620AE, * earlier testing hitting this same problem likely * happened to be with revision < 2 cams using an * OV7620 and revision 2 cams using an OV7620AE. */ if (sd->revision > 0 && sd->gspca_dev.pixfmt.width == 640) { reg_w(sd, 0x20, 0x60); reg_w(sd, 0x21, 0x1f); } else { reg_w(sd, 0x20, 0x00); reg_w(sd, 0x21, 0x19); } break; case SEN_OV7620: reg_w(sd, 0x20, 0x00); reg_w(sd, 0x21, 0x19); break; default: reg_w(sd, 0x21, 0x19); } } else reg_w(sd, 0x71, 0x17); /* Compression-related? */ /* FIXME: Sensor-specific */ /* Bit 5 is what matters here. Of course, it is ""reserved"" */ i2c_w(sd, 0x54, 0x23); reg_w(sd, 0x2f, 0x80); if (sd->bridge == BRIDGE_OV518PLUS) { reg_w(sd, 0x24, 0x94); reg_w(sd, 0x25, 0x90); ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */ ov518_reg_w32(sd, 0xc6, 540, 2); /* 21ch */ ov518_reg_w32(sd, 0xc7, 540, 2); /* 21ch */ ov518_reg_w32(sd, 0xc8, 108, 2); /* 6ch */ ov518_reg_w32(sd, 0xca, 131098, 3); /* 2001ah */ ov518_reg_w32(sd, 0xcb, 532, 2); /* 214h */ ov518_reg_w32(sd, 0xcc, 2400, 2); /* 960h */ ov518_reg_w32(sd, 0xcd, 32, 2); /* 20h */ ov518_reg_w32(sd, 0xce, 608, 2); /* 260h */ } else { reg_w(sd, 0x24, 0x9f); reg_w(sd, 0x25, 0x90); ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */ ov518_reg_w32(sd, 0xc6, 381, 2); /* 17dh */ ov518_reg_w32(sd, 0xc7, 381, 2); /* 17dh */ ov518_reg_w32(sd, 0xc8, 128, 2); /* 80h */ ov518_reg_w32(sd, 0xca, 183331, 3); /* 2cc23h */ ov518_reg_w32(sd, 0xcb, 746, 2); /* 2eah */ ov518_reg_w32(sd, 0xcc, 1750, 2); /* 6d6h */ ov518_reg_w32(sd, 0xcd, 45, 2); /* 2dh */ ov518_reg_w32(sd, 0xce, 851, 2); /* 353h */ } reg_w(sd, 0x2f, 0x80); }",CWE-476,12 0,"bool WebGraphicsContext3DDefaultImpl::supportsCopyTextureToParentTextureCHROMIUM() { return false; } ",none,24 0,"EmbeddedWorkerContextClient::EmbeddedWorkerContextClient( int embedded_worker_id, int64 service_worker_version_id, const GURL& script_url) : embedded_worker_id_(embedded_worker_id), service_worker_version_id_(service_worker_version_id), script_url_(script_url), sender_(ChildThread::current()->thread_safe_sender()), main_thread_proxy_(base::MessageLoopProxy::current()), weak_factory_(this) { g_worker_client_tls.Pointer()->Set(this); } ",none,24 0,"DataObjectItem::DataObjectItem(ItemKind kind, const String& type, uint64_t sequence_number) : source_(kClipboardSource), kind_(kind), type_(type), sequence_number_(sequence_number) {} ",none,24 0," EmbeddedWorkerBrowserTest() : last_worker_status_(EmbeddedWorkerInstance::STOPPED) {} ",none,24 0," virtual ~ServiceWorkerVersionBrowserTest() {} ",none,24 1,"static int load_script(struct linux_binprm *bprm) { const char *i_arg, *i_name; char *cp; struct file *file; char interp[BINPRM_BUF_SIZE]; int retval; if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!') || (bprm->recursion_depth > BINPRM_MAX_RECURSION)) return -ENOEXEC; /* * This section does the #! interpretation. * Sorta complicated, but hopefully it will work. -TYT */ bprm->recursion_depth++; allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; bprm->buf[BINPRM_BUF_SIZE - 1] = '\0'; if ((cp = strchr(bprm->buf, '\n')) == NULL) cp = bprm->buf+BINPRM_BUF_SIZE-1; *cp = '\0'; while (cp > bprm->buf) { cp--; if ((*cp == ' ') || (*cp == '\t')) *cp = '\0'; else break; } for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++); if (*cp == '\0') return -ENOEXEC; /* No interpreter name found */ i_name = cp; i_arg = NULL; for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++) /* nothing */ ; while ((*cp == ' ') || (*cp == '\t')) *cp++ = '\0'; if (*cp) i_arg = cp; strcpy (interp, i_name); /* * OK, we've parsed out the interpreter name and * (optional) argument. * Splice in (1) the interpreter's name for argv[0] * (2) (optional) argument to interpreter * (3) filename of shell script (replace argv[0]) * * This is done in reverse order, because of how the * user environment and arguments are stored. */ retval = remove_arg_zero(bprm); if (retval) return retval; retval = copy_strings_kernel(1, &bprm->interp, bprm); if (retval < 0) return retval; bprm->argc++; if (i_arg) { retval = copy_strings_kernel(1, &i_arg, bprm); if (retval < 0) return retval; bprm->argc++; } retval = copy_strings_kernel(1, &i_name, bprm); if (retval) return retval; bprm->argc++; bprm->interp = interp; /* * OK, now restart the process with the interpreter's dentry. */ file = open_exec(interp); if (IS_ERR(file)) return PTR_ERR(file); bprm->file = file; retval = prepare_binprm(bprm); if (retval < 0) return retval; return search_binary_handler(bprm); }",CWE-200,4 1,"exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d, unsigned int ds, ExifLong o, ExifLong s) { /* Sanity checks */ if (o >= ds) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, ""ExifData"", ""Bogus thumbnail offset (%u)."", o); return; } if (s > ds - o) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, ""ExifData"", ""Bogus thumbnail size (%u), max would be %u."", s, ds-o); return; } if (data->data) exif_mem_free (data->priv->mem, data->data); if (!(data->data = exif_data_alloc (data, s))) { EXIF_LOG_NO_MEMORY (data->priv->log, ""ExifData"", s); data->size = 0; return; } data->size = s; memcpy (data->data, d + o, s); }",CWE-190,2 1,"size_t zmalloc_size(void *ptr) { void *realptr = (char*)ptr-PREFIX_SIZE; size_t size = *((size_t*)realptr); /* Assume at least that all the allocations are padded at sizeof(long) by * the underlying allocator. */ if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1)); return size+PREFIX_SIZE; }",CWE-787,16 0,"void SpeechSynthesis::resume() { if (!currentSpeechUtterance()) return; m_platformSpeechSynthesizer->resume(); } ",none,24 0,"ServiceWorkerScriptContext::~ServiceWorkerScriptContext() {} ",none,24 0,"void WebGraphicsContext3DDefaultImpl::generateMipmap(unsigned long target) { makeContextCurrent(); if (glGenerateMipmapEXT) glGenerateMipmapEXT(target); } ",none,24 1,"prepare_repo_download_targets(LrHandle *handle, LrYumRepo *repo, LrYumRepoMd *repomd, LrMetadataTarget *mdtarget, GSList **targets, GSList **cbdata_list, GError **err) { char *destdir; /* Destination dir */ destdir = handle->destdir; assert(destdir); assert(strlen(destdir)); assert(!err || *err == NULL); if(handle->cachedir) { lr_yum_switch_to_zchunk(handle, repomd); repo->use_zchunk = TRUE; } else { g_debug(""%s: Cache directory not set, disabling zchunk"", __func__); repo->use_zchunk = FALSE; } for (GSList *elem = repomd->records; elem; elem = g_slist_next(elem)) { int fd; char *path; LrDownloadTarget *target; LrYumRepoMdRecord *record = elem->data; CbData *cbdata = NULL; void *user_cbdata = NULL; LrEndCb endcb = NULL; if (mdtarget != NULL) { user_cbdata = mdtarget->cbdata; endcb = mdtarget->endcb; } assert(record); if (!lr_yum_repomd_record_enabled(handle, record->type, repomd->records)) continue; char *location_href = record->location_href; gboolean is_zchunk = FALSE; #ifdef WITH_ZCHUNK if (handle->cachedir && record->header_checksum) is_zchunk = TRUE; #endif /* WITH_ZCHUNK */ GSList *checksums = NULL; if (is_zchunk) { #ifdef WITH_ZCHUNK if(!prepare_repo_download_zck_target(handle, record, &path, &fd, &checksums, targets, err)) return FALSE; #endif /* WITH_ZCHUNK */ } else { if(!prepare_repo_download_std_target(handle, record, &path, &fd, &checksums, targets, err)) return FALSE; } if (handle->user_cb || handle->hmfcb) { cbdata = cbdata_new(handle->user_data, user_cbdata, handle->user_cb, handle->hmfcb, record->type); *cbdata_list = g_slist_append(*cbdata_list, cbdata); } target = lr_downloadtarget_new(handle, location_href, record->location_base, fd, NULL, checksums, 0, 0, NULL, cbdata, endcb, NULL, NULL, 0, 0, NULL, FALSE, is_zchunk); if(is_zchunk) { #ifdef WITH_ZCHUNK target->expectedsize = record->size_header; target->zck_header_size = record->size_header; #endif /* WITH_ZCHUNK */ } if (mdtarget != NULL) mdtarget->repomd_records_to_download++; *targets = g_slist_append(*targets, target); /* Because path may already exists in repo (while update) */ lr_yum_repo_update(repo, record->type, path); lr_free(path); } return TRUE; }",CWE-22,5 1,"static int __init lp_setup (char *str) { static int parport_ptr; int x; if (get_option(&str, &x)) { if (x == 0) { /* disable driver on ""lp="" or ""lp=0"" */ parport_nr[0] = LP_PARPORT_OFF; } else { printk(KERN_WARNING ""warning: 'lp=0x%x' is deprecated, ignored\n"", x); return 0; } } else if (!strncmp(str, ""parport"", 7)) { int n = simple_strtoul(str+7, NULL, 10); if (parport_ptr < LP_NO) parport_nr[parport_ptr++] = n; else printk(KERN_INFO ""lp: too many ports, %s ignored.\n"", str); } else if (!strcmp(str, ""auto"")) { parport_nr[0] = LP_PARPORT_AUTO; } else if (!strcmp(str, ""none"")) { parport_nr[parport_ptr++] = LP_PARPORT_NONE; } else if (!strcmp(str, ""reset"")) { reset = 1; } return 1; }",CWE-787,16 1,"static int hva_to_pfn_remapped(struct vm_area_struct *vma, unsigned long addr, bool *async, bool write_fault, bool *writable, kvm_pfn_t *p_pfn) { kvm_pfn_t pfn; pte_t *ptep; spinlock_t *ptl; int r; r = follow_pte(vma->vm_mm, addr, &ptep, &ptl); if (r) { /* * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does * not call the fault handler, so do it here. */ bool unlocked = false; r = fixup_user_fault(current->mm, addr, (write_fault ? FAULT_FLAG_WRITE : 0), &unlocked); if (unlocked) return -EAGAIN; if (r) return r; r = follow_pte(vma->vm_mm, addr, &ptep, &ptl); if (r) return r; } if (write_fault && !pte_write(*ptep)) { pfn = KVM_PFN_ERR_RO_FAULT; goto out; } if (writable) *writable = pte_write(*ptep); pfn = pte_pfn(*ptep); /* * Get a reference here because callers of *hva_to_pfn* and * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the * returned pfn. This is only needed if the VMA has VM_MIXEDMAP * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will * simply do nothing for reserved pfns. * * Whoever called remap_pfn_range is also going to call e.g. * unmap_mapping_range before the underlying pages are freed, * causing a call to our MMU notifier. */ kvm_get_pfn(pfn); out: pte_unmap_unlock(ptep, ptl); *p_pfn = pfn; return 0; }",CWE-119,0 1,"void APar_ExtractDetails(FILE *isofile, uint8_t optional_output) { char uint32_buffer[5]; Trackage track = {0}; AtomicInfo *mvhdAtom = APar_FindAtom(""moov.mvhd"", false, VERSIONED_ATOM, 0); if (mvhdAtom != NULL) { APar_ExtractMovieDetails(uint32_buffer, isofile, mvhdAtom); fprintf(stdout, ""Movie duration: %.3lf seconds (%s) - %.2lf* kbp/sec bitrate "" ""(*=approximate)\n"", movie_info.seconds, secsTOtime(movie_info.seconds), movie_info.simple_bitrate_calc); if (optional_output & SHOW_DATE_INFO) { fprintf(stdout, "" Presentation Creation Date (UTC): %s\n"", APar_extract_UTC(movie_info.creation_time)); fprintf(stdout, "" Presentation Modification Date (UTC): %s\n"", APar_extract_UTC(movie_info.modified_time)); } } AtomicInfo *iodsAtom = APar_FindAtom(""moov.iods"", false, VERSIONED_ATOM, 0); if (iodsAtom != NULL) { movie_info.contains_iods = true; APar_Extract_iods_Info(isofile, iodsAtom); } if (optional_output & SHOW_TRACK_INFO) { APar_TrackLevelInfo(&track, NULL); // With track_num set to 0, it will return the // total trak atom into total_tracks here. fprintf( stdout, ""Low-level details. Total tracks: %u\n"", track.total_tracks); fprintf(stdout, ""Trk Type Handler Kind Lang Bytes\n""); if (track.total_tracks > 0) { while (track.total_tracks > track.track_num) { track.track_num += 1; TrackInfo track_info = {0}; // tracknum, handler type, handler name APar_ExtractTrackDetails(uint32_buffer, isofile, &track, &track_info); uint16_t more_whitespace = purge_extraneous_characters(track_info.track_hdlr_name); if (strlen(track_info.track_hdlr_name) == 0) { memcpy(track_info.track_hdlr_name, ""[none listed]"", 13); } fprintf(stdout, ""%u %s %s"", track.track_num, uint32tochar4(track_info.track_type, uint32_buffer), track_info.track_hdlr_name); uint16_t handler_len = strlen(track_info.track_hdlr_name); if (handler_len < 25 + more_whitespace) { for (uint16_t i = handler_len; i < 25 + more_whitespace; i++) { fprintf(stdout, "" ""); } } // codec, language fprintf(stdout, "" %s %s %"" PRIu64, uint32tochar4(track_info.track_codec, uint32_buffer), track_info.unpacked_lang, track_info.sample_aggregate); if (track_info.encoder_name[0] != 0 && track_info.contains_esds) { purge_extraneous_characters(track_info.encoder_name); fprintf(stdout, "" Encoder: %s"", track_info.encoder_name); } if (track_info.type_of_track & DRM_PROTECTED_TRACK) { fprintf(stdout, "" (protected %s)"", uint32tochar4(track_info.protected_codec, uint32_buffer)); } fprintf(stdout, ""\n""); /*---------------------------------*/ if (track_info.type_of_track & VIDEO_TRACK || track_info.type_of_track & AUDIO_TRACK) { APar_Print_TrackDetails(&track_info); } if (optional_output & SHOW_DATE_INFO) { fprintf(stdout, "" Creation Date (UTC): %s\n"", APar_extract_UTC(track_info.creation_time)); fprintf(stdout, "" Modification Date (UTC): %s\n"", APar_extract_UTC(track_info.modified_time)); } } } } }",CWE-787,16 1,"UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames) { UINT32 index; size_t position; BOOL asciiNames; int formatNameLength; char* szFormatName; WCHAR* wszFormatName; UINT32 dataLen = formatList->dataLen; CLIPRDR_FORMAT* formats = NULL; UINT error = CHANNEL_RC_OK; asciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE; index = 0; formatList->numFormats = 0; position = Stream_GetPosition(s); if (!formatList->dataLen) { /* empty format list */ formatList->formats = NULL; formatList->numFormats = 0; } else if (!useLongFormatNames) { formatList->numFormats = (dataLen / 36); if ((formatList->numFormats * 36) != dataLen) { WLog_ERR(TAG, ""Invalid short format list length: %"" PRIu32 """", dataLen); return ERROR_INTERNAL_ERROR; } if (formatList->numFormats) formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT)); if (!formats) { WLog_ERR(TAG, ""calloc failed!""); return CHANNEL_RC_NO_MEMORY; } formatList->formats = formats; while (dataLen) { Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */ dataLen -= 4; formats[index].formatName = NULL; /* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is ""a 32-byte block containing * the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters * or 16 Unicode characters)"" * However, both Windows RDSH and mstsc violate this specs as seen in the following * example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.] * These are 16 unicode charaters - *without* terminating null ! */ if (asciiNames) { szFormatName = (char*)Stream_Pointer(s); if (szFormatName[0]) { /* ensure null termination */ formats[index].formatName = (char*)malloc(32 + 1); if (!formats[index].formatName) { WLog_ERR(TAG, ""malloc failed!""); error = CHANNEL_RC_NO_MEMORY; goto error_out; } CopyMemory(formats[index].formatName, szFormatName, 32); formats[index].formatName[32] = '\0'; } } else { wszFormatName = (WCHAR*)Stream_Pointer(s); if (wszFormatName[0]) { /* ConvertFromUnicode always returns a null-terminated * string on success, even if the source string isn't. */ if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16, &(formats[index].formatName), 0, NULL, NULL) < 1) { WLog_ERR(TAG, ""failed to convert short clipboard format name""); error = ERROR_INTERNAL_ERROR; goto error_out; } } } Stream_Seek(s, 32); dataLen -= 32; index++; } } else { while (dataLen) { Stream_Seek(s, 4); /* formatId (4 bytes) */ dataLen -= 4; wszFormatName = (WCHAR*)Stream_Pointer(s); if (!wszFormatName[0]) formatNameLength = 0; else formatNameLength = _wcslen(wszFormatName); Stream_Seek(s, (formatNameLength + 1) * 2); dataLen -= ((formatNameLength + 1) * 2); formatList->numFormats++; } dataLen = formatList->dataLen; Stream_SetPosition(s, position); if (formatList->numFormats) formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT)); if (!formats) { WLog_ERR(TAG, ""calloc failed!""); return CHANNEL_RC_NO_MEMORY; } formatList->formats = formats; while (dataLen) { Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */ dataLen -= 4; formats[index].formatName = NULL; wszFormatName = (WCHAR*)Stream_Pointer(s); if (!wszFormatName[0]) formatNameLength = 0; else formatNameLength = _wcslen(wszFormatName); if (formatNameLength) { if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, -1, &(formats[index].formatName), 0, NULL, NULL) < 1) { WLog_ERR(TAG, ""failed to convert long clipboard format name""); error = ERROR_INTERNAL_ERROR; goto error_out; } } Stream_Seek(s, (formatNameLength + 1) * 2); dataLen -= ((formatNameLength + 1) * 2); index++; } } return error; error_out: cliprdr_free_format_list(formatList); return error; }",CWE-125,1 0,"AudioContext::AudioContext(Document* document) : ActiveDOMObject(document) , m_isStopScheduled(false) , m_isCleared(false) , m_isInitialized(false) , m_destinationNode(nullptr) , m_isResolvingResumePromises(false) , m_automaticPullNodesNeedUpdating(false) , m_connectionCount(0) , m_didInitializeContextGraphMutex(false) , m_audioThread(0) , m_isOfflineContext(false) , m_contextState(Suspended) , m_cachedSampleFrame(0) { m_didInitializeContextGraphMutex = true; m_destinationNode = DefaultAudioDestinationNode::create(this); initialize(); #if DEBUG_AUDIONODE_REFERENCES fprintf(stderr, ""%p: AudioContext::AudioContext() #%u\n"", this, AudioContext::s_hardwareContextCount); #endif } ",none,24 1,"static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_codestream_info_t *l_cstr_info = 00; OPJ_UINT32 l_remaining_data; opj_tcd_marker_info_t* marker_info = NULL; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); if (total_data_size < 4) { opj_event_msg(p_manager, EVT_ERROR, ""Not enough bytes in output buffer to write SOD marker\n""); return OPJ_FALSE; } opj_write_bytes(p_data, J2K_MS_SOD, 2); /* SOD */ /* make room for the EOF marker */ l_remaining_data = total_data_size - 4; /* update tile coder */ p_tile_coder->tp_num = p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ; p_tile_coder->cur_tp_num = p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) { //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1; l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; } else {*/ /* TODO if (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream)) { cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream); }*/ /*}*/ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2); */ assert(0 && ""TODO""); #endif /* USE_JPWL */ /* <m_specific_param.m_encoder.m_current_tile_part_number == 0) { p_tile_coder->tcd_image->tiles->packno = 0; #ifdef deadcode if (l_cstr_info) { l_cstr_info->packno = 0; } #endif } *p_data_written = 0; if (p_j2k->m_specific_param.m_encoder.m_PLT) { marker_info = opj_tcd_marker_info_create( p_j2k->m_specific_param.m_encoder.m_PLT); if (marker_info == NULL) { opj_event_msg(p_manager, EVT_ERROR, ""Cannot encode tile: opj_tcd_marker_info_create() failed\n""); return OPJ_FALSE; } } assert(l_remaining_data > p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT); l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT; if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data + 2, p_data_written, l_remaining_data, l_cstr_info, marker_info, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, ""Cannot encode tile\n""); opj_tcd_marker_info_destroy(marker_info); return OPJ_FALSE; } /* For SOD */ *p_data_written += 2; if (p_j2k->m_specific_param.m_encoder.m_PLT) { OPJ_UINT32 l_data_written_PLT = 0; OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc( p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT); if (!p_PLT_buffer) { opj_event_msg(p_manager, EVT_ERROR, ""Cannot allocate memory\n""); opj_tcd_marker_info_destroy(marker_info); return OPJ_FALSE; } if (!opj_j2k_write_plt_in_memory(p_j2k, marker_info, p_PLT_buffer, &l_data_written_PLT, p_manager)) { opj_tcd_marker_info_destroy(marker_info); opj_free(p_PLT_buffer); return OPJ_FALSE; } assert(l_data_written_PLT <= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT); /* Move PLT marker(s) before SOD */ memmove(p_data + l_data_written_PLT, p_data, *p_data_written); memcpy(p_data, p_PLT_buffer, l_data_written_PLT); opj_free(p_PLT_buffer); *p_data_written += l_data_written_PLT; } opj_tcd_marker_info_destroy(marker_info); return OPJ_TRUE; }",CWE-20,3 0,"ACTION_P2(CaptureStopped, decoder, vc_impl) { decoder->OnStopped(vc_impl); } ",none,24 0,"void EmbeddedWorkerContextClient::workerContextStarted( blink::WebServiceWorkerContextProxy* proxy) { DCHECK(!worker_task_runner_); worker_task_runner_ = new WorkerThreadTaskRunner( WorkerTaskRunner::Instance()->CurrentWorkerId()); DCHECK_NE(0, WorkerTaskRunner::Instance()->CurrentWorkerId()); DCHECK(g_worker_client_tls.Pointer()->Get() == NULL); DCHECK(!script_context_); g_worker_client_tls.Pointer()->Set(this); script_context_.reset(new ServiceWorkerScriptContext(this, proxy)); worker_task_runner_->PostTask( FROM_HERE, base::Bind(&EmbeddedWorkerContextClient::SendWorkerStarted, weak_factory_.GetWeakPtr())); } ",none,24 0,"DataObjectItem* DataObjectItem::CreateFromURL(const String& url, const String& title) { DataObjectItem* item = MakeGarbageCollected(kStringKind, kMimeTypeTextURIList); item->data_ = url; item->title_ = title; return item; } ",none,24 1,"GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragmentBox *moof_box, u64 moof_offset, s32 compressed_diff, u64 *cumulated_offset, Bool is_first_merge) { u32 i, j, chunk_size, track_num; u64 base_offset, data_offset, traf_duration; u32 def_duration, DescIndex, def_size, def_flags; u32 duration, size, flags, prev_trun_data_offset, sample_index; u8 pad, sync; u16 degr; Bool first_samp_in_traf=GF_TRUE; Bool store_traf_map=GF_FALSE; u8 *moof_template=NULL; u32 moof_template_size=0; Bool is_seg_start = GF_FALSE; u64 seg_start=0, sidx_start=0, sidx_end=0, frag_start=0, last_dts=0; GF_TrackFragmentRunBox *trun; GF_TrunEntry *ent; #ifdef GF_ENABLE_CTRN GF_TrackFragmentBox *traf_ref = NULL; #endif GF_Err stbl_AppendTime(GF_SampleTableBox *stbl, u32 duration, u32 nb_pack); GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack); GF_Err stbl_AppendChunk(GF_SampleTableBox *stbl, u64 offset); GF_Err stbl_AppendSampleToChunk(GF_SampleTableBox *stbl, u32 DescIndex, u32 samplesInChunk); GF_Err stbl_AppendCTSOffset(GF_SampleTableBox *stbl, s32 CTSOffset); GF_Err stbl_AppendRAP(GF_SampleTableBox *stbl, u8 isRap); GF_Err stbl_AppendPadding(GF_SampleTableBox *stbl, u8 padding); GF_Err stbl_AppendDegradation(GF_SampleTableBox *stbl, u16 DegradationPriority); if (trak->Header->trackID != traf->tfhd->trackID) return GF_OK; if (!trak->Media->information->sampleTable || !trak->Media->information->sampleTable->SampleSize || !trak->Media->information->sampleTable->TimeToSample || !trak->Media->information->sampleTable->SampleToChunk || !trak->Media->information->sampleTable->ChunkOffset ) { return GF_ISOM_INVALID_FILE; } if (!traf->trex->track) traf->trex->track = trak; //setup all our defaults DescIndex = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DESC) ? traf->tfhd->sample_desc_index : traf->trex->def_sample_desc_index; if (!DescIndex) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] default sample description set to 0, likely broken ! Fixing to 1\n"" )); DescIndex = 1; } else if (DescIndex > gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] default sample description set to %d but only %d sample description(s), likely broken ! Fixing to 1\n"", DescIndex, gf_list_count(trak->Media->information->sampleTable->SampleDescription->child_boxes))); DescIndex = 1; } #ifdef GF_ENABLE_CTRN if (traf->trex->inherit_from_traf_id) { u32 traf_count = gf_list_count(moof_box->TrackList); for (i=0; iTrackList, i); if (atraf->tfhd && atraf->tfhd->trackID==traf->trex->inherit_from_traf_id) { traf_ref = atraf; break; } } } #endif def_duration = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_DUR) ? traf->tfhd->def_sample_duration : traf->trex->def_sample_duration; def_size = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ? traf->tfhd->def_sample_size : traf->trex->def_sample_size; def_flags = (traf->tfhd->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ? traf->tfhd->def_sample_flags : traf->trex->def_sample_flags; //locate base offset, by default use moof (dash-like) base_offset = moof_offset; //explicit base offset, use it if (traf->tfhd->flags & GF_ISOM_TRAF_BASE_OFFSET) base_offset = traf->tfhd->base_data_offset; //no moof offset and no explicit offset, the offset is the end of the last written chunk of //the previous traf. For the first traf, *cumulated_offset is actually moof offset else if (!(traf->tfhd->flags & GF_ISOM_MOOF_BASE_OFFSET)) base_offset = *cumulated_offset; chunk_size = 0; prev_trun_data_offset = 0; data_offset = 0; traf_duration = 0; /*in playback mode*/ if (traf->tfdt && is_first_merge) { #ifndef GPAC_DISABLE_LOG if (trak->moov->mov->NextMoofNumber && trak->present_in_scalable_segment && trak->sample_count_at_seg_start && (trak->dts_at_seg_start != traf->tfdt->baseMediaDecodeTime)) { s32 drift = (s32) ((s64) traf->tfdt->baseMediaDecodeTime - (s64)trak->dts_at_seg_start); if (drift<0) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] Warning: TFDT timing ""LLD"" less than cumulated timing ""LLD"" - using tfdt\n"", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start )); } else { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""[iso file] TFDT timing ""LLD"" higher than cumulated timing ""LLD"" (last sample got extended in duration)\n"", traf->tfdt->baseMediaDecodeTime, trak->dts_at_seg_start )); } } #endif trak->dts_at_seg_start = traf->tfdt->baseMediaDecodeTime; } else if (traf->tfxd) { trak->dts_at_seg_start = traf->tfxd->absolute_time_in_track_timescale; } if (traf->tfxd) { trak->last_tfxd_value = traf->tfxd->absolute_time_in_track_timescale; trak->last_tfxd_value += traf->tfxd->fragment_duration_in_track_timescale; } if (traf->tfrf) { if (trak->tfrf) gf_isom_box_del_parent(&trak->child_boxes, (GF_Box *)trak->tfrf); trak->tfrf = traf->tfrf; gf_list_del_item(traf->child_boxes, traf->tfrf); gf_list_add(trak->child_boxes, trak->tfrf); } if (trak->moov->mov->signal_frag_bounds) { store_traf_map = GF_TRUE; if (is_first_merge) { GF_MovieFragmentBox *moof_clone = NULL; gf_isom_box_freeze_order((GF_Box *)moof_box); gf_isom_clone_box((GF_Box *)moof_box, (GF_Box **)&moof_clone); if (moof_clone) { GF_BitStream *bs; for (i=0; iTrackList); i++) { GF_TrackFragmentBox *traf_clone = gf_list_get(moof_clone->TrackList, i); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->TrackRuns); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroups); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sampleGroupsDescription); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sub_samples); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_offsets); gf_isom_box_array_reset_parent(&traf_clone->child_boxes, traf_clone->sai_sizes); if (traf_clone->sample_encryption) { gf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sample_encryption); traf_clone->sample_encryption = NULL; } if (traf_clone->sdtp) { gf_isom_box_del_parent(&traf_clone->child_boxes, (GF_Box *) traf_clone->sdtp); traf_clone->sdtp = NULL; } } gf_isom_box_size((GF_Box *)moof_clone); bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); if (trak->moov->mov->seg_styp) { gf_isom_box_size(trak->moov->mov->seg_styp); gf_isom_box_write(trak->moov->mov->seg_styp, bs); } if (trak->moov->mov->root_sidx) { gf_isom_box_size((GF_Box *)trak->moov->mov->root_sidx); gf_isom_box_write((GF_Box *)trak->moov->mov->root_sidx, bs); } if (trak->moov->mov->seg_ssix) { gf_isom_box_size(trak->moov->mov->seg_ssix); gf_isom_box_write(trak->moov->mov->seg_ssix, bs); } gf_isom_box_write((GF_Box *)moof_clone, bs); gf_isom_box_del((GF_Box*)moof_clone); gf_bs_get_content(bs, &moof_template, &moof_template_size); gf_bs_del(bs); } } if (trak->moov->mov->seg_styp) { is_seg_start = GF_TRUE; seg_start = trak->moov->mov->styp_start_offset; } if (trak->moov->mov->root_sidx) { is_seg_start = GF_TRUE; sidx_start = trak->moov->mov->sidx_start_offset; sidx_end = trak->moov->mov->sidx_end_offset; if (! seg_start || (sidx_startmoov->mov->current_top_box_start; } else if (trak->moov->mov->store_traf_map) { store_traf_map = GF_TRUE; } sample_index = 0; i=0; while ((trun = (GF_TrackFragmentRunBox *)gf_list_enum(traf->TrackRuns, &i))) { //merge the run for (j=0; jsample_count; j++) { GF_Err e; s32 cts_offset=0; if (jnb_samples) { ent = &trun->samples[j]; } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Track %d doesn't have enough trun entries (%d) compared to sample count (%d) in run\n"", traf->trex->trackID, trun->nb_samples, trun->sample_count )); break; } size = def_size; duration = def_duration; flags = def_flags; //CTS - if flag not set (trun or ctrn) defaults to 0 which is the base value after alloc //we just need to overrite its value if inherited cts_offset = ent->CTS_Offset; #ifdef GF_ENABLE_CTRN if (trun->use_ctrn) { if (!j && (trun->ctrn_flags & GF_ISOM_CTRN_FIRST_SAMPLE) ) { if (trun->ctrn_first_dur) duration = ent->Duration; if (trun->ctrn_first_size) size = ent->size; if (trun->ctrn_first_ctts) flags = ent->flags; } else { if (trun->ctrn_dur) duration = ent->Duration; if (trun->ctrn_size) size = ent->size; if (trun->ctrn_sample_flags) flags = ent->flags; } /*re-override*/ if (trun->ctrn_flags & 0xF0) { GF_TrunEntry *ref_entry; if (!traf_ref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Track %d use traf inheritance to track ID %d but reference traf not found\n"", traf->trex->trackID, traf->trex->inherit_from_traf_id )); break; } ref_entry = traf_get_sample_entry(traf_ref, sample_index); if (!ref_entry) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Track %d use traf inheritance but sample %d not found in reference traf\n"", traf->trex->trackID, sample_index+1 )); break; } if (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_DUR) duration = ref_entry->Duration; if (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_SIZE) size = ref_entry->size; if (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_FLAGS) flags = ref_entry->flags; if (trun->ctrn_flags & GF_ISOM_CTRN_INHERIT_CTSO) cts_offset = ref_entry->CTS_Offset; } } else #endif { if (trun->flags & GF_ISOM_TRUN_DURATION) duration = ent->Duration; if (trun->flags & GF_ISOM_TRUN_SIZE) size = ent->size; if (trun->flags & GF_ISOM_TRUN_FLAGS) { flags = ent->flags; } else if (!j && (trun->flags & GF_ISOM_TRUN_FIRST_FLAG)) { flags = trun->first_sample_flags; } } sample_index++; /*store the resolved value in case we have inheritance*/ ent->size = size; ent->Duration = duration; ent->flags = flags; ent->CTS_Offset = cts_offset; last_dts += duration; //add size first if (!trak->Media->information->sampleTable->SampleSize) { trak->Media->information->sampleTable->SampleSize = (GF_SampleSizeBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSZ); if (!trak->Media->information->sampleTable->SampleSize) return GF_OUT_OF_MEM; } e = stbl_AppendSize(trak->Media->information->sampleTable, size, ent->nb_pack); if (e) return e; //then TS if (!trak->Media->information->sampleTable->TimeToSample) { trak->Media->information->sampleTable->TimeToSample = (GF_TimeToSampleBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STTS); if (!trak->Media->information->sampleTable->TimeToSample) return GF_OUT_OF_MEM; } e = stbl_AppendTime(trak->Media->information->sampleTable, duration, ent->nb_pack); if (e) return e; //add chunk on first sample if (!j) { u64 final_offset; data_offset = base_offset; //we have an explicit data offset for this trun if (trun->flags & GF_ISOM_TRUN_DATA_OFFSET) { data_offset += trun->data_offset; /*reset chunk size since data is now relative to this trun*/ chunk_size = 0; /*remember this data offset for following trun*/ prev_trun_data_offset = trun->data_offset; /*if mdat is located after the moof, and the moof was compressed, adjust offset otherwise the offset does not need adjustment*/ if (trun->data_offset>=0) { data_offset -= compressed_diff; prev_trun_data_offset -= compressed_diff; } } //we had an explicit data offset for the previous trun, use it + chunk size else if (prev_trun_data_offset) { /*data offset is previous chunk size plus previous offset of the trun*/ data_offset += prev_trun_data_offset + chunk_size; } //no explicit data offset, continuous data after last data in previous chunk else { data_offset += chunk_size; //data offset of first trun in first traf, adjust if compressed moof if ((i==1) && (trun->data_offset>=0)) { data_offset -= compressed_diff; } } final_offset = data_offset; //adjust offset if moov was also compressed and we are still in the same file //so that later call to gf_isom_get_sample properly adjust back the offset if (trak->moov->compressed_diff) { final_offset += trak->moov->compressed_diff; } if (!trak->Media->information->sampleTable->ChunkOffset) { trak->Media->information->sampleTable->ChunkOffset = gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STCO); if (!trak->Media->information->sampleTable->ChunkOffset) return GF_OUT_OF_MEM; } e = stbl_AppendChunk(trak->Media->information->sampleTable, final_offset); if (e) return e; //then sampleToChunk if (!trak->Media->information->sampleTable->SampleToChunk) { trak->Media->information->sampleTable->SampleToChunk = (GF_SampleToChunkBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_STSC); if (!trak->Media->information->sampleTable->SampleToChunk) return GF_OUT_OF_MEM; } e = stbl_AppendSampleToChunk(trak->Media->information->sampleTable, DescIndex, trun->sample_count); if (e) return e; } chunk_size += size; if (store_traf_map && first_samp_in_traf) { first_samp_in_traf = GF_FALSE; e = stbl_AppendTrafMap(trak->Media->information->sampleTable, is_seg_start, seg_start, frag_start, moof_template, moof_template_size, sidx_start, sidx_end); if (e) return e; //do not deallocate, the memory is now owned by traf map moof_template = NULL; moof_template_size = 0; } if (ent->nb_pack>1) { j+= ent->nb_pack-1; traf_duration += ent->nb_pack*duration; continue; } traf_duration += duration; e = stbl_AppendCTSOffset(trak->Media->information->sampleTable, cts_offset); if (e) return e; //flags sync = GF_ISOM_GET_FRAG_SYNC(flags); if (trak->Media->information->sampleTable->no_sync_found && sync) { trak->Media->information->sampleTable->no_sync_found = 0; } e = stbl_AppendRAP(trak->Media->information->sampleTable, sync); if (e) return e; pad = GF_ISOM_GET_FRAG_PAD(flags); if (pad) { e = stbl_AppendPadding(trak->Media->information->sampleTable, pad); if (e) return e; } degr = GF_ISOM_GET_FRAG_DEG(flags); if (degr) { e = stbl_AppendDegradation(trak->Media->information->sampleTable, degr); if (e) return e; } e = stbl_AppendDependencyType(trak->Media->information->sampleTable, GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags)); if (e) return e; } } if (trak->moov->mov->is_smooth && !traf->tfdt && !traf->tfxd) { if (is_first_merge) trak->dts_at_seg_start = trak->dts_at_next_seg_start; trak->dts_at_next_seg_start += last_dts; } if (traf_duration && trak->editBox && trak->editBox->editList) { for (i=0; ieditBox->editList->entryList); i++) { GF_EdtsEntry *edts_e = gf_list_get(trak->editBox->editList->entryList, i); if (edts_e->was_empty_dur) { u64 extend_dur = traf_duration; extend_dur *= trak->moov->mvhd->timeScale; extend_dur /= trak->Media->mediaHeader->timeScale; edts_e->segmentDuration += extend_dur; } else if (!edts_e->segmentDuration) { edts_e->was_empty_dur = GF_TRUE; if ((s64) traf_duration > edts_e->mediaTime) traf_duration -= edts_e->mediaTime; else traf_duration = 0; edts_e->segmentDuration = traf_duration; edts_e->segmentDuration *= trak->moov->mvhd->timeScale; edts_e->segmentDuration /= trak->Media->mediaHeader->timeScale; } } } //in any case, update the cumulated offset //this will handle hypothetical files mixing MOOF offset and implicit non-moof offset *cumulated_offset = data_offset + chunk_size; /*merge sample groups*/ if (traf->sampleGroups) { GF_List *groups; GF_List *groupDescs; Bool is_identical_sgpd = GF_TRUE; u32 *new_idx = NULL, new_idx_count=0; if (!trak->Media->information->sampleTable->sampleGroups) trak->Media->information->sampleTable->sampleGroups = gf_list_new(); if (!trak->Media->information->sampleTable->sampleGroupsDescription) trak->Media->information->sampleTable->sampleGroupsDescription = gf_list_new(); groupDescs = trak->Media->information->sampleTable->sampleGroupsDescription; for (i=0; isampleGroupsDescription); i++) { GF_SampleGroupDescriptionBox *new_sgdesc = NULL; GF_SampleGroupDescriptionBox *sgdesc = gf_list_get(traf->sampleGroupsDescription, i); for (j=0; jgrouping_type==sgdesc->grouping_type) break; new_sgdesc = NULL; } /*new description, move it to our sample table*/ if (!new_sgdesc) { gf_list_add(groupDescs, sgdesc); gf_list_add(trak->Media->information->sampleTable->child_boxes, sgdesc); gf_list_rem(traf->sampleGroupsDescription, i); gf_list_del_item(traf->child_boxes, sgdesc); i--; } /*merge descriptions*/ else { u32 count; is_identical_sgpd = gf_isom_is_identical_sgpd(new_sgdesc, sgdesc, 0); if (is_identical_sgpd) continue; new_idx_count = gf_list_count(sgdesc->group_descriptions); new_idx = (u32 *)gf_malloc(new_idx_count * sizeof(u32)); if (!new_idx) return GF_OUT_OF_MEM; count = 0; while (gf_list_count(sgdesc->group_descriptions)) { void *sgpd_entry = gf_list_get(sgdesc->group_descriptions, 0); Bool new_entry = GF_TRUE; for (j = 0; j < gf_list_count(new_sgdesc->group_descriptions); j++) { void *ptr = gf_list_get(new_sgdesc->group_descriptions, j); if (gf_isom_is_identical_sgpd(sgpd_entry, ptr, new_sgdesc->grouping_type)) { new_idx[count] = j + 1; count ++; new_entry = GF_FALSE; gf_free(sgpd_entry); break; } } if (new_entry) { gf_list_add(new_sgdesc->group_descriptions, sgpd_entry); new_idx[count] = gf_list_count(new_sgdesc->group_descriptions); count ++; } gf_list_rem(sgdesc->group_descriptions, 0); } } } groups = trak->Media->information->sampleTable->sampleGroups; for (i=0; isampleGroups); i++) { GF_SampleGroupBox *stbl_group = NULL; GF_SampleGroupBox *frag_group = gf_list_get(traf->sampleGroups, i); for (j=0; jgrouping_type==stbl_group->grouping_type) && (frag_group->grouping_type_parameter==stbl_group->grouping_type_parameter)) break; stbl_group = NULL; } if (!stbl_group) { stbl_group = (GF_SampleGroupBox *) gf_isom_box_new_parent(&trak->Media->information->sampleTable->child_boxes, GF_ISOM_BOX_TYPE_SBGP); if (!stbl_group) return GF_OUT_OF_MEM; stbl_group->grouping_type = frag_group->grouping_type; stbl_group->grouping_type_parameter = frag_group->grouping_type_parameter; stbl_group->version = frag_group->version; gf_list_add(groups, stbl_group); } if (is_identical_sgpd) { //adjust sgpd index: in traf index start at 0x1001 for (j = 0; j < frag_group->entry_count; j++) frag_group->sample_entries[j].group_description_index &= 0x0FFFF; if (frag_group->entry_count && stbl_group->entry_count && (frag_group->sample_entries[0].group_description_index==stbl_group->sample_entries[stbl_group->entry_count-1].group_description_index) ) { stbl_group->sample_entries[stbl_group->entry_count - 1].sample_count += frag_group->sample_entries[0].sample_count; if (frag_group->entry_count>1) { stbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count - 1)); memcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[1], sizeof(GF_SampleGroupEntry) * (frag_group->entry_count - 1)); stbl_group->entry_count += frag_group->entry_count - 1; } } else { stbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count)); memcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count); stbl_group->entry_count += frag_group->entry_count; } } else { stbl_group->sample_entries = gf_realloc(stbl_group->sample_entries, sizeof(GF_SampleGroupEntry) * (stbl_group->entry_count + frag_group->entry_count)); //adjust sgpd index for (j = 0; j < frag_group->entry_count; j++) { u32 sgidx = frag_group->sample_entries[j].group_description_index; if (sgidx > 0x10000) { sgidx -= 0x10001; if (sgidx>=new_idx_count) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[isobmf] corrupted sample group index in fragment %d but only %d group descriptions in fragment\n"", sgidx, new_idx_count)); } else { frag_group->sample_entries[j].group_description_index = new_idx[sgidx]; } } } memcpy(&stbl_group->sample_entries[stbl_group->entry_count], &frag_group->sample_entries[0], sizeof(GF_SampleGroupEntry) * frag_group->entry_count); stbl_group->entry_count += frag_group->entry_count; } } if (new_idx) gf_free(new_idx); } /*content is encrypted*/ track_num = gf_isom_get_tracknum_from_id(trak->moov, trak->Header->trackID); if (gf_isom_is_cenc_media(trak->moov->mov, track_num, DescIndex) || traf->sample_encryption) { /*Merge sample auxiliary encryption information*/ GF_SampleEncryptionBox *senc = NULL; u32 scheme_type; gf_isom_get_cenc_info(trak->moov->mov, track_num, DescIndex, NULL, &scheme_type, NULL); if (traf->sample_encryption) { for (i = 0; i < gf_list_count(trak->Media->information->sampleTable->child_boxes); i++) { GF_Box *a = (GF_Box *)gf_list_get(trak->Media->information->sampleTable->child_boxes, i); if (a->type != traf->sample_encryption->type) continue; if ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) { senc = (GF_SampleEncryptionBox *)a; break; } else if (a->type ==GF_ISOM_BOX_TYPE_SENC) { senc = (GF_SampleEncryptionBox *)a; break; } } if (!senc && trak->sample_encryption) senc = trak->sample_encryption; if (!senc) { if (traf->sample_encryption->piff_type==1) { senc = (GF_SampleEncryptionBox *)gf_isom_create_piff_psec_box(1, 0x2, 0, 0, NULL); } else { senc = gf_isom_create_samp_enc_box(1, 0x2); } if (!trak->Media->information->sampleTable->child_boxes) trak->Media->information->sampleTable->child_boxes = gf_list_new(); trak->sample_encryption = senc; if (!trak->child_boxes) trak->child_boxes = gf_list_new(); gf_list_add(trak->child_boxes, senc); } } /*get sample auxiliary information by saiz/saio rather than by parsing senc box*/ if (gf_isom_cenc_has_saiz_saio_traf(traf, scheme_type)) { u32 nb_saio; u32 aux_info_type; u64 offset; GF_Err e; Bool is_encrypted; GF_SampleAuxiliaryInfoOffsetBox *saio = NULL; GF_SampleAuxiliaryInfoSizeBox *saiz = NULL; offset = nb_saio = 0; for (i = 0; i < gf_list_count(traf->sai_offsets); i++) { saio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(traf->sai_offsets, i); aux_info_type = saio->aux_info_type; if (!aux_info_type) aux_info_type = scheme_type; /*if we have only 1 sai_offsets, assume that its type is cenc*/ if ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) || (aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) || (gf_list_count(traf->sai_offsets) == 1)) { offset = saio->offsets[0] + moof_offset; nb_saio = saio->entry_count; break; } } for (i = 0; i < gf_list_count(traf->sai_sizes); i++) { saiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i); aux_info_type = saiz->aux_info_type; if (!aux_info_type) aux_info_type = scheme_type; /*if we have only 1 sai_sizes, assume that its type is cenc*/ if ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) || (aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) || (gf_list_count(traf->sai_sizes) == 1)) { break; } } if (saiz && saio && senc) { for (i = 0; i < saiz->sample_count; i++) { GF_CENCSampleAuxInfo *sai; const u8 *key_info=NULL; u32 key_info_size; u64 cur_position; if (nb_saio != 1) offset = saio->offsets[i] + moof_offset; size = saiz->default_sample_info_size ? saiz->default_sample_info_size : saiz->sample_info_size[i]; cur_position = gf_bs_get_position(trak->moov->mov->movieFileMap->bs); gf_bs_seek(trak->moov->mov->movieFileMap->bs, offset); GF_SAFEALLOC(sai, GF_CENCSampleAuxInfo); if (!sai) return GF_OUT_OF_MEM; e = gf_isom_get_sample_cenc_info_internal(trak, traf, senc, i+1, &is_encrypted, NULL, NULL, &key_info, &key_info_size); if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[isobmf] could not get cenc info for sample %d: %s\n"", i+1, gf_error_to_string(e) )); return e; } if (is_encrypted) { sai->cenc_data_size = size; sai->cenc_data = gf_malloc(sizeof(u8)*size); if (!sai->cenc_data) return GF_OUT_OF_MEM; gf_bs_read_data(trak->moov->mov->movieFileMap->bs, sai->cenc_data, sai->cenc_data_size); } else { sai->isNotProtected=1; } if (key_info) { //not multikey if (!key_info[0]) { //size greater than IV if (size > key_info[3]) senc->flags = 0x00000002; } //multikey, always use subsamples else { senc->flags = 0x00000002; } } gf_bs_seek(trak->moov->mov->movieFileMap->bs, cur_position); gf_list_add(senc->samp_aux_info, sai); e = gf_isom_cenc_merge_saiz_saio(senc, trak->Media->information->sampleTable, offset, size); if (e) return e; if (nb_saio == 1) offset += size; } } } else if (traf->sample_encryption) { senc_Parse(trak->moov->mov->movieFileMap->bs, trak, traf, traf->sample_encryption); trak->sample_encryption->AlgorithmID = traf->sample_encryption->AlgorithmID; if (!trak->sample_encryption->IV_size) trak->sample_encryption->IV_size = traf->sample_encryption->IV_size; if (!trak->sample_encryption->samp_aux_info) trak->sample_encryption->samp_aux_info = gf_list_new(); gf_list_transfer(trak->sample_encryption->samp_aux_info, traf->sample_encryption->samp_aux_info); if (traf->sample_encryption->flags & 0x00000002) trak->sample_encryption->flags |= 0x00000002; } } return GF_OK; }",CWE-476,12 0,"const AtomicString& SpeechSynthesis::interfaceName() const { return EventTargetNames::SpeechSynthesisUtterance; } ",none,24 1,"service_info *FindServiceControlURLPath( service_table *table, const char *controlURLPath) { service_info *finger = NULL; uri_type parsed_url; uri_type parsed_url_in; if (table && parse_uri(controlURLPath, strlen(controlURLPath), &parsed_url_in) == HTTP_SUCCESS) { finger = table->serviceList; while (finger) { if (finger->controlURL) { if (parse_uri(finger->controlURL, strlen(finger->controlURL), &parsed_url) == HTTP_SUCCESS) { if (!token_cmp(&parsed_url.pathquery, &parsed_url_in.pathquery)) { return finger; } } } finger = finger->next; } } return NULL; }",CWE-476,12 0,"void TranslateManager::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::NAV_ENTRY_COMMITTED: { NavigationController* controller = Source(source).ptr(); NavigationController::LoadCommittedDetails* load_details = Details(details).ptr(); NavigationEntry* entry = controller->GetActiveEntry(); if (!entry) { NOTREACHED(); return; } if (!load_details->is_main_frame && controller->tab_contents()->language_state().translation_declined()) { return; } if (entry->transition_type() != PageTransition::RELOAD && load_details->type != NavigationType::SAME_PAGE) { return; } MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod( &TranslateManager::InitiateTranslationPosted, controller->tab_contents()->render_view_host()->process()->id(), controller->tab_contents()->render_view_host()->routing_id(), controller->tab_contents()->language_state(). original_language())); break; } case NotificationType::TAB_LANGUAGE_DETERMINED: { TabContents* tab = Source(source).ptr(); LanguageState& language_state = tab->language_state(); if (language_state.page_translatable() && !language_state.translation_pending() && !language_state.translation_declined() && !language_state.IsPageTranslated()) { std::string language = *(Details(details).ptr()); InitiateTranslation(tab, language); } break; } case NotificationType::PAGE_TRANSLATED: { TabContents* tab = Source(source).ptr(); PageTranslatedDetails* page_translated_details = Details(details).ptr(); PageTranslated(tab, page_translated_details); break; } case NotificationType::PROFILE_DESTROYED: { Profile* profile = Source(source).ptr(); notification_registrar_.Remove(this, NotificationType::PROFILE_DESTROYED, source); size_t count = accept_languages_.erase(profile->GetPrefs()); DCHECK(count > 0); pref_change_registrar_.Remove(prefs::kAcceptLanguages, this); break; } case NotificationType::PREF_CHANGED: { DCHECK(*Details(details).ptr() == prefs::kAcceptLanguages); PrefService* prefs = Source(source).ptr(); InitAcceptLanguages(prefs); break; } default: NOTREACHED(); } } ",none,24 0,"void SoftwareFrameManager::GetCurrentFrameMailbox( cc::TextureMailbox* mailbox, scoped_ptr* callback) { DCHECK(HasCurrentFrame()); *mailbox = cc::TextureMailbox( current_frame_->shared_memory_.get(), current_frame_->frame_size_pixels_); *callback = cc::SingleReleaseCallback::Create( base::Bind(ReleaseMailbox, current_frame_)); } ",none,24 1," StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) { uint8_t * pucAllocatedMemory; uint8_t ucFlags; /* In case the stream buffer is going to be used as a message buffer * (that is, it will hold discrete messages with a little meta data that * says how big the next message is) check the buffer will be large enough * to hold at least one message. */ if( xIsMessageBuffer == pdTRUE ) { /* Is a message buffer but not statically allocated. */ ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); } else { /* Not a message buffer and not statically allocated. */ ucFlags = 0; configASSERT( xBufferSizeBytes > 0 ); } configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); /* A trigger level of 0 would cause a waiting task to unblock even when * the buffer was empty. */ if( xTriggerLevelBytes == ( size_t ) 0 ) { xTriggerLevelBytes = ( size_t ) 1; } /* A stream buffer requires a StreamBuffer_t structure and a buffer. * Both are allocated in a single call to pvPortMalloc(). The * StreamBuffer_t structure is placed at the start of the allocated memory * and the buffer follows immediately after. The requested size is * incremented so the free space is returned as the user would expect - * this is a quirk of the implementation that means otherwise the free * space would be reported as one byte smaller than would be logically * expected. */ xBufferSizeBytes++; pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ if( pucAllocatedMemory != NULL ) { prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ xBufferSizeBytes, xTriggerLevelBytes, ucFlags ); traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); } else { traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); } return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ } ",CWE-190,2 1,"ngx_gmtime(time_t t, ngx_tm_t *tp) { ngx_int_t yday; ngx_uint_t n, sec, min, hour, mday, mon, year, wday, days, leap; /* the calculation is valid for positive time_t only */ n = (ngx_uint_t) t; days = n / 86400; /* January 1, 1970 was Thursday */ wday = (4 + days) % 7; n %= 86400; hour = n / 3600; n %= 3600; min = n / 60; sec = n % 60; /* * the algorithm based on Gauss' formula, * see src/core/ngx_parse_time.c */ /* days since March 1, 1 BC */ days = days - (31 + 28) + 719527; /* * The ""days"" should be adjusted to 1 only, however, some March 1st's go * to previous year, so we adjust them to 2. This causes also shift of the * last February days to next year, but we catch the case when ""yday"" * becomes negative. */ year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1); yday = days - (365 * year + year / 4 - year / 100 + year / 400); if (yday < 0) { leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0)); yday = 365 + leap + yday; year--; } /* * The empirical formula that maps ""yday"" to month. * There are at least 10 variants, some of them are: * mon = (yday + 31) * 15 / 459 * mon = (yday + 31) * 17 / 520 * mon = (yday + 31) * 20 / 612 */ mon = (yday + 31) * 10 / 306; /* the Gauss' formula that evaluates days before the month */ mday = yday - (367 * mon / 12 - 30) + 1; if (yday >= 306) { year++; mon -= 10; /* * there is no ""yday"" in Win32 SYSTEMTIME * * yday -= 306; */ } else { mon += 2; /* * there is no ""yday"" in Win32 SYSTEMTIME * * yday += 31 + 28 + leap; */ } tp->ngx_tm_sec = (ngx_tm_sec_t) sec; tp->ngx_tm_min = (ngx_tm_min_t) min; tp->ngx_tm_hour = (ngx_tm_hour_t) hour; tp->ngx_tm_mday = (ngx_tm_mday_t) mday; tp->ngx_tm_mon = (ngx_tm_mon_t) mon; tp->ngx_tm_year = (ngx_tm_year_t) year; tp->ngx_tm_wday = (ngx_tm_wday_t) wday; }",CWE-190,2 1,"static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ int i; WhereConst *pConst; if( pExpr->op!=TK_COLUMN ) return WRC_Continue; if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue; pConst = pWalker->u.pConst; for(i=0; inConst; i++){ Expr *pColumn = pConst->apExpr[i*2]; if( pColumn==pExpr ) continue; if( pColumn->iTable!=pExpr->iTable ) continue; if( pColumn->iColumn!=pExpr->iColumn ) continue; /* A match is found. Add the EP_FixedCol property */ pConst->nChng++; ExprClearProperty(pExpr, EP_Leaf); ExprSetProperty(pExpr, EP_FixedCol); assert( pExpr->pLeft==0 ); pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); break; } return WRC_Prune; }",CWE-125,1 1," void Compute(tensorflow::OpKernelContext* context) override { 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(); 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-125,1 0,"void EmbeddedWorkerContextClient::workerContextFailedToStart() { DCHECK(main_thread_proxy_->RunsTasksOnCurrentThread()); DCHECK(!script_context_); RenderThreadImpl::current()->embedded_worker_dispatcher()-> WorkerContextDestroyed(embedded_worker_id_); } ",none,24 1,"gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; int32 fromskew, toskew; uint32 nrow; int ret = 1, flip; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tmsize_t bufsize; bufsize = TIFFTileSize(tif); if (bufsize == 0) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), ""%s"", ""No space for tile buffer""); return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col, row+img->row_offset, 0, 0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } _TIFFfree(buf); if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } return (ret); }",CWE-190,2 1,"void M_LoadDefaults (void) { int i; int len; FILE* f; char def[80]; char strparm[100]; char* newstring; int parm; boolean isstring; // set everything to base values numdefaults = sizeof(defaults)/sizeof(defaults[0]); for (i=0 ; ibuf); pn = imap_next_word (s); if ((idata->state >= IMAP_SELECTED) && isdigit ((unsigned char) *s)) { pn = s; s = imap_next_word (s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (ascii_strncasecmp (""EXISTS"", s, 6) == 0) { dprint (2, (debugfile, ""Handling EXISTS\n"")); /* new mail arrived */ mutt_atoui (pn, &count); if ( !(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ dprint (1, (debugfile, ""Message count is out of sync"")); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) dprint (3, (debugfile, ""cmd_handle_untagged: superfluous EXISTS message.\n"")); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { dprint (2, (debugfile, ""cmd_handle_untagged: New mail in %s - %d messages total.\n"", idata->mailbox, count)); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->newMailCount = count; } } /* pn vs. s: need initial seqno */ else if (ascii_strncasecmp (""EXPUNGE"", s, 7) == 0) cmd_parse_expunge (idata, pn); else if (ascii_strncasecmp (""FETCH"", s, 5) == 0) cmd_parse_fetch (idata, pn); } else if (ascii_strncasecmp (""CAPABILITY"", s, 10) == 0) cmd_parse_capability (idata, s); else if (!ascii_strncasecmp (""OK [CAPABILITY"", s, 14)) cmd_parse_capability (idata, pn); else if (!ascii_strncasecmp (""OK [CAPABILITY"", pn, 14)) cmd_parse_capability (idata, imap_next_word (pn)); else if (ascii_strncasecmp (""LIST"", s, 4) == 0) cmd_parse_list (idata, s); else if (ascii_strncasecmp (""LSUB"", s, 4) == 0) cmd_parse_lsub (idata, s); else if (ascii_strncasecmp (""MYRIGHTS"", s, 8) == 0) cmd_parse_myrights (idata, s); else if (ascii_strncasecmp (""SEARCH"", s, 6) == 0) cmd_parse_search (idata, s); else if (ascii_strncasecmp (""STATUS"", s, 6) == 0) cmd_parse_status (idata, s); else if (ascii_strncasecmp (""ENABLED"", s, 7) == 0) cmd_parse_enabled (idata, s); else if (ascii_strncasecmp (""BYE"", s, 3) == 0) { dprint (2, (debugfile, ""Handling BYE\n"")); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS (s); mutt_error (""%s"", s); mutt_sleep (2); cmd_handle_fatal (idata); return -1; } else if (option (OPTIMAPSERVERNOISE) && (ascii_strncasecmp (""NO"", s, 2) == 0)) { dprint (2, (debugfile, ""Handling untagged NO\n"")); /* Display the warning message from the server */ mutt_error (""%s"", s+3); mutt_sleep (2); } return 0; }",CWE-20,3 1,"main(int argc, char *argv[]) { char pidstr[16]; ssize_t ret; int c, log_method; char *logfile, *pidfile; int facility, fd; char *username = NULL; char *chrootdir = NULL; int configtest = 0; int singleprocess = 0; #ifdef HAVE_GETOPT_LONG int opt_idx; #endif pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0]; srand((unsigned int)time(NULL)); log_method = L_STDERR_SYSLOG; logfile = PATH_RADVD_LOG; conf_file = PATH_RADVD_CONF; facility = LOG_FACILITY; pidfile = PATH_RADVD_PID; /* parse args */ #define OPTIONS_STR ""d:C:l:m:p:t:u:vhcs"" #ifdef HAVE_GETOPT_LONG while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0) #else while ((c = getopt(argc, argv, OPTIONS_STR)) > 0) #endif { switch (c) { case 'C': conf_file = optarg; break; case 'd': set_debuglevel(atoi(optarg)); break; case 'f': facility = atoi(optarg); break; case 'l': logfile = optarg; break; case 'p': pidfile = optarg; break; case 'm': if (!strcmp(optarg, ""syslog"")) { log_method = L_SYSLOG; } else if (!strcmp(optarg, ""stderr_syslog"")) { log_method = L_STDERR_SYSLOG; } else if (!strcmp(optarg, ""stderr"")) { log_method = L_STDERR; } else if (!strcmp(optarg, ""logfile"")) { log_method = L_LOGFILE; } else if (!strcmp(optarg, ""none"")) { log_method = L_NONE; } else { fprintf(stderr, ""%s: unknown log method: %s\n"", pname, optarg); exit(1); } break; case 't': chrootdir = strdup(optarg); break; case 'u': username = strdup(optarg); break; case 'v': version(); break; case 'c': configtest = 1; break; case 's': singleprocess = 1; break; case 'h': usage(); #ifdef HAVE_GETOPT_LONG case ':': fprintf(stderr, ""%s: option %s: parameter expected\n"", pname, prog_opt[opt_idx].name); exit(1); #endif case '?': exit(1); } } if (chrootdir) { if (!username) { fprintf(stderr, ""Chroot as root is not safe, exiting\n""); exit(1); } if (chroot(chrootdir) == -1) { perror(""chroot""); exit (1); } if (chdir(""/"") == -1) { perror(""chdir""); exit (1); } /* username will be switched later */ } if (configtest) { log_method = L_STDERR; } if (log_open(log_method, pname, logfile, facility) < 0) { perror(""log_open""); exit(1); } if (!configtest) { flog(LOG_INFO, ""version %s started"", VERSION); } /* get a raw socket for sending and receiving ICMPv6 messages */ sock = open_icmpv6_socket(); if (sock < 0) { perror(""open_icmpv6_socket""); exit(1); } /* check that 'other' cannot write the file * for non-root, also that self/own group can't either */ if (check_conffile_perm(username, conf_file) < 0) { if (get_debuglevel() == 0) { flog(LOG_ERR, ""Exiting, permissions on conf_file invalid.\n""); exit(1); } else flog(LOG_WARNING, ""Insecure file permissions, but continuing anyway""); } /* if we know how to do it, check whether forwarding is enabled */ if (check_ip6_forwarding()) { flog(LOG_WARNING, ""IPv6 forwarding seems to be disabled, but continuing anyway.""); } /* parse config file */ if (readin_config(conf_file) < 0) { flog(LOG_ERR, ""Exiting, failed to read config file.\n""); exit(1); } if (configtest) { fprintf(stderr, ""Syntax OK\n""); exit(0); } /* drop root privileges if requested. */ if (username) { if (!singleprocess) { dlog(LOG_DEBUG, 3, ""Initializing privsep""); if (privsep_init() < 0) flog(LOG_WARNING, ""Failed to initialize privsep.""); } if (drop_root_privileges(username) < 0) { perror(""drop_root_privileges""); exit(1); } } if ((fd = open(pidfile, O_RDONLY, 0)) > 0) { ret = read(fd, pidstr, sizeof(pidstr) - 1); if (ret < 0) { flog(LOG_ERR, ""cannot read radvd pid file, terminating: %s"", strerror(errno)); exit(1); } pidstr[ret] = '\0'; if (!kill((pid_t)atol(pidstr), 0)) { flog(LOG_ERR, ""radvd already running, terminating.""); exit(1); } close(fd); fd = open(pidfile, O_CREAT|O_TRUNC|O_WRONLY, 0644); } else /* FIXME: not atomic if pidfile is on an NFS mounted volume */ fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd < 0) { flog(LOG_ERR, ""cannot create radvd pid file, terminating: %s"", strerror(errno)); exit(1); } /* * okay, config file is read in, socket and stuff is setup, so * lets fork now... */ if (get_debuglevel() == 0) { /* Detach from controlling terminal */ if (daemon(0, 0) < 0) perror(""daemon""); /* close old logfiles, including stderr */ log_close(); /* reopen logfiles, but don't log to stderr unless explicitly requested */ if (log_method == L_STDERR_SYSLOG) log_method = L_SYSLOG; if (log_open(log_method, pname, logfile, facility) < 0) { perror(""log_open""); exit(1); } } /* * config signal handlers */ signal(SIGHUP, sighup_handler); signal(SIGTERM, sigterm_handler); signal(SIGINT, sigint_handler); signal(SIGUSR1, sigusr1_handler); snprintf(pidstr, sizeof(pidstr), ""%ld\n"", (long)getpid()); ret = write(fd, pidstr, strlen(pidstr)); if (ret != strlen(pidstr)) { flog(LOG_ERR, ""cannot write radvd pid file, terminating: %s"", strerror(errno)); exit(1); } close(fd); config_interface(); kickoff_adverts(); main_loop(); stop_adverts(); unlink(pidfile); return 0; }",CWE-20,3 0," void StopOnIOThread(const base::Closure& done, ServiceWorkerStatusCode* result) { ASSERT_TRUE(version_); version_->StopWorker(CreateReceiver(BrowserThread::UI, done, result)); } ",none,24 0,"unsigned bytesPerComponent(unsigned type) { switch (type) { case GL_BYTE: case GL_UNSIGNED_BYTE: return 1; case GL_SHORT: case GL_UNSIGNED_SHORT: case GL_UNSIGNED_SHORT_5_6_5: case GL_UNSIGNED_SHORT_4_4_4_4: case GL_UNSIGNED_SHORT_5_5_5_1: return 2; case GL_FLOAT: return 4; default: return 4; } } ",none,24 1,"static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int rc = SQLITE_OK; /* Success code from a subroutine */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest dest; /* Alternative data destination */ Select *pDelete = 0; /* Chain of simple selects to delete */ sqlite3 *db; /* Database connection */ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ assert( p && p->pPrior ); /* Calling function guarantees this much */ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); assert( p->selFlags & SF_Compound ); db = pParse->db; pPrior = p->pPrior; dest = *pDest; if( pPrior->pOrderBy || pPrior->pLimit ){ sqlite3ErrorMsg(pParse,""%s clause should come after %s not before"", pPrior->pOrderBy!=0 ? ""ORDER BY"" : ""LIMIT"", selectOpName(p->op)); rc = 1; goto multi_select_end; } v = sqlite3GetVdbe(pParse); assert( v!=0 ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); dest.eDest = SRT_Table; } /* Special handling for a compound-select that originates as a VALUES clause. */ if( p->selFlags & SF_MultiValue ){ rc = multiSelectValues(pParse, p, &dest); if( rc>=0 ) goto multi_select_end; rc = SQLITE_OK; } /* Make sure all SELECTs in the statement have the same number of elements ** in their result sets. */ assert( p->pEList && pPrior->pEList ); assert( p->pEList->nExpr==pPrior->pEList->nExpr ); #ifndef SQLITE_OMIT_CTE if( p->selFlags & SF_Recursive ){ generateWithRecursiveQuery(pParse, p, &dest); }else #endif /* Compound SELECTs that have an ORDER BY clause are handled separately. */ if( p->pOrderBy ){ return multiSelectOrderBy(pParse, p, pDest); }else{ #ifndef SQLITE_OMIT_EXPLAIN if( pPrior->pPrior==0 ){ ExplainQueryPlan((pParse, 1, ""COMPOUND QUERY"")); ExplainQueryPlan((pParse, 1, ""LEFT-MOST SUBQUERY"")); } #endif /* Generate code for the left and right SELECT statements. */ switch( p->op ){ case TK_ALL: { int addr = 0; int nLimit; assert( !pPrior->pLimit ); pPrior->iLimit = p->iLimit; pPrior->iOffset = p->iOffset; pPrior->pLimit = p->pLimit; rc = sqlite3Select(pParse, pPrior, &dest); p->pLimit = 0; if( rc ){ goto multi_select_end; } p->pPrior = 0; p->iLimit = pPrior->iLimit; p->iOffset = pPrior->iOffset; if( p->iLimit ){ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); VdbeComment((v, ""Jump ahead if LIMIT reached"")); if( p->iOffset ){ sqlite3VdbeAddOp3(v, OP_OffsetLimit, p->iLimit, p->iOffset+1, p->iOffset); } } ExplainQueryPlan((pParse, 1, ""UNION ALL"")); rc = sqlite3Select(pParse, p, &dest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); if( pPrior->pLimit && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) ){ p->nSelectRow = sqlite3LogEst((u64)nLimit); } if( addr ){ sqlite3VdbeJumpHere(v, addr); } break; } case TK_EXCEPT: case TK_UNION: { int unionTab; /* Cursor number of the temp table holding result */ u8 op = 0; /* One of the SRT_ operations to apply to self */ int priorOp; /* The SRT_ operation to apply to prior selects */ Expr *pLimit; /* Saved values of p->nLimit */ int addr; SelectDest uniondest; testcase( p->op==TK_EXCEPT ); testcase( p->op==TK_UNION ); priorOp = SRT_Union; if( dest.eDest==priorOp ){ /* We can reuse a temporary table generated by a SELECT to our ** right. */ assert( p->pLimit==0 ); /* Not allowed on leftward elements */ unionTab = dest.iSDParm; }else{ /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); } /* Code the SELECT statements to our left */ assert( !pPrior->pOrderBy ); sqlite3SelectDestInit(&uniondest, priorOp, unionTab); rc = sqlite3Select(pParse, pPrior, &uniondest); if( rc ){ goto multi_select_end; } /* Code the current SELECT statement */ if( p->op==TK_EXCEPT ){ op = SRT_Except; }else{ assert( p->op==TK_UNION ); op = SRT_Union; } p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; uniondest.eDest = op; ExplainQueryPlan((pParse, 1, ""%s USING TEMP B-TREE"", selectOpName(p->op))); rc = sqlite3Select(pParse, p, &uniondest); testcase( rc!=SQLITE_OK ); /* Query flattening in sqlite3Select() might refill p->pOrderBy. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ sqlite3ExprListDelete(db, p->pOrderBy); pDelete = p->pPrior; p->pPrior = pPrior; p->pOrderBy = 0; if( p->op==TK_UNION ){ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->iLimit = 0; p->iOffset = 0; /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); iBreak = sqlite3VdbeMakeLabel(pParse); iCont = sqlite3VdbeMakeLabel(pParse); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); iStart = sqlite3VdbeCurrentAddr(v); selectInnerLoop(pParse, p, unionTab, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); } break; } default: assert( p->op==TK_INTERSECT ); { int tab1, tab2; int iCont, iBreak, iStart; Expr *pLimit; int addr; SelectDest intersectdest; int r1; /* INTERSECT is different from the others since it requires ** two temporary tables. Hence it has its own case. Begin ** by allocating the tables we will need. */ tab1 = pParse->nTab++; tab2 = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); /* Code the SELECTs to our left into temporary table ""tab1"". */ sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); rc = sqlite3Select(pParse, pPrior, &intersectdest); if( rc ){ goto multi_select_end; } /* Code the current SELECT into temporary table ""tab2"" */ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); assert( p->addrOpenEphm[1] == -1 ); p->addrOpenEphm[1] = addr; p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; intersectdest.iSDParm = tab2; ExplainQueryPlan((pParse, 1, ""%s USING TEMP B-TREE"", selectOpName(p->op))); rc = sqlite3Select(pParse, p, &intersectdest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; if( p->nSelectRow>pPrior->nSelectRow ){ p->nSelectRow = pPrior->nSelectRow; } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; /* Generate code to take the intersection of the two temporary ** tables. */ assert( p->pEList ); iBreak = sqlite3VdbeMakeLabel(pParse); iCont = sqlite3VdbeMakeLabel(pParse); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); r1 = sqlite3GetTempReg(pParse); iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r1); selectInnerLoop(pParse, p, tab1, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); break; } } #ifndef SQLITE_OMIT_EXPLAIN if( p->pNext==0 ){ ExplainQueryPlanPop(pParse); } #endif } /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ if( p->selFlags & SF_UsesEphemeral ){ int i; /* Loop counter */ KeyInfo *pKeyInfo; /* Collating sequence for the result set */ Select *pLoop; /* For looping through SELECT statements */ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ int nCol; /* Number of columns in result set */ assert( p->pNext==0 ); nCol = p->pEList->nExpr; pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM_BKPT; goto multi_select_end; } for(i=0, apColl=pKeyInfo->aColl; ipDfltColl; } } for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ for(i=0; i<2; i++){ int addr = pLoop->addrOpenEphm[i]; if( addr<0 ){ /* If [0] is unused then [1] is also unused. So we can ** always safely abort as soon as the first unused slot is found */ assert( pLoop->addrOpenEphm[1]<0 ); break; } sqlite3VdbeChangeP2(v, addr, nCol); sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } sqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; sqlite3SelectDelete(db, pDelete); return rc; }",CWE-476,12 1,"static GF_Err av1dmx_parse_flush_sample(GF_Filter *filter, GF_AV1DmxCtx *ctx) { u32 pck_size; GF_FilterPacket *pck; u8 *output; gf_bs_get_content_no_truncate(ctx->state.bs, &ctx->state.frame_obus, &pck_size, &ctx->state.frame_obus_alloc); if (!pck_size) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[AV1Dmx] no frame OBU, skipping OBU\n"")); return GF_OK; } pck = gf_filter_pck_new_alloc(ctx->opid, pck_size, &output); if (ctx->src_pck) gf_filter_pck_merge_properties(ctx->src_pck, pck); gf_filter_pck_set_cts(pck, ctx->cts); gf_filter_pck_set_sap(pck, ctx->state.frame_state.key_frame ? GF_FILTER_SAP_1 : 0); memcpy(output, ctx->state.frame_obus, pck_size); if (ctx->deps) { u8 flags = 0; //dependsOn flags = ( ctx->state.frame_state.key_frame) ? 2 : 1; flags <<= 2; //dependedOn flags |= ctx->state.frame_state.refresh_frame_flags ? 1 : 2; flags <<= 2; //hasRedundant //flags |= ctx->has_redundant ? 1 : 2; gf_filter_pck_set_dependency_flags(pck, flags); } gf_filter_pck_send(pck); av1dmx_update_cts(ctx); gf_av1_reset_state(&ctx->state, GF_FALSE); return GF_OK; }",CWE-787,16 0,"EmbeddedWorkerContextClient::~EmbeddedWorkerContextClient() { DCHECK(g_worker_client_tls.Pointer()->Get() != NULL); g_worker_client_tls.Pointer()->Set(NULL); } ",none,24 1,"TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteFullyConnectedParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); if (kernel_type == kReference) { FullyConnectedParams op_params; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; if (filter->sparsity != nullptr) { const auto& sparsity = *filter->sparsity; reference_ops::FullyConnectedSparseWeight( sparsity, op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(filter), GetTensorData(filter), GetTensorShape(bias), GetTensorData(bias), GetTensorShape(output), GetTensorData(output)); } else { reference_ops::FullyConnected( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(filter), GetTensorData(filter), GetTensorShape(bias), GetTensorData(bias), GetTensorShape(output), GetTensorData(output)); } } else if (kernel_type == kLegacyPie) { return EvalPie(context, node, params, data, input, filter, bias, output); } else { FullyConnectedParams op_params; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; if (filter->sparsity != nullptr) { const auto& sparsity = *filter->sparsity; if (!SupportedSparsityFormat(sparsity)) { TF_LITE_KERNEL_LOG(context, ""Unsupported sparse fully-connected weight format.""); return kTfLiteError; } if (sparsity.dim_metadata_size == kDimMetadataSizeRandomSparse) { // Random sparse. optimized_ops::FullyConnectedSparseWeight( sparsity, op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(filter), GetTensorData(filter), GetTensorShape(bias), GetTensorData(bias), GetTensorShape(output), GetTensorData(output)); } else if (sparsity.dim_metadata_size == kDimMetadataSizeBlockSparse && sparsity.dim_metadata[2].dense_size == 4) { // Block sparse with block size of 1x4. optimized_ops::FullyConnectedSparseWeight1x4( sparsity, op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(filter), GetTensorData(filter), GetTensorShape(bias), GetTensorData(bias), GetTensorShape(output), GetTensorData(output), CpuBackendContext::GetFromContext(context)); } else { TF_LITE_KERNEL_LOG(context, ""Unsupported sparse fully-connected weight format.""); return kTfLiteError; } } else { op_params.lhs_cacheable = IsConstantTensor(filter); op_params.rhs_cacheable = IsConstantTensor(input); optimized_ops::FullyConnected( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(filter), GetTensorData(filter), GetTensorShape(bias), GetTensorData(bias), GetTensorShape(output), GetTensorData(output), CpuBackendContext::GetFromContext(context)); } } return kTfLiteOk; }",CWE-787,16 0,"void SoftwareFrameManager::SetVisibility(bool visible) { if (HasCurrentFrame()) { if (visible) { RendererFrameManager::GetInstance()->LockFrame(this); } else { RendererFrameManager::GetInstance()->UnlockFrame(this); } } } ",none,24 1,"static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount) { int a; char *decode; size_t len; *pszEncoding = NULL; /* Copy the comment */ if (ByteCount>=8) { const zend_encoding *from, *to; if (!memcmp(szValuePtr, ""UNICODE\0"", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, ""\xFE\xFF"", 2)) { decode = ""UCS-2BE""; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, ""\xFF\xFE"", 2)) { decode = ""UCS-2LE""; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } to = zend_multibyte_fetch_encoding(ImageInfo->encode_unicode); from = zend_multibyte_fetch_encoding(decode); /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (!to || !from || zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, to, from) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, ""ASCII\0\0\0"", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, ""JIS\0\0\0\0\0"", 8)) { /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ to = zend_multibyte_fetch_encoding(ImageInfo->encode_jis); from = zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le); if (!to || !from || zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, to, from) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, ""\0\0\0\0\0\0\0\0"", 8)) { /* 8 NULL means undefined and should be ASCII... */ *pszEncoding = estrdup(""UNDEFINED""); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount); return strlen(*pszInfoPtr); }",CWE-125,1 0,"void VideoRendererBase::Stop(const base::Closure& callback) { if (state_ == kStopped) { callback.Run(); return; } base::PlatformThreadHandle thread_to_join = base::kNullThreadHandle; { base::AutoLock auto_lock(lock_); state_ = kStopped; statistics_cb_.Reset(); time_cb_.Reset(); if (!pending_paint_ && !pending_paint_with_last_available_) DoStopOrError_Locked(); if (thread_ != base::kNullThreadHandle) { frame_available_.Signal(); thread_to_join = thread_; thread_ = base::kNullThreadHandle; } } if (thread_to_join != base::kNullThreadHandle) base::PlatformThread::Join(thread_to_join); decoder_->Stop(callback); } ",none,24 0,"bool BlobURLRequestJob::ReadFile(const BlobData::Item& item) { DCHECK(stream_.get()); DCHECK(stream_->IsOpen()); DCHECK(read_buf_remaining_bytes_ >= bytes_to_read_); int rv = stream_->Read(read_buf_->data() + read_buf_offset_, bytes_to_read_, &io_callback_); if (rv == net::ERR_IO_PENDING) { SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); return false; } if (rv < 0) { NotifyFailure(net::ERR_FAILED); return false; } if (GetStatus().is_io_pending()) DidRead(rv); else AdvanceBytesRead(rv); return true; } ",none,24 1,"GF_Err flac_dmx_process(GF_Filter *filter) { GF_FLACDmxCtx *ctx = gf_filter_get_udta(filter); GF_FilterPacket *pck, *dst_pck; u8 *output; u8 *start; Bool final_flush=GF_FALSE; u32 pck_size, remain, prev_pck_size; u64 cts = GF_FILTER_NO_TS; FLACHeader hdr; //always reparse duration if (!ctx->duration.num) flac_dmx_check_dur(filter, ctx); if (ctx->opid && !ctx->is_playing) return GF_OK; pck = gf_filter_pid_get_packet(ctx->ipid); if (!pck) { if (gf_filter_pid_is_eos(ctx->ipid)) { if (!ctx->flac_buffer_size) { 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; } final_flush = GF_TRUE; } else { return GF_OK; } } prev_pck_size = ctx->flac_buffer_size; if (pck && !ctx->resume_from) { u8 *data = (u8 *) gf_filter_pck_get_data(pck, &pck_size); if (ctx->byte_offset != GF_FILTER_NO_BO) { u64 byte_offset = gf_filter_pck_get_byte_offset(pck); if (!ctx->flac_buffer_size) { ctx->byte_offset = byte_offset; } else if (ctx->byte_offset + ctx->flac_buffer_size != byte_offset) { ctx->byte_offset = GF_FILTER_NO_BO; if ((byte_offset != GF_FILTER_NO_BO) && (byte_offset>ctx->flac_buffer_size) ) { ctx->byte_offset = byte_offset - ctx->flac_buffer_size; } } } if (ctx->flac_buffer_size + pck_size > ctx->flac_buffer_alloc) { ctx->flac_buffer_alloc = ctx->flac_buffer_size + pck_size; ctx->flac_buffer = gf_realloc(ctx->flac_buffer, ctx->flac_buffer_alloc); } memcpy(ctx->flac_buffer + ctx->flac_buffer_size, data, pck_size); ctx->flac_buffer_size += pck_size; } //input pid sets some timescale - we flushed pending data , update cts if (ctx->timescale && pck) { cts = gf_filter_pck_get_cts(pck); } if (cts == GF_FILTER_NO_TS) { //avoids updating cts prev_pck_size = 0; } remain = ctx->flac_buffer_size; start = ctx->flac_buffer; if (ctx->resume_from) { start += ctx->resume_from - 1; remain -= ctx->resume_from - 1; ctx->resume_from = 0; } while (remain>2) { u32 next_frame=0, nb_samp; u32 cur_size = remain-2; u8 *cur_buf = start+2; u8 *hdr_start = NULL; if (final_flush) { next_frame = remain; } else { while (cur_size) { //wait till we have a frame header hdr_start = memchr(cur_buf, 0xFF, cur_size); if (!hdr_start) break; next_frame = (u32) (hdr_start-start); if (next_frame == remain) break; if ((hdr_start[1]&0xFC) == 0xF8) { if (flac_parse_header(ctx, hdr_start, (u32) remain - next_frame, &hdr)) break; } cur_buf = hdr_start+1; cur_size = (u32) (cur_buf - start); assert(cur_size<=remain); cur_size = remain - cur_size; hdr_start = NULL; } if (!hdr_start) break; if (next_frame == remain) break; } if (!ctx->initialized) { u32 size = next_frame; u32 dsi_end = 0; //we have a header gf_bs_reassign_buffer(ctx->bs, ctx->flac_buffer, size); u32 magic = gf_bs_read_u32(ctx->bs); if (magic != GF_4CC('f','L','a','C')) { } while (gf_bs_available(ctx->bs)) { Bool last = gf_bs_read_int(ctx->bs, 1); u32 type = gf_bs_read_int(ctx->bs, 7); u32 len = gf_bs_read_int(ctx->bs, 24); if (type==0) { u16 min_block_size = gf_bs_read_u16(ctx->bs); u16 max_block_size = gf_bs_read_u16(ctx->bs); /*u32 min_frame_size = */gf_bs_read_u24(ctx->bs); /*u32 max_frame_size = */gf_bs_read_u24(ctx->bs); ctx->sample_rate = gf_bs_read_int(ctx->bs, 20); ctx->nb_channels = 1 + gf_bs_read_int(ctx->bs, 3); ctx->bits_per_sample = 1 + gf_bs_read_int(ctx->bs, 5); if (min_block_size==max_block_size) ctx->block_size = min_block_size; else ctx->block_size = 0; ctx->duration.num = gf_bs_read_long_int(ctx->bs, 36); ctx->duration.den = ctx->sample_rate; //ignore the rest gf_bs_skip_bytes(ctx->bs, 16); dsi_end = (u32) gf_bs_get_position(ctx->bs); } else { //ignore the rest for now //TODO: expose metadata, pictures and co gf_bs_skip_bytes(ctx->bs, len); } if (last) break; } flac_dmx_check_pid(filter, ctx, ctx->flac_buffer+4, dsi_end-4); remain -= size; start += size; ctx->initialized = GF_TRUE; if (!ctx->is_playing) break; continue; } //we have a next frame, check we are synchronize if ((start[0] != 0xFF) && ((start[1]&0xFC) != 0xF8)) { GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, (""[FLACDmx] invalid frame, droping %d bytes and resyncing\n"", next_frame)); start += next_frame; remain -= next_frame; continue; } flac_parse_header(ctx,start, next_frame, &hdr); if (hdr.sample_rate != ctx->sample_rate) { ctx->sample_rate = hdr.sample_rate; gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_SAMPLE_RATE, & PROP_UINT(ctx->sample_rate)); } nb_samp = hdr.block_size; if (ctx->in_seek) { u64 nb_samples_at_seek = (u64) (ctx->start_range * ctx->sample_rate); if (ctx->cts + nb_samp >= nb_samples_at_seek) { //u32 samples_to_discard = (ctx->cts + nb_samp ) - nb_samples_at_seek; ctx->in_seek = GF_FALSE; } } if (ctx->timescale && !prev_pck_size && (cts != GF_FILTER_NO_TS) ) { ctx->cts = cts; cts = GF_FILTER_NO_TS; } if (!ctx->in_seek) { dst_pck = gf_filter_pck_new_alloc(ctx->opid, next_frame, &output); memcpy(output, start, next_frame); gf_filter_pck_set_cts(dst_pck, ctx->cts); if (!ctx->timescale || (ctx->timescale==ctx->sample_rate) ) gf_filter_pck_set_duration(dst_pck, nb_samp); else { gf_filter_pck_set_duration(dst_pck, (nb_samp * ctx->timescale) / ctx->sample_rate); } gf_filter_pck_set_sap(dst_pck, GF_FILTER_SAP_1); gf_filter_pck_set_framing(dst_pck, GF_TRUE, GF_TRUE); if (ctx->byte_offset != GF_FILTER_NO_BO) { gf_filter_pck_set_byte_offset(dst_pck, ctx->byte_offset); } gf_filter_pck_send(dst_pck); } flac_dmx_update_cts(ctx, nb_samp); assert (start[0] == 0xFF); assert((start[1]&0xFC) == 0xF8); start += next_frame; assert(remain >= next_frame); remain -= next_frame; } if (!pck) { ctx->flac_buffer_size = 0; return flac_dmx_process(filter); } else { if (remain < ctx->flac_buffer_size) { memmove(ctx->flac_buffer, start, remain); } ctx->flac_buffer_size = remain; gf_filter_pid_drop_packet(ctx->ipid); } return GF_OK; }",CWE-787,16 1,"int ReadJpegSections (FILE * infile, ReadMode_t ReadMode) { int a; int HaveCom = FALSE; a = fgetc(infile); if (a != 0xff || fgetc(infile) != M_SOI){ return FALSE; } ImageInfo.JfifHeader.XDensity = ImageInfo.JfifHeader.YDensity = 300; ImageInfo.JfifHeader.ResolutionUnits = 1; for(;;){ int itemlen; int prev; int marker = 0; int ll,lh, got; uchar * Data; CheckSectionsAllocated(); prev = 0; for (a=0;;a++){ marker = fgetc(infile); if (marker != 0xff && prev == 0xff) break; if (marker == EOF){ ErrFatal(""Unexpected end of file""); } prev = marker; } if (a > 10){ ErrNonfatal(""Extraneous %d padding bytes before section %02X"",a-1,marker); } Sections[SectionsRead].Type = marker; // Read the length of the section. lh = fgetc(infile); ll = fgetc(infile); if (lh == EOF || ll == EOF){ ErrFatal(""Unexpected end of file""); } itemlen = (lh << 8) | ll; if (itemlen < 2){ ErrFatal(""invalid marker""); } Sections[SectionsRead].Size = itemlen; Data = (uchar *)malloc(itemlen); if (Data == NULL){ ErrFatal(""Could not allocate memory""); } Sections[SectionsRead].Data = Data; // Store first two pre-read bytes. Data[0] = (uchar)lh; Data[1] = (uchar)ll; got = fread(Data+2, 1, itemlen-2, infile); // Read the whole section. if (got != itemlen-2){ ErrFatal(""Premature end of file?""); } SectionsRead += 1; switch(marker){ case M_SOS: // stop before hitting compressed data // If reading entire image is requested, read the rest of the data. if (ReadMode & READ_IMAGE){ int cp, ep, size; // Determine how much file is left. cp = ftell(infile); fseek(infile, 0, SEEK_END); ep = ftell(infile); fseek(infile, cp, SEEK_SET); size = ep-cp; Data = (uchar *)malloc(size); if (Data == NULL){ ErrFatal(""could not allocate data for entire image""); } got = fread(Data, 1, size, infile); if (got != size){ ErrFatal(""could not read the rest of the image""); } CheckSectionsAllocated(); Sections[SectionsRead].Data = Data; Sections[SectionsRead].Size = size; Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER; SectionsRead ++; HaveAll = 1; } return TRUE; case M_DQT: // Use for jpeg quality guessing process_DQT(Data, itemlen); break; case M_DHT: // Use for jpeg quality guessing process_DHT(Data, itemlen); break; case M_EOI: // in case it's a tables-only JPEG stream fprintf(stderr,""No image in jpeg!\n""); return FALSE; case M_COM: // Comment section if (HaveCom || ((ReadMode & READ_METADATA) == 0)){ // Discard this section. free(Sections[--SectionsRead].Data); }else{ process_COM(Data, itemlen); HaveCom = TRUE; } break; case M_JFIF: // Regular jpegs always have this tag, exif images have the exif // marker instead, althogh ACDsee will write images with both markers. // this program will re-create this marker on absence of exif marker. // hence no need to keep the copy from the file. if (itemlen < 16){ fprintf(stderr,""Jfif header too short\n""); goto ignore; } if (memcmp(Data+2, ""JFIF\0"",5)){ fprintf(stderr,""Header missing JFIF marker\n""); } ImageInfo.JfifHeader.Present = TRUE; ImageInfo.JfifHeader.ResolutionUnits = Data[9]; ImageInfo.JfifHeader.XDensity = (Data[10]<<8) | Data[11]; ImageInfo.JfifHeader.YDensity = (Data[12]<<8) | Data[13]; if (ShowTags){ printf(""JFIF SOI marker: Units: %d "",ImageInfo.JfifHeader.ResolutionUnits); switch(ImageInfo.JfifHeader.ResolutionUnits){ case 0: printf(""(aspect ratio)""); break; case 1: printf(""(dots per inch)""); break; case 2: printf(""(dots per cm)""); break; default: printf(""(unknown)""); break; } printf("" X-density=%d Y-density=%d\n"",ImageInfo.JfifHeader.XDensity, ImageInfo.JfifHeader.YDensity); if (Data[14] || Data[15]){ fprintf(stderr,""Ignoring jfif header thumbnail\n""); } } ignore: free(Sections[--SectionsRead].Data); break; case M_EXIF: // There can be different section using the same marker. if (ReadMode & READ_METADATA){ if (memcmp(Data+2, ""Exif"", 4) == 0){ process_EXIF(Data, itemlen); break; }else if (memcmp(Data+2, ""http:"", 5) == 0){ Sections[SectionsRead-1].Type = M_XMP; // Change tag for internal purposes. if (ShowTags){ printf(""Image contains XMP section, %d bytes long\n"", itemlen); if (ShowTags){ ShowXmp(Sections[SectionsRead-1]); } } break; } } // Oterwise, discard this section. free(Sections[--SectionsRead].Data); break; case M_IPTC: if (ReadMode & READ_METADATA){ if (ShowTags){ printf(""Image contains IPTC section, %d bytes long\n"", itemlen); } // Note: We just store the IPTC section. Its relatively straightforward // and we don't act on any part of it, so just display it at parse time. }else{ free(Sections[--SectionsRead].Data); } break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if (itemlen < 8){ fprintf(stderr,""Section too short\n""); break; } process_SOFn(Data, marker); break; default: // Skip any other sections. if (ShowTags){ printf(""Jpeg section marker 0x%02x size %d\n"",marker, itemlen); } break; } } return TRUE; } ",CWE-787,16 1,"filter_session_io(struct io *io, int evt, void *arg) { struct filter_session *fs = arg; char *line = NULL; ssize_t len; log_trace(TRACE_IO, ""filter session: %p: %s %s"", fs, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(fs->io, &len); /* No complete line received */ if (line == NULL) return; filter_data(fs->id, line); goto nextline; case IO_DISCONNECTED: io_free(fs->io); fs->io = NULL; break; } }",CWE-476,12 0,"void SoftwareFrameManager::DiscardCurrentFrame() { if (!HasCurrentFrame()) return; current_frame_ = NULL; RendererFrameManager::GetInstance()->RemoveFrame(this); } ",none,24 0,"void ServiceWorkerScriptContext::OnMessageReceived( int request_id, const IPC::Message& message) { DCHECK_EQ(kInvalidRequestId, current_request_id_); current_request_id_ = request_id; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ServiceWorkerScriptContext, message) IPC_MESSAGE_HANDLER(ServiceWorkerMsg_InstallEvent, OnInstallEvent) IPC_MESSAGE_HANDLER(ServiceWorkerMsg_FetchEvent, OnFetchEvent) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); current_request_id_ = kInvalidRequestId; } ",none,24 1,"size_t intsetBlobLen(intset *is) { return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding); }",CWE-190,2 0,"SoftwareFrameManager::~SoftwareFrameManager() { DiscardCurrentFrame(); } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::getActiveAttrib(WebGLId program, unsigned long index, ActiveInfo& info) { makeContextCurrent(); if (!program) { synthesizeGLError(GL_INVALID_VALUE); return false; } GLint maxNameLength = -1; glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxNameLength); if (maxNameLength < 0) return false; GLchar* name = 0; if (!tryFastMalloc(maxNameLength * sizeof(GLchar)).getValue(name)) { synthesizeGLError(GL_OUT_OF_MEMORY); return false; } GLsizei length = 0; GLint size = -1; GLenum type = 0; glGetActiveAttrib(program, index, maxNameLength, &length, &size, &type, name); if (size < 0) { fastFree(name); return false; } info.name = WebString::fromUTF8(name, length); info.type = type; info.size = size; fastFree(name); return true; } ",none,24 0,"void ContentSettingsStore::RemoveObserver(Observer* observer) { DCHECK(OnCorrectThread()); observers_.RemoveObserver(observer); } ",none,24 1,"static php_iconv_err_t _php_iconv_mime_decode(smart_str *pretval, const char *str, size_t str_nbytes, const char *enc, const char **next_pos, int mode) { php_iconv_err_t err = PHP_ICONV_ERR_SUCCESS; iconv_t cd = (iconv_t)(-1), cd_pl = (iconv_t)(-1); const char *p1; size_t str_left; unsigned int scan_stat = 0; const char *csname = NULL; size_t csname_len; const char *encoded_text = NULL; size_t encoded_text_len = 0; const char *encoded_word = NULL; const char *spaces = NULL; php_iconv_enc_scheme_t enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; if (next_pos != NULL) { *next_pos = NULL; } cd_pl = iconv_open(enc, ICONV_ASCII_ENCODING); if (cd_pl == (iconv_t)(-1)) { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } p1 = str; for (str_left = str_nbytes; str_left > 0; str_left--, p1++) { int eos = 0; switch (scan_stat) { case 0: /* expecting any character */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': /* a chunk of whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ err = _php_iconv_appendc(pretval, *p1, cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { if (mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR) { err = PHP_ICONV_ERR_SUCCESS; } else { goto out; } } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } break; } break; case 1: /* expecting a delimiter */ if (*p1 != '?') { if (*p1 == '\r' || *p1 == '\n') { --p1; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } csname = p1 + 1; scan_stat = 2; break; case 2: /* expecting a charset name */ switch (*p1) { case '?': /* normal delimiter: encoding scheme follows */ scan_stat = 3; break; case '*': /* new style delimiter: locale id follows */ scan_stat = 10; break; case '\r': case '\n': /* not an encoded-word */ --p1; _php_iconv_appendc(pretval, '=', cd_pl); _php_iconv_appendc(pretval, '?', cd_pl); err = _php_iconv_appendl(pretval, csname, (size_t)((p1 + 1) - csname), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } csname = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } continue; } if (scan_stat != 2) { char tmpbuf[80]; if (csname == NULL) { err = PHP_ICONV_ERR_MALFORMED; goto out; } csname_len = (size_t)(p1 - csname); if (csname_len > sizeof(tmpbuf) - 1) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } memcpy(tmpbuf, csname, csname_len); tmpbuf[csname_len] = '\0'; if (cd != (iconv_t)(-1)) { iconv_close(cd); } cd = iconv_open(enc, tmpbuf); if (cd == (iconv_t)(-1)) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* Bad character set, but the user wants us to * press on. In this case, we'll just insert the * undecoded encoded word, since there isn't really * a more sensible behaviour available; the only * other options are to swallow the encoded word * entirely or decode it with an arbitrarily chosen * single byte encoding, both of which seem to have * a higher WTF factor than leaving it undecoded. * * Given this approach, we need to skip ahead to * the end of the encoded word. */ int qmarks = 2; while (qmarks > 0 && str_left > 1) { if (*(++p1) == '?') { --qmarks; } --str_left; } /* Look ahead to check for the terminating = that * should be there as well; if it's there, we'll * also include that. If it's not, there isn't much * we can do at this point. */ if (*(p1 + 1) == '=') { ++p1; --str_left; } err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } /* Let's go back and see if there are further * encoded words or bare content, and hope they * might actually have a valid character set. */ scan_stat = 12; break; } else { #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { err = PHP_ICONV_ERR_WRONG_CHARSET; } else { err = PHP_ICONV_ERR_CONVERTER; } #else err = PHP_ICONV_ERR_UNKNOWN; #endif goto out; } } } break; case 3: /* expecting a encoding scheme specifier */ switch (*p1) { case 'b': case 'B': enc_scheme = PHP_ICONV_ENC_SCHEME_BASE64; scan_stat = 4; break; case 'q': case 'Q': enc_scheme = PHP_ICONV_ENC_SCHEME_QPRINT; scan_stat = 4; break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } break; case 4: /* expecting a delimiter */ if (*p1 != '?') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } encoded_text = p1 + 1; scan_stat = 5; break; case 5: /* expecting an encoded portion */ if (*p1 == '?') { encoded_text_len = (size_t)(p1 - encoded_text); scan_stat = 6; } break; case 7: /* expecting a ""\n"" character */ if (*p1 == '\n') { scan_stat = 8; } else { /* bare CR */ _php_iconv_appendc(pretval, '\r', cd_pl); _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 0; } break; case 8: /* checking whether the following line is part of a folded header */ if (*p1 != ' ' && *p1 != '\t') { --p1; str_left = 1; /* quit_loop */ break; } if (encoded_word == NULL) { _php_iconv_appendc(pretval, ' ', cd_pl); } spaces = NULL; scan_stat = 11; break; case 6: /* expecting a End-Of-Chunk character ""="" */ if (*p1 != '=') { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } scan_stat = 9; if (str_left == 1) { eos = 1; } else { break; } case 9: /* choice point, seeing what to do next.*/ switch (*p1) { default: /* Handle non-RFC-compliant formats * * RFC2047 requires the character that comes right * after an encoded word (chunk) to be a whitespace, * while there are lots of broken implementations that * generate such malformed headers that don't fulfill * that requirement. */ if (!eos) { if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } scan_stat = 12; break; } } /* break is omitted intentionally */ case '\r': case '\n': case ' ': case '\t': { zend_string *decoded_text; switch (enc_scheme) { case PHP_ICONV_ENC_SCHEME_BASE64: decoded_text = php_base64_decode((unsigned char*)encoded_text, encoded_text_len); break; case PHP_ICONV_ENC_SCHEME_QPRINT: decoded_text = php_quot_print_decode((unsigned char*)encoded_text, encoded_text_len, 1); break; default: decoded_text = NULL; break; } if (decoded_text == NULL) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)((p1 + 1) - encoded_word), cd_pl); if (err != PHP_ICONV_ERR_SUCCESS) { goto out; } encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } else { err = PHP_ICONV_ERR_UNKNOWN; goto out; } } err = _php_iconv_appendl(pretval, ZSTR_VAL(decoded_text), ZSTR_LEN(decoded_text), cd); zend_string_release(decoded_text); if (err != PHP_ICONV_ERR_SUCCESS) { if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { /* pass the entire chunk through the converter */ err = _php_iconv_appendl(pretval, encoded_word, (size_t)(p1 - encoded_word), cd_pl); encoded_word = NULL; if (err != PHP_ICONV_ERR_SUCCESS) { break; } } else { goto out; } } if (eos) { /* reached end-of-string. done. */ scan_stat = 0; break; } switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ scan_stat = 1; break; case ' ': case '\t': /* medial whitespaces */ spaces = p1; scan_stat = 11; break; default: /* first letter of a non-encoded word */ _php_iconv_appendc(pretval, *p1, cd_pl); scan_stat = 12; break; } } break; } break; case 10: /* expects a language specifier. dismiss it for now */ if (*p1 == '?') { scan_stat = 3; } break; case 11: /* expecting a chunk of whitespaces */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case '=': /* first letter of an encoded chunk */ if (spaces != NULL && encoded_word == NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } encoded_word = p1; scan_stat = 1; break; case ' ': case '\t': break; default: /* first letter of a non-encoded word */ if (spaces != NULL) { _php_iconv_appendl(pretval, spaces, (size_t)(p1 - spaces), cd_pl); spaces = NULL; } _php_iconv_appendc(pretval, *p1, cd_pl); encoded_word = NULL; if ((mode & PHP_ICONV_MIME_DECODE_STRICT)) { scan_stat = 12; } else { scan_stat = 0; } break; } break; case 12: /* expecting a non-encoded word */ switch (*p1) { case '\r': /* part of an EOL sequence? */ scan_stat = 7; break; case '\n': scan_stat = 8; break; case ' ': case '\t': spaces = p1; scan_stat = 11; break; case '=': /* first letter of an encoded chunk */ if (!(mode & PHP_ICONV_MIME_DECODE_STRICT)) { encoded_word = p1; scan_stat = 1; break; } /* break is omitted intentionally */ default: _php_iconv_appendc(pretval, *p1, cd_pl); break; } break; } } switch (scan_stat) { case 0: case 8: case 11: case 12: break; default: if ((mode & PHP_ICONV_MIME_DECODE_CONTINUE_ON_ERROR)) { if (scan_stat == 1) { _php_iconv_appendc(pretval, '=', cd_pl); } err = PHP_ICONV_ERR_SUCCESS; } else { err = PHP_ICONV_ERR_MALFORMED; goto out; } } if (next_pos != NULL) { *next_pos = p1; } smart_str_0(pretval); out: if (cd != (iconv_t)(-1)) { iconv_close(cd); } if (cd_pl != (iconv_t)(-1)) { iconv_close(cd_pl); } return err; }",CWE-125,1 0,"void SpeechSynthesis::boundaryEventOccurred(PassRefPtr utterance, SpeechBoundary boundary, unsigned charIndex) { DEFINE_STATIC_LOCAL(const String, wordBoundaryString, (""word"")); DEFINE_STATIC_LOCAL(const String, sentenceBoundaryString, (""sentence"")); switch (boundary) { case SpeechWordBoundary: fireEvent(EventTypeNames::boundary, static_cast(utterance->client()), charIndex, wordBoundaryString); break; case SpeechSentenceBoundary: fireEvent(EventTypeNames::boundary, static_cast(utterance->client()), charIndex, sentenceBoundaryString); break; default: ASSERT_NOT_REACHED(); } } ",none,24 1," void Compute(OpKernelContext *ctx) override { // (0) validations const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape, *b_shape, *thresh_t; OP_REQUIRES_OK(ctx, ctx->input(""a_indices"", &a_indices)); OP_REQUIRES_OK(ctx, ctx->input(""b_indices"", &b_indices)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()) && TensorShapeUtils::IsMatrix(b_indices->shape()), errors::InvalidArgument( ""Input indices should be matrices but received shapes: "", a_indices->shape().DebugString(), "" and "", b_indices->shape().DebugString())); const int64 a_nnz = a_indices->dim_size(0); const int64 b_nnz = b_indices->dim_size(0); OP_REQUIRES_OK(ctx, ctx->input(""a_values"", &a_values_t)); OP_REQUIRES_OK(ctx, ctx->input(""b_values"", &b_values_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values_t->shape()) && TensorShapeUtils::IsVector(b_values_t->shape()), errors::InvalidArgument( ""Input values should be vectors but received shapes: "", a_values_t->shape().DebugString(), "" and "", b_values_t->shape().DebugString())); auto a_values = ctx->input(1).vec(); auto b_values = ctx->input(4).vec(); OP_REQUIRES( ctx, a_values.size() == a_nnz && b_values.size() == b_nnz, errors::InvalidArgument(""Expected "", a_nnz, "" and "", b_nnz, "" non-empty input values, got "", a_values.size(), "" and "", b_values.size())); OP_REQUIRES_OK(ctx, ctx->input(""a_shape"", &a_shape)); OP_REQUIRES_OK(ctx, ctx->input(""b_shape"", &b_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()) && TensorShapeUtils::IsVector(b_shape->shape()), errors::InvalidArgument( ""Input shapes should be a vector but received shapes "", a_shape->shape().DebugString(), "" and "", b_shape->shape().DebugString())); OP_REQUIRES( ctx, a_shape->IsSameSize(*b_shape), errors::InvalidArgument( ""Operands do not have the same ranks; got shapes: "", a_shape->SummarizeValue(10), "" and "", b_shape->SummarizeValue(10))); const auto a_shape_flat = a_shape->flat(); const auto b_shape_flat = b_shape->flat(); for (int i = 0; i < a_shape->NumElements(); ++i) { OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i), errors::InvalidArgument( ""Operands' shapes do not match: got "", a_shape_flat(i), "" and "", b_shape_flat(i), "" for dimension "", i)); } OP_REQUIRES_OK(ctx, ctx->input(""thresh"", &thresh_t)); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()), errors::InvalidArgument( ""The magnitude threshold must be a scalar: got shape "", thresh_t->shape().DebugString())); // std::abs() so that it works for complex{64,128} values as well const Treal thresh = thresh_t->scalar()(); // (1) do a pass over inputs, and append values and indices to vectors auto a_indices_mat = a_indices->matrix(); auto b_indices_mat = b_indices->matrix(); std::vector> entries_to_copy; // from_a?, idx entries_to_copy.reserve(a_nnz + b_nnz); std::vector out_values; const int num_dims = a_shape->dim_size(0); OP_REQUIRES(ctx, num_dims > 0, errors::InvalidArgument(""Invalid input_a shape. Received: "", a_shape->DebugString())); // The input and output sparse tensors are assumed to be ordered along // increasing dimension number. int64 i = 0, j = 0; T s; while (i < a_nnz && j < b_nnz) { switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j, num_dims)) { case -1: entries_to_copy.emplace_back(true, i); out_values.push_back(a_values(i)); ++i; break; case 0: s = a_values(i) + b_values(j); if (thresh <= std::abs(s)) { entries_to_copy.emplace_back(true, i); out_values.push_back(s); } ++i; ++j; break; case 1: entries_to_copy.emplace_back(false, j); out_values.push_back(b_values(j)); ++j; break; } } #define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \ while (IDX < A_OR_B##_nnz) { \ entries_to_copy.emplace_back(IS_A, IDX); \ out_values.push_back(A_OR_B##_values(IDX)); \ ++IDX; \ } // at most one of these calls appends new values HANDLE_LEFTOVERS(a, i, true); HANDLE_LEFTOVERS(b, j, false); #undef HANDLE_LEFTOVERS // (2) allocate and fill output tensors const int64 sum_nnz = out_values.size(); Tensor *out_indices_t, *out_values_t; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}), &out_indices_t)); OP_REQUIRES_OK( ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t)); auto out_indices_mat = out_indices_t->matrix(); auto out_values_flat = out_values_t->vec(); for (i = 0; i < sum_nnz; ++i) { const bool from_a = entries_to_copy[i].first; const int64 idx = entries_to_copy[i].second; out_indices_mat.chip<0>(i) = from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx); } if (sum_nnz > 0) { std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0)); } ctx->set_output(2, *a_shape); }",CWE-787,16 1,"int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length) { size_t item_len; mysql->affected_rows= net_field_length_ll(&pos); mysql->insert_id= net_field_length_ll(&pos); mysql->server_status=uint2korr(pos); pos+=2; mysql->warning_count=uint2korr(pos); pos+=2; if (pos < mysql->net.read_pos+length) { if ((item_len= net_field_length(&pos))) mysql->info=(char*) pos; /* check if server supports session tracking */ if (mysql->server_capabilities & CLIENT_SESSION_TRACKING) { ma_clear_session_state(mysql); pos+= item_len; if (mysql->server_status & SERVER_SESSION_STATE_CHANGED) { int i; if (pos < mysql->net.read_pos + length) { LIST *session_item; MYSQL_LEX_STRING *str= NULL; enum enum_session_state_type si_type; uchar *old_pos= pos; size_t item_len= net_field_length(&pos); /* length for all items */ /* length was already set, so make sure that info will be zero terminated */ if (mysql->info) *old_pos= 0; while (item_len > 0) { size_t plen; char *data; old_pos= pos; si_type= (enum enum_session_state_type)net_field_length(&pos); switch(si_type) { case SESSION_TRACK_SCHEMA: case SESSION_TRACK_STATE_CHANGE: case SESSION_TRACK_TRANSACTION_CHARACTERISTICS: case SESSION_TRACK_SYSTEM_VARIABLES: if (si_type != SESSION_TRACK_STATE_CHANGE) net_field_length(&pos); /* ignore total length, item length will follow next */ plen= net_field_length(&pos); if (!(session_item= ma_multi_malloc(0, &session_item, sizeof(LIST), &str, sizeof(MYSQL_LEX_STRING), &data, plen, NULL))) { ma_clear_session_state(mysql); SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0); return -1; } str->length= plen; str->str= data; memcpy(str->str, (char *)pos, plen); pos+= plen; session_item->data= str; mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item); /* in case schema has changed, we have to update mysql->db */ if (si_type == SESSION_TRACK_SCHEMA) { free(mysql->db); mysql->db= malloc(plen + 1); memcpy(mysql->db, str->str, plen); mysql->db[plen]= 0; } else if (si_type == SESSION_TRACK_SYSTEM_VARIABLES) { my_bool set_charset= 0; /* make sure that we update charset in case it has changed */ if (!strncmp(str->str, ""character_set_client"", str->length)) set_charset= 1; plen= net_field_length(&pos); if (!(session_item= ma_multi_malloc(0, &session_item, sizeof(LIST), &str, sizeof(MYSQL_LEX_STRING), &data, plen, NULL))) { ma_clear_session_state(mysql); SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0); return -1; } str->length= plen; str->str= data; memcpy(str->str, (char *)pos, plen); pos+= plen; session_item->data= str; mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item); if (set_charset && strncmp(mysql->charset->csname, str->str, str->length) != 0) { char cs_name[64]; MARIADB_CHARSET_INFO *cs_info; memcpy(cs_name, str->str, str->length); cs_name[str->length]= 0; if ((cs_info = (MARIADB_CHARSET_INFO *)mysql_find_charset_name(cs_name))) mysql->charset= cs_info; } } break; default: /* not supported yet */ plen= net_field_length(&pos); pos+= plen; break; } item_len-= (pos - old_pos); } } for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++) { mysql->extension->session_state[i].list= list_reverse(mysql->extension->session_state[i].list); mysql->extension->session_state[i].current= mysql->extension->session_state[i].list; } } } } /* CONC-351: clear session state information */ else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING) ma_clear_session_state(mysql); return(0); }",CWE-20,3 1,"static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowTIFFException(severity,message) \ { \ if (tiff_pixels != (unsigned char *) NULL) \ tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ 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); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,""rb"",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { 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,exception); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,""quantum:format"",""floating-point"", exception); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,""tiff:photometric"",""min-is-black"", exception); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,""tiff:photometric"",""min-is-white"", exception); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,""tiff:photometric"",""palette"",exception); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,""tiff:photometric"",""RGB"",exception); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,""tiff:photometric"",""CIELAB"",exception); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,""tiff:photometric"",""CIE Log2(L)"", exception); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,""tiff:photometric"",""LOGLUV"",exception); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,""tiff:photometric"",""MASK"",exception); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,""tiff:photometric"",""separated"",exception); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,""tiff:photometric"",""YCBCR"",exception); break; } default: { (void) SetImageProperty(image,""tiff:photometric"",""unknown"",exception); 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"", exception)); } 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"",exception); image->endian=LSBEndian; } else { (void) SetImageProperty(image,""tiff:endian"",""msb"",exception); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace,exception); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace,exception); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace,exception); TIFFGetProfiles(tiff,image,exception); TIFFGetProperties(tiff,image,exception); option=GetImageOption(image_info,""tiff:exif-properties""); if (IsStringFalse(option) == MagickFalse) /* enabled by default */ TIFFGetEXIFProperties(tiff,image,exception); (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->resolution.x=x_resolution; image->resolution.y=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5); image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { 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) { 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[MagickPathExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MagickPathExtent, ""%dx%d"",horizontal,vertical); (void) SetImageProperty(image,""jpeg:sampling-factor"", sampling_factor,exception); (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; 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,exception) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } } value=(unsigned short) image->scene; if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* 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,exception); if (status == MagickFalse) { TIFFClose(tiff); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ tiff_pixels=(unsigned char *) NULL; 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; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,""tiff:alpha"",""unspecified"",exception); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->alpha_trait=BlendPixelTrait; } else for (i=0; i < extra_samples; i++) { image->alpha_trait=BlendPixelTrait; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,""tiff:alpha"",""associated"", exception); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,""tiff:alpha"",""unassociated"", exception); } } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MagickPathExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MagickPathExtent,""%u"", (unsigned int) rows_per_strip); (void) SetImageProperty(image,""tiff:rows-per-strip"",value,exception); } if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->alpha_trait == UndefinedPixelTrait) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; tiff_pixels=(unsigned char *) AcquireMagickMemory(MagickMax( TIFFScanlineSize(tiff),(ssize_t) (image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0)))))); if (tiff_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->alpha_trait != UndefinedPixelTrait) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) tiff_pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); 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 ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { int status; register Quantum *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456)),q); SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984)),q); SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816)),q); SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q); q+=GetPixelChannels(image); 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: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p))),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p))),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p))),q); p++; q+=GetPixelChannels(image); } 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 ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ 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""); (void) SetImageStorageClass(image,DirectClass,exception); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); for (y=0; y < (ssize_t) image->rows; y+=rows) { register ssize_t x; register Quantum *magick_restrict q, *magick_restrict tile; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+ x); for (row=rows_remaining; row > 0; row--) { if (image->alpha_trait != UndefinedPixelTrait) for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p++; q+=GetPixelChannels(image); } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); p++; q+=GetPixelChannels(image); } p+=columns-columns_remaining; q-=GetPixelChannels(image)*(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; q+=GetPixelChannels(image)*(image->columns-1); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)),q); p--; q-=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); 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; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image=DestroyImageList(image); return((Image *)NULL); } } return(GetFirstImageInList(image)); }",CWE-125,1 1,"extern ""C"" int64_t enc_untrusted_syscall(int sysno, ...) { if (!enc_is_error_handler_set()) { enc_set_error_handler(default_error_handler); } asylo::system_call::SystemCallDescriptor descriptor{sysno}; if (!descriptor.is_valid()) { error_handler(""system_call.cc: Invalid SystemCallDescriptor encountered.""); } // Collect the passed parameter list into an array. std::array parameters; va_list args; va_start(args, sysno); for (int i = 0; i < descriptor.parameter_count(); i++) { parameters[i] = va_arg(args, uint64_t); } va_end(args); // Allocate a buffer for the serialized request. asylo::primitives::Extent request; asylo::primitives::PrimitiveStatus status; status = asylo::system_call::SerializeRequest(sysno, parameters, &request); if (!status.ok()) { error_handler( ""system_call.cc: Encountered serialization error when serializing "" ""syscall parameters.""); } std::unique_ptr request_owner(request.As()); // Invoke the system call dispatch callback to execute the system call. uint8_t *response_buffer; size_t response_size; if (!enc_is_syscall_dispatcher_set()) { error_handler(""system_.cc: system call dispatcher not set.""); } status = global_syscall_callback(request.As(), request.size(), &response_buffer, &response_size); if (!status.ok()) { error_handler( ""system_call.cc: Callback from syscall dispatcher was unsuccessful.""); } std::unique_ptr response_owner(response_buffer); if (!response_buffer) { error_handler( ""system_call.cc: null response buffer received for the syscall.""); } // Copy outputs back into pointer parameters. auto response_reader = asylo::system_call::MessageReader({response_buffer, response_size}); const asylo::primitives::PrimitiveStatus response_status = response_reader.Validate(); if (!response_status.ok()) { error_handler( ""system_call.cc: Error deserializing response buffer into response "" ""reader.""); } for (int i = 0; i < asylo::system_call::kParameterMax; i++) { asylo::system_call::ParameterDescriptor parameter = descriptor.parameter(i); if (parameter.is_out()) { size_t size; if (parameter.is_fixed()) { size = parameter.size(); } else { size = parameters[parameter.size()] * parameter.element_size(); } const void *src = response_reader.parameter_address(i); void *dst = reinterpret_cast(parameters[i]); if (dst != nullptr) { memcpy(dst, src, size); } } } uint64_t result = response_reader.header()->result; if (static_cast(result) == -1) { int klinux_errno = response_reader.header()->error_number; // Simply having a return value of -1 from a syscall is not a necessary // condition that the syscall failed. Some syscalls can return -1 when // successful (eg., lseek). The reliable way to check for syscall failure is // to therefore check both return value and presence of a non-zero errno. if (klinux_errno != 0) { errno = FromkLinuxErrno(klinux_errno); } } return result; }",CWE-125,1 0,"bool SpeechSynthesis::pending() const { return m_utteranceQueue.size() > 1; } ",none,24 1,"static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx) { struct kvm_vcpu *vcpu; struct kvm_vcpu_hv_synic *synic; vcpu = get_vcpu_by_vpidx(kvm, vpidx); if (!vcpu) return NULL; synic = to_hv_synic(vcpu); return (synic->active) ? synic : NULL; }",CWE-476,12 1,"void rsi_mac80211_detach(struct rsi_hw *adapter) { struct ieee80211_hw *hw = adapter->hw; enum nl80211_band band; if (hw) { ieee80211_stop_queues(hw); ieee80211_unregister_hw(hw); ieee80211_free_hw(hw); } for (band = 0; band < NUM_NL80211_BANDS; band++) { struct ieee80211_supported_band *sband = &adapter->sbands[band]; kfree(sband->channels); } #ifdef CONFIG_RSI_DEBUGFS rsi_remove_dbgfs(adapter); kfree(adapter->dfsentry); #endif }",CWE-416,10 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; 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) { ldout(s->cct, 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) { ldout(s->cct, 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); 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) { 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. */ response_attrs[aiter->second] = iter->second.c_str(); } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type = iter->second.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{ bufferlist::iterator it = iter->second.begin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << ""Error caught buffer::error couldn't decode TagSet "" << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } } } 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 0,"TranslateManager* TranslateManager::GetInstance() { return Singleton::get(); } ",none,24 0,"RuleIterator* ContentSettingsStore::GetRuleIterator( ContentSettingsType type, const content_settings::ResourceIdentifier& identifier, bool incognito) const { ScopedVector iterators; ExtensionEntryMap::const_reverse_iterator entry; scoped_ptr auto_lock(new base::AutoLock(lock_)); for (entry = entries_.rbegin(); entry != entries_.rend(); ++entry) { if (!entry->second->enabled) continue; if (incognito) { iterators.push_back( entry->second->incognito_session_only_settings.GetRuleIterator( type, identifier, NULL)); iterators.push_back( entry->second->incognito_persistent_settings.GetRuleIterator( type, identifier, NULL)); } else { iterators.push_back( entry->second->settings.GetRuleIterator(type, identifier, NULL)); } } return new ConcatenationIterator(&iterators, auto_lock.release()); } ",none,24 0," FFmpegVideoDecoderTest() : decryptor_(new AesDecryptor(&decryptor_client_)), decoder_(new FFmpegVideoDecoder(base::Bind(&Identity, &message_loop_))), demuxer_(new StrictMock()), read_cb_(base::Bind(&FFmpegVideoDecoderTest::FrameReady, base::Unretained(this))) { CHECK(FFmpegGlue::GetInstance()); decoder_->set_decryptor(decryptor_.get()); frame_buffer_.reset(new uint8[kCodedSize.GetArea()]); end_of_stream_buffer_ = DecoderBuffer::CreateEOSBuffer(); i_frame_buffer_ = ReadTestDataFile(""vp8-I-frame-320x240""); corrupt_i_frame_buffer_ = ReadTestDataFile(""vp8-corrupt-I-frame""); encrypted_i_frame_buffer_ = ReadTestDataFile( ""vp8-encrypted-I-frame-320x240""); config_.Initialize(kCodecVP8, VIDEO_CODEC_PROFILE_UNKNOWN, kVideoFormat, kCodedSize, kVisibleRect, kFrameRate.num, kFrameRate.den, kAspectRatio.num, kAspectRatio.den, NULL, 0, true); } ",none,24 1,"static int do_mount(const char *mnt, char **typep, mode_t rootmode, int fd, const char *opts, const char *dev, char **sourcep, char **mnt_optsp) { int res; int flags = MS_NOSUID | MS_NODEV; char *optbuf; char *mnt_opts = NULL; const char *s; char *d; char *fsname = NULL; char *subtype = NULL; char *source = NULL; char *type = NULL; int blkdev = 0; optbuf = (char *) malloc(strlen(opts) + 128); if (!optbuf) { fprintf(stderr, ""%s: failed to allocate memory\n"", progname); return -1; } for (s = opts, d = optbuf; *s;) { unsigned len; const char *fsname_str = ""fsname=""; const char *subtype_str = ""subtype=""; bool escape_ok = begins_with(s, fsname_str) || begins_with(s, subtype_str); for (len = 0; s[len]; len++) { if (escape_ok && s[len] == '\\' && s[len + 1]) len++; else if (s[len] == ',') break; } if (begins_with(s, fsname_str)) { if (!get_string_opt(s, len, fsname_str, &fsname)) goto err; } else if (begins_with(s, subtype_str)) { if (!get_string_opt(s, len, subtype_str, &subtype)) goto err; } else if (opt_eq(s, len, ""blkdev"")) { if (getuid() != 0) { fprintf(stderr, ""%s: option blkdev is privileged\n"", progname); goto err; } blkdev = 1; } else if (opt_eq(s, len, ""auto_unmount"")) { auto_unmount = 1; } else if (!begins_with(s, ""fd="") && !begins_with(s, ""rootmode="") && !begins_with(s, ""user_id="") && !begins_with(s, ""group_id="")) { int on; int flag; int skip_option = 0; if (opt_eq(s, len, ""large_read"")) { struct utsname utsname; unsigned kmaj, kmin; res = uname(&utsname); if (res == 0 && sscanf(utsname.release, ""%u.%u"", &kmaj, &kmin) == 2 && (kmaj > 2 || (kmaj == 2 && kmin > 4))) { fprintf(stderr, ""%s: note: 'large_read' mount option is deprecated for %i.%i kernels\n"", progname, kmaj, kmin); skip_option = 1; } } if (getuid() != 0 && !user_allow_other && (opt_eq(s, len, ""allow_other"") || opt_eq(s, len, ""allow_root""))) { fprintf(stderr, ""%s: option %.*s only allowed if 'user_allow_other' is set in %s\n"", progname, len, s, FUSE_CONF); goto err; } if (!skip_option) { if (find_mount_flag(s, len, &on, &flag)) { if (on) flags |= flag; else flags &= ~flag; } else { memcpy(d, s, len); d += len; *d++ = ','; } } } s += len; if (*s) s++; } *d = '\0'; res = get_mnt_opts(flags, optbuf, &mnt_opts); if (res == -1) goto err; sprintf(d, ""fd=%i,rootmode=%o,user_id=%u,group_id=%u"", fd, rootmode, getuid(), getgid()); source = malloc((fsname ? strlen(fsname) : 0) + (subtype ? strlen(subtype) : 0) + strlen(dev) + 32); type = malloc((subtype ? strlen(subtype) : 0) + 32); if (!type || !source) { fprintf(stderr, ""%s: failed to allocate memory\n"", progname); goto err; } if (subtype) sprintf(type, ""%s.%s"", blkdev ? ""fuseblk"" : ""fuse"", subtype); else strcpy(type, blkdev ? ""fuseblk"" : ""fuse""); if (fsname) strcpy(source, fsname); else strcpy(source, subtype ? subtype : dev); res = mount_notrunc(source, mnt, type, flags, optbuf); if (res == -1 && errno == ENODEV && subtype) { /* Probably missing subtype support */ strcpy(type, blkdev ? ""fuseblk"" : ""fuse""); if (fsname) { if (!blkdev) sprintf(source, ""%s#%s"", subtype, fsname); } else { strcpy(source, type); } res = mount_notrunc(source, mnt, type, flags, optbuf); } if (res == -1 && errno == EINVAL) { /* It could be an old version not supporting group_id */ sprintf(d, ""fd=%i,rootmode=%o,user_id=%u"", fd, rootmode, getuid()); res = mount_notrunc(source, mnt, type, flags, optbuf); } if (res == -1) { int errno_save = errno; if (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk()) fprintf(stderr, ""%s: 'fuseblk' support missing\n"", progname); else fprintf(stderr, ""%s: mount failed: %s\n"", progname, strerror(errno_save)); goto err; } *sourcep = source; *typep = type; *mnt_optsp = mnt_opts; free(fsname); free(optbuf); return 0; err: free(fsname); free(subtype); free(source); free(type); free(mnt_opts); free(optbuf); return -1; }",CWE-269,6 0,"void WebGraphicsContext3DDefaultImpl::synthesizeGLError(unsigned long error) { m_syntheticErrors.add(error); } ",none,24 0,"DataObjectItem* DataObjectItem::CreateFromClipboard(const String& type, uint64_t sequence_number) { if (type == kMimeTypeImagePng) { return MakeGarbageCollected(kFileKind, type, sequence_number); } return MakeGarbageCollected(kStringKind, type, sequence_number); } ",none,24 1,"CallResult> JSObject::getComputedWithReceiver_RJS( Handle selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> receiver) { // Try the fast-path first: no ""index-like"" properties and the ""name"" already // is a valid integer index. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { // Do we have this value present in our array storage? If so, return it. PseudoHandle<> ourValue = createPseudoHandle( getOwnIndexed(selfHandle.get(), runtime, *arrayIndex)); if (LLVM_LIKELY(!ourValue->isEmpty())) return ourValue; } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Locate the descriptor. propObj contains the object which may be anywhere // along the prototype chain. MutableHandle propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!propObj) return createPseudoHandle(HermesValue::encodeUndefinedValue()); if (LLVM_LIKELY( !desc.flags.accessor && !desc.flags.hostObject && !desc.flags.proxyObject)) return createPseudoHandle( getComputedSlotValue(propObj.get(), runtime, desc)); if (desc.flags.accessor) { auto *accessor = vmcast( getComputedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, receiver); } else if (desc.flags.hostObject) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); auto propRes = vmcast(selfHandle.get())->get(id); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return createPseudoHandle(*propRes); } else { assert(desc.flags.proxyObject && ""descriptor flags are impossible""); CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return JSProxy::getComputed(propObj, runtime, *key, receiver); } }",CWE-125,1 0,"bool VideoRendererBase::HasEnded() { base::AutoLock auto_lock(lock_); return state_ == kEnded; } ",none,24 1,"Agraph_t *agroot(void* obj) { switch (AGTYPE(obj)) { case AGINEDGE: case AGOUTEDGE: return ((Agedge_t *) obj)->node->root; case AGNODE: return ((Agnode_t *) obj)->root; case AGRAPH: return ((Agraph_t *) obj)->root; default: /* actually can't occur if only 2 bit tags */ agerr(AGERR, ""agroot of a bad object""); return NILgraph; } }",CWE-476,12 0,"void SoftwareFrameManager::SwapToNewFrameComplete(bool visible) { DCHECK(HasCurrentFrame()); RendererFrameManager::GetInstance()->AddFrame(this, visible); } ",none,24 0,"void SpeechSynthesis::didResumeSpeaking(PassRefPtr utterance) { m_isPaused = false; if (utterance->client()) fireEvent(EventTypeNames::resume, static_cast(utterance->client()), 0, String()); } ",none,24 0,"void SpeechSynthesis::didStartSpeaking(PassRefPtr utterance) { if (utterance->client()) fireEvent(EventTypeNames::start, static_cast(utterance->client()), 0, String()); } ",none,24 0,"WebString WebGraphicsContext3DDefaultImpl::getProgramInfoLog(WebGLId program) { makeContextCurrent(); GLint logLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); if (!logLength) return WebString(); GLchar* log = 0; if (!tryFastMalloc(logLength * sizeof(GLchar)).getValue(log)) return WebString(); GLsizei returnedLogLength; glGetProgramInfoLog(program, logLength, &returnedLogLength, log); ASSERT(logLength == returnedLogLength + 1); WebString res = WebString::fromUTF8(log, returnedLogLength); fastFree(log); return res; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::unmapBufferSubDataCHROMIUM(const void* mem) { } ",none,24 1," void Compute(OpKernelContext* ctx) override { // This call processes inputs 1 and 2 to write output 0. ReshapeOp::Compute(ctx); const float input_min_float = ctx->input(2).flat()(0); const float input_max_float = ctx->input(3).flat()(0); Tensor* output_min = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_min)); output_min->flat()(0) = input_min_float; Tensor* output_max = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(2, TensorShape({}), &output_max)); output_max->flat()(0) = input_max_float; }",CWE-787,16 1," void Compute(OpKernelContext* context) override { const Tensor& image = context->input(0); OP_REQUIRES(context, image.dims() == 3, errors::InvalidArgument(""image must be 3-dimensional"", image.shape().DebugString())); OP_REQUIRES( context, FastBoundsCheck(image.NumElements(), std::numeric_limits::max()), errors::InvalidArgument(""image cannot have >= int32 max elements"")); const int32 height = static_cast(image.dim_size(0)); const int32 width = static_cast(image.dim_size(1)); const int32 channels = static_cast(image.dim_size(2)); // In some cases, we pass width*channels*2 to png. const int32 max_row_width = std::numeric_limits::max() / 2; OP_REQUIRES(context, FastBoundsCheck(width * channels, max_row_width), errors::InvalidArgument(""image too wide to encode"")); OP_REQUIRES(context, channels >= 1 && channels <= 4, errors::InvalidArgument( ""image must have 1, 2, 3, or 4 channels, got "", channels)); // Encode image to png string Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({}), &output)); if (desired_channel_bits_ == 8) { OP_REQUIRES(context, png::WriteImageToBuffer( image.flat().data(), width, height, width * channels, channels, desired_channel_bits_, compression_, &output->scalar()(), nullptr), errors::Internal(""PNG encoding failed"")); } else { OP_REQUIRES(context, png::WriteImageToBuffer( image.flat().data(), width, height, width * channels * 2, channels, desired_channel_bits_, compression_, &output->scalar()(), nullptr), errors::Internal(""PNG encoding failed"")); } }",CWE-787,16 1,"inline int MatchingDim(const RuntimeShape& shape1, int index1, const RuntimeShape& shape2, int index2) { TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2)); return shape1.Dims(index1); }",CWE-125,1 1,"static int blosc_c(struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; int dont_split = (context->header_flags & 0x10) >> 4; int dict_training = context->use_dict && context->dict_cdict == NULL; int32_t j, neblock, nstreams; int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int64_t maxout; int32_t typesize = context->typesize; const char* compname; int accel; const uint8_t* _src; uint8_t *_tmp = tmp, *_tmp2 = tmp2; uint8_t *_tmp3 = thread_context->tmp4; int last_filter_index = last_filter(context->filters, 'c'); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (last_filter_index >= 0 || context->prefilter != NULL) { /* Apply the filter pipeline just for the prefilter */ if (memcpyed && context->prefilter != NULL) { // We only need the prefilter output _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } return bsize; } /* Apply regular filter pipeline */ _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } } else { _src = src + offset; } assert(context->clevel > 0); /* Calculate acceleration for different compressors */ accel = get_accel(context); /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !dict_training) { nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (j = 0; j < nstreams; j++) { if (!dict_training) { dest += sizeof(int32_t); ntbytes += sizeof(int32_t); ctbytes += sizeof(int32_t); } // See if we have a run here const uint8_t* ip = (uint8_t*)_src + j * neblock; const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock; if (get_run(ip, ipbound)) { // A run. Encode the repeated byte as a negative length in the length of the split. int32_t value = _src[j * neblock]; _sw32(dest - 4, -value); continue; } maxout = neblock; #if defined(HAVE_SNAPPY) if (context->compcode == BLOSC_SNAPPY) { maxout = (int32_t)snappy_max_compressed_length((size_t)neblock); } #endif /* HAVE_SNAPPY */ if (ntbytes + maxout > maxbytes) { /* avoid buffer * overrun */ maxout = (int64_t)maxbytes - (int64_t)ntbytes; if (maxout <= 0) { return 0; /* non-compressible block */ } } if (dict_training) { // We are in the build dict state, so don't compress // TODO: copy only a percentage for sampling memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = (int32_t)neblock; } else if (context->compcode == BLOSC_BLOSCLZ) { cbytes = blosclz_compress(context->clevel, _src + j * neblock, (int)neblock, dest, (int)maxout); } #if defined(HAVE_LZ4) else if (context->compcode == BLOSC_LZ4) { void *hash_table = NULL; #ifdef HAVE_IPP hash_table = (void*)thread_context->lz4_hash_table; #endif cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel, hash_table); } else if (context->compcode == BLOSC_LZ4HC) { cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (context->compcode == BLOSC_LIZARD) { cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (context->compcode == BLOSC_SNAPPY) { cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (context->compcode == BLOSC_ZLIB) { cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (context->compcode == BLOSC_ZSTD) { cbytes = zstd_wrap_compress(thread_context, (char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZSTD */ else { blosc_compcode_to_compname(context->compcode, &compname); fprintf(stderr, ""Blosc has not been compiled with '%s' "", compname); fprintf(stderr, ""compression support. Please use one having it.""); return -5; /* signals no compression support */ } if (cbytes > maxout) { /* Buffer overrun caused by compression (should never happen) */ return -1; } if (cbytes < 0) { /* cbytes should never be negative */ return -2; } if (!dict_training) { if (cbytes == 0 || cbytes == neblock) { /* The compressor has been unable to compress data at all. */ /* Before doing the copy, check that we are not running into a buffer overflow. */ if ((ntbytes + neblock) > maxbytes) { return 0; /* Non-compressible data */ } memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = neblock; } _sw32(dest - 4, cbytes); } dest += cbytes; ntbytes += cbytes; ctbytes += cbytes; } /* Closes j < nstreams */ //printf(""c%d"", ctbytes); return ctbytes; }",CWE-787,16 1,"GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP) { int i, j, ret; unsigned char count; if(flag) { scd->curbit = 0; scd->lastbit = 0; scd->last_byte = 0; scd->done = FALSE; return 0; } if((scd->curbit + code_size) >= scd->lastbit) { if(scd->done) { if(scd->curbit >= scd->lastbit) { /* Oh well */ } return -1; } scd->buf[0] = scd->buf[scd->last_byte - 2]; scd->buf[1] = scd->buf[scd->last_byte - 1]; if((count = GetDataBlock(fd, &scd->buf[2], ZeroDataBlockP)) <= 0) { scd->done = TRUE; } scd->last_byte = 2 + count; scd->curbit = (scd->curbit - scd->lastbit) + 16; scd->lastbit = (2 + count) * 8; } ret = 0; for (i = scd->curbit, j = 0; j < code_size; ++i, ++j) { ret |= ((scd->buf[i / 8] & (1 << (i % 8))) != 0) << j; } scd->curbit += code_size; return ret; }",CWE-119,0 1,"static void set_error_response(h2_stream *stream, int http_status) { if (!h2_stream_is_ready(stream)) { stream->rtmp->http_status = http_status; } }",CWE-476,12 1,"mt76_add_fragment(struct mt76_dev *dev, struct mt76_queue *q, void *data, int len, bool more) { struct page *page = virt_to_head_page(data); int offset = data - page_address(page); struct sk_buff *skb = q->rx_head; offset += q->buf_offset; skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset, len, q->buf_size); if (more) return; q->rx_head = NULL; dev->drv->rx_skb(dev, q - dev->q_rx, skb); }",CWE-787,16 0,"int WebGraphicsContext3DDefaultImpl::height() { return m_cachedHeight; } ",none,24 1,"unsigned long perf_instruction_pointer(struct pt_regs *regs) { bool use_siar = regs_use_siar(regs); unsigned long siar = mfspr(SPRN_SIAR); if (ppmu->flags & PPMU_P10_DD1) { if (siar) return siar; else return regs->nip; } else if (use_siar && siar_valid(regs)) return mfspr(SPRN_SIAR) + perf_ip_adjust(regs); else if (use_siar) return 0; // no valid instruction pointer else return regs->nip; }",CWE-476,12 0,"void VideoRendererBase::Flush(const base::Closure& callback) { base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, kPaused); flush_cb_ = callback; state_ = kFlushingDecoder; base::AutoUnlock auto_unlock(lock_); decoder_->Reset(base::Bind(&VideoRendererBase::OnDecoderFlushDone, this)); } ",none,24 0," void InitializeDecoderSuccessfully() { decoder_->Initialize( NULL, NewExpectedStatusCB(PIPELINE_OK), NewStatisticsCB()); message_loop_.RunAllPending(); } ",none,24 1,"UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength = oldLength + srcLength; // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; }",CWE-190,2 0,"ExecutionContext* SpeechSynthesis::executionContext() const { return ContextLifecycleObserver::executionContext(); } ",none,24 1,"int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, ""static"")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, ""relative"")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to ""clone"" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; }",CWE-787,16 0,"bool WebGraphicsContext3DDefaultImpl::getActiveUniform(WebGLId program, unsigned long index, ActiveInfo& info) { makeContextCurrent(); GLint maxNameLength = -1; glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLength); if (maxNameLength < 0) return false; GLchar* name = 0; if (!tryFastMalloc(maxNameLength * sizeof(GLchar)).getValue(name)) { synthesizeGLError(GL_OUT_OF_MEMORY); return false; } GLsizei length = 0; GLint size = -1; GLenum type = 0; glGetActiveUniform(program, index, maxNameLength, &length, &size, &type, name); if (size < 0) { fastFree(name); return false; } info.name = WebString::fromUTF8(name, length); info.type = type; info.size = size; fastFree(name); return true; } ",none,24 1,"snmp_ber_decode_string_len_buffer(unsigned char *buf, uint32_t *buff_len, const char **str, uint32_t *length) { uint8_t type, i, length_bytes; buf = snmp_ber_decode_type(buf, buff_len, &type); if(buf == NULL || type != BER_DATA_TYPE_OCTET_STRING) { /* * Sanity check * Invalid type in buffer */ return NULL; } if((*buf & 0x80) == 0) { *length = (uint32_t)*buf++; (*buff_len)--; } else { length_bytes = (uint8_t)(*buf++ & 0x7F); (*buff_len)--; if(length_bytes > 4) { /* * Sanity check * It will not fit in the uint32_t */ return NULL; } *length = (uint32_t)*buf++; (*buff_len)--; for(i = 1; i < length_bytes; ++i) { *length <<= 8; *length |= *buf++; (*buff_len)--; } } *str = (const char *)buf; *buff_len -= *length; return buf + *length; }",CWE-125,1 1,"static Image *ReadXPMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char *grey, key[MaxTextExtent], target[MaxTextExtent], *xpm_buffer; Image *image; MagickBooleanType active, status; register char *next, *p, *q; register IndexPacket *indexes; register PixelPacket *r; register ssize_t x; size_t length; SplayTreeInfo *xpm_colors; ssize_t count, j, y; unsigned long colors, columns, rows, width; /* 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); } /* Read XPM file. */ length=MaxTextExtent; xpm_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*xpm_buffer)); if (xpm_buffer == (char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); *xpm_buffer='\0'; p=xpm_buffer; while (ReadBlobString(image,p) != (char *) NULL) { if ((*p == '#') && ((p == xpm_buffer) || (*(p-1) == '\n'))) continue; if ((*p == '}') && (*(p+1) == ';')) break; p+=strlen(p); if ((size_t) (p-xpm_buffer+MaxTextExtent) < length) continue; length<<=1; xpm_buffer=(char *) ResizeQuantumMemory(xpm_buffer,length+MaxTextExtent, sizeof(*xpm_buffer)); if (xpm_buffer == (char *) NULL) break; p=xpm_buffer+strlen(xpm_buffer); } if (xpm_buffer == (char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Remove comments. */ count=0; width=0; for (p=xpm_buffer; *p != '\0'; p++) { if (*p != '""') continue; count=(ssize_t) sscanf(p+1,""%lu %lu %lu %lu"",&columns,&rows,&colors,&width); image->columns=columns; image->rows=rows; image->colors=colors; if (count == 4) break; } if ((count != 4) || (width == 0) || (width > 3) || (image->columns == 0) || (image->rows == 0) || (image->colors == 0) || (image->colors > MaxColormapSize)) { xpm_buffer=DestroyString(xpm_buffer); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } /* Remove unquoted characters. */ active=MagickFalse; for (q=xpm_buffer; *p != '\0'; ) { if (*p++ == '""') { if (active != MagickFalse) *q++='\n'; active=active != MagickFalse ? MagickFalse : MagickTrue; } if (active != MagickFalse) *q++=(*p); } *q='\0'; if (active != MagickFalse) { xpm_buffer=DestroyString(xpm_buffer); ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); } /* Initialize image structure. */ xpm_colors=NewSplayTree(CompareXPMColor,RelinquishMagickMemory, (void *(*)(void *)) NULL); if (AcquireImageColormap(image,image->colors) == MagickFalse) { xpm_colors=DestroySplayTree(xpm_colors); xpm_buffer=DestroyString(xpm_buffer); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } /* Read image colormap. */ image->depth=1; next=NextXPMLine(xpm_buffer); for (j=0; (j < (ssize_t) image->colors) && (next != (char *) NULL); j++) { char symbolic[MagickPathExtent]; MagickPixelPacket pixel; p=next; next=NextXPMLine(p); if (next == (char *) NULL) break; length=MagickMin((size_t) width,MagickPathExtent-1); if (CopyXPMColor(key,p,length) != (ssize_t) length) break; status=AddValueToSplayTree(xpm_colors,ConstantString(key),(void *) j); /* Parse color. */ (void) CopyMagickString(target,""gray"",MaxTextExtent); q=(char *) NULL; if (strlen(p) > width) q=ParseXPMColor(p+width,MagickTrue); *symbolic='\0'; if (q != (char *) NULL) { while ((isspace((int) ((unsigned char) *q)) == 0) && (*q != '\0')) q++; if ((next-q) < 0) break; if (next != (char *) NULL) (void) CopyXPMColor(target,q,MagickMin((size_t) (next-q), MaxTextExtent-1)); else (void) CopyMagickString(target,q,MaxTextExtent); q=ParseXPMColor(target,MagickFalse); (void) CopyXPMColor(symbolic,q,MagickMin((size_t) (next-q), MagickPathExtent-1)); if (q != (char *) NULL) *q='\0'; } StripString(target); if (*symbolic != '\0') (void) AddValueToSplayTree(xpm_symbolic,ConstantString(target), ConstantString(symbolic)); grey=strstr(target,""grey""); if (grey != (char *) NULL) grey[2]='a'; if (LocaleCompare(target,""none"") == 0) { image->storage_class=DirectClass; image->matte=MagickTrue; } status=QueryColorCompliance(target,XPMCompliance,&image->colormap[j], exception); if (status == MagickFalse) break; (void) QueryMagickColorCompliance(target,XPMCompliance,&pixel,exception); if (image->depth < pixel.depth) image->depth=pixel.depth; } if (j < (ssize_t) image->colors) { xpm_colors=DestroySplayTree(xpm_colors); xpm_buffer=DestroyString(xpm_buffer); ThrowReaderException(CorruptImageError,""CorruptImage""); } j=0; if (image_info->ping == MagickFalse) { /* Read image pixels. */ status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); xpm_colors=DestroySplayTree(xpm_colors); xpm_buffer=DestroyString(xpm_buffer); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { p=NextXPMLine(p); if (p == (char *) NULL) break; r=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { ssize_t count; count=CopyXPMColor(key,p,MagickMin(width,MaxTextExtent-1)); if (count != (ssize_t) width) break; j=(ssize_t) GetValueFromSplayTree(xpm_colors,key); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,j); *r=image->colormap[j]; p+=count; r++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (ssize_t) image->rows) { xpm_colors=DestroySplayTree(xpm_colors); xpm_buffer=DestroyString(xpm_buffer); ThrowReaderException(CorruptImageError,""NotEnoughPixelData""); } } /* Relinquish resources. */ xpm_colors=DestroySplayTree(xpm_colors); xpm_buffer=DestroyString(xpm_buffer); (void) CloseBlob(image); return(GetFirstImageInList(image)); }",CWE-787,16 1,"static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base) { const size_t available = (uintptr_t)end - (uintptr_t)start; const BOOL rc = available >= size * base; return rc; }",CWE-787,16 1,"pixFewColorsOctcubeQuantMixed(PIX *pixs, l_int32 level, l_int32 darkthresh, l_int32 lightthresh, l_int32 diffthresh, l_float32 minfract, l_int32 maxspan) { l_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index; l_int32 rval, gval, bval, val, minval, maxval; l_int32 *lut; l_uint32 *datac, *datam, *datad, *linec, *linem, *lined; PIX *pixc, *pixm, *pixg, *pixd; PIXCMAP *cmap, *cmapd; PROCNAME(""pixFewColorsOctcubeQuantMixed""); if (!pixs || pixGetDepth(pixs) != 32) return (PIX *)ERROR_PTR(""pixs undefined or not 32 bpp"", procName, NULL); if (level <= 0) level = 3; if (level > 6) return (PIX *)ERROR_PTR(""invalid level"", procName, NULL); if (darkthresh <= 0) darkthresh = 20; if (lightthresh <= 0) lightthresh = 244; if (diffthresh <= 0) diffthresh = 20; if (minfract <= 0.0) minfract = 0.05; if (maxspan <= 2) maxspan = 15; /* Start with a simple fixed octcube quantizer. */ if ((pixc = pixFewColorsOctcubeQuant1(pixs, level)) == NULL) return (PIX *)ERROR_PTR(""too many colors"", procName, NULL); /* Identify and save color entries in the colormap. Set up a LUT * that returns -1 for any gray pixel. */ cmap = pixGetColormap(pixc); ncolors = pixcmapGetCount(cmap); cmapd = pixcmapCreate(8); lut = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32)); for (i = 0; i < 256; i++) lut[i] = -1; for (i = 0, index = 0; i < ncolors; i++) { pixcmapGetColor(cmap, i, &rval, &gval, &bval); minval = L_MIN(rval, gval); minval = L_MIN(minval, bval); if (minval > lightthresh) /* near white */ continue; maxval = L_MAX(rval, gval); maxval = L_MAX(maxval, bval); if (maxval < darkthresh) /* near black */ continue; /* Use the max diff between components to test for color */ if (maxval - minval >= diffthresh) { pixcmapAddColor(cmapd, rval, gval, bval); lut[i] = index; index++; } } /* Generate dest pix with just the color pixels set to their * colormap indices. At the same time, make a 1 bpp mask * of the non-color pixels */ pixGetDimensions(pixs, &w, &h, NULL); pixd = pixCreate(w, h, 8); pixSetColormap(pixd, cmapd); pixm = pixCreate(w, h, 1); datac = pixGetData(pixc); datam = pixGetData(pixm); datad = pixGetData(pixd); wplc = pixGetWpl(pixc); wplm = pixGetWpl(pixm); wpld = pixGetWpl(pixd); for (i = 0; i < h; i++) { linec = datac + i * wplc; linem = datam + i * wplm; lined = datad + i * wpld; for (j = 0; j < w; j++) { val = GET_DATA_BYTE(linec, j); if (lut[val] == -1) SET_DATA_BIT(linem, j); else SET_DATA_BYTE(lined, j, lut[val]); } } /* Fill in the gray values. Use a grayscale version of pixs * as input, along with the mask over the actual gray pixels. */ pixg = pixConvertTo8(pixs, 0); pixGrayQuantFromHisto(pixd, pixg, pixm, minfract, maxspan); LEPT_FREE(lut); pixDestroy(&pixc); pixDestroy(&pixm); pixDestroy(&pixg); return pixd; }",CWE-125,1 0,"void AudioManagerBase::Shutdown() { scoped_ptr audio_thread; { base::AutoLock lock(audio_thread_lock_); audio_thread_.swap(audio_thread); } if (!audio_thread.get()) return; CHECK_NE(MessageLoop::current(), audio_thread->message_loop()); audio_thread->message_loop()->PostTask(FROM_HERE, base::Bind( &AudioManagerBase::ShutdownOnAudioThread, base::Unretained(this))); audio_thread->Stop(); } ",none,24 1,"get_ruser(pam_handle_t *pamh, char *ruserbuf, size_t ruserbuflen) { const void *ruser; struct passwd *pwd; if (ruserbuf == NULL || ruserbuflen < 1) return -2; /* Get the name of the source user. */ if (pam_get_item(pamh, PAM_RUSER, &ruser) != PAM_SUCCESS) { ruser = NULL; } if ((ruser == NULL) || (strlen(ruser) == 0)) { /* Barring that, use the current RUID. */ pwd = pam_modutil_getpwuid(pamh, getuid()); if (pwd != NULL) { ruser = pwd->pw_name; } } if (ruser == NULL || strlen(ruser) >= ruserbuflen) { *ruserbuf = '\0'; return -1; } strcpy(ruserbuf, ruser); return 0; }",CWE-22,5 1,"static ExprList *exprListAppendList( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ ExprList *pAppend, /* List of values to append. Might be NULL */ int bIntToNull ){ if( pAppend ){ int i; int nInit = pList ? pList->nExpr : 0; for(i=0; inExpr; i++){ Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); if( bIntToNull && pDup && pDup->op==TK_INTEGER ){ pDup->op = TK_NULL; pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); } pList = sqlite3ExprListAppend(pParse, pList, pDup); if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; } } return pList; }",CWE-476,12 1,"Pl_ASCII85Decoder::flush() { if (this->pos == 0) { QTC::TC(""libtests"", ""Pl_ASCII85Decoder no-op flush""); return; } unsigned long lval = 0; for (int i = 0; i < 5; ++i) { lval *= 85; lval += (this->inbuf[i] - 33U); } unsigned char outbuf[4]; memset(outbuf, 0, 4); for (int i = 3; i >= 0; --i) { outbuf[i] = lval & 0xff; lval >>= 8; } QTC::TC(""libtests"", ""Pl_ASCII85Decoder partial flush"", (this->pos == 5) ? 0 : 1); getNext()->write(outbuf, this->pos - 1); this->pos = 0; memset(this->inbuf, 117, 5); }",CWE-787,16 1,"GF_Err url_box_read(GF_Box *s, GF_BitStream *bs) { GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s; if (ptr->size) { ptr->location = (char*)gf_malloc((u32) ptr->size); if (! ptr->location) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->location, (u32)ptr->size); } return GF_OK; }",CWE-787,16 0,"DataObjectItem* DataObjectItem::CreateFromFile(File* file) { DataObjectItem* item = MakeGarbageCollected(kFileKind, file->type()); item->file_ = file; return item; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::angleDestroyCompilers() { if (m_fragmentCompiler) { ShDestruct(m_fragmentCompiler); m_fragmentCompiler = 0; } if (m_vertexCompiler) { ShDestruct(m_vertexCompiler); m_vertexCompiler = 0; } } ",none,24 1,"otError Commissioner::GeneratePskc(const char * aPassPhrase, const char * aNetworkName, const Mac::ExtendedPanId &aExtPanId, Pskc & aPskc) { otError error = OT_ERROR_NONE; const char *saltPrefix = ""Thread""; uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; uint16_t saltLen = 0; VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) && (strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, strlen(saltPrefix)); saltLen += static_cast(strlen(saltPrefix)); memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId)); saltLen += OT_EXT_PAN_ID_SIZE; memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName)); saltLen += static_cast(strlen(aNetworkName)); otPbkdf2Cmac(reinterpret_cast(aPassPhrase), static_cast(strlen(aPassPhrase)), reinterpret_cast(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8); exit: return error; }",CWE-787,16 0,"void WebGraphicsContext3DDefaultImpl::resolveMultisampledFramebuffer(unsigned x, unsigned y, unsigned width, unsigned height) { if (m_attributes.antialias) { bool mustRestoreFBO = (m_boundFBO != m_multisampleFBO); glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_multisampleFBO); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_fbo); glBlitFramebufferEXT(x, y, x + width, y + height, x, y, x + width, y + height, GL_COLOR_BUFFER_BIT, GL_LINEAR); if (mustRestoreFBO) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); } } ",none,24 1,"const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context, const TfLiteNode* node, int index) { const bool use_tensor = index < node->inputs->size && node->inputs->data[index] != kTfLiteOptionalTensor; if (use_tensor) { return GetMutableInput(context, node, index); } return nullptr; }",CWE-125,1 0,"OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) { ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i != entries_.end()) { switch (scope) { case kExtensionPrefsScopeRegular: return &(i->second->settings); case kExtensionPrefsScopeRegularOnly: NOTREACHED(); return NULL; case kExtensionPrefsScopeIncognitoPersistent: return &(i->second->incognito_persistent_settings); case kExtensionPrefsScopeIncognitoSessionOnly: return &(i->second->incognito_session_only_settings); } } return NULL; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::readPixels(long x, long y, unsigned long width, unsigned long height, unsigned long format, unsigned long type, void* pixels) { makeContextCurrent(); glFlush(); bool needsResolve = (m_attributes.antialias && m_boundFBO == m_multisampleFBO); if (needsResolve) { resolveMultisampledFramebuffer(x, y, width, height); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); glFlush(); } glReadPixels(x, y, width, height, format, type, pixels); if (needsResolve) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); } ",none,24 1," void Compute(OpKernelContext* ctx) override { const Tensor& in0 = ctx->input(0); const Tensor& in1 = ctx->input(1); ValidateInputTensors(ctx, in0, in1); MatMulBCast bcast(in0.shape().dim_sizes(), in1.shape().dim_sizes()); OP_REQUIRES( ctx, bcast.IsValid(), errors::InvalidArgument( ""In[0] and In[1] must have compatible batch dimensions: "", in0.shape().DebugString(), "" vs. "", in1.shape().DebugString())); TensorShape out_shape = bcast.output_batch_shape(); auto batch_size = bcast.output_batch_size(); auto d0 = in0.dim_size(in0.dims() - 2); // Band size. auto d1 = in0.dim_size(in0.dims() - 1); Tensor in0_reshaped; OP_REQUIRES( ctx, in0_reshaped.CopyFrom(in0, TensorShape({bcast.x_batch_size(), d0, d1})), errors::Internal(""Failed to reshape In[0] from "", in0.shape().DebugString())); auto d2 = in1.dim_size(in1.dims() - 2); auto d3 = in1.dim_size(in1.dims() - 1); Tensor in1_reshaped; OP_REQUIRES( ctx, in1_reshaped.CopyFrom(in1, TensorShape({bcast.y_batch_size(), d2, d3})), errors::Internal(""Failed to reshape In[1] from "", in1.shape().DebugString())); OP_REQUIRES(ctx, d1 == d2, errors::InvalidArgument( ""In[0] mismatch In[1] shape: "", d1, "" vs. "", d2, "": "", in0.shape().DebugString(), "" "", in1.shape().DebugString(), "" "", lower_, "" "", adjoint_)); out_shape.AddDim(d1); out_shape.AddDim(d3); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out)); if (out->NumElements() == 0) { return; } Tensor out_reshaped; OP_REQUIRES(ctx, out_reshaped.CopyFrom(*out, TensorShape({batch_size, d1, d3})), errors::Internal(""Failed to reshape output from "", out->shape().DebugString())); LaunchBatchBandedTriangularSolve::Launch( ctx, in0_reshaped, in1_reshaped, adjoint_, lower_, bcast, &out_reshaped); }",CWE-787,16 1,"formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); }",CWE-476,12 1,"static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, ""received Bandwidth Measure Results PDU""); Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; }",CWE-125,1 1,"void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct, struct ndpi_flow_struct* flow) { struct ndpi_packet_struct* packet = &flow->packet; const u_int8_t * ovpn_payload = packet->payload; const u_int8_t * session_remote; u_int8_t opcode; u_int8_t alen; int8_t hmac_size; int8_t failed = 0; if(packet->payload_packet_len >= 40) { // skip openvpn TCP transport packet size if(packet->tcp != NULL) ovpn_payload += 2; opcode = ovpn_payload[0] & P_OPCODE_MASK; if(packet->udp) { #ifdef DEBUG printf(""[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\n"", flow->num_processed_pkts, opcode, check_pkid_and_detect_hmac_size(ovpn_payload), htons(packet->udp->source), htons(packet->udp->dest), packet->payload_packet_len); #endif if( (flow->num_processed_pkts == 1) && ( ((packet->payload_packet_len == 112) && ((opcode == 168) || (opcode == 192)) ) || ((packet->payload_packet_len == 80) && ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200))) )) { NDPI_LOG_INFO(ndpi_struct,""found openvpn\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN); return; } } if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 || opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) { if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) { memcpy(flow->ovpn_session_id, ovpn_payload+1, 8); NDPI_LOG_DBG2(ndpi_struct, ""session key: %02x%02x%02x%02x%02x%02x%02x%02x\n"", flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3], flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]); } } else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) { hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload); if(hmac_size > 0) { alen = ovpn_payload[P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size)]; if (alen > 0) { session_remote = ovpn_payload + P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size) + 1 + alen * 4; if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) { NDPI_LOG_INFO(ndpi_struct,""found openvpn\n""); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN); return; } else { NDPI_LOG_DBG2(ndpi_struct, ""key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\n"", session_remote[0], session_remote[1], session_remote[2], session_remote[3], session_remote[4], session_remote[5], session_remote[6], session_remote[7]); failed = 1; } } else failed = 1; } else failed = 1; } else failed = 1; flow->ovpn_counter++; if(failed) { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); } } }",CWE-125,1 0,"unsigned int WebGraphicsContext3DDefaultImpl::getPlatformTextureId() { return m_texture; } ",none,24 0,"void AudioManagerBase::Init() { base::AutoLock lock(audio_thread_lock_); DCHECK(!audio_thread_.get()); audio_thread_.reset(new base::Thread(""AudioThread"")); CHECK(audio_thread_->Start()); } ",none,24 1,"buflist_match( regmatch_T *rmp, buf_T *buf, int ignore_case) // when TRUE ignore case, when FALSE use 'fic' { char_u *match; // First try the short file name, then the long file name. match = fname_match(rmp, buf->b_sfname, ignore_case); if (match == NULL) match = fname_match(rmp, buf->b_ffname, ignore_case); return match; }",CWE-476,12 1,"void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){ int i = 0; int iTbl = 0; while( i<128 ){ int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ]; int n = (aFts5UnicodeData[iTbl] >> 5) + i; for(; i<128 && ipacket; union ja3_info ja3; u_int8_t invalid_ja3 = 0; u_int16_t tls_version, ja3_str_len; char ja3_str[JA3_STR_LEN]; ndpi_MD5_CTX ctx; u_char md5_hash[16]; int i; u_int16_t total_len; u_int8_t handshake_type; char buffer[64] = { '\0' }; int is_quic = (quic_version != 0); int is_dtls = packet->udp && (!is_quic); #ifdef DEBUG_TLS printf(""TLS %s() called\n"", __FUNCTION__); #endif memset(&ja3, 0, sizeof(ja3)); handshake_type = packet->payload[0]; total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0)) return(0); /* Not found */ total_len = packet->payload_packet_len; /* At least ""magic"" 3 bytes, null for string end, otherwise no need to waste cpu cycles */ if(total_len > 4) { u_int16_t base_offset = (!is_dtls) ? 38 : 46; u_int16_t version_offset = (!is_dtls) ? 4 : 12; u_int16_t offset = (!is_dtls) ? 38 : 46, extension_len, j; u_int8_t session_id_len = 0; if((base_offset >= total_len) || (version_offset + 1) >= total_len) return 0; /* Not found */ session_id_len = packet->payload[base_offset]; #ifdef DEBUG_TLS printf(""TLS [len: %u][handshake_type: %02X]\n"", packet->payload_packet_len, handshake_type); #endif tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset])); if(handshake_type == 0x02 /* Server Hello */) { int i, rc; ja3.server.tls_handshake_version = tls_version; #ifdef DEBUG_TLS printf(""TLS Server Hello [version: 0x%04X]\n"", tls_version); #endif /* The server hello decides about the TLS version of this flow https://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3 */ if(packet->udp) offset += session_id_len + 1; else { if(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */) offset += session_id_len+1; } if((offset+3) > packet->payload_packet_len) return(0); /* Not found */ ja3.server.num_cipher = 1, ja3.server.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset])); if((flow->protos.tls_quic_stun.tls_quic.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.server.cipher[0])) == 1) ndpi_set_risk(flow, NDPI_TLS_WEAK_CIPHER); flow->protos.tls_quic_stun.tls_quic.server_cipher = ja3.server.cipher[0]; #ifdef DEBUG_TLS printf(""TLS [server][session_id_len: %u][cipher: %04X]\n"", session_id_len, ja3.server.cipher[0]); #endif offset += 2 + 1; if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */ extension_len = ntohs(*((u_int16_t*)&packet->payload[offset])); else extension_len = 0; #ifdef DEBUG_TLS printf(""TLS [server][extension_len: %u]\n"", extension_len); #endif offset += 2; for(i=0; i packet->payload_packet_len) break; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset])); extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2])); if(ja3.server.num_tls_extension < MAX_NUM_JA3) ja3.server.tls_extension[ja3.server.num_tls_extension++] = extension_id; #ifdef DEBUG_TLS printf(""TLS [server][extension_id: %u/0x%04X][len: %u]\n"", extension_id, extension_id, extension_len); #endif if(extension_id == 43 /* supported versions */) { if(extension_len >= 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4])); #ifdef DEBUG_TLS printf(""TLS [server] [TLS version: 0x%04X]\n"", tls_version); #endif flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.server.tls_supported_version = tls_version; } } else if(extension_id == 16 /* application_layer_protocol_negotiation (ALPN) */) { u_int16_t s_offset = offset+4; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0, i; #ifdef DEBUG_TLS printf(""Server TLS [ALPN: block_len=%u/len=%u]\n"", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len) { #ifdef DEBUG_TLS printf(""Server TLS [ALPN: %u]\n"", alpn_len); #endif if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_ipayload[s_offset+alpn_i]; } s_offset += alpn_len, alpn_str_len += alpn_len;; } else { ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN); break; } } else { ndpi_set_risk(flow, NDPI_TLS_UNCOMMON_ALPN); break; } } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf(""Server TLS [ALPN: %s][len: %u]\n"", alpn_str, alpn_str_len); #endif if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL) flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str); if(flow->protos.tls_quic_stun.tls_quic.alpn != NULL) tlsCheckUncommonALPN(flow); snprintf(ja3.server.alpn, sizeof(ja3.server.alpn), ""%s"", alpn_str); /* Replace , with - as in JA3 */ for(i=0; ja3.server.alpn[i] != '\0'; i++) if(ja3.server.alpn[i] == ',') ja3.server.alpn[i] = '-'; } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+4 + 1; #ifdef DEBUG_TLS printf(""Server TLS [EllipticCurveFormat: len=%u]\n"", extension_len); #endif if((s_offset+extension_len-1) <= total_len) { for(i=0; ipayload[s_offset+i]; #ifdef DEBUG_TLS printf(""Server TLS [EllipticCurveFormat: %u]\n"", s_group); #endif if(ja3.server.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.server.elliptic_curve_point_format[ja3.server.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Server TLS Invalid num elliptic %u\n"", ja3.server.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Server TLS Invalid len %u vs %u\n"", s_offset+extension_len, total_len); #endif } } i += 4 + extension_len, offset += 4 + extension_len; } /* for */ ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), ""%u,"", ja3.server.tls_handshake_version); for(i=0; i 0) ? ""-"" : """", ja3.server.cipher[i]); if(rc <= 0) break; else ja3_str_len += rc; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",""); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i 0) ? ""-"" : """", ja3.server.tls_extension[i]); if(rc <= 0) break; else ja3_str_len += rc; } if(ndpi_struct->enable_ja3_plus) { for(i=0; i 0) ? ""-"" : """", ja3.server.elliptic_curve_point_format[i]); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break; } if(ja3.server.alpn[0] != '\0') { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",%s"", ja3.server.alpn); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; } #ifdef DEBUG_TLS printf(""[JA3+] Server: %s \n"", ja3_str); #endif } else { #ifdef DEBUG_TLS printf(""[JA3] Server: %s \n"", ja3_str); #endif } ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { int rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_server[j], sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_server)-j, ""%02x"", md5_hash[i]); if(rc <= 0) break; else j += rc; } #ifdef DEBUG_TLS printf(""[JA3] Server: %s \n"", flow->protos.tls_quic_stun.tls_quic.ja3_server); #endif } else if(handshake_type == 0x01 /* Client Hello */) { u_int16_t cipher_len, cipher_offset; u_int8_t cookie_len = 0; flow->protos.tls_quic_stun.tls_quic.ssl_version = ja3.client.tls_handshake_version = tls_version; if(flow->protos.tls_quic_stun.tls_quic.ssl_version < 0x0302) /* TLSv1.1 */ ndpi_set_risk(flow, NDPI_TLS_OBSOLETE_VERSION); if((session_id_len+base_offset+3) > packet->payload_packet_len) return(0); /* Not found */ if(!is_dtls) { cipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8); cipher_offset = base_offset + session_id_len + 3; } else { cookie_len = packet->payload[base_offset+session_id_len+1]; #ifdef DEBUG_TLS printf(""[JA3] Client: DTLS cookie len %d\n"", cookie_len); #endif if((session_id_len+base_offset+cookie_len+4) > packet->payload_packet_len) return(0); /* Not found */ cipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+session_id_len+cookie_len+2])); cipher_offset = base_offset + session_id_len + cookie_len + 4; } #ifdef DEBUG_TLS printf(""Client TLS [client cipher_len: %u][tls_version: 0x%04X]\n"", cipher_len, tls_version); #endif if((cipher_offset+cipher_len) <= total_len) { u_int8_t safari_ciphers = 0, chrome_ciphers = 0; for(i=0; ipayload[cipher_offset+i]; #ifdef DEBUG_TLS printf(""Client TLS [cipher suite: %u/0x%04X] [%d/%u]\n"", ntohs(*id), ntohs(*id), i, cipher_len); #endif if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) { u_int16_t cipher_id = ntohs(*id); /* Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html] https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ if(ja3.client.num_cipher < MAX_NUM_JA3) ja3.client.cipher[ja3.client.num_cipher++] = cipher_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid cipher %u\n"", ja3.client.num_cipher); #endif } switch(cipher_id) { case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: safari_ciphers++; break; case TLS_CIPHER_GREASE_RESERVED_0: case TLS_AES_128_GCM_SHA256: case TLS_AES_256_GCM_SHA384: case TLS_CHACHA20_POLY1305_SHA256: chrome_ciphers++; break; case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case TLS_RSA_WITH_AES_128_CBC_SHA: case TLS_RSA_WITH_AES_256_CBC_SHA: case TLS_RSA_WITH_AES_128_GCM_SHA256: case TLS_RSA_WITH_AES_256_GCM_SHA384: safari_ciphers++, chrome_ciphers++; break; } } i += 2; } /* for */ if(chrome_ciphers == 13) flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 1; else if(safari_ciphers == 12) flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 1; } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid len %u vs %u\n"", (cipher_offset+cipher_len), total_len); #endif } offset = base_offset + session_id_len + cookie_len + cipher_len + 2; offset += (!is_dtls) ? 1 : 2; if(offset < total_len) { u_int16_t compression_len; u_int16_t extensions_len; compression_len = packet->payload[offset]; offset++; #ifdef DEBUG_TLS printf(""Client TLS [compression_len: %u]\n"", compression_len); #endif // offset += compression_len + 3; offset += compression_len; if(offset+1 < total_len) { extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset])); offset += 2; #ifdef DEBUG_TLS printf(""Client TLS [extensions_len: %u]\n"", extensions_len); #endif if((extensions_len+offset) <= total_len) { /* Move to the first extension Type is u_int to avoid possible overflow on extension_len addition */ u_int extension_offset = 0; u_int32_t j; while(extension_offset < extensions_len && offset+extension_offset+4 <= total_len) { u_int16_t extension_id, extension_len, extn_off = offset+extension_offset; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; #ifdef DEBUG_TLS printf(""Client TLS [extension_id: %u][extension_len: %u]\n"", extension_id, extension_len); #endif if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) { /* Skip GREASE */ if(ja3.client.num_tls_extension < MAX_NUM_JA3) ja3.client.tls_extension[ja3.client.num_tls_extension++] = extension_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid extensions %u\n"", ja3.client.num_tls_extension); #endif } } if(extension_id == 0 /* server name */) { u_int16_t len; #ifdef DEBUG_TLS printf(""[TLS] Extensions: found server name\n""); #endif if((offset+extension_offset+4) < packet->payload_packet_len) { len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4]; len = (u_int)ndpi_min(len, sizeof(buffer)-1); if((offset+extension_offset+5+len) <= packet->payload_packet_len) { strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len); buffer[len] = '\0'; cleanupServerName(buffer, sizeof(buffer)); snprintf(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, sizeof(flow->protos.tls_quic_stun.tls_quic.client_requested_server_name), ""%s"", buffer); #ifdef DEBUG_TLS printf(""[TLS] SNI: [%s]\n"", buffer); #endif if(!is_quic) { if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; } else { if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_QUIC, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; } if(ndpi_check_dga_name(ndpi_struct, flow, flow->protos.tls_quic_stun.tls_quic.client_requested_server_name, 1)) { char *sni = flow->protos.tls_quic_stun.tls_quic.client_requested_server_name; int len = strlen(sni); #ifdef DEBUG_TLS printf(""[TLS] SNI: (DGA) [%s]\n"", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name); #endif if((len >= 4) /* Check if it ends in .com or .net */ && ((strcmp(&sni[len-4], "".com"") == 0) || (strcmp(&sni[len-4], "".net"") == 0)) && (strncmp(sni, ""www."", 4) == 0)) /* Not starting with www.... */ ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TOR, NDPI_PROTOCOL_TLS); } else { #ifdef DEBUG_TLS printf(""[TLS] SNI: (NO DGA) [%s]\n"", flow->protos.tls_quic_stun.tls_quic.client_requested_server_name); #endif } } else { #ifdef DEBUG_TLS printf(""[TLS] Extensions server len too short: %u vs %u\n"", offset+extension_offset+5+len, packet->payload_packet_len); #endif } } } else if(extension_id == 10 /* supported groups */) { u_int16_t s_offset = offset+extension_offset + 2; #ifdef DEBUG_TLS printf(""Client TLS [EllipticCurveGroups: len=%u]\n"", extension_len); #endif if((s_offset+extension_len-2) <= total_len) { for(i=0; ipayload[s_offset+i])); #ifdef DEBUG_TLS printf(""Client TLS [EllipticCurve: %u/0x%04X]\n"", s_group, s_group); #endif if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) { /* Skip GREASE */ if(ja3.client.num_elliptic_curve < MAX_NUM_JA3) ja3.client.elliptic_curve[ja3.client.num_elliptic_curve++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid num elliptic %u\n"", ja3.client.num_elliptic_curve); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid len %u vs %u\n"", (s_offset+extension_len-1), total_len); #endif } } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+extension_offset + 1; #ifdef DEBUG_TLS printf(""Client TLS [EllipticCurveFormat: len=%u]\n"", extension_len); #endif if((s_offset+extension_len-1) <= total_len) { for(i=0; ipayload[s_offset+i]; #ifdef DEBUG_TLS printf(""Client TLS [EllipticCurveFormat: %u]\n"", s_group); #endif if(ja3.client.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.client.elliptic_curve_point_format[ja3.client.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid num elliptic %u\n"", ja3.client.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf(""Client TLS Invalid len %u vs %u\n"", s_offset+extension_len, total_len); #endif } } else if(extension_id == 13 /* signature algorithms */) { u_int16_t s_offset = offset+extension_offset, safari_signature_algorithms = 0, chrome_signature_algorithms = 0; u_int16_t tot_signature_algorithms_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); #ifdef DEBUG_TLS printf(""Client TLS [SIGNATURE_ALGORITHMS: block_len=%u/len=%u]\n"", extension_len, tot_signature_algorithms_len); #endif s_offset += 2; tot_signature_algorithms_len = ndpi_min((sizeof(ja3.client.signature_algorithms) / 2) - 1, tot_signature_algorithms_len); #ifdef TLS_HANDLE_SIGNATURE_ALGORITMS flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms = ndpi_min(tot_signature_algorithms_len / 2, MAX_NUM_TLS_SIGNATURE_ALGORITHMS); memcpy(flow->protos.tls_quic_stun.tls_quic.client_signature_algorithms, &packet->payload[s_offset], 2 /* 16 bit */*flow->protos.tls_quic_stun.tls_quic.num_tls_signature_algorithms); #endif for(i=0; ipayload[s_offset+i]); if(rc < 0) break; } for(i=0; ipayload[s_offset+i])); // printf(""=>> %04X\n"", cipher_id); switch(cipher_id) { case ECDSA_SECP521R1_SHA512: flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls = 1; break; case ECDSA_SECP256R1_SHA256: case ECDSA_SECP384R1_SHA384: case RSA_PKCS1_SHA256: case RSA_PKCS1_SHA384: case RSA_PKCS1_SHA512: case RSA_PSS_RSAE_SHA256: case RSA_PSS_RSAE_SHA384: case RSA_PSS_RSAE_SHA512: chrome_signature_algorithms++, safari_signature_algorithms++; break; } } if(flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_firefox_tls) flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0, flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0; if(safari_signature_algorithms != 8) flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_safari_tls = 0; if(chrome_signature_algorithms != 8) flow->protos.tls_quic_stun.tls_quic.browser_euristics.is_chrome_tls = 0; ja3.client.signature_algorithms[i*2] = '\0'; #ifdef DEBUG_TLS printf(""Client TLS [SIGNATURE_ALGORITHMS: %s]\n"", ja3.client.signature_algorithms); #endif } else if(extension_id == 16 /* application_layer_protocol_negotiation */) { u_int16_t s_offset = offset+extension_offset; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0, i; #ifdef DEBUG_TLS printf(""Client TLS [ALPN: block_len=%u/len=%u]\n"", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len && (s_offset + alpn_len) <= total_len) { #ifdef DEBUG_TLS printf(""Client TLS [ALPN: %u]\n"", alpn_len); #endif if((alpn_str_len+alpn_len+1) < (sizeof(alpn_str)-1)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_ipayload[s_offset+alpn_i]; s_offset += alpn_len, alpn_str_len += alpn_len;; } else break; } else break; } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf(""Client TLS [ALPN: %s][len: %u]\n"", alpn_str, alpn_str_len); #endif if(flow->protos.tls_quic_stun.tls_quic.alpn == NULL) flow->protos.tls_quic_stun.tls_quic.alpn = ndpi_strdup(alpn_str); snprintf(ja3.client.alpn, sizeof(ja3.client.alpn), ""%s"", alpn_str); /* Replace , with - as in JA3 */ for(i=0; ja3.client.alpn[i] != '\0'; i++) if(ja3.client.alpn[i] == ',') ja3.client.alpn[i] = '-'; } else if(extension_id == 43 /* supported versions */) { u_int16_t s_offset = offset+extension_offset; u_int8_t version_len = packet->payload[s_offset]; char version_str[256]; u_int8_t version_str_len = 0; version_str[0] = 0; #ifdef DEBUG_TLS printf(""Client TLS [TLS version len: %u]\n"", version_len); #endif if(version_len == (extension_len-1)) { u_int8_t j; u_int16_t supported_versions_offset = 0; s_offset++; // careful not to overflow and loop forever with u_int8_t for(j=0; j+1payload[s_offset+j])); u_int8_t unknown_tls_version; #ifdef DEBUG_TLS printf(""Client TLS [TLS version: %s/0x%04X]\n"", ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version), tls_version); #endif if((version_str_len+8) < sizeof(version_str)) { int rc = snprintf(&version_str[version_str_len], sizeof(version_str) - version_str_len, ""%s%s"", (version_str_len > 0) ? "","" : """", ndpi_ssl_version2str(flow, tls_version, &unknown_tls_version)); if(rc <= 0) break; else version_str_len += rc; rc = snprintf(&ja3.client.supported_versions[supported_versions_offset], sizeof(ja3.client.supported_versions)-supported_versions_offset, ""%s%04X"", (j > 0) ? ""-"" : """", tls_version); if(rc > 0) supported_versions_offset += rc; } } #ifdef DEBUG_TLS printf(""Client TLS [SUPPORTED_VERSIONS: %s]\n"", ja3.client.supported_versions); #endif if(flow->protos.tls_quic_stun.tls_quic.tls_supported_versions == NULL) flow->protos.tls_quic_stun.tls_quic.tls_supported_versions = ndpi_strdup(version_str); } } else if(extension_id == 65486 /* encrypted server name */) { /* - https://tools.ietf.org/html/draft-ietf-tls-esni-06 - https://blog.cloudflare.com/encrypted-sni/ */ u_int16_t e_offset = offset+extension_offset; u_int16_t initial_offset = e_offset; u_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset])); flow->protos.tls_quic_stun.tls_quic.encrypted_sni.cipher_suite = cipher_suite; e_offset += 2; /* Cipher suite len */ /* Key Share Entry */ e_offset += 2; /* Group */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { /* Record Digest */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset])); e_offset += 2; if((e_offset+e_sni_len-extension_len-initial_offset) >= 0 && e_offset+e_sni_len < packet->payload_packet_len) { #ifdef DEBUG_ENCRYPTED_SNI printf(""Client TLS [Encrypted Server Name len: %u]\n"", e_sni_len); #endif if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) { flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1); if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni) { u_int16_t i, off; for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) { int rc = sprintf(&flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off], ""%02X"", packet->payload[i] & 0XFF); if(rc <= 0) { flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni[off] = '\0'; break; } else off += rc; } } } } } } } else if(extension_id == 65445 || /* QUIC transport parameters (drafts version) */ extension_id == 57) { /* QUIC transport parameters (final version) */ u_int16_t s_offset = offset+extension_offset; uint16_t final_offset; int using_var_int = is_version_with_var_int_transport_params(quic_version); if(!using_var_int) { if(s_offset+1 >= total_len) { final_offset = 0; /* Force skipping extension */ } else { u_int16_t seq_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); s_offset += 2; final_offset = MIN(total_len, s_offset + seq_len); } } else { final_offset = MIN(total_len, s_offset + extension_len); } while(s_offset < final_offset) { u_int64_t param_type, param_len; if(!using_var_int) { if(s_offset+3 >= final_offset) break; param_type = ntohs(*((u_int16_t*)&packet->payload[s_offset])); param_len = ntohs(*((u_int16_t*)&packet->payload[s_offset + 2])); s_offset += 4; } else { if(s_offset >= final_offset || (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset) break; s_offset += quic_len(&packet->payload[s_offset], ¶m_type); if(s_offset >= final_offset || (s_offset + quic_len_buffer_still_required(packet->payload[s_offset])) >= final_offset) break; s_offset += quic_len(&packet->payload[s_offset], ¶m_len); } #ifdef DEBUG_TLS printf(""Client TLS [QUIC TP: Param 0x%x Len %d]\n"", (int)param_type, (int)param_len); #endif if(s_offset+param_len > final_offset) break; if(param_type==0x3129) { #ifdef DEBUG_TLS printf(""UA [%.*s]\n"", (int)param_len, &packet->payload[s_offset]); #endif http_process_user_agent(ndpi_struct, flow, &packet->payload[s_offset], param_len); break; } s_offset += param_len; } } extension_offset += extension_len; /* Move to the next extension */ #ifdef DEBUG_TLS printf(""Client TLS [extension_offset/len: %u/%u]\n"", extension_offset, extension_len); #endif } /* while */ if(!invalid_ja3) { int rc; compute_ja3c: ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), ""%u,"", ja3.client.tls_handshake_version); for(i=0; i 0) ? ""-"" : """", ja3.client.cipher[i]); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",""); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; /* ********** */ for(i=0; i 0) ? ""-"" : """", ja3.client.tls_extension[i]); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",""); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; /* ********** */ for(i=0; i 0) ? ""-"" : """", ja3.client.elliptic_curve[i]); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",""); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; for(i=0; i 0) ? ""-"" : """", ja3.client.elliptic_curve_point_format[i]); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; else break; } if(ndpi_struct->enable_ja3_plus) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "",%s,%s,%s"", ja3.client.signature_algorithms, ja3.client.supported_versions, ja3.client.alpn); if((rc > 0) && (ja3_str_len + rc < JA3_STR_LEN)) ja3_str_len += rc; } #ifdef DEBUG_JA3C printf(""[JA3+] Client: %s \n"", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { rc = snprintf(&flow->protos.tls_quic_stun.tls_quic.ja3_client[j], sizeof(flow->protos.tls_quic_stun.tls_quic.ja3_client)-j, ""%02x"", md5_hash[i]); if(rc > 0) j += rc; else break; } #ifdef DEBUG_JA3C printf(""[JA3] Client: %s \n"", flow->protos.tls_quic_stun.tls_quic.ja3_client); #endif if(ndpi_struct->malicious_ja3_automa.ac_automa != NULL) { u_int16_t rc1 = ndpi_match_string(ndpi_struct->malicious_ja3_automa.ac_automa, flow->protos.tls_quic_stun.tls_quic.ja3_client); if(rc1 > 0) ndpi_set_risk(flow, NDPI_MALICIOUS_JA3); } } /* Before returning to the caller we need to make a final check */ if((flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0303) /* >= TLSv1.2 */ && (flow->protos.tls_quic_stun.tls_quic.alpn == NULL) /* No ALPN */) { ndpi_set_risk(flow, NDPI_TLS_NOT_CARRYING_HTTPS); } /* Suspicious Domain Fronting: https://github.com/SixGenInc/Noctilucent/blob/master/docs/ */ if(flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni && flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] != '\0') { ndpi_set_risk(flow, NDPI_TLS_SUSPICIOUS_ESNI_USAGE); } /* Add check for missing SNI */ if((flow->protos.tls_quic_stun.tls_quic.client_requested_server_name[0] == 0) && (flow->protos.tls_quic_stun.tls_quic.ssl_version >= 0x0302) /* TLSv1.1 */ && (flow->protos.tls_quic_stun.tls_quic.encrypted_sni.esni == NULL) /* No ESNI */ ) { /* This is a bit suspicious */ ndpi_set_risk(flow, NDPI_TLS_MISSING_SNI); } return(2 /* Client Certificate */); } else { #ifdef DEBUG_TLS printf(""[TLS] Client: too short [%u vs %u]\n"", (extensions_len+offset), total_len); #endif } } else if(offset == total_len) { /* TLS does not have extensions etc */ goto compute_ja3c; } } else { #ifdef DEBUG_TLS printf(""[JA3] Client: invalid length detected\n""); #endif } } } return(0); /* Not found */ }",CWE-787,16 0,"void ReleaseMailbox(scoped_refptr frame, uint32 sync_point, bool lost_resource) {} ",none,24 0,"void SpeechSynthesis::voicesDidChange() { m_voiceList.clear(); if (!executionContext()->activeDOMObjectsAreStopped()) dispatchEvent(Event::create(EventTypeNames::voiceschanged)); } ",none,24 0,"SearchEngineTabHelper::SearchEngineTabHelper(WebContents* web_contents) : content::WebContentsObserver(web_contents), delegate_(nullptr), weak_ptr_factory_(this) { DCHECK(web_contents); } ",none,24 1,"static struct property *dlpar_parse_cc_property(struct cc_workarea *ccwa) { struct property *prop; char *name; char *value; prop = kzalloc(sizeof(*prop), GFP_KERNEL); if (!prop) return NULL; name = (char *)ccwa + be32_to_cpu(ccwa->name_offset); prop->name = kstrdup(name, GFP_KERNEL); prop->length = be32_to_cpu(ccwa->prop_length); value = (char *)ccwa + be32_to_cpu(ccwa->prop_offset); prop->value = kmemdup(value, prop->length, GFP_KERNEL); if (!prop->value) { dlpar_free_cc_property(prop); return NULL; } return prop; }",CWE-476,12 1,"std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset forbiddenCommands; std::bitset forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the ""set vibrato speed"" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as ""stop song"" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends ""in between"", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset plugSetProgram; for(const auto ¶m : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; }",CWE-125,1 0,"bool AudioManagerBase::IsRecordingInProcess() { return !base::AtomicRefCountIsZero(&num_active_input_streams_); } ",none,24 1," static int iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) { int err = 0; u32 portid; struct iscsi_uevent *ev = nlmsg_data(nlh); struct iscsi_transport *transport = NULL; struct iscsi_internal *priv; struct iscsi_cls_session *session; struct iscsi_cls_conn *conn; struct iscsi_endpoint *ep = NULL; if (!netlink_capable(skb, CAP_SYS_ADMIN)) return -EPERM; if (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE) *group = ISCSI_NL_GRP_UIP; else *group = ISCSI_NL_GRP_ISCSID; priv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle)); if (!priv) return -EINVAL; transport = priv->iscsi_transport; if (!try_module_get(transport->owner)) return -EINVAL; portid = NETLINK_CB(skb).portid; switch (nlh->nlmsg_type) { case ISCSI_UEVENT_CREATE_SESSION: err = iscsi_if_create_session(priv, ep, ev, portid, ev->u.c_session.initial_cmdsn, ev->u.c_session.cmds_max, ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; break; } err = iscsi_if_create_session(priv, ep, ev, portid, ev->u.c_bound_session.initial_cmdsn, ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (!session) err = -EINVAL; else if (iscsi_session_has_conns(ev->u.d_session.sid)) err = -EBUSY; else transport->destroy_session(session); break; case ISCSI_UEVENT_DESTROY_SESSION_ASYNC: session = iscsi_session_lookup(ev->u.d_session.sid); if (!session) err = -EINVAL; else if (iscsi_session_has_conns(ev->u.d_session.sid)) err = -EBUSY; else { unsigned long flags; /* Prevent this session from being found again */ spin_lock_irqsave(&sesslock, flags); list_del_init(&session->sess_list); spin_unlock_irqrestore(&sesslock, flags); queue_work(iscsi_destroy_workq, &session->destroy_work); } break; case ISCSI_UEVENT_UNBIND_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) scsi_queue_work(iscsi_session_to_shost(session), &session->unbind_work); else err = -EINVAL; break; case ISCSI_UEVENT_CREATE_CONN: err = iscsi_if_create_conn(transport, ev); break; case ISCSI_UEVENT_DESTROY_CONN: err = iscsi_if_destroy_conn(transport, ev); break; case ISCSI_UEVENT_BIND_CONN: session = iscsi_session_lookup(ev->u.b_conn.sid); conn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid); if (conn && conn->ep) iscsi_if_ep_disconnect(transport, conn->ep->id); if (!session || !conn) { err = -EINVAL; break; } mutex_lock(&conn_mutex); ev->r.retcode = transport->bind_conn(session, conn, ev->u.b_conn.transport_eph, ev->u.b_conn.is_leading); mutex_unlock(&conn_mutex); if (ev->r.retcode || !transport->ep_connect) break; ep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph); if (ep) { ep->conn = conn; mutex_lock(&conn->ep_mutex); conn->ep = ep; mutex_unlock(&conn->ep_mutex); } else iscsi_cls_conn_printk(KERN_ERR, conn, ""Could not set ep conn "" ""binding\n""); break; case ISCSI_UEVENT_SET_PARAM: err = iscsi_set_param(transport, ev); break; case ISCSI_UEVENT_START_CONN: conn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid); if (conn) { mutex_lock(&conn_mutex); ev->r.retcode = transport->start_conn(conn); if (!ev->r.retcode) conn->state = ISCSI_CONN_UP; mutex_unlock(&conn_mutex); } else err = -EINVAL; break; case ISCSI_UEVENT_STOP_CONN: conn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid); if (conn) iscsi_if_stop_conn(conn, ev->u.stop_conn.flag); else err = -EINVAL; break; case ISCSI_UEVENT_SEND_PDU: conn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid); if (conn) { mutex_lock(&conn_mutex); ev->r.retcode = transport->send_pdu(conn, (struct iscsi_hdr*)((char*)ev + sizeof(*ev)), (char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size, ev->u.send_pdu.data_size); mutex_unlock(&conn_mutex); } else err = -EINVAL; break; case ISCSI_UEVENT_GET_STATS: err = iscsi_if_get_stats(transport, nlh); break; case ISCSI_UEVENT_TRANSPORT_EP_CONNECT: case ISCSI_UEVENT_TRANSPORT_EP_POLL: case ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT: case ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST: err = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type); break; case ISCSI_UEVENT_TGT_DSCVR: err = iscsi_tgt_dscvr(transport, ev); break; case ISCSI_UEVENT_SET_HOST_PARAM: err = iscsi_set_host_param(transport, ev); break; case ISCSI_UEVENT_PATH_UPDATE: err = iscsi_set_path(transport, ev); break; case ISCSI_UEVENT_SET_IFACE_PARAMS: err = iscsi_set_iface_params(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_PING: err = iscsi_send_ping(transport, ev); break; case ISCSI_UEVENT_GET_CHAP: err = iscsi_get_chap(transport, nlh); break; case ISCSI_UEVENT_DELETE_CHAP: err = iscsi_delete_chap(transport, ev); break; case ISCSI_UEVENT_SET_FLASHNODE_PARAMS: err = iscsi_set_flashnode_param(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_NEW_FLASHNODE: err = iscsi_new_flashnode(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_DEL_FLASHNODE: err = iscsi_del_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGIN_FLASHNODE: err = iscsi_login_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGOUT_FLASHNODE: err = iscsi_logout_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGOUT_FLASHNODE_SID: err = iscsi_logout_flashnode_sid(transport, ev); break; case ISCSI_UEVENT_SET_CHAP: err = iscsi_set_chap(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_GET_HOST_STATS: err = iscsi_get_host_stats(transport, nlh); break; default: err = -ENOSYS; break; } ",CWE-125,1 1,"bool CClient::OnTextMessage(CTextMessage& Message) { CString sTargets = Message.GetTarget(); VCString vTargets; sTargets.Split("","", vTargets, false); for (CString& sTarget : vTargets) { Message.SetTarget(sTarget); if (m_pNetwork) { // May be nullptr. Message.SetChan(m_pNetwork->FindChan(sTarget)); } if (sTarget.TrimPrefix(m_pUser->GetStatusPrefix())) { if (sTarget.Equals(""status"")) { CString sMsg = Message.GetText(); UserCommand(sMsg); } else { CALLMOD(sTarget, this, m_pUser, m_pNetwork, OnModCommand(Message.GetText())); } continue; } bool bContinue = false; NETWORKMODULECALL(OnUserTextMessage(Message), m_pUser, m_pNetwork, this, &bContinue); if (bContinue) continue; if (!GetIRCSock()) { // Some lagmeters do a PRIVMSG to their own nick, ignore those. if (!sTarget.Equals(m_sNick)) PutStatus( t_f(""Your message to {1} got lost, you are not connected "" ""to IRC!"")(Message.GetTarget())); continue; } if (m_pNetwork) { AddBuffer(Message); EchoMessage(Message); PutIRC(Message.ToString(CMessage::ExcludePrefix | CMessage::ExcludeTags)); } } return true; }",CWE-476,12 1,"rb_str_justify(int argc, VALUE *argv, VALUE str, char jflag) { rb_encoding *enc; VALUE w; long width, len, flen = 1, fclen = 1; VALUE res; char *p; const char *f = "" ""; long n, llen, rlen; volatile VALUE pad; int singlebyte = 1, cr; rb_scan_args(argc, argv, ""11"", &w, &pad); enc = STR_ENC_GET(str); width = NUM2LONG(w); if (argc == 2) { StringValue(pad); enc = rb_enc_check(str, pad); f = RSTRING_PTR(pad); flen = RSTRING_LEN(pad); fclen = str_strlen(pad, enc); singlebyte = single_byte_optimizable(pad); if (flen == 0 || fclen == 0) { rb_raise(rb_eArgError, ""zero width padding""); } } len = str_strlen(str, enc); if (width < 0 || len >= width) return rb_str_dup(str); n = width - len; llen = (jflag == 'l') ? 0 : ((jflag == 'r') ? n : n/2); rlen = n - llen; cr = ENC_CODERANGE(str); res = rb_str_new5(str, 0, RSTRING_LEN(str)+n*flen/fclen+2); p = RSTRING_PTR(res); while (llen) { if (flen <= 1) { *p++ = *f; llen--; } else if (llen > fclen) { memcpy(p,f,flen); p += flen; llen -= fclen; } else { char *fp = str_nth(f, f+flen, llen, enc, singlebyte); n = fp - f; memcpy(p,f,n); p+=n; break; } } memcpy(p, RSTRING_PTR(str), RSTRING_LEN(str)); p+=RSTRING_LEN(str); while (rlen) { if (flen <= 1) { *p++ = *f; rlen--; } else if (rlen > fclen) { memcpy(p,f,flen); p += flen; rlen -= fclen; } else { char *fp = str_nth(f, f+flen, rlen, enc, singlebyte); n = fp - f; memcpy(p,f,n); p+=n; break; } } *p = '\0'; STR_SET_LEN(res, p-RSTRING_PTR(res)); OBJ_INFECT(res, str); if (!NIL_P(pad)) OBJ_INFECT(res, pad); rb_enc_associate(res, enc); if (argc == 2) cr = ENC_CODERANGE_AND(cr, ENC_CODERANGE(pad)); if (cr != ENC_CODERANGE_BROKEN) ENC_CODERANGE_SET(res, cr); return res; }",CWE-119,0 1,"static int mt_touch_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max, struct mt_application *app) { struct mt_device *td = hid_get_drvdata(hdev); struct mt_class *cls = &td->mtclass; int code; struct hid_usage *prev_usage = NULL; /* * Model touchscreens providing buttons as touchpads. */ if (field->application == HID_DG_TOUCHSCREEN && (usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) { app->mt_flags |= INPUT_MT_POINTER; td->inputmode_value = MT_INPUTMODE_TOUCHPAD; } /* count the buttons on touchpads */ if ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) app->buttons_count++; if (usage->usage_index) prev_usage = &field->usage[usage->usage_index - 1]; switch (usage->hid & HID_USAGE_PAGE) { case HID_UP_GENDESK: switch (usage->hid) { case HID_GD_X: if (prev_usage && (prev_usage->hid == usage->hid)) { code = ABS_MT_TOOL_X; MT_STORE_FIELD(cx); } else { code = ABS_MT_POSITION_X; MT_STORE_FIELD(x); } set_abs(hi->input, code, field, cls->sn_move); /* * A system multi-axis that exports X and Y has a high * chance of being used directly on a surface */ if (field->application == HID_GD_SYSTEM_MULTIAXIS) { __set_bit(INPUT_PROP_DIRECT, hi->input->propbit); input_set_abs_params(hi->input, ABS_MT_TOOL_TYPE, MT_TOOL_DIAL, MT_TOOL_DIAL, 0, 0); } return 1; case HID_GD_Y: if (prev_usage && (prev_usage->hid == usage->hid)) { code = ABS_MT_TOOL_Y; MT_STORE_FIELD(cy); } else { code = ABS_MT_POSITION_Y; MT_STORE_FIELD(y); } set_abs(hi->input, code, field, cls->sn_move); return 1; } return 0; case HID_UP_DIGITIZER: switch (usage->hid) { case HID_DG_INRANGE: if (app->quirks & MT_QUIRK_HOVERING) { input_set_abs_params(hi->input, ABS_MT_DISTANCE, 0, 1, 0, 0); } MT_STORE_FIELD(inrange_state); return 1; case HID_DG_CONFIDENCE: if (cls->name == MT_CLS_WIN_8 && (field->application == HID_DG_TOUCHPAD || field->application == HID_DG_TOUCHSCREEN)) app->quirks |= MT_QUIRK_CONFIDENCE; if (app->quirks & MT_QUIRK_CONFIDENCE) input_set_abs_params(hi->input, ABS_MT_TOOL_TYPE, MT_TOOL_FINGER, MT_TOOL_PALM, 0, 0); MT_STORE_FIELD(confidence_state); return 1; case HID_DG_TIPSWITCH: if (field->application != HID_GD_SYSTEM_MULTIAXIS) input_set_capability(hi->input, EV_KEY, BTN_TOUCH); MT_STORE_FIELD(tip_state); return 1; case HID_DG_CONTACTID: MT_STORE_FIELD(contactid); app->touches_by_report++; return 1; case HID_DG_WIDTH: if (!(app->quirks & MT_QUIRK_NO_AREA)) set_abs(hi->input, ABS_MT_TOUCH_MAJOR, field, cls->sn_width); MT_STORE_FIELD(w); return 1; case HID_DG_HEIGHT: if (!(app->quirks & MT_QUIRK_NO_AREA)) { set_abs(hi->input, ABS_MT_TOUCH_MINOR, field, cls->sn_height); /* * Only set ABS_MT_ORIENTATION if it is not * already set by the HID_DG_AZIMUTH usage. */ if (!test_bit(ABS_MT_ORIENTATION, hi->input->absbit)) input_set_abs_params(hi->input, ABS_MT_ORIENTATION, 0, 1, 0, 0); } MT_STORE_FIELD(h); return 1; case HID_DG_TIPPRESSURE: set_abs(hi->input, ABS_MT_PRESSURE, field, cls->sn_pressure); MT_STORE_FIELD(p); return 1; case HID_DG_SCANTIME: input_set_capability(hi->input, EV_MSC, MSC_TIMESTAMP); app->scantime = &field->value[usage->usage_index]; app->scantime_logical_max = field->logical_maximum; return 1; case HID_DG_CONTACTCOUNT: app->have_contact_count = true; app->raw_cc = &field->value[usage->usage_index]; return 1; case HID_DG_AZIMUTH: /* * Azimuth has the range of [0, MAX) representing a full * revolution. Set ABS_MT_ORIENTATION to a quarter of * MAX according the definition of ABS_MT_ORIENTATION */ input_set_abs_params(hi->input, ABS_MT_ORIENTATION, -field->logical_maximum / 4, field->logical_maximum / 4, cls->sn_move ? field->logical_maximum / cls->sn_move : 0, 0); MT_STORE_FIELD(a); return 1; case HID_DG_CONTACTMAX: /* contact max are global to the report */ return -1; case HID_DG_TOUCH: /* Legacy devices use TIPSWITCH and not TOUCH. * Let's just ignore this field. */ return -1; } /* let hid-input decide for the others */ return 0; case HID_UP_BUTTON: code = BTN_MOUSE + ((usage->hid - 1) & HID_USAGE); /* * MS PTP spec says that external buttons left and right have * usages 2 and 3. */ if ((app->quirks & MT_QUIRK_WIN8_PTP_BUTTONS) && field->application == HID_DG_TOUCHPAD && (usage->hid & HID_USAGE) > 1) code--; if (field->application == HID_GD_SYSTEM_MULTIAXIS) code = BTN_0 + ((usage->hid - 1) & HID_USAGE); hid_map_usage(hi, usage, bit, max, EV_KEY, code); input_set_capability(hi->input, EV_KEY, code); return 1; case 0xff000000: /* we do not want to map these: no input-oriented meaning */ return -1; } return 0; }",CWE-787,16 1,"ec_p_init (mpi_ec_t ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { int i; static int use_barrett; if (!use_barrett) { if (getenv (""GCRYPT_BARRETT"")) use_barrett = 1; else use_barrett = -1; } /* Fixme: Do we want to check some constraints? e.g. a < p */ ctx->model = model; ctx->dialect = dialect; ctx->flags = flags; if (dialect == ECC_DIALECT_ED25519) ctx->nbits = 256; else ctx->nbits = mpi_get_nbits (p); ctx->p = mpi_copy (p); ctx->a = mpi_copy (a); ctx->b = mpi_copy (b); ctx->t.p_barrett = use_barrett > 0? _gcry_mpi_barrett_init (ctx->p, 0):NULL; _gcry_mpi_ec_get_reset (ctx); /* Allocate scratch variables. */ for (i=0; i< DIM(ctx->t.scratch); i++) ctx->t.scratch[i] = mpi_alloc_like (ctx->p); /* Prepare for fast reduction. */ /* FIXME: need a test for NIST values. However it does not gain us any real advantage, for 384 bits it is actually slower than using mpi_mulm. */ /* ctx->nist_nbits = mpi_get_nbits (ctx->p); */ /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* ctx->s[i] = mpi_new (192); */ /* ctx->c = mpi_new (192*2); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* ctx->s[i] = mpi_new (384); */ /* ctx->c = mpi_new (384*2); */ /* } */ }",CWE-200,4 0,"unsigned WebGraphicsContext3DDefaultImpl::createRenderbuffer() { makeContextCurrent(); GLuint o; glGenRenderbuffersEXT(1, &o); return o; } ",none,24 1,"static int dwa_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { int64_t version, lo_usize, lo_size; int64_t ac_size, dc_size, rle_usize, rle_csize, rle_raw_size; int64_t ac_count, dc_count, ac_compression; const int dc_w = td->xsize >> 3; const int dc_h = td->ysize >> 3; GetByteContext gb, agb; int skip, ret; if (compressed_size <= 88) return AVERROR_INVALIDDATA; version = AV_RL64(src + 0); if (version != 2) return AVERROR_INVALIDDATA; lo_usize = AV_RL64(src + 8); lo_size = AV_RL64(src + 16); ac_size = AV_RL64(src + 24); dc_size = AV_RL64(src + 32); rle_csize = AV_RL64(src + 40); rle_usize = AV_RL64(src + 48); rle_raw_size = AV_RL64(src + 56); ac_count = AV_RL64(src + 64); dc_count = AV_RL64(src + 72); ac_compression = AV_RL64(src + 80); if (compressed_size < 88LL + lo_size + ac_size + dc_size + rle_csize) return AVERROR_INVALIDDATA; bytestream2_init(&gb, src + 88, compressed_size - 88); skip = bytestream2_get_le16(&gb); if (skip < 2) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, skip - 2); if (lo_size > 0) { if (lo_usize > uncompressed_size) return AVERROR_INVALIDDATA; bytestream2_skip(&gb, lo_size); } if (ac_size > 0) { unsigned long dest_len = ac_count * 2LL; GetByteContext agb = gb; if (ac_count > 3LL * td->xsize * s->scan_lines_per_block) return AVERROR_INVALIDDATA; av_fast_padded_malloc(&td->ac_data, &td->ac_size, dest_len); if (!td->ac_data) return AVERROR(ENOMEM); switch (ac_compression) { case 0: ret = huf_uncompress(s, td, &agb, (int16_t *)td->ac_data, ac_count); if (ret < 0) return ret; break; case 1: if (uncompress(td->ac_data, &dest_len, agb.buffer, ac_size) != Z_OK || dest_len != ac_count * 2LL) return AVERROR_INVALIDDATA; break; default: return AVERROR_INVALIDDATA; } bytestream2_skip(&gb, ac_size); } if (dc_size > 0) { unsigned long dest_len = dc_count * 2LL; GetByteContext agb = gb; if (dc_count > (6LL * td->xsize * td->ysize + 63) / 64) return AVERROR_INVALIDDATA; av_fast_padded_malloc(&td->dc_data, &td->dc_size, FFALIGN(dest_len, 64) * 2); if (!td->dc_data) return AVERROR(ENOMEM); if (uncompress(td->dc_data + FFALIGN(dest_len, 64), &dest_len, agb.buffer, dc_size) != Z_OK || (dest_len != dc_count * 2LL)) return AVERROR_INVALIDDATA; s->dsp.predictor(td->dc_data + FFALIGN(dest_len, 64), dest_len); s->dsp.reorder_pixels(td->dc_data, td->dc_data + FFALIGN(dest_len, 64), dest_len); bytestream2_skip(&gb, dc_size); } if (rle_raw_size > 0 && rle_csize > 0 && rle_usize > 0) { unsigned long dest_len = rle_usize; av_fast_padded_malloc(&td->rle_data, &td->rle_size, rle_usize); if (!td->rle_data) return AVERROR(ENOMEM); av_fast_padded_malloc(&td->rle_raw_data, &td->rle_raw_size, rle_raw_size); if (!td->rle_raw_data) return AVERROR(ENOMEM); if (uncompress(td->rle_data, &dest_len, gb.buffer, rle_csize) != Z_OK || (dest_len != rle_usize)) return AVERROR_INVALIDDATA; ret = rle(td->rle_raw_data, td->rle_data, rle_usize, rle_raw_size); if (ret < 0) return ret; bytestream2_skip(&gb, rle_csize); } bytestream2_init(&agb, td->ac_data, ac_count * 2); for (int y = 0; y < td->ysize; y += 8) { for (int x = 0; x < td->xsize; x += 8) { memset(td->block, 0, sizeof(td->block)); for (int j = 0; j < 3; j++) { float *block = td->block[j]; const int idx = (x >> 3) + (y >> 3) * dc_w + dc_w * dc_h * j; uint16_t *dc = (uint16_t *)td->dc_data; union av_intfloat32 dc_val; dc_val.i = half2float(dc[idx], s->mantissatable, s->exponenttable, s->offsettable); block[0] = dc_val.f; ac_uncompress(s, &agb, block); dct_inverse(block); } { const float scale = s->pixel_type == EXR_FLOAT ? 2.f : 1.f; const int o = s->nb_channels == 4; float *bo = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 0) + x; float *go = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 1) + x; float *ro = ((float *)td->uncompressed_data) + y * td->xsize * s->nb_channels + td->xsize * (o + 2) + x; float *yb = td->block[0]; float *ub = td->block[1]; float *vb = td->block[2]; for (int yy = 0; yy < 8; yy++) { for (int xx = 0; xx < 8; xx++) { const int idx = xx + yy * 8; convert(yb[idx], ub[idx], vb[idx], &bo[xx], &go[xx], &ro[xx]); bo[xx] = to_linear(bo[xx], scale); go[xx] = to_linear(go[xx], scale); ro[xx] = to_linear(ro[xx], scale); } bo += td->xsize * s->nb_channels; go += td->xsize * s->nb_channels; ro += td->xsize * s->nb_channels; } } } } if (s->nb_channels < 4) return 0; for (int y = 0; y < td->ysize && td->rle_raw_data; y++) { uint32_t *ao = ((uint32_t *)td->uncompressed_data) + y * td->xsize * s->nb_channels; uint8_t *ai0 = td->rle_raw_data + y * td->xsize; uint8_t *ai1 = td->rle_raw_data + y * td->xsize + rle_raw_size / 2; for (int x = 0; x < td->xsize; x++) { uint16_t ha = ai0[x] | (ai1[x] << 8); ao[x] = half2float(ha, s->mantissatable, s->exponenttable, s->offsettable); } } return 0; }",CWE-20,3 0," virtual ~MockVideoCaptureImplManager() {} ",none,24 1,"uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg, char *buffer) { // Swap data begins 164 chars into data buffer: // offset = deposit function hash + address + address + uint256 uint16_t offset = 4 + (5 * 32); int16_t len = msg->data_length - offset; if (msg->has_data_length && len > 0) { memcpy(buffer, msg->data_initial_chunk.bytes + offset, len); // String length must be < 255 characters return len < 256 ? (uint8_t)len : 0; } return 0; }",CWE-787,16 0," virtual ~RTCVideoDecoderTest() { message_loop_.RunAllPending(); } ",none,24 1,"GF_Err abst_box_read(GF_Box *s, GF_BitStream *bs) { GF_AdobeBootstrapInfoBox *ptr = (GF_AdobeBootstrapInfoBox *)s; int i; u32 tmp_strsize; char *tmp_str; Bool zfound=GF_FALSE; GF_Err e; ISOM_DECREASE_SIZE(ptr, 25) ptr->bootstrapinfo_version = gf_bs_read_u32(bs); ptr->profile = gf_bs_read_int(bs, 2); ptr->live = gf_bs_read_int(bs, 1); ptr->update = gf_bs_read_int(bs, 1); ptr->reserved = gf_bs_read_int(bs, 4); ptr->time_scale = gf_bs_read_u32(bs); ptr->current_media_time = gf_bs_read_u64(bs); ptr->smpte_time_code_offset = gf_bs_read_u64(bs); i=0; if (ptr->size<8) return GF_ISOM_INVALID_FILE; tmp_strsize =(u32)ptr->size; tmp_str = gf_malloc(sizeof(char)*tmp_strsize); if (!tmp_str) return GF_OUT_OF_MEM; memset(tmp_str, 0, sizeof(char)*tmp_strsize); while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) { zfound = GF_TRUE; break; } i++; } if (!zfound) return GF_ISOM_INVALID_FILE; if (i) { ptr->movie_identifier = gf_strdup(tmp_str); } ISOM_DECREASE_SIZE(ptr, 1) ptr->server_entry_count = gf_bs_read_u8(bs); for (i=0; iserver_entry_count; i++) { int j=0; zfound = GF_FALSE; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[j] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[j]) { zfound = GF_TRUE; break; } j++; } if (!zfound) return GF_ISOM_INVALID_FILE; if (j) { gf_list_insert(ptr->server_entry_table, gf_strdup(tmp_str), i); } } ISOM_DECREASE_SIZE(ptr, 1) ptr->quality_entry_count = gf_bs_read_u8(bs); for (i=0; iquality_entry_count; i++) { int j=0; zfound = GF_FALSE; tmp_strsize=(u32)ptr->size; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[j] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[j]) { zfound = GF_TRUE; break; } j++; } if (!zfound) return GF_ISOM_INVALID_FILE; if (j) { gf_list_insert(ptr->quality_entry_table, gf_strdup(tmp_str), i); } } i=0; tmp_strsize=(u32)ptr->size; zfound = GF_FALSE; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) { zfound = GF_TRUE; break; } i++; } if (!zfound) return GF_ISOM_INVALID_FILE; if (i) { ptr->drm_data = gf_strdup(tmp_str); } i=0; tmp_strsize=(u32)ptr->size; zfound = GF_FALSE; while (tmp_strsize) { ISOM_DECREASE_SIZE(ptr, 1) tmp_str[i] = gf_bs_read_u8(bs); tmp_strsize--; if (!tmp_str[i]) { zfound = GF_TRUE; break; } i++; } if (!zfound) return GF_ISOM_INVALID_FILE; if (i) { ptr->meta_data = gf_strdup(tmp_str); } ISOM_DECREASE_SIZE(ptr, 1) ptr->segment_run_table_count = gf_bs_read_u8(bs); for (i=0; isegment_run_table_count; i++) { GF_AdobeSegmentRunTableBox *asrt = NULL; e = gf_isom_box_parse((GF_Box **)&asrt, bs); if (e) { if (asrt) gf_isom_box_del((GF_Box*)asrt); gf_free(tmp_str); return e; } gf_list_add(ptr->segment_run_table_entries, asrt); } ISOM_DECREASE_SIZE(ptr, 1) ptr->fragment_run_table_count = gf_bs_read_u8(bs); for (i=0; ifragment_run_table_count; i++) { GF_AdobeFragmentRunTableBox *afrt = NULL; e = gf_isom_box_parse((GF_Box **)&afrt, bs); if (e) { if (afrt) gf_isom_box_del((GF_Box*)afrt); gf_free(tmp_str); return e; } gf_list_add(ptr->fragment_run_table_entries, afrt); } gf_free(tmp_str); return GF_OK; }",CWE-476,12 0,"void AssociateURLFetcherWithWebContents(content::WebContents* web_contents, net::URLFetcher* url_fetcher) { content::AssociateURLFetcherWithRenderFrame( url_fetcher, web_contents->GetURL(), web_contents->GetRenderProcessHost()->GetID(), web_contents->GetMainFrame()->GetRoutingID()); } ",none,24 0,"void BlobURLRequestJob::Start() { MessageLoop::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&BlobURLRequestJob::DidStart)); } ",none,24 0," ServiceWorkerVersionBrowserTest() : next_registration_id_(1) {} ",none,24 1,"mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, struct cfg80211_ssid *req_ssid) { int rsn_ie_len = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_ad_hoc_start *adhoc_start = &cmd->params.adhoc_start; struct mwifiex_bssdescriptor *bss_desc; u32 cmd_append_size = 0; u32 i; u16 tmp_cap; struct mwifiex_ie_types_chan_list_param_set *chan_tlv; u8 radio_type; struct mwifiex_ie_types_htcap *ht_cap; struct mwifiex_ie_types_htinfo *ht_info; u8 *pos = (u8 *) adhoc_start + sizeof(struct host_cmd_ds_802_11_ad_hoc_start); if (!adapter) return -1; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START); bss_desc = &priv->curr_bss_params.bss_descriptor; priv->attempted_bss_desc = bss_desc; /* * Fill in the parameters for 2 data structures: * 1. struct host_cmd_ds_802_11_ad_hoc_start command * 2. bss_desc * Driver will fill up SSID, bss_mode,IBSS param, Physical Param, * probe delay, and Cap info. * Firmware will fill up beacon period, Basic rates * and operational rates. */ memset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN); memcpy(adhoc_start->ssid, req_ssid->ssid, req_ssid->ssid_len); mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: SSID = %s\n"", adhoc_start->ssid); memset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN); memcpy(bss_desc->ssid.ssid, req_ssid->ssid, req_ssid->ssid_len); bss_desc->ssid.ssid_len = req_ssid->ssid_len; /* Set the BSS mode */ adhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS; bss_desc->bss_mode = NL80211_IFTYPE_ADHOC; adhoc_start->beacon_period = cpu_to_le16(priv->beacon_period); bss_desc->beacon_period = priv->beacon_period; /* Set Physical param set */ /* Parameter IE Id */ #define DS_PARA_IE_ID 3 /* Parameter IE length */ #define DS_PARA_IE_LEN 1 adhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID; adhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN; if (!mwifiex_get_cfp(priv, adapter->adhoc_start_band, (u16) priv->adhoc_channel, 0)) { struct mwifiex_chan_freq_power *cfp; cfp = mwifiex_get_cfp(priv, adapter->adhoc_start_band, FIRST_VALID_CHANNEL, 0); if (cfp) priv->adhoc_channel = (u8) cfp->channel; } if (!priv->adhoc_channel) { mwifiex_dbg(adapter, ERROR, ""ADHOC_S_CMD: adhoc_channel cannot be 0\n""); return -1; } mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: creating ADHOC on channel %d\n"", priv->adhoc_channel); priv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel; priv->curr_bss_params.band = adapter->adhoc_start_band; bss_desc->channel = priv->adhoc_channel; adhoc_start->phy_param_set.ds_param_set.current_chan = priv->adhoc_channel; memcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set, sizeof(union ieee_types_phy_param_set)); /* Set IBSS param set */ /* IBSS parameter IE Id */ #define IBSS_PARA_IE_ID 6 /* IBSS parameter IE length */ #define IBSS_PARA_IE_LEN 2 adhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID; adhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN; adhoc_start->ss_param_set.ibss_param_set.atim_window = cpu_to_le16(priv->atim_window); memcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set, sizeof(union ieee_types_ss_param_set)); /* Set Capability info */ bss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS; tmp_cap = WLAN_CAPABILITY_IBSS; /* Set up privacy in bss_desc */ if (priv->sec_info.encryption_mode) { /* Ad-Hoc capability privacy on */ mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: wep_status set privacy to WEP\n""); bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP; tmp_cap |= WLAN_CAPABILITY_PRIVACY; } else { mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: wep_status NOT set,\t"" ""setting privacy to ACCEPT ALL\n""); bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL; } memset(adhoc_start->data_rate, 0, sizeof(adhoc_start->data_rate)); mwifiex_get_active_data_rates(priv, adhoc_start->data_rate); if ((adapter->adhoc_start_band & BAND_G) && (priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) { if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, false)) { mwifiex_dbg(adapter, ERROR, ""ADHOC_S_CMD: G Protection config failed\n""); return -1; } } /* Find the last non zero */ for (i = 0; i < sizeof(adhoc_start->data_rate); i++) if (!adhoc_start->data_rate[i]) break; priv->curr_bss_params.num_of_rates = i; /* Copy the ad-hoc creating rates into Current BSS rate structure */ memcpy(&priv->curr_bss_params.data_rates, &adhoc_start->data_rate, priv->curr_bss_params.num_of_rates); mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: rates=%4ph\n"", adhoc_start->data_rate); mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: AD-HOC Start command is ready\n""); if (IS_SUPPORT_MULTI_BANDS(adapter)) { /* Append a channel TLV */ chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos; chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); chan_tlv->header.len = cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set)); memset(chan_tlv->chan_scan_param, 0x00, sizeof(struct mwifiex_chan_scan_param_set)); chan_tlv->chan_scan_param[0].chan_number = (u8) priv->curr_bss_params.bss_descriptor.channel; mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: TLV Chan = %d\n"", chan_tlv->chan_scan_param[0].chan_number); chan_tlv->chan_scan_param[0].radio_type = mwifiex_band_to_radio_type(priv->curr_bss_params.band); if (adapter->adhoc_start_band & BAND_GN || adapter->adhoc_start_band & BAND_AN) { if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_ABOVE) chan_tlv->chan_scan_param[0].radio_type |= (IEEE80211_HT_PARAM_CHA_SEC_ABOVE << 4); else if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_BELOW) chan_tlv->chan_scan_param[0].radio_type |= (IEEE80211_HT_PARAM_CHA_SEC_BELOW << 4); } mwifiex_dbg(adapter, INFO, ""info: ADHOC_S_CMD: TLV Band = %d\n"", chan_tlv->chan_scan_param[0].radio_type); pos += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); cmd_append_size += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); } /* Append vendor specific IE TLV */ cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ADHOC, &pos); if (priv->sec_info.wpa_enabled) { rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos); if (rsn_ie_len == -1) return -1; cmd_append_size += rsn_ie_len; } if (adapter->adhoc_11n_enabled) { /* Fill HT CAPABILITY */ ht_cap = (struct mwifiex_ie_types_htcap *) pos; memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap)); ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); ht_cap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); radio_type = mwifiex_band_to_radio_type( priv->adapter->config_bands); mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap); if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_NONE) { u16 tmp_ht_cap; tmp_ht_cap = le16_to_cpu(ht_cap->ht_cap.cap_info); tmp_ht_cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; tmp_ht_cap &= ~IEEE80211_HT_CAP_SGI_40; ht_cap->ht_cap.cap_info = cpu_to_le16(tmp_ht_cap); } pos += sizeof(struct mwifiex_ie_types_htcap); cmd_append_size += sizeof(struct mwifiex_ie_types_htcap); /* Fill HT INFORMATION */ ht_info = (struct mwifiex_ie_types_htinfo *) pos; memset(ht_info, 0, sizeof(struct mwifiex_ie_types_htinfo)); ht_info->header.type = cpu_to_le16(WLAN_EID_HT_OPERATION); ht_info->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_operation)); ht_info->ht_oper.primary_chan = (u8) priv->curr_bss_params.bss_descriptor.channel; if (adapter->sec_chan_offset) { ht_info->ht_oper.ht_param = adapter->sec_chan_offset; ht_info->ht_oper.ht_param |= IEEE80211_HT_PARAM_CHAN_WIDTH_ANY; } ht_info->ht_oper.operation_mode = cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT); ht_info->ht_oper.basic_set[0] = 0xff; pos += sizeof(struct mwifiex_ie_types_htinfo); cmd_append_size += sizeof(struct mwifiex_ie_types_htinfo); } cmd->size = cpu_to_le16((u16)(sizeof(struct host_cmd_ds_802_11_ad_hoc_start) + S_DS_GEN + cmd_append_size)); if (adapter->adhoc_start_band == BAND_B) tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME; else tmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME; adhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap); return 0; }",CWE-787,16 0,"bool BlobURLRequestJob::ReadItem() { if (remaining_bytes_ == 0) return true; if (item_index_ >= blob_data_->items().size()) { NotifyFailure(net::ERR_FAILED); return false; } bytes_to_read_ = ComputeBytesToRead(); if (bytes_to_read_ == 0) { AdvanceItem(); return ReadItem(); } const BlobData::Item& item = blob_data_->items().at(item_index_); switch (item.type()) { case BlobData::TYPE_DATA: return ReadBytes(item); case BlobData::TYPE_FILE: return DispatchReadFile(item); default: DCHECK(false); return false; } } ",none,24 0,"WebString WebGraphicsContext3DDefaultImpl::getString(unsigned long name) { makeContextCurrent(); return WebString::fromUTF8(reinterpret_cast(glGetString(name))); } ",none,24 0,"void ContentSettingsStore::RegisterExtension( const std::string& ext_id, const base::Time& install_time, bool is_enabled) { base::AutoLock lock(lock_); ExtensionEntryMap::iterator i = FindEntry(ext_id); if (i != entries_.end()) { delete i->second; entries_.erase(i); } ExtensionEntry* entry = new ExtensionEntry; entry->id = ext_id; entry->enabled = is_enabled; entries_.insert(std::make_pair(install_time, entry)); } ",none,24 0,"bool SearchEngineTabHelper::OnMessageReceived( const IPC::Message& message, content::RenderFrameHost* render_frame_host) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(SearchEngineTabHelper, message) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_PageHasOSDD, OnPageHasOSDD) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } ",none,24 1,"} void print_udta(GF_ISOFile *file, u32 track_number, Bool has_itags) { u32 i, count; count = gf_isom_get_udta_count(file, track_number); if (!count) return; if (has_itags) { for (i=0; ikeepBlanks = 0; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; /*ctxt->sax->fatalError = NULL;*/ old = php_libxml_disable_entity_loader(1); xmlParseDocument(ctxt); php_libxml_disable_entity_loader(old); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; }",CWE-200,4 1,"static x3f_huffnode_t *new_node(x3f_hufftree_t *tree) { x3f_huffnode_t *t = &tree->nodes[tree->free_node_index]; t->branch[0] = NULL; t->branch[1] = NULL; t->leaf = UNDEFINED_LEAF; tree->free_node_index++; return t; }",CWE-125,1 0,"void VideoRendererBase::ThreadMain() { base::PlatformThread::SetName(""CrVideoRenderer""); const base::TimeDelta kIdleTimeDelta = base::TimeDelta::FromMilliseconds(10); uint32 frames_dropped = 0; for (;;) { if (frames_dropped > 0) { PipelineStatistics statistics; statistics.video_frames_dropped = frames_dropped; statistics_cb_.Run(statistics); frames_dropped = 0; } base::AutoLock auto_lock(lock_); if (state_ == kStopped) return; if (state_ != kPlaying || playback_rate_ == 0) { frame_available_.TimedWait(kIdleTimeDelta); continue; } if (ready_frames_.empty()) { frame_available_.TimedWait(kIdleTimeDelta); continue; } if (!current_frame_) { if (ready_frames_.front()->IsEndOfStream()) { state_ = kEnded; host()->NotifyEnded(); ready_frames_.clear(); continue; } frame_available_.TimedWait(kIdleTimeDelta); continue; } base::TimeDelta remaining_time = CalculateSleepDuration(ready_frames_.front(), playback_rate_); if (remaining_time.InMicroseconds() > 0) { remaining_time = std::min(remaining_time, kIdleTimeDelta); frame_available_.TimedWait(remaining_time); continue; } if (ready_frames_.front()->IsEndOfStream()) { state_ = kEnded; host()->NotifyEnded(); ready_frames_.clear(); continue; } if (pending_paint_) { while (!ready_frames_.empty()) { if (ready_frames_.front()->IsEndOfStream()) break; base::TimeDelta remaining_time = ready_frames_.front()->GetTimestamp() - host()->GetTime(); if (remaining_time.InMicroseconds() > 0) break; if (!drop_frames_) break; ++frames_dropped; ready_frames_.pop_front(); AttemptRead_Locked(); } frame_available_.TimedWait(kIdleTimeDelta); continue; } DCHECK(!pending_paint_); DCHECK(!ready_frames_.empty()); current_frame_ = ready_frames_.front(); ready_frames_.pop_front(); AttemptRead_Locked(); base::AutoUnlock auto_unlock(lock_); paint_cb_.Run(); } } ",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; 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; } gimp_progress_init_printf (_(""Opening '%s'""), gimp_filename_to_utf8 (filename)); /* 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) || ((info.bpp == 15 || info.bpp == 24) && info.alphaBits != 0) || (info.bpp == 16 && info.alphaBits != 1) || (info.bpp == 32 && info.alphaBits != 8)) { g_message (""Unhandled sub-format in '%s' (type = %u, bpp = %u, alpha = %u)"", gimp_filename_to_utf8 (filename), info.imageType, info.bpp, info.alphaBits); 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,"codegen(codegen_scope *s, node *tree, int val) { int nt; int rlev = s->rlev; if (!tree) { if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } return; } s->rlev++; if (s->rlev > MRB_CODEGEN_LEVEL_MAX) { codegen_error(s, ""too complex expression""); } if (s->irep && s->filename_index != tree->filename_index) { mrb_sym fname = mrb_parser_get_filename(s->parser, s->filename_index); const char *filename = mrb_sym_name_len(s->mrb, fname, NULL); mrb_debug_info_append_file(s->mrb, s->irep->debug_info, filename, s->lines, s->debug_start_pos, s->pc); s->debug_start_pos = s->pc; s->filename_index = tree->filename_index; s->filename_sym = mrb_parser_get_filename(s->parser, tree->filename_index); } nt = nint(tree->car); s->lineno = tree->lineno; tree = tree->cdr; switch (nt) { case NODE_BEGIN: if (val && !tree) { genop_1(s, OP_LOADNIL, cursp()); push(); } while (tree) { codegen(s, tree->car, tree->cdr ? NOVAL : val); tree = tree->cdr; } break; case NODE_RESCUE: { int noexc; uint32_t exend, pos1, pos2, tmp; struct loopinfo *lp; int catch_entry, begin, end; if (tree->car == NULL) goto exit; lp = loop_push(s, LOOP_BEGIN); lp->pc0 = new_label(s); catch_entry = catch_handler_new(s); begin = s->pc; codegen(s, tree->car, VAL); pop(); lp->type = LOOP_RESCUE; end = s->pc; noexc = genjmp_0(s, OP_JMP); catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc); tree = tree->cdr; exend = JMPLINK_START; pos1 = JMPLINK_START; if (tree->car) { node *n2 = tree->car; int exc = cursp(); genop_1(s, OP_EXCEPT, exc); push(); while (n2) { node *n3 = n2->car; node *n4 = n3->car; dispatch(s, pos1); pos2 = JMPLINK_START; do { if (n4 && n4->car && nint(n4->car->car) == NODE_SPLAT) { codegen(s, n4->car, VAL); gen_move(s, cursp(), exc, 0); push_n(2); pop_n(2); /* space for one arg and a block */ pop(); genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1); } else { if (n4) { codegen(s, n4->car, VAL); } else { genop_2(s, OP_GETCONST, cursp(), new_sym(s, MRB_SYM_2(s->mrb, StandardError))); push(); } pop(); genop_2(s, OP_RESCUE, exc, cursp()); } tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, val); pos2 = tmp; if (n4) { n4 = n4->cdr; } } while (n4); pos1 = genjmp_0(s, OP_JMP); dispatch_linked(s, pos2); pop(); if (n3->cdr->car) { gen_assignment(s, n3->cdr->car, NULL, exc, NOVAL); } if (n3->cdr->cdr->car) { codegen(s, n3->cdr->cdr->car, val); if (val) pop(); } tmp = genjmp(s, OP_JMP, exend); exend = tmp; n2 = n2->cdr; push(); } if (pos1 != JMPLINK_START) { dispatch(s, pos1); genop_1(s, OP_RAISEIF, exc); } } pop(); tree = tree->cdr; dispatch(s, noexc); if (tree->car) { codegen(s, tree->car, val); } else if (val) { push(); } dispatch_linked(s, exend); loop_pop(s, NOVAL); } break; case NODE_ENSURE: if (!tree->cdr || !tree->cdr->cdr || (nint(tree->cdr->cdr->car) == NODE_BEGIN && tree->cdr->cdr->cdr)) { int catch_entry, begin, end, target; int idx; catch_entry = catch_handler_new(s); begin = s->pc; codegen(s, tree->car, val); end = target = s->pc; push(); idx = cursp(); genop_1(s, OP_EXCEPT, idx); push(); codegen(s, tree->cdr->cdr, NOVAL); pop(); genop_1(s, OP_RAISEIF, idx); pop(); catch_handler_set(s, catch_entry, MRB_CATCH_ENSURE, begin, end, target); } else { /* empty ensure ignored */ codegen(s, tree->car, val); } break; case NODE_LAMBDA: if (val) { int idx = lambda_body(s, tree, 1); genop_2(s, OP_LAMBDA, cursp(), idx); push(); } break; case NODE_BLOCK: if (val) { int idx = lambda_body(s, tree, 1); genop_2(s, OP_BLOCK, cursp(), idx); push(); } break; case NODE_IF: { uint32_t pos1, pos2; mrb_bool nil_p = FALSE; node *elsepart = tree->cdr->cdr->car; if (!tree->car) { codegen(s, elsepart, val); goto exit; } if (true_always(tree->car)) { codegen(s, tree->cdr->car, val); goto exit; } if (false_always(tree->car)) { codegen(s, elsepart, val); goto exit; } if (nint(tree->car->car) == NODE_CALL) { node *n = tree->car->cdr; mrb_sym mid = nsym(n->cdr->car); mrb_sym sym_nil_p = MRB_SYM_Q_2(s->mrb, nil); if (mid == sym_nil_p && n->cdr->cdr->car == NULL) { nil_p = TRUE; codegen(s, n->car, VAL); } } if (!nil_p) { codegen(s, tree->car, VAL); } pop(); if (val || tree->cdr->car) { if (nil_p) { pos2 = genjmp2_0(s, OP_JMPNIL, cursp(), val); pos1 = genjmp_0(s, OP_JMP); dispatch(s, pos2); } else { pos1 = genjmp2_0(s, OP_JMPNOT, cursp(), val); } codegen(s, tree->cdr->car, val); if (val) pop(); if (elsepart || val) { pos2 = genjmp_0(s, OP_JMP); dispatch(s, pos1); codegen(s, elsepart, val); dispatch(s, pos2); } else { dispatch(s, pos1); } } else { /* empty then-part */ if (elsepart) { if (nil_p) { pos1 = genjmp2_0(s, OP_JMPNIL, cursp(), val); } else { pos1 = genjmp2_0(s, OP_JMPIF, cursp(), val); } codegen(s, elsepart, val); dispatch(s, pos1); } else if (val && !nil_p) { genop_1(s, OP_LOADNIL, cursp()); push(); } } } break; case NODE_AND: { uint32_t pos; if (true_always(tree->car)) { codegen(s, tree->cdr, val); goto exit; } if (false_always(tree->car)) { codegen(s, tree->car, val); goto exit; } codegen(s, tree->car, VAL); pop(); pos = genjmp2_0(s, OP_JMPNOT, cursp(), val); codegen(s, tree->cdr, val); dispatch(s, pos); } break; case NODE_OR: { uint32_t pos; if (true_always(tree->car)) { codegen(s, tree->car, val); goto exit; } if (false_always(tree->car)) { codegen(s, tree->cdr, val); goto exit; } codegen(s, tree->car, VAL); pop(); pos = genjmp2_0(s, OP_JMPIF, cursp(), val); codegen(s, tree->cdr, val); dispatch(s, pos); } break; case NODE_WHILE: case NODE_UNTIL: { if (true_always(tree->car)) { if (nt == NODE_UNTIL) { if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } goto exit; } } else if (false_always(tree->car)) { if (nt == NODE_WHILE) { if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } goto exit; } } uint32_t pos = JMPLINK_START; struct loopinfo *lp = loop_push(s, LOOP_NORMAL); if (!val) lp->reg = -1; lp->pc0 = new_label(s); codegen(s, tree->car, VAL); pop(); if (nt == NODE_WHILE) { pos = genjmp2_0(s, OP_JMPNOT, cursp(), NOVAL); } else { pos = genjmp2_0(s, OP_JMPIF, cursp(), NOVAL); } lp->pc1 = new_label(s); codegen(s, tree->cdr, NOVAL); genjmp(s, OP_JMP, lp->pc0); dispatch(s, pos); loop_pop(s, val); } break; case NODE_FOR: for_body(s, tree); if (val) push(); break; case NODE_CASE: { int head = 0; uint32_t pos1, pos2, pos3, tmp; node *n; pos3 = JMPLINK_START; if (tree->car) { head = cursp(); codegen(s, tree->car, VAL); } tree = tree->cdr; while (tree) { n = tree->car->car; pos1 = pos2 = JMPLINK_START; while (n) { codegen(s, n->car, VAL); if (head) { gen_move(s, cursp(), head, 0); push(); push(); pop(); pop(); pop(); if (nint(n->car->car) == NODE_SPLAT) { genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, __case_eqq)), 1); } else { genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_OPSYM_2(s->mrb, eqq)), 1); } } else { pop(); } tmp = genjmp2(s, OP_JMPIF, cursp(), pos2, NOVAL); pos2 = tmp; n = n->cdr; } if (tree->car->car) { pos1 = genjmp_0(s, OP_JMP); dispatch_linked(s, pos2); } codegen(s, tree->car->cdr, val); if (val) pop(); tmp = genjmp(s, OP_JMP, pos3); pos3 = tmp; dispatch(s, pos1); tree = tree->cdr; } if (val) { uint32_t pos = cursp(); genop_1(s, OP_LOADNIL, cursp()); if (pos3 != JMPLINK_START) dispatch_linked(s, pos3); if (head) pop(); if (cursp() != pos) { gen_move(s, cursp(), pos, 0); } push(); } else { if (pos3 != JMPLINK_START) { dispatch_linked(s, pos3); } if (head) { pop(); } } } break; case NODE_SCOPE: scope_body(s, tree, NOVAL); break; case NODE_FCALL: case NODE_CALL: gen_call(s, tree, val, 0); break; case NODE_SCALL: gen_call(s, tree, val, 1); break; case NODE_DOT2: codegen(s, tree->car, val); codegen(s, tree->cdr, val); if (val) { pop(); pop(); genop_1(s, OP_RANGE_INC, cursp()); push(); } break; case NODE_DOT3: codegen(s, tree->car, val); codegen(s, tree->cdr, val); if (val) { pop(); pop(); genop_1(s, OP_RANGE_EXC, cursp()); push(); } break; case NODE_COLON2: { int sym = new_sym(s, nsym(tree->cdr)); codegen(s, tree->car, VAL); pop(); genop_2(s, OP_GETMCNST, cursp(), sym); if (val) push(); } break; case NODE_COLON3: { int sym = new_sym(s, nsym(tree)); genop_1(s, OP_OCLASS, cursp()); genop_2(s, OP_GETMCNST, cursp(), sym); if (val) push(); } break; case NODE_ARRAY: { int n; n = gen_values(s, tree, val, 0); if (val) { if (n >= 0) { pop_n(n); genop_2(s, OP_ARRAY, cursp(), n); } push(); } } break; case NODE_HASH: case NODE_KW_HASH: { int nk = gen_hash(s, tree, val, GEN_LIT_ARY_MAX); if (val && nk >= 0) { pop_n(nk*2); genop_2(s, OP_HASH, cursp(), nk); push(); } } break; case NODE_SPLAT: codegen(s, tree, val); break; case NODE_ASGN: gen_assignment(s, tree->car, tree->cdr, 0, val); break; case NODE_MASGN: { int len = 0, n = 0, post = 0; node *t = tree->cdr, *p; int rhs = cursp(); if (nint(t->car) == NODE_ARRAY && t->cdr && nosplat(t->cdr)) { /* fixed rhs */ t = t->cdr; while (t) { codegen(s, t->car, VAL); len++; t = t->cdr; } tree = tree->car; if (tree->car) { /* pre */ t = tree->car; n = 0; while (t) { if (n < len) { gen_assignment(s, t->car, NULL, rhs+n, NOVAL); n++; } else { genop_1(s, OP_LOADNIL, rhs+n); gen_assignment(s, t->car, NULL, rhs+n, NOVAL); } t = t->cdr; } } t = tree->cdr; if (t) { if (t->cdr) { /* post count */ p = t->cdr->car; while (p) { post++; p = p->cdr; } } if (t->car) { /* rest (len - pre - post) */ int rn; if (len < post + n) { rn = 0; } else { rn = len - post - n; } genop_3(s, OP_ARRAY2, cursp(), rhs+n, rn); gen_assignment(s, t->car, NULL, cursp(), NOVAL); n += rn; } if (t->cdr && t->cdr->car) { t = t->cdr->car; while (ncar, NULL, rhs+n, NOVAL); t = t->cdr; n++; } } } pop_n(len); if (val) { genop_2(s, OP_ARRAY, rhs, len); push(); } } else { /* variable rhs */ codegen(s, t, VAL); gen_vmassignment(s, tree->car, rhs, val); if (!val) { pop(); } } } break; case NODE_OP_ASGN: { mrb_sym sym = nsym(tree->cdr->car); mrb_int len; const char *name = mrb_sym_name_len(s->mrb, sym, &len); int idx, callargs = -1, vsp = -1; if ((len == 2 && name[0] == '|' && name[1] == '|') && (nint(tree->car->car) == NODE_CONST || nint(tree->car->car) == NODE_CVAR)) { int catch_entry, begin, end; int noexc, exc; struct loopinfo *lp; lp = loop_push(s, LOOP_BEGIN); lp->pc0 = new_label(s); catch_entry = catch_handler_new(s); begin = s->pc; exc = cursp(); codegen(s, tree->car, VAL); end = s->pc; noexc = genjmp_0(s, OP_JMP); lp->type = LOOP_RESCUE; catch_handler_set(s, catch_entry, MRB_CATCH_RESCUE, begin, end, s->pc); genop_1(s, OP_EXCEPT, exc); genop_1(s, OP_LOADF, exc); dispatch(s, noexc); loop_pop(s, NOVAL); } else if (nint(tree->car->car) == NODE_CALL) { node *n = tree->car->cdr; int base, i, nargs = 0; callargs = 0; if (val) { vsp = cursp(); push(); } codegen(s, n->car, VAL); /* receiver */ idx = new_sym(s, nsym(n->cdr->car)); base = cursp()-1; if (n->cdr->cdr->car) { nargs = gen_values(s, n->cdr->cdr->car->car, VAL, 13); if (nargs >= 0) { callargs = nargs; } else { /* varargs */ push(); nargs = 1; callargs = CALL_MAXARGS; } } /* copy receiver and arguments */ gen_move(s, cursp(), base, 1); for (i=0; icar, VAL); } if (len == 2 && ((name[0] == '|' && name[1] == '|') || (name[0] == '&' && name[1] == '&'))) { uint32_t pos; pop(); if (val) { if (vsp >= 0) { gen_move(s, vsp, cursp(), 1); } pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val); } else { pos = genjmp2_0(s, name[0]=='|'?OP_JMPIF:OP_JMPNOT, cursp(), val); } codegen(s, tree->cdr->cdr->car, VAL); pop(); if (val && vsp >= 0) { gen_move(s, vsp, cursp(), 1); } if (nint(tree->car->car) == NODE_CALL) { if (callargs == CALL_MAXARGS) { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } else { pop_n(callargs); callargs++; } pop(); idx = new_sym(s, attrsym(s, nsym(tree->car->cdr->cdr->car))); genop_3(s, OP_SEND, cursp(), idx, callargs); } else { gen_assignment(s, tree->car, NULL, cursp(), val); } dispatch(s, pos); goto exit; } codegen(s, tree->cdr->cdr->car, VAL); push(); pop(); pop(); pop(); if (len == 1 && name[0] == '+') { gen_addsub(s, OP_ADD, cursp()); } else if (len == 1 && name[0] == '-') { gen_addsub(s, OP_SUB, cursp()); } else if (len == 1 && name[0] == '*') { genop_1(s, OP_MUL, cursp()); } else if (len == 1 && name[0] == '/') { genop_1(s, OP_DIV, cursp()); } else if (len == 1 && name[0] == '<') { genop_1(s, OP_LT, cursp()); } else if (len == 2 && name[0] == '<' && name[1] == '=') { genop_1(s, OP_LE, cursp()); } else if (len == 1 && name[0] == '>') { genop_1(s, OP_GT, cursp()); } else if (len == 2 && name[0] == '>' && name[1] == '=') { genop_1(s, OP_GE, cursp()); } else { idx = new_sym(s, sym); genop_3(s, OP_SEND, cursp(), idx, 1); } if (callargs < 0) { gen_assignment(s, tree->car, NULL, cursp(), val); } else { if (val && vsp >= 0) { gen_move(s, vsp, cursp(), 0); } if (callargs == CALL_MAXARGS) { pop(); genop_2(s, OP_ARYPUSH, cursp(), 1); } else { pop_n(callargs); callargs++; } pop(); idx = new_sym(s, attrsym(s,nsym(tree->car->cdr->cdr->car))); genop_3(s, OP_SEND, cursp(), idx, callargs); } } break; case NODE_SUPER: { codegen_scope *s2 = s; int lv = 0; int n = 0, nk = 0, st = 0; push(); while (!s2->mscope) { lv++; s2 = s2->prev; if (!s2) break; } if (tree) { node *args = tree->car; if (args) { st = n = gen_values(s, args, VAL, 14); if (n < 0) { st = 1; n = 15; push(); } } /* keyword arguments */ if (s2 && (s2->ainfo & 0x1) && tree->cdr->car) { nk = gen_hash(s, tree->cdr->car->cdr, VAL, 14); if (nk < 0) {st++; nk = 15;} else st += nk*2; n |= nk<<4; } /* block arguments */ if (tree->cdr->cdr) { codegen(s, tree->cdr->cdr, VAL); } else if (!s2) {/* super at top-level */ push(); /* no need to push block */ } else { gen_blkmove(s, s2->ainfo, lv); } st++; } else { if (!s2) push(); else gen_blkmove(s, s2->ainfo, lv); st++; } pop_n(st+1); genop_2(s, OP_SUPER, cursp(), n); if (val) push(); } break; case NODE_ZSUPER: { codegen_scope *s2 = s; int lv = 0; uint16_t ainfo = 0; int n = CALL_MAXARGS; int sp = cursp(); push(); /* room for receiver */ while (!s2->mscope) { lv++; s2 = s2->prev; if (!s2) break; } if (s2 && s2->ainfo > 0) { ainfo = s2->ainfo; } if (ainfo > 0) { genop_2S(s, OP_ARGARY, cursp(), (ainfo<<4)|(lv & 0xf)); push(); push(); push(); /* ARGARY pushes 3 values at most */ pop(); pop(); pop(); /* keyword arguments */ if (ainfo & 0x1) { n |= CALL_MAXARGS<<4; push(); } /* block argument */ if (tree && tree->cdr && tree->cdr->cdr) { push(); codegen(s, tree->cdr->cdr, VAL); } } else { /* block argument */ if (tree && tree->cdr && tree->cdr->cdr) { codegen(s, tree->cdr->cdr, VAL); } else { gen_blkmove(s, 0, lv); } n = 0; } s->sp = sp; genop_2(s, OP_SUPER, cursp(), n); if (val) push(); } break; case NODE_RETURN: if (tree) { gen_retval(s, tree); } else { genop_1(s, OP_LOADNIL, cursp()); } if (s->loop) { gen_return(s, OP_RETURN_BLK, cursp()); } else { gen_return(s, OP_RETURN, cursp()); } if (val) push(); break; case NODE_YIELD: { codegen_scope *s2 = s; int lv = 0, ainfo = -1; int n = 0, sendv = 0; while (!s2->mscope) { lv++; s2 = s2->prev; if (!s2) break; } if (s2) { ainfo = (int)s2->ainfo; } if (ainfo < 0) codegen_error(s, ""invalid yield (SyntaxError)""); push(); if (tree) { n = gen_values(s, tree, VAL, 14); if (n < 0) { n = sendv = 1; push(); } } push();pop(); /* space for a block */ pop_n(n+1); genop_2S(s, OP_BLKPUSH, cursp(), (ainfo<<4)|(lv & 0xf)); if (sendv) n = CALL_MAXARGS; genop_3(s, OP_SEND, cursp(), new_sym(s, MRB_SYM_2(s->mrb, call)), n); if (val) push(); } break; case NODE_BREAK: loop_break(s, tree); if (val) push(); break; case NODE_NEXT: if (!s->loop) { raise_error(s, ""unexpected next""); } else if (s->loop->type == LOOP_NORMAL) { codegen(s, tree, NOVAL); genjmp(s, OP_JMPUW, s->loop->pc0); } else { if (tree) { codegen(s, tree, VAL); pop(); } else { genop_1(s, OP_LOADNIL, cursp()); } gen_return(s, OP_RETURN, cursp()); } if (val) push(); break; case NODE_REDO: if (!s->loop || s->loop->type == LOOP_BEGIN || s->loop->type == LOOP_RESCUE) { raise_error(s, ""unexpected redo""); } else { genjmp(s, OP_JMPUW, s->loop->pc1); } if (val) push(); break; case NODE_RETRY: { const char *msg = ""unexpected retry""; const struct loopinfo *lp = s->loop; while (lp && lp->type != LOOP_RESCUE) { lp = lp->prev; } if (!lp) { raise_error(s, msg); } else { genjmp(s, OP_JMPUW, lp->pc0); } if (val) push(); } break; case NODE_LVAR: if (val) { int idx = lv_idx(s, nsym(tree)); if (idx > 0) { gen_move(s, cursp(), idx, val); } else { gen_getupvar(s, cursp(), nsym(tree)); } push(); } break; case NODE_NVAR: if (val) { int idx = nint(tree); gen_move(s, cursp(), idx, val); push(); } break; case NODE_GVAR: { int sym = new_sym(s, nsym(tree)); genop_2(s, OP_GETGV, cursp(), sym); if (val) push(); } break; case NODE_IVAR: { int sym = new_sym(s, nsym(tree)); genop_2(s, OP_GETIV, cursp(), sym); if (val) push(); } break; case NODE_CVAR: { int sym = new_sym(s, nsym(tree)); genop_2(s, OP_GETCV, cursp(), sym); if (val) push(); } break; case NODE_CONST: { int sym = new_sym(s, nsym(tree)); genop_2(s, OP_GETCONST, cursp(), sym); if (val) push(); } break; case NODE_BACK_REF: if (val) { char buf[] = {'$', nchar(tree)}; int sym = new_sym(s, mrb_intern(s->mrb, buf, sizeof(buf))); genop_2(s, OP_GETGV, cursp(), sym); push(); } break; case NODE_NTH_REF: if (val) { mrb_state *mrb = s->mrb; mrb_value str; int sym; str = mrb_format(mrb, ""$%d"", nint(tree)); sym = new_sym(s, mrb_intern_str(mrb, str)); genop_2(s, OP_GETGV, cursp(), sym); push(); } break; case NODE_ARG: /* should not happen */ break; case NODE_BLOCK_ARG: if (!tree) { int idx = lv_idx(s, MRB_OPSYM_2(s->mrb, and)); if (idx == 0) { codegen_error(s, ""no anonymous block argument""); } gen_move(s, cursp(), idx, val); } else { codegen(s, tree, val); } break; case NODE_INT: if (val) { char *p = (char*)tree->car; int base = nint(tree->cdr->car); mrb_int i; mrb_bool overflow; i = readint(s, p, base, FALSE, &overflow); if (overflow) { int off = new_litbn(s, p, base, FALSE); genop_2(s, OP_LOADL, cursp(), off); } else { gen_int(s, cursp(), i); } push(); } break; #ifndef MRB_NO_FLOAT case NODE_FLOAT: if (val) { char *p = (char*)tree; mrb_float f = mrb_float_read(p, NULL); int off = new_lit(s, mrb_float_value(s->mrb, f)); genop_2(s, OP_LOADL, cursp(), off); push(); } break; #endif case NODE_NEGATE: { nt = nint(tree->car); switch (nt) { #ifndef MRB_NO_FLOAT case NODE_FLOAT: if (val) { char *p = (char*)tree->cdr; mrb_float f = mrb_float_read(p, NULL); int off = new_lit(s, mrb_float_value(s->mrb, -f)); genop_2(s, OP_LOADL, cursp(), off); push(); } break; #endif case NODE_INT: if (val) { char *p = (char*)tree->cdr->car; int base = nint(tree->cdr->cdr->car); mrb_int i; mrb_bool overflow; i = readint(s, p, base, TRUE, &overflow); if (overflow) { int off = new_litbn(s, p, base, TRUE); genop_2(s, OP_LOADL, cursp(), off); } else { gen_int(s, cursp(), i); } push(); } break; default: if (val) { codegen(s, tree, VAL); pop(); push_n(2);pop_n(2); /* space for receiver&block */ mrb_sym minus = MRB_OPSYM_2(s->mrb, minus); if (!gen_uniop(s, minus, cursp())) { genop_3(s, OP_SEND, cursp(), new_sym(s, minus), 0); } push(); } else { codegen(s, tree, NOVAL); } break; } } break; case NODE_STR: if (val) { char *p = (char*)tree->car; size_t len = (intptr_t)tree->cdr; int ai = mrb_gc_arena_save(s->mrb); int off = new_lit(s, mrb_str_new(s->mrb, p, len)); mrb_gc_arena_restore(s->mrb, ai); genop_2(s, OP_STRING, cursp(), off); push(); } break; case NODE_HEREDOC: tree = ((struct mrb_parser_heredoc_info *)tree)->doc; /* fall through */ case NODE_DSTR: if (val) { node *n = tree; if (!n) { genop_1(s, OP_LOADNIL, cursp()); push(); break; } codegen(s, n->car, VAL); n = n->cdr; while (n) { codegen(s, n->car, VAL); pop(); pop(); genop_1(s, OP_STRCAT, cursp()); push(); n = n->cdr; } } else { node *n = tree; while (n) { if (nint(n->car->car) != NODE_STR) { codegen(s, n->car, NOVAL); } n = n->cdr; } } break; case NODE_WORDS: gen_literal_array(s, tree, FALSE, val); break; case NODE_SYMBOLS: gen_literal_array(s, tree, TRUE, val); break; case NODE_DXSTR: { node *n; int ai = mrb_gc_arena_save(s->mrb); int sym = new_sym(s, MRB_SYM_2(s->mrb, Kernel)); genop_1(s, OP_LOADSELF, cursp()); push(); codegen(s, tree->car, VAL); n = tree->cdr; while (n) { if (nint(n->car->car) == NODE_XSTR) { n->car->car = (struct mrb_ast_node*)(intptr_t)NODE_STR; mrb_assert(!n->cdr); /* must be the end */ } codegen(s, n->car, VAL); pop(); pop(); genop_1(s, OP_STRCAT, cursp()); push(); n = n->cdr; } push(); /* for block */ pop_n(3); sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */ genop_3(s, OP_SEND, cursp(), sym, 1); if (val) push(); mrb_gc_arena_restore(s->mrb, ai); } break; case NODE_XSTR: { char *p = (char*)tree->car; size_t len = (intptr_t)tree->cdr; int ai = mrb_gc_arena_save(s->mrb); int off = new_lit(s, mrb_str_new(s->mrb, p, len)); int sym; genop_1(s, OP_LOADSELF, cursp()); push(); genop_2(s, OP_STRING, cursp(), off); push(); push(); pop_n(3); sym = new_sym(s, MRB_OPSYM_2(s->mrb, tick)); /* ` */ genop_3(s, OP_SEND, cursp(), sym, 1); if (val) push(); mrb_gc_arena_restore(s->mrb, ai); } break; case NODE_REGX: if (val) { char *p1 = (char*)tree->car; char *p2 = (char*)tree->cdr->car; char *p3 = (char*)tree->cdr->cdr; int ai = mrb_gc_arena_save(s->mrb); int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS)); int off = new_lit(s, mrb_str_new_cstr(s->mrb, p1)); int argc = 1; genop_1(s, OP_OCLASS, cursp()); genop_2(s, OP_GETMCNST, cursp(), sym); push(); genop_2(s, OP_STRING, cursp(), off); push(); if (p2 || p3) { if (p2) { /* opt */ off = new_lit(s, mrb_str_new_cstr(s->mrb, p2)); genop_2(s, OP_STRING, cursp(), off); } else { genop_1(s, OP_LOADNIL, cursp()); } push(); argc++; if (p3) { /* enc */ off = new_lit(s, mrb_str_new(s->mrb, p3, 1)); genop_2(s, OP_STRING, cursp(), off); push(); argc++; } } push(); /* space for a block */ pop_n(argc+2); sym = new_sym(s, MRB_SYM_2(s->mrb, compile)); genop_3(s, OP_SEND, cursp(), sym, argc); mrb_gc_arena_restore(s->mrb, ai); push(); } break; case NODE_DREGX: if (val) { node *n = tree->car; int ai = mrb_gc_arena_save(s->mrb); int sym = new_sym(s, mrb_intern_lit(s->mrb, REGEXP_CLASS)); int argc = 1; int off; char *p; genop_1(s, OP_OCLASS, cursp()); genop_2(s, OP_GETMCNST, cursp(), sym); push(); codegen(s, n->car, VAL); n = n->cdr; while (n) { codegen(s, n->car, VAL); pop(); pop(); genop_1(s, OP_STRCAT, cursp()); push(); n = n->cdr; } n = tree->cdr->cdr; if (n->car) { /* tail */ p = (char*)n->car; off = new_lit(s, mrb_str_new_cstr(s->mrb, p)); codegen(s, tree->car, VAL); genop_2(s, OP_STRING, cursp(), off); pop(); genop_1(s, OP_STRCAT, cursp()); push(); } if (n->cdr->car) { /* opt */ char *p2 = (char*)n->cdr->car; off = new_lit(s, mrb_str_new_cstr(s->mrb, p2)); genop_2(s, OP_STRING, cursp(), off); push(); argc++; } if (n->cdr->cdr) { /* enc */ char *p2 = (char*)n->cdr->cdr; off = new_lit(s, mrb_str_new_cstr(s->mrb, p2)); genop_2(s, OP_STRING, cursp(), off); push(); argc++; } push(); /* space for a block */ pop_n(argc+2); sym = new_sym(s, MRB_SYM_2(s->mrb, compile)); genop_3(s, OP_SEND, cursp(), sym, argc); mrb_gc_arena_restore(s->mrb, ai); push(); } else { node *n = tree->car; while (n) { if (nint(n->car->car) != NODE_STR) { codegen(s, n->car, NOVAL); } n = n->cdr; } } break; case NODE_SYM: if (val) { int sym = new_sym(s, nsym(tree)); genop_2(s, OP_LOADSYM, cursp(), sym); push(); } break; case NODE_DSYM: codegen(s, tree, val); if (val) { gen_intern(s); } break; case NODE_SELF: if (val) { genop_1(s, OP_LOADSELF, cursp()); push(); } break; case NODE_NIL: if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } break; case NODE_TRUE: if (val) { genop_1(s, OP_LOADT, cursp()); push(); } break; case NODE_FALSE: if (val) { genop_1(s, OP_LOADF, cursp()); push(); } break; case NODE_ALIAS: { int a = new_sym(s, nsym(tree->car)); int b = new_sym(s, nsym(tree->cdr)); genop_2(s, OP_ALIAS, a, b); if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } } break; case NODE_UNDEF: { node *t = tree; while (t) { int symbol = new_sym(s, nsym(t->car)); genop_1(s, OP_UNDEF, symbol); t = t->cdr; } if (val) { genop_1(s, OP_LOADNIL, cursp()); push(); } } break; case NODE_CLASS: { int idx; node *body; if (tree->car->car == (node*)0) { genop_1(s, OP_LOADNIL, cursp()); push(); } else if (tree->car->car == (node*)1) { genop_1(s, OP_OCLASS, cursp()); push(); } else { codegen(s, tree->car->car, VAL); } if (tree->cdr->car) { codegen(s, tree->cdr->car, VAL); } else { genop_1(s, OP_LOADNIL, cursp()); push(); } pop(); pop(); idx = new_sym(s, nsym(tree->car->cdr)); genop_2(s, OP_CLASS, cursp(), idx); body = tree->cdr->cdr->car; if (nint(body->cdr->car) == NODE_BEGIN && body->cdr->cdr == NULL) { genop_1(s, OP_LOADNIL, cursp()); } else { idx = scope_body(s, body, val); genop_2(s, OP_EXEC, cursp(), idx); } if (val) { push(); } } break; case NODE_MODULE: { int idx; if (tree->car->car == (node*)0) { genop_1(s, OP_LOADNIL, cursp()); push(); } else if (tree->car->car == (node*)1) { genop_1(s, OP_OCLASS, cursp()); push(); } else { codegen(s, tree->car->car, VAL); } pop(); idx = new_sym(s, nsym(tree->car->cdr)); genop_2(s, OP_MODULE, cursp(), idx); if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN && tree->cdr->car->cdr->cdr == NULL) { genop_1(s, OP_LOADNIL, cursp()); } else { idx = scope_body(s, tree->cdr->car, val); genop_2(s, OP_EXEC, cursp(), idx); } if (val) { push(); } } break; case NODE_SCLASS: { int idx; codegen(s, tree->car, VAL); pop(); genop_1(s, OP_SCLASS, cursp()); if (nint(tree->cdr->car->cdr->car) == NODE_BEGIN && tree->cdr->car->cdr->cdr == NULL) { genop_1(s, OP_LOADNIL, cursp()); } else { idx = scope_body(s, tree->cdr->car, val); genop_2(s, OP_EXEC, cursp(), idx); } if (val) { push(); } } break; case NODE_DEF: { int sym = new_sym(s, nsym(tree->car)); int idx = lambda_body(s, tree->cdr, 0); genop_1(s, OP_TCLASS, cursp()); push(); genop_2(s, OP_METHOD, cursp(), idx); push(); pop(); pop(); genop_2(s, OP_DEF, cursp(), sym); if (val) push(); } break; case NODE_SDEF: { node *recv = tree->car; int sym = new_sym(s, nsym(tree->cdr->car)); int idx = lambda_body(s, tree->cdr->cdr, 0); codegen(s, recv, VAL); pop(); genop_1(s, OP_SCLASS, cursp()); push(); genop_2(s, OP_METHOD, cursp(), idx); pop(); genop_2(s, OP_DEF, cursp(), sym); if (val) push(); } break; case NODE_POSTEXE: codegen(s, tree, NOVAL); break; default: break; } exit: s->rlev = rlev; }",CWE-476,12 1,"managesieve_parser_read_string(struct managesieve_parser *parser, const unsigned char *data, size_t data_size) { size_t i; /* QUOTED-CHAR = SAFE-UTF8-CHAR / ""\"" QUOTED-SPECIALS * quoted = <""> *QUOTED-CHAR <""> * ;; limited to 1024 octets between the <"">s */ /* read until we've found non-escaped "", CR or LF */ for (i = parser->cur_pos; i < data_size; i++) { if (data[i] == '""') { if ( !uni_utf8_data_is_valid(data+1, i-1) ) { parser->error = ""Invalid UTF-8 character in quoted-string.""; return FALSE; } managesieve_parser_save_arg(parser, data, i); i++; /* skip the trailing '""' too */ break; } if (data[i] == '\\') { if (i+1 == data_size) { /* known data ends with '\' - leave it to next time as well if it happens to be \"" */ break; } /* save the first escaped char */ if (parser->str_first_escape < 0) parser->str_first_escape = i; /* skip the escaped char */ i++; if ( !IS_QUOTED_SPECIAL(data[i]) ) { parser->error = ""Escaped quoted-string character is not a QUOTED-SPECIAL.""; return FALSE; } continue; } if ( (data[i] & 0x80) == 0 && !IS_SAFE_CHAR(data[i]) ) { parser->error = ""String contains invalid character.""; return FALSE; } } parser->cur_pos = i; return ( parser->cur_type == ARG_PARSE_NONE ); }",CWE-787,16 0,"void WebGraphicsContext3DDefaultImpl::getFramebufferAttachmentParameteriv(unsigned long target, unsigned long attachment, unsigned long pname, int* value) { makeContextCurrent(); if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) attachment = GL_DEPTH_ATTACHMENT; // Or GL_STENCIL_ATTACHMENT, either works. glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, value); } ",none,24 0,"const OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) const { ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i == entries_.end()) return NULL; switch (scope) { case kExtensionPrefsScopeRegular: return &(i->second->settings); case kExtensionPrefsScopeRegularOnly: NOTREACHED(); return NULL; case kExtensionPrefsScopeIncognitoPersistent: return &(i->second->incognito_persistent_settings); case kExtensionPrefsScopeIncognitoSessionOnly: return &(i->second->incognito_session_only_settings); } NOTREACHED(); return NULL; } ",none,24 1,"static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager) { OPJ_UINT32(*l_gain_ptr)(OPJ_UINT32) = 00; OPJ_UINT32 compno, resno, bandno, precno, cblkno; opj_tcp_t * l_tcp = 00; opj_cp_t * l_cp = 00; opj_tcd_tile_t * l_tile = 00; opj_tccp_t *l_tccp = 00; opj_tcd_tilecomp_t *l_tilec = 00; opj_image_comp_t * l_image_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_stepsize_t * l_step_size = 00; opj_tcd_precinct_t *l_current_precinct = 00; opj_image_t *l_image = 00; OPJ_UINT32 p, q; OPJ_UINT32 l_level_no; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_gain; OPJ_INT32 l_x0b, l_y0b; OPJ_UINT32 l_tx0, l_ty0; /* extent of precincts , top left, bottom right**/ OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end; /* number of precinct for a resolution */ OPJ_UINT32 l_nb_precincts; /* room needed to store l_nb_precinct precinct for a resolution */ OPJ_UINT32 l_nb_precinct_size; /* number of code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks; /* room needed to store l_nb_code_blocks code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks_size; /* size of data for a tile */ OPJ_UINT32 l_data_size; l_cp = p_tcd->cp; l_tcp = &(l_cp->tcps[p_tile_no]); l_tile = p_tcd->tcd_image->tiles; l_tccp = l_tcp->tccps; l_tilec = l_tile->comps; l_image = p_tcd->image; l_image_comp = p_tcd->image->comps; p = p_tile_no % l_cp->tw; /* tile coordinates */ q = p_tile_no / l_cp->tw; /*fprintf(stderr, ""Tile coordinate = %d,%d\n"", p, q);*/ /* 4 borders of the tile rescale on the image if necessary */ l_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */ l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0); l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1); /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */ if ((l_tile->x0 < 0) || (l_tile->x1 <= l_tile->x0)) { opj_event_msg(manager, EVT_ERROR, ""Tile X coordinates are not supported\n""); return OPJ_FALSE; } l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */ l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0); l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1); /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */ if ((l_tile->y0 < 0) || (l_tile->y1 <= l_tile->y0)) { opj_event_msg(manager, EVT_ERROR, ""Tile Y coordinates are not supported\n""); return OPJ_FALSE; } /* testcase 1888.pdf.asan.35.988 */ if (l_tccp->numresolutions == 0) { opj_event_msg(manager, EVT_ERROR, ""tiles require at least one resolution\n""); return OPJ_FALSE; } /*fprintf(stderr, ""Tile border = %d,%d,%d,%d\n"", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/ /*tile->numcomps = image->numcomps; */ for (compno = 0; compno < l_tile->numcomps; ++compno) { /*fprintf(stderr, ""compno = %d/%d\n"", compno, l_tile->numcomps);*/ l_image_comp->resno_decoded = 0; /* border of each l_tile component (global) */ l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx); l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy); l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx); l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy); l_tilec->compno = compno; /*fprintf(stderr, ""\tTile compo border = %d,%d,%d,%d\n"", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/ l_tilec->numresolutions = l_tccp->numresolutions; if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) { l_tilec->minimum_num_resolutions = 1; } else { l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce; } if (isEncoder) { OPJ_SIZE_T l_tile_data_size; /* compute l_data_size with overflow check */ OPJ_SIZE_T w = (OPJ_SIZE_T)(l_tilec->x1 - l_tilec->x0); OPJ_SIZE_T h = (OPJ_SIZE_T)(l_tilec->y1 - l_tilec->y0); /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */ if (h > 0 && w > SIZE_MAX / h) { opj_event_msg(manager, EVT_ERROR, ""Size of tile data exceeds system limits\n""); return OPJ_FALSE; } l_tile_data_size = w * h; if (SIZE_MAX / sizeof(OPJ_UINT32) < l_tile_data_size) { opj_event_msg(manager, EVT_ERROR, ""Size of tile data exceeds system limits\n""); return OPJ_FALSE; } l_tile_data_size = l_tile_data_size * sizeof(OPJ_UINT32); l_tilec->data_size_needed = l_tile_data_size; } l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof( opj_tcd_resolution_t); opj_image_data_free(l_tilec->data_win); l_tilec->data_win = NULL; l_tilec->win_x0 = 0; l_tilec->win_y0 = 0; l_tilec->win_x1 = 0; l_tilec->win_y1 = 0; if (l_tilec->resolutions == 00) { l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size); if (! l_tilec->resolutions) { return OPJ_FALSE; } /*fprintf(stderr, ""\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n"",l_data_size);*/ l_tilec->resolutions_size = l_data_size; memset(l_tilec->resolutions, 0, l_data_size); } else if (l_data_size > l_tilec->resolutions_size) { opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc( l_tilec->resolutions, l_data_size); if (! new_resolutions) { opj_event_msg(manager, EVT_ERROR, ""Not enough memory for tile resolutions\n""); opj_free(l_tilec->resolutions); l_tilec->resolutions = NULL; l_tilec->resolutions_size = 0; return OPJ_FALSE; } l_tilec->resolutions = new_resolutions; /*fprintf(stderr, ""\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n"", l_tilec->resolutions_size, l_data_size);*/ memset(((OPJ_BYTE*) l_tilec->resolutions) + l_tilec->resolutions_size, 0, l_data_size - l_tilec->resolutions_size); l_tilec->resolutions_size = l_data_size; } l_level_no = l_tilec->numresolutions; l_res = l_tilec->resolutions; l_step_size = l_tccp->stepsizes; if (l_tccp->qmfbid == 0) { l_gain_ptr = &opj_dwt_getgain_real; } else { l_gain_ptr = &opj_dwt_getgain; } /*fprintf(stderr, ""\tlevel_no=%d\n"",l_level_no);*/ for (resno = 0; resno < l_tilec->numresolutions; ++resno) { /*fprintf(stderr, ""\t\tresno = %d/%d\n"", resno, l_tilec->numresolutions);*/ OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/; OPJ_UINT32 cbgwidthexpn, cbgheightexpn; OPJ_UINT32 cblkwidthexpn, cblkheightexpn; --l_level_no; /* border for each resolution level (global) */ l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); /*fprintf(stderr, ""\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n"", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/ /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; /*fprintf(stderr, ""\t\t\tpdx=%d, pdy=%d\n"", l_pdx, l_pdy);*/ /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx; l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy; l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx; l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy; /*fprintf(stderr, ""\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n"", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/ l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)(( l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx); l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)(( l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy); /*fprintf(stderr, ""\t\t\tres_pw=%d, res_ph=%d\n"", l_res->pw, l_res->ph );*/ if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) { opj_event_msg(manager, EVT_ERROR, ""Size of tile data exceeds system limits\n""); return OPJ_FALSE; } l_nb_precincts = l_res->pw * l_res->ph; if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) < l_nb_precincts) { opj_event_msg(manager, EVT_ERROR, ""Size of tile data exceeds system limits\n""); return OPJ_FALSE; } l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t); if (resno == 0) { tlcbgxstart = l_tl_prc_x_start; tlcbgystart = l_tl_prc_y_start; /*brcbgxend = l_br_prc_x_end;*/ /* brcbgyend = l_br_prc_y_end;*/ cbgwidthexpn = l_pdx; cbgheightexpn = l_pdy; l_res->numbands = 1; } else { tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1); tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1); /*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/ /*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/ cbgwidthexpn = l_pdx - 1; cbgheightexpn = l_pdy - 1; l_res->numbands = 3; } cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn); cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn); l_band = l_res->bands; for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) { OPJ_INT32 numbps; /*fprintf(stderr, ""\t\t\tband_no=%d/%d\n"", bandno, l_res->numbands );*/ if (resno == 0) { l_band->bandno = 0 ; l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); } else { l_band->bandno = bandno + 1; /* x0b = 1 if bandno = 1 or 3 */ l_x0b = l_band->bandno & 1; /* y0b = 1 if bandno = 2 or 3 */ l_y0b = (OPJ_INT32)((l_band->bandno) >> 1); /* l_band border (global) */ l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); } if (isEncoder) { /* Skip empty bands */ if (opj_tcd_is_band_empty(l_band)) { /* Do not zero l_band->precints to avoid leaks */ /* but make sure we don't use it later, since */ /* it will point to precincts of previous bands... */ continue; } } /** avoid an if with storing function pointer */ l_gain = (*l_gain_ptr)(l_band->bandno); numbps = (OPJ_INT32)(l_image_comp->prec + l_gain); l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32)(numbps - l_step_size->expn)))) * fraction; /* Mb value of Equation E-2 in ""E.1 Inverse quantization * procedure"" of the standard */ l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; if (!l_band->precincts && (l_nb_precincts > 0U)) { l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */ l_nb_precinct_size); if (! l_band->precincts) { opj_event_msg(manager, EVT_ERROR, ""Not enough memory to handle band precints\n""); return OPJ_FALSE; } /*fprintf(stderr, ""\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n"",l_nb_precinct_size); */ memset(l_band->precincts, 0, l_nb_precinct_size); l_band->precincts_data_size = l_nb_precinct_size; } else if (l_band->precincts_data_size < l_nb_precinct_size) { opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc( l_band->precincts,/*3 * */ l_nb_precinct_size); if (! new_precincts) { opj_event_msg(manager, EVT_ERROR, ""Not enough memory to handle band precints\n""); opj_free(l_band->precincts); l_band->precincts = NULL; l_band->precincts_data_size = 0; return OPJ_FALSE; } l_band->precincts = new_precincts; /*fprintf(stderr, ""\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n"",l_band->precincts_data_size, l_nb_precinct_size);*/ memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size, 0, l_nb_precinct_size - l_band->precincts_data_size); l_band->precincts_data_size = l_nb_precinct_size; } l_current_precinct = l_band->precincts; for (precno = 0; precno < l_nb_precincts; ++precno) { OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn); OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn); OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn); OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn); /*fprintf(stderr, ""\t precno=%d; bandno=%d, resno=%d; compno=%d\n"", precno, bandno , resno, compno);*/ /*fprintf(stderr, ""\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n"",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/ /* precinct size (global) */ /*fprintf(stderr, ""\t cbgxstart=%d, l_band->x0 = %d \n"",cbgxstart, l_band->x0);*/ l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0); l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0); l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1); l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1); /*fprintf(stderr, ""\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n"",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/ tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, ""\t tlcblkxstart =%d\n"",tlcblkxstart );*/ tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, ""\t tlcblkystart =%d\n"",tlcblkystart );*/ brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, ""\t brcblkxend =%d\n"",brcblkxend );*/ brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, ""\t brcblkyend =%d\n"",brcblkyend );*/ l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn); l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn); l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch; /*fprintf(stderr, ""\t\t\t\t precinct_cw = %d x recinct_ch = %d\n"",l_current_precinct->cw, l_current_precinct->ch); */ if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof_block) < l_nb_code_blocks) { opj_event_msg(manager, EVT_ERROR, ""Size of code block data exceeds system limits\n""); return OPJ_FALSE; } l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block; if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) { l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size); if (! l_current_precinct->cblks.blocks) { return OPJ_FALSE; } /*fprintf(stderr, ""\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n"",l_nb_code_blocks_size);*/ memset(l_current_precinct->cblks.blocks, 0, l_nb_code_blocks_size); l_current_precinct->block_size = l_nb_code_blocks_size; } else if (l_nb_code_blocks_size > l_current_precinct->block_size) { void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size); if (! new_blocks) { opj_free(l_current_precinct->cblks.blocks); l_current_precinct->cblks.blocks = NULL; l_current_precinct->block_size = 0; opj_event_msg(manager, EVT_ERROR, ""Not enough memory for current precinct codeblock element\n""); return OPJ_FALSE; } l_current_precinct->cblks.blocks = new_blocks; /*fprintf(stderr, ""\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n"",l_current_precinct->block_size, l_nb_code_blocks_size); */ memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size , 0 , l_nb_code_blocks_size - l_current_precinct->block_size); l_current_precinct->block_size = l_nb_code_blocks_size; } if (! l_current_precinct->incltree) { l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager); } else { l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->imsbtree) { l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager); } else { l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager); } for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn); OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn); OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn); OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn); if (isEncoder) { opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno; if (! opj_tcd_code_block_enc_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) { return OPJ_FALSE; } } else { opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno; if (! opj_tcd_code_block_dec_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); } } ++l_current_precinct; } /* precno */ } /* bandno */ ++l_res; } /* resno */ ++l_tccp; ++l_tilec; ++l_image_comp; } /* compno */ return OPJ_TRUE; }",CWE-787,16 1,"static int changedline (const Proto *p, int oldpc, int newpc) { while (oldpc++ < newpc) { if (p->lineinfo[oldpc] != 0) return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc)); } return 0; /* no line changes in the way */ }",CWE-787,16 0,"void AudioContext::addChangedChannelCountMode(AudioNode* node) { ASSERT(isGraphOwner()); ASSERT(isMainThread()); m_deferredCountModeChange.add(node); } ",none,24 1,"FastHufDecoder::FastHufDecoder (const char *&table, int numBytes, int minSymbol, int maxSymbol, int rleSymbol) : _rleSymbol (rleSymbol), _numSymbols (0), _minCodeLength (255), _maxCodeLength (0), _idToSymbol (0) { // // List of symbols that we find with non-zero code lengths // (listed in the order we find them). Store these in the // same format as the code book stores codes + lengths - // low 6 bits are the length, everything above that is // the symbol. // std::vector symbols; // // The 'base' table is the minimum code at each code length. base[i] // is the smallest code (numerically) of length i. // Int64 base[MAX_CODE_LEN + 1]; // // The 'offset' table is the position (in sorted order) of the first id // of a given code lenght. Array is indexed by code length, like base. // Int64 offset[MAX_CODE_LEN + 1]; // // Count of how many codes at each length there are. Array is // indexed by code length, like base and offset. // size_t codeCount[MAX_CODE_LEN + 1]; for (int i = 0; i <= MAX_CODE_LEN; ++i) { codeCount[i] = 0; base[i] = 0xffffffffffffffffULL; offset[i] = 0; } // // Count the number of codes, the min/max code lengths, the number of // codes with each length, and record symbols with non-zero code // length as we find them. // const char *currByte = table; Int64 currBits = 0; int currBitCount = 0; const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; for (Int64 symbol = static_cast(minSymbol); symbol <= static_cast(maxSymbol); symbol++) { if (currByte - table > numBytes) { throw IEX_NAMESPACE::InputExc (""Error decoding Huffman table "" ""(Truncated table data).""); } // // Next code length - either: // 0-58 (literal code length) // 59-62 (various lengths runs of 0) // 63 (run of n 0's, with n is the next 8 bits) // Int64 codeLen = readBits (6, currBits, currBitCount, currByte); if (codeLen == (Int64) LONG_ZEROCODE_RUN) { if (currByte - table > numBytes) { throw IEX_NAMESPACE::InputExc (""Error decoding Huffman table "" ""(Truncated table data).""); } int runLen = readBits (8, currBits, currBitCount, currByte) + SHORTEST_LONG_RUN; if (symbol + runLen > static_cast(maxSymbol + 1)) { throw IEX_NAMESPACE::InputExc (""Error decoding Huffman table "" ""(Run beyond end of table).""); } symbol += runLen - 1; } else if (codeLen >= static_cast(SHORT_ZEROCODE_RUN)) { int runLen = codeLen - SHORT_ZEROCODE_RUN + 2; if (symbol + runLen > static_cast(maxSymbol + 1)) { throw IEX_NAMESPACE::InputExc (""Error decoding Huffman table "" ""(Run beyond end of table).""); } symbol += runLen - 1; } else if (codeLen != 0) { symbols.push_back ((symbol << 6) | (codeLen & 63)); if (codeLen < _minCodeLength) _minCodeLength = codeLen; if (codeLen > _maxCodeLength) _maxCodeLength = codeLen; codeCount[codeLen]++; } } for (int i = 0; i < MAX_CODE_LEN; ++i) _numSymbols += codeCount[i]; table = currByte; // // Compute base - once we have the code length counts, there // is a closed form solution for this // { double* countTmp = new double[_maxCodeLength+1]; for (int l = _minCodeLength; l <= _maxCodeLength; ++l) { countTmp[l] = (double)codeCount[l] * (double)(2 << (_maxCodeLength-l)); } for (int l = _minCodeLength; l <= _maxCodeLength; ++l) { double tmp = 0; for (int k =l + 1; k <= _maxCodeLength; ++k) tmp += countTmp[k]; tmp /= (double)(2 << (_maxCodeLength - l)); base[l] = (Int64)ceil (tmp); } delete [] countTmp; } // // Compute offset - these are the positions of the first // id (not symbol) that has length [i] // offset[_maxCodeLength] = 0; for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--) offset[i] = offset[i + 1] + codeCount[i + 1]; // // Allocate and fill the symbol-to-id mapping. Smaller Ids should be // mapped to less-frequent symbols (which have longer codes). Use // the offset table to tell us where the id's for a given code // length start off. // _idToSymbol = new int[_numSymbols]; Int64 mapping[MAX_CODE_LEN + 1]; for (int i = 0; i < MAX_CODE_LEN + 1; ++i) mapping[i] = -1; for (int i = _minCodeLength; i <= _maxCodeLength; ++i) mapping[i] = offset[i]; for (std::vector::const_iterator i = symbols.begin(); i != symbols.end(); ++i) { int codeLen = *i & 63; int symbol = *i >> 6; if (mapping[codeLen] >= static_cast(_numSymbols)) { delete[] _idToSymbol; _idToSymbol = NULL; throw IEX_NAMESPACE::InputExc (""Huffman decode error "" ""(Invalid symbol in header).""); } _idToSymbol[mapping[codeLen]] = symbol; mapping[codeLen]++; } // // exceptions can be thrown whilst building tables. Delete // _idToSynmbol before re-throwing to prevent memory leak // try { buildTables(base, offset); }catch(...) { delete[] _idToSymbol; _idToSymbol = NULL; throw; } }",CWE-190,2 1,"opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params) { png_structp png = NULL; png_infop info = NULL; double gamma; int bit_depth, interlace_type, compression_type, filter_type; OPJ_UINT32 i; png_uint_32 width, height = 0U; int color_type; FILE *reader = NULL; OPJ_BYTE** rows = NULL; OPJ_INT32* row32s = NULL; /* j2k: */ opj_image_t *image = NULL; opj_image_cmptparm_t cmptparm[4]; OPJ_UINT32 nr_comp; OPJ_BYTE sigbuf[8]; convert_XXx32s_C1R cvtXXTo32s = NULL; convert_32s_CXPX cvtCxToPx = NULL; OPJ_INT32* planes[4]; if ((reader = fopen(read_idf, ""rb"")) == NULL) { fprintf(stderr, ""pngtoimage: can not open %s\n"", read_idf); return NULL; } if (fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0) { fprintf(stderr, ""pngtoimage: %s is no valid PNG file\n"", read_idf); goto fin; } if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) == NULL) { goto fin; } if ((info = png_create_info_struct(png)) == NULL) { goto fin; } if (setjmp(png_jmpbuf(png))) { goto fin; } png_init_io(png, reader); png_set_sig_bytes(png, MAGIC_SIZE); png_read_info(png, info); if (png_get_IHDR(png, info, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type) == 0) { goto fin; } /* png_set_expand(): * expand paletted images to RGB, expand grayscale images of * less than 8-bit depth to 8-bit depth, and expand tRNS chunks * to alpha channels. */ if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_expand(png); } if (png_get_valid(png, info, PNG_INFO_tRNS)) { png_set_expand(png); } /* We might wan't to expand background */ /* if(png_get_valid(png, info, PNG_INFO_bKGD)) { png_color_16p bgnd; png_get_bKGD(png, info, &bgnd); png_set_background(png, bgnd, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); } */ if (!png_get_gAMA(png, info, &gamma)) { gamma = 1.0; } /* we're not displaying but converting, screen gamma == 1.0 */ png_set_gamma(png, 1.0, gamma); png_read_update_info(png, info); color_type = png_get_color_type(png, info); switch (color_type) { case PNG_COLOR_TYPE_GRAY: nr_comp = 1; break; case PNG_COLOR_TYPE_GRAY_ALPHA: nr_comp = 2; break; case PNG_COLOR_TYPE_RGB: nr_comp = 3; break; case PNG_COLOR_TYPE_RGB_ALPHA: nr_comp = 4; break; default: fprintf(stderr, ""pngtoimage: colortype %d is not supported\n"", color_type); goto fin; } cvtCxToPx = convert_32s_CXPX_LUT[nr_comp]; bit_depth = png_get_bit_depth(png, info); switch (bit_depth) { case 1: case 2: case 4: case 8: cvtXXTo32s = convert_XXu32s_C1R_LUT[bit_depth]; break; case 16: /* 16 bpp is specific to PNG */ cvtXXTo32s = convert_16u32s_C1R; break; default: fprintf(stderr, ""pngtoimage: bit depth %d is not supported\n"", bit_depth); goto fin; } rows = (OPJ_BYTE**)calloc(height + 1, sizeof(OPJ_BYTE*)); if (rows == NULL) { fprintf(stderr, ""pngtoimage: memory out\n""); goto fin; } for (i = 0; i < height; ++i) { rows[i] = (OPJ_BYTE*)malloc(png_get_rowbytes(png, info)); if (rows[i] == NULL) { fprintf(stderr, ""pngtoimage: memory out\n""); goto fin; } } png_read_image(png, rows); /* Create image */ memset(cmptparm, 0, sizeof(cmptparm)); for (i = 0; i < nr_comp; ++i) { cmptparm[i].prec = (OPJ_UINT32)bit_depth; /* bits_per_pixel: 8 or 16 */ cmptparm[i].bpp = (OPJ_UINT32)bit_depth; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)params->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)params->subsampling_dy; cmptparm[i].w = (OPJ_UINT32)width; cmptparm[i].h = (OPJ_UINT32)height; } image = opj_image_create(nr_comp, &cmptparm[0], (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY); if (image == NULL) { goto fin; } image->x0 = (OPJ_UINT32)params->image_offset_x0; image->y0 = (OPJ_UINT32)params->image_offset_y0; image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32) params->subsampling_dx + 1 + image->x0); image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32) params->subsampling_dy + 1 + image->y0); row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32)); if (row32s == NULL) { goto fin; } /* Set alpha channel */ image->comps[nr_comp - 1U].alpha = 1U - (nr_comp & 1U); for (i = 0; i < nr_comp; i++) { planes[i] = image->comps[i].data; } for (i = 0; i < height; ++i) { cvtXXTo32s(rows[i], row32s, (OPJ_SIZE_T)width * nr_comp); cvtCxToPx(row32s, planes, width); planes[0] += width; planes[1] += width; planes[2] += width; planes[3] += width; } fin: if (rows) { for (i = 0; i < height; ++i) if (rows[i]) { free(rows[i]); } free(rows); } if (row32s) { free(row32s); } if (png) { png_destroy_read_struct(&png, &info, NULL); } fclose(reader); return image; }/* pngtoimage() */",CWE-787,16 0,"void AudioManagerBase::DecreaseActiveInputStreamCount() { DCHECK(IsRecordingInProcess()); base::AtomicRefCountDec(&num_active_input_streams_); } ",none,24 1,"static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer, UINT32 rowDelta, UINT32 width, UINT32 height) { const BYTE* pbSrc = pbSrcBuffer; const BYTE* pbEnd; const BYTE* pbDestEnd; BYTE* pbDest = pbDestBuffer; PIXEL temp; PIXEL fgPel = WHITE_PIXEL; BOOL fInsertFgPel = FALSE; BOOL fFirstLine = TRUE; BYTE bitmask; PIXEL pixelA, pixelB; UINT32 runLength; UINT32 code; UINT32 advance; RLEEXTRA if ((rowDelta == 0) || (rowDelta < width)) return FALSE; if (!pbSrcBuffer || !pbDestBuffer) return FALSE; pbEnd = pbSrcBuffer + cbSrcBuffer; pbDestEnd = pbDestBuffer + rowDelta * height; while (pbSrc < pbEnd) { /* Watch out for the end of the first scanline. */ if (fFirstLine) { if ((UINT32)(pbDest - pbDestBuffer) >= rowDelta) { fFirstLine = FALSE; fInsertFgPel = FALSE; } } /* Extract the compression order code ID from the compression order header. */ code = ExtractCodeId(*pbSrc); /* Handle Background Run Orders. */ if (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN) { runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (fFirstLine) { if (fInsertFgPel) { if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, fgPel); DESTNEXTPIXEL(pbDest); runLength = runLength - 1; } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, BLACK_PIXEL); DESTNEXTPIXEL(pbDest); }); } else { if (fInsertFgPel) { DESTREADPIXEL(temp, pbDest - rowDelta); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, temp ^ fgPel); DESTNEXTPIXEL(pbDest); runLength--; } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTREADPIXEL(temp, pbDest - rowDelta); DESTWRITEPIXEL(pbDest, temp); DESTNEXTPIXEL(pbDest); }); } /* A follow-on background run order will need a foreground pel inserted. */ fInsertFgPel = TRUE; continue; } /* For any of the other run-types a follow-on background run order does not need a foreground pel inserted. */ fInsertFgPel = FALSE; switch (code) { /* Handle Foreground Run Orders. */ case REGULAR_FG_RUN: case MEGA_MEGA_FG_RUN: case LITE_SET_FG_FG_RUN: case MEGA_MEGA_SET_FG_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN) { SRCREADPIXEL(fgPel, pbSrc); SRCNEXTPIXEL(pbSrc); } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; if (fFirstLine) { UNROLL(runLength, { DESTWRITEPIXEL(pbDest, fgPel); DESTNEXTPIXEL(pbDest); }); } else { UNROLL(runLength, { DESTREADPIXEL(temp, pbDest - rowDelta); DESTWRITEPIXEL(pbDest, temp ^ fgPel); DESTNEXTPIXEL(pbDest); }); } break; /* Handle Dithered Run Orders. */ case LITE_DITHERED_RUN: case MEGA_MEGA_DITHERED_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; SRCREADPIXEL(pixelA, pbSrc); SRCNEXTPIXEL(pbSrc); SRCREADPIXEL(pixelB, pbSrc); SRCNEXTPIXEL(pbSrc); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, pixelA); DESTNEXTPIXEL(pbDest); DESTWRITEPIXEL(pbDest, pixelB); DESTNEXTPIXEL(pbDest); }); break; /* Handle Color Run Orders. */ case REGULAR_COLOR_RUN: case MEGA_MEGA_COLOR_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; SRCREADPIXEL(pixelA, pbSrc); SRCNEXTPIXEL(pbSrc); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, pixelA); DESTNEXTPIXEL(pbDest); }); break; /* Handle Foreground/Background Image Orders. */ case REGULAR_FGBG_IMAGE: case MEGA_MEGA_FGBG_IMAGE: case LITE_SET_FG_FGBG_IMAGE: case MEGA_MEGA_SET_FGBG_IMAGE: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE) { SRCREADPIXEL(fgPel, pbSrc); SRCNEXTPIXEL(pbSrc); } if (fFirstLine) { while (runLength > 8) { bitmask = *pbSrc; pbSrc = pbSrc + 1; pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8); if (!pbDest) return FALSE; runLength = runLength - 8; } } else { while (runLength > 8) { bitmask = *pbSrc; pbSrc = pbSrc + 1; pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8); if (!pbDest) return FALSE; runLength = runLength - 8; } } if (runLength > 0) { bitmask = *pbSrc; pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength); } if (!pbDest) return FALSE; } break; /* Handle Color Image Orders. */ case REGULAR_COLOR_IMAGE: case MEGA_MEGA_COLOR_IMAGE: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { SRCREADPIXEL(temp, pbSrc); SRCNEXTPIXEL(pbSrc); DESTWRITEPIXEL(pbDest, temp); DESTNEXTPIXEL(pbDest); }); break; /* Handle Special Order 1. */ case SPECIAL_FGBG_1: pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); } if (!pbDest) return FALSE; break; /* Handle Special Order 2. */ case SPECIAL_FGBG_2: pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); } if (!pbDest) return FALSE; break; /* Handle White Order. */ case SPECIAL_WHITE: pbSrc = pbSrc + 1; if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, WHITE_PIXEL); DESTNEXTPIXEL(pbDest); break; /* Handle Black Order. */ case SPECIAL_BLACK: pbSrc = pbSrc + 1; if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, BLACK_PIXEL); DESTNEXTPIXEL(pbDest); break; default: return FALSE; } } return TRUE; }",CWE-125,1 1,"static bool ntlmssp_check_buffer(const struct ntlmssp_buffer *buffer, size_t data_size, const char **error) { uint32_t offset = read_le32(&buffer->offset); uint16_t length = read_le16(&buffer->length); uint16_t space = read_le16(&buffer->space); /* Empty buffer is ok */ if (length == 0 && space == 0) return TRUE; if (offset >= data_size) { *error = ""buffer offset out of bounds""; return FALSE; } if (offset + space > data_size) { *error = ""buffer end out of bounds""; return FALSE; } return TRUE; }",CWE-125,1 0,"void EmbeddedWorkerContextClient::workerContextDestroyed() { script_context_.reset(); main_thread_proxy_->PostTask( FROM_HERE, base::Bind(&CallWorkerContextDestroyedOnMainThread, embedded_worker_id_)); } ",none,24 1,"unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name) { int i; u_entry_T *uep; char_u **array; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = undo_read_4c(bi); uep->ue_bot = undo_read_4c(bi); uep->ue_lcount = undo_read_4c(bi); uep->ue_size = undo_read_4c(bi); if (uep->ue_size > 0) { array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } else array = NULL; uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = undo_read_4c(bi); if (line_len >= 0) line = read_string_decrypt(bi, line_len); else { line = NULL; corruption_error(""line length"", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; }",CWE-190,2 0,"void WebGraphicsContext3DDefaultImpl::prepareTexture() { if (!m_renderDirectlyToWebView) { resolveMultisampledFramebuffer(0, 0, m_cachedWidth, m_cachedHeight); } } ",none,24 1,"PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2( pj_pool_t *pool, pjmedia_sdp_neg *neg, unsigned flags, const pjmedia_sdp_session *local) { pjmedia_sdp_session *new_offer; pjmedia_sdp_session *old_offer; char media_used[PJMEDIA_MAX_SDP_MEDIA]; unsigned oi; /* old offer media index */ pj_status_t status; /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL); /* Can only do this in STATE_DONE. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, PJMEDIA_SDPNEG_EINSTATE); /* Validate the new offer */ status = pjmedia_sdp_validate(local); if (status != PJ_SUCCESS) return status; /* Change state to STATE_LOCAL_OFFER */ neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; /* Init vars */ pj_bzero(media_used, sizeof(media_used)); old_offer = neg->active_local_sdp; new_offer = pjmedia_sdp_session_clone(pool, local); /* RFC 3264 Section 8: When issuing an offer that modifies the session, * the ""o="" line of the new SDP MUST be identical to that in the * previous SDP, except that the version in the origin field MUST * increment by one from the previous SDP. */ pj_strdup(pool, &new_offer->origin.user, &old_offer->origin.user); new_offer->origin.id = old_offer->origin.id; pj_strdup(pool, &new_offer->origin.net_type, &old_offer->origin.net_type); pj_strdup(pool, &new_offer->origin.addr_type,&old_offer->origin.addr_type); pj_strdup(pool, &new_offer->origin.addr, &old_offer->origin.addr); if ((flags & PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE) == 0) { /* Generating the new offer, in the case media lines doesn't match the * active SDP (e.g. current/active SDP's have m=audio and m=video lines, * and the new offer only has m=audio line), the negotiator will fix * the new offer by reordering and adding the missing media line with * port number set to zero. */ for (oi = 0; oi < old_offer->media_count; ++oi) { pjmedia_sdp_media *om; pjmedia_sdp_media *nm; unsigned ni; /* new offer media index */ pj_bool_t found = PJ_FALSE; om = old_offer->media[oi]; for (ni = oi; ni < new_offer->media_count; ++ni) { nm = new_offer->media[ni]; if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) { if (ni != oi) { /* The same media found but the position unmatched to * the old offer, so let's put this media in the right * place, and keep the order of the rest. */ pj_array_insert( new_offer->media, /* array */ sizeof(new_offer->media[0]), /* elmt size*/ ni, /* count */ oi, /* pos */ &nm); /* new elmt */ } found = PJ_TRUE; break; } } if (!found) { pjmedia_sdp_media *m; m = sdp_media_clone_deactivate(pool, om, om, local); pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), new_offer->media_count++, oi, &m); } } } else { /* If media type change is allowed, the negotiator only needs to fix * the new offer by adding the missing media line(s) with port number * set to zero. */ for (oi = new_offer->media_count; oi < old_offer->media_count; ++oi) { pjmedia_sdp_media *m; m = sdp_media_clone_deactivate(pool, old_offer->media[oi], old_offer->media[oi], local); pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), new_offer->media_count++, oi, &m); } } /* New_offer fixed */ #if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION new_offer->origin.version = old_offer->origin.version; if (pjmedia_sdp_session_cmp(new_offer, neg->initial_sdp, 0) != PJ_SUCCESS) { ++new_offer->origin.version; } #else new_offer->origin.version = old_offer->origin.version + 1; #endif neg->initial_sdp_tmp = neg->initial_sdp; neg->initial_sdp = new_offer; neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, new_offer); return PJ_SUCCESS; }",CWE-200,4 1,"int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = ""tempfile.tif""; char *mode = ""r""; TIFF *tiff; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE((""in decoder: bytes %d\n"", bytes)); TRACE((""State: count %d, state %d, x %d, y %d, ystep %d\n"", state->count, state->state, state->x, state->y, state->ystep)); TRACE((""State: xsize %d, ysize %d, xoff %d, yoff %d \n"", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE((""State: bits %d, bytes %d \n"", state->bits, state->bytes)); TRACE((""Buffer: %p: %c%c%c%c\n"", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE((""State->Buffer: %c%c%c%c\n"", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE((""Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n"", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE((""Image: image8 %p, image32 %p, image %p, block %p \n"", im->image8, im->image32, im->image, im->block)); TRACE((""Image: pixelsize: %d, linesize %d \n"", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE((""Opening using fd: %d\n"",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE((""Opening from string\n"")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE((""Error, didn't get the tiff\n"")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE((""reading tiff ifd %u\n"", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE((""error in TIFFSetSubDirectory"")); return -1; } } if (TIFFIsTiled(tiff)) { UINT32 x, y, tile_y, row_byte_size; UINT32 tile_width, tile_length, current_tile_width; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size row_byte_size = (tile_width * state->bits + 7) / 8; state->bytes = row_byte_size * tile_length; /* overflow check for malloc */ if (state->bytes > INT_MAX - 1) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } /* realloc to fit whole tile */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; TRACE((""TIFFTileSize: %d\n"", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) { TRACE((""Decode Error, Tile at %dx%d\n"", x, y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Read tile at %dx%d; \n\n"", x, y)); current_tile_width = min(tile_width, state->xsize - x); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) { TRACE((""Writing tile data at %dx%d using tile_width: %d; \n"", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE((""chars: %x%x%x%x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, current_tile_width ); } } } } else { UINT32 strip_row, row_byte_size; UINT8 *new_data; UINT32 rows_per_strip; int ret; ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { rows_per_strip = state->ysize; } TRACE((""RowsPerStrip: %u \n"", rows_per_strip)); // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size row_byte_size = (state->xsize * state->bits + 7) / 8; state->bytes = rows_per_strip * row_byte_size; TRACE((""StripSize: %d \n"", state->bytes)); /* realloc to fit whole strip */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) { TRACE((""Decode Error, strip %d\n"", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Decoded strip for row %d \n"", state->y)); // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) { TRACE((""Writing data into line %d ; \n"", state->y + strip_row)); // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); // TRACE((""chars: %x %x %x %x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize); } } } TIFFClose(tiff); TRACE((""Done Decoding, Returning \n"")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }",CWE-787,16 1,"Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr, TF_DataType* out_tf_datatype) { PyObject* key; PyObject* value; Py_ssize_t pos = 0; if (PyDict_Next(descr->fields, &pos, &key, &value)) { // In Python 3, the keys of numpy custom struct types are unicode, unlike // Python 2, where the keys are bytes. const char* key_string = PyBytes_Check(key) ? PyBytes_AsString(key) : PyBytes_AsString(PyUnicode_AsASCIIString(key)); if (!key_string) { return errors::Internal(""Corrupt numpy type descriptor""); } tensorflow::string key = key_string; // The typenames here should match the field names in the custom struct // types constructed in test_util.py. // TODO(mrry,keveman): Investigate Numpy type registration to replace this // hard-coding of names. if (key == ""quint8"") { *out_tf_datatype = TF_QUINT8; } else if (key == ""qint8"") { *out_tf_datatype = TF_QINT8; } else if (key == ""qint16"") { *out_tf_datatype = TF_QINT16; } else if (key == ""quint16"") { *out_tf_datatype = TF_QUINT16; } else if (key == ""qint32"") { *out_tf_datatype = TF_QINT32; } else if (key == ""resource"") { *out_tf_datatype = TF_RESOURCE; } else { return errors::Internal(""Unsupported numpy data type""); } return Status::OK(); } return errors::Internal(""Unsupported numpy data type""); }",CWE-476,12 1,"int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr) { jp2_box_t *box; jp2_ftyp_t *ftyp; jp2_ihdr_t *ihdr; jas_stream_t *tmpstream; int allcmptssame; jp2_bpcc_t *bpcc; long len; uint_fast16_t cmptno; jp2_colr_t *colr; char buf[4096]; uint_fast32_t overhead; jp2_cdefchan_t *cdefchanent; jp2_cdef_t *cdef; int i; uint_fast32_t typeasoc; jas_iccprof_t *iccprof; jas_stream_t *iccstream; int pos; int needcdef; int prec; int sgnd; box = 0; tmpstream = 0; iccstream = 0; iccprof = 0; if (jas_image_numcmpts(image) < 1) { jas_eprintf(""image must have at least one component\n""); goto error; } allcmptssame = 1; sgnd = jas_image_cmptsgnd(image, 0); prec = jas_image_cmptprec(image, 0); for (i = 1; i < jas_image_numcmpts(image); ++i) { if (jas_image_cmptsgnd(image, i) != sgnd || jas_image_cmptprec(image, i) != prec) { allcmptssame = 0; break; } } /* Output the signature box. */ if (!(box = jp2_box_create(JP2_BOX_JP))) { jas_eprintf(""cannot create JP box\n""); goto error; } box->data.jp.magic = JP2_JP_MAGIC; if (jp2_box_put(box, out)) { jas_eprintf(""cannot write JP box\n""); goto error; } jp2_box_destroy(box); box = 0; /* Output the file type box. */ if (!(box = jp2_box_create(JP2_BOX_FTYP))) { jas_eprintf(""cannot create FTYP box\n""); goto error; } ftyp = &box->data.ftyp; ftyp->majver = JP2_FTYP_MAJVER; ftyp->minver = JP2_FTYP_MINVER; ftyp->numcompatcodes = 1; ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE; if (jp2_box_put(box, out)) { jas_eprintf(""cannot write FTYP box\n""); goto error; } jp2_box_destroy(box); box = 0; /* * Generate the data portion of the JP2 header box. * We cannot simply output the header for this box * since we do not yet know the correct value for the length * field. */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jas_eprintf(""cannot create temporary stream\n""); goto error; } /* Generate image header box. */ if (!(box = jp2_box_create(JP2_BOX_IHDR))) { jas_eprintf(""cannot create IHDR box\n""); goto error; } ihdr = &box->data.ihdr; ihdr->width = jas_image_width(image); ihdr->height = jas_image_height(image); ihdr->numcmpts = jas_image_numcmpts(image); ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0), jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL; ihdr->comptype = JP2_IHDR_COMPTYPE; ihdr->csunk = 0; ihdr->ipr = 0; if (jp2_box_put(box, tmpstream)) { jas_eprintf(""cannot write IHDR box\n""); goto error; } jp2_box_destroy(box); box = 0; /* Generate bits per component box. */ if (!allcmptssame) { if (!(box = jp2_box_create(JP2_BOX_BPCC))) { jas_eprintf(""cannot create BPCC box\n""); goto error; } bpcc = &box->data.bpcc; bpcc->numcmpts = jas_image_numcmpts(image); if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) { jas_eprintf(""memory allocation failed\n""); goto error; } for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) { bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image, cmptno), jas_image_cmptprec(image, cmptno)); } if (jp2_box_put(box, tmpstream)) { jas_eprintf(""cannot write BPCC box\n""); goto error; } jp2_box_destroy(box); box = 0; } /* Generate color specification box. */ if (!(box = jp2_box_create(JP2_BOX_COLR))) { jas_eprintf(""cannot create COLR box\n""); goto error; } colr = &box->data.colr; switch (jas_image_clrspc(image)) { case JAS_CLRSPC_SRGB: case JAS_CLRSPC_SYCBCR: case JAS_CLRSPC_SGRAY: colr->method = JP2_COLR_ENUM; colr->csid = clrspctojp2(jas_image_clrspc(image)); colr->pri = JP2_COLR_PRI; colr->approx = 0; break; default: colr->method = JP2_COLR_ICC; colr->pri = JP2_COLR_PRI; colr->approx = 0; /* Ensure that cmprof_ is not null. */ if (!jas_image_cmprof(image)) { jas_eprintf(""CM profile is null\n""); goto error; } if (!(iccprof = jas_iccprof_createfromcmprof( jas_image_cmprof(image)))) { jas_eprintf(""cannot create ICC profile\n""); goto error; } if (!(iccstream = jas_stream_memopen(0, 0))) { jas_eprintf(""cannot create temporary stream\n""); goto error; } if (jas_iccprof_save(iccprof, iccstream)) { jas_eprintf(""cannot write ICC profile\n""); goto error; } if ((pos = jas_stream_tell(iccstream)) < 0) { jas_eprintf(""cannot get stream position\n""); goto error; } colr->iccplen = pos; if (!(colr->iccp = jas_malloc(pos))) { jas_eprintf(""memory allocation failed\n""); goto error; } jas_stream_rewind(iccstream); if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen) { jas_eprintf(""cannot read temporary stream\n""); goto error; } jas_stream_close(iccstream); iccstream = 0; jas_iccprof_destroy(iccprof); iccprof = 0; break; } if (jp2_box_put(box, tmpstream)) { jas_eprintf(""cannot write box\n""); goto error; } jp2_box_destroy(box); box = 0; needcdef = 1; switch (jas_clrspc_fam(jas_image_clrspc(image))) { case JAS_CLRSPC_FAM_RGB: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) && jas_image_cmpttype(image, 1) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) && jas_image_cmpttype(image, 2) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)) needcdef = 0; break; case JAS_CLRSPC_FAM_YCBCR: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) && jas_image_cmpttype(image, 1) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) && jas_image_cmpttype(image, 2) == JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR)) needcdef = 0; break; case JAS_CLRSPC_FAM_GRAY: if (jas_image_cmpttype(image, 0) == JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y)) needcdef = 0; break; default: abort(); break; } if (needcdef) { if (!(box = jp2_box_create(JP2_BOX_CDEF))) { jas_eprintf(""cannot create CDEF box\n""); goto error; } cdef = &box->data.cdef; cdef->numchans = jas_image_numcmpts(image); cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)); for (i = 0; i < jas_image_numcmpts(image); ++i) { cdefchanent = &cdef->ents[i]; cdefchanent->channo = i; typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i)); cdefchanent->type = typeasoc >> 16; cdefchanent->assoc = typeasoc & 0x7fff; } if (jp2_box_put(box, tmpstream)) { jas_eprintf(""cannot write CDEF box\n""); goto error; } jp2_box_destroy(box); box = 0; } /* Determine the total length of the JP2 header box. */ len = jas_stream_tell(tmpstream); jas_stream_rewind(tmpstream); /* * Output the JP2 header box and all of the boxes which it contains. */ if (!(box = jp2_box_create(JP2_BOX_JP2H))) { jas_eprintf(""cannot create JP2H box\n""); goto error; } box->len = len + JP2_BOX_HDRLEN(false); if (jp2_box_put(box, out)) { jas_eprintf(""cannot write JP2H box\n""); goto error; } jp2_box_destroy(box); box = 0; if (jas_stream_copy(out, tmpstream, len)) { jas_eprintf(""cannot copy stream\n""); goto error; } jas_stream_close(tmpstream); tmpstream = 0; /* * Output the contiguous code stream box. */ if (!(box = jp2_box_create(JP2_BOX_JP2C))) { jas_eprintf(""cannot create JP2C box\n""); goto error; } box->len = 0; if (jp2_box_put(box, out)) { jas_eprintf(""cannot write JP2C box\n""); goto error; } jp2_box_destroy(box); box = 0; /* Output the JPEG-2000 code stream. */ overhead = jas_stream_getrwcount(out); sprintf(buf, ""%s\n_jp2overhead=%lu\n"", (optstr ? optstr : """"), (unsigned long) overhead); if (jpc_encode(image, out, buf)) { jas_eprintf(""jpc_encode failed\n""); goto error; } return 0; error: if (iccprof) { jas_iccprof_destroy(iccprof); } if (iccstream) { jas_stream_close(iccstream); } if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return -1; }",CWE-125,1 1,"static int rtsx_usb_ms_drv_remove(struct platform_device *pdev) { struct rtsx_usb_ms *host = platform_get_drvdata(pdev); struct memstick_host *msh = host->msh; int err; host->eject = true; cancel_work_sync(&host->handle_req); mutex_lock(&host->host_mutex); if (host->req) { dev_dbg(ms_dev(host), ""%s: Controller removed during transfer\n"", dev_name(&msh->dev)); host->req->error = -ENOMEDIUM; do { err = memstick_next_req(msh, &host->req); if (!err) host->req->error = -ENOMEDIUM; } while (!err); } mutex_unlock(&host->host_mutex); memstick_remove_host(msh); memstick_free_host(msh); /* Balance possible unbalanced usage count * e.g. unconditional module removal */ if (pm_runtime_active(ms_dev(host))) pm_runtime_put(ms_dev(host)); pm_runtime_disable(ms_dev(host)); platform_set_drvdata(pdev, NULL); dev_dbg(ms_dev(host), "": Realtek USB Memstick controller has been removed\n""); return 0; }",CWE-416,10 1,"static BOOL rdp_read_font_capability_set(wStream* s, UINT16 length, rdpSettings* settings) { WINPR_UNUSED(settings); if (length > 4) Stream_Seek_UINT16(s); /* fontSupportFlags (2 bytes) */ if (length > 6) Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ return TRUE; }",CWE-125,1 1,"CString CWebSock::GetSkinPath(const CString& sSkinName) { CString sRet = CZNC::Get().GetZNCPath() + ""/webskins/"" + sSkinName; if (!CFile::IsDir(sRet)) { sRet = CZNC::Get().GetCurPath() + ""/webskins/"" + sSkinName; if (!CFile::IsDir(sRet)) { sRet = CString(_SKINDIR_) + ""/"" + sSkinName; } } return sRet + ""/""; }",CWE-22,5 0," NullVideoFrame() {} ",none,24 1,"unsigned long move_page_tables(struct vm_area_struct *vma, unsigned long old_addr, struct vm_area_struct *new_vma, unsigned long new_addr, unsigned long len, bool need_rmap_locks) { unsigned long extent, next, old_end; struct mmu_notifier_range range; pmd_t *old_pmd, *new_pmd; old_end = old_addr + len; flush_cache_range(vma, old_addr, old_end); mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm, old_addr, old_end); mmu_notifier_invalidate_range_start(&range); for (; old_addr < old_end; old_addr += extent, new_addr += extent) { cond_resched(); next = (old_addr + PMD_SIZE) & PMD_MASK; /* even if next overflowed, extent below will be ok */ extent = next - old_addr; if (extent > old_end - old_addr) extent = old_end - old_addr; old_pmd = get_old_pmd(vma->vm_mm, old_addr); if (!old_pmd) continue; new_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr); if (!new_pmd) break; if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd)) { if (extent == HPAGE_PMD_SIZE) { bool moved; /* See comment in move_ptes() */ if (need_rmap_locks) take_rmap_locks(vma); moved = move_huge_pmd(vma, old_addr, new_addr, old_end, old_pmd, new_pmd); if (need_rmap_locks) drop_rmap_locks(vma); if (moved) continue; } split_huge_pmd(vma, old_pmd, old_addr); if (pmd_trans_unstable(old_pmd)) continue; } else if (extent == PMD_SIZE) { #ifdef CONFIG_HAVE_MOVE_PMD /* * If the extent is PMD-sized, try to speed the move by * moving at the PMD level if possible. */ bool moved; if (need_rmap_locks) take_rmap_locks(vma); moved = move_normal_pmd(vma, old_addr, new_addr, old_end, old_pmd, new_pmd); if (need_rmap_locks) drop_rmap_locks(vma); if (moved) continue; #endif } if (pte_alloc(new_vma->vm_mm, new_pmd)) break; next = (new_addr + PMD_SIZE) & PMD_MASK; if (extent > next - new_addr) extent = next - new_addr; move_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma, new_pmd, new_addr, need_rmap_locks); } mmu_notifier_invalidate_range_end(&range); return len + old_addr - old_end; /* how much done */ }",CWE-119,0 1,"get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; } return 1; }",CWE-200,4 0,"AudioManagerBase::~AudioManagerBase() { CHECK(!audio_thread_.get()); DCHECK_EQ(0, num_output_streams_); DCHECK_EQ(0, num_input_streams_); } ",none,24 0,"base::TimeDelta VideoRendererBase::CalculateSleepDuration( const scoped_refptr& next_frame, float playback_rate) { base::TimeDelta now = host()->GetTime(); base::TimeDelta this_pts = current_frame_->GetTimestamp(); base::TimeDelta next_pts; if (!next_frame->IsEndOfStream()) { next_pts = next_frame->GetTimestamp(); } else { next_pts = this_pts + current_frame_->GetDuration(); } base::TimeDelta sleep = next_pts - now; return base::TimeDelta::FromMicroseconds( static_cast(sleep.InMicroseconds() / playback_rate)); } ",none,24 1,"void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0) { int x,y,w,v,z; int x1, y1, w1, h1; int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2; unsigned char *srcptr, *dstptr; /* Nothing to do!!! */ if (screen==ptr) return; x1 = x0; y1 = y0; w1 = w0; h1 = h0; rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, ""rfbScaledScreenUpdateRect""); x0 = ScaleX(ptr, screen, x1); y0 = ScaleY(ptr, screen, y1); w0 = ScaleX(ptr, screen, w1); h0 = ScaleY(ptr, screen, h1); bitsPerPixel = screen->bitsPerPixel; bytesPerPixel = bitsPerPixel / 8; bytesPerLine = w1 * bytesPerPixel; srcptr = (unsigned char *)(screen->frameBuffer + (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel)); dstptr = (unsigned char *)(ptr->frameBuffer + ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel)); /* The area of the source framebuffer for each destination pixel */ areaX = ScaleX(ptr,screen,1); areaY = ScaleY(ptr,screen,1); area2 = areaX*areaY; /* Ensure that we do not go out of bounds */ if ((x1+w1) > (ptr->width)) { if (x1==0) w1=ptr->width; else x1 = ptr->width - w1; } if ((y1+h1) > (ptr->height)) { if (y1==0) h1=ptr->height; else y1 = ptr->height - h1; } /* * rfbLog(""rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\n"", * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY, * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer); */ if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */ unsigned char *srcptr2; unsigned long pixel_value, red, green, blue; unsigned int redShift = screen->serverFormat.redShift; unsigned int greenShift = screen->serverFormat.greenShift; unsigned int blueShift = screen->serverFormat.blueShift; unsigned long redMax = screen->serverFormat.redMax; unsigned long greenMax = screen->serverFormat.greenMax; unsigned long blueMax = screen->serverFormat.blueMax; /* for each *destination* pixel... */ for (y = 0; y < h1; y++) { for (x = 0; x < w1; x++) { red = green = blue = 0; /* Get the totals for rgb from the source grid... */ for (w = 0; w < areaX; w++) { for (v = 0; v < areaY; v++) { srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) + (v * screen->paddedWidthInBytes)]; pixel_value = 0; switch (bytesPerPixel) { case 4: pixel_value = *((unsigned int *)srcptr2); break; case 2: pixel_value = *((unsigned short *)srcptr2); break; case 1: pixel_value = *((unsigned char *)srcptr2); break; default: /* fixme: endianness problem? */ for (z = 0; z < bytesPerPixel; z++) pixel_value += (srcptr2[z] << (8 * z)); break; } /* srcptr2 += bytesPerPixel; */ red += ((pixel_value >> redShift) & redMax); green += ((pixel_value >> greenShift) & greenMax); blue += ((pixel_value >> blueShift) & blueMax); } } /* We now have a total for all of the colors, find the average! */ red /= area2; green /= area2; blue /= area2; /* Stuff the new value back into memory */ pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift); switch (bytesPerPixel) { case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break; case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break; case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break; default: /* fixme: endianness problem? */ for (z = 0; z < bytesPerPixel; z++) dstptr[z]=(pixel_value >> (8 * z)) & 0xff; break; } dstptr += bytesPerPixel; } srcptr += (screen->paddedWidthInBytes * areaY); dstptr += (ptr->paddedWidthInBytes - bytesPerLine); } } else { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */ for (y = y1; y < (y1+h1); y++) { for (x = x1; x < (x1+w1); x++) memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)], &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel); } } }",CWE-787,16 1," static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; }",CWE-125,1 0,"unsigned componentsPerPixel(unsigned format, unsigned type) { switch (type) { case GL_UNSIGNED_SHORT_5_6_5: case GL_UNSIGNED_SHORT_4_4_4_4: case GL_UNSIGNED_SHORT_5_5_5_1: return 1; default: break; } switch (format) { case GL_LUMINANCE: return 1; case GL_LUMINANCE_ALPHA: return 2; case GL_RGB: return 3; case GL_RGBA: case GL_BGRA_EXT: return 4; default: return 4; } } ",none,24 1,"CallResult JSObject::putComputedWithReceiver_RJS( Handle selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> valueHandle, Handle<> receiver, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && ""mustExist flag cannot be used with computed properties""); // Try the fast-path first: has ""index-like"" properties, the ""name"" // already is a valid integer index, selfHandle and receiver are the // same, and it is present in storage. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) { if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) { auto result = setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( ""Cannot assign to read-only property""); } return false; } } } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Look for the property in this object or along the prototype chain. MutableHandle propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // If the property exists (or, we hit a proxy/hostobject on the way // up the chain) if (propObj) { // Get the simple case out of the way: If the property already // exists on selfHandle, is not an accessor, selfHandle and // receiver are the same, selfHandle is not a host // object/proxy/internal setter, and the property is writable, // just write into the same slot. if (LLVM_LIKELY( selfHandle == propObj && selfHandle.getHermesValue().getRaw() == receiver->getRaw() && !desc.flags.accessor && !desc.flags.internalSetter && !desc.flags.hostObject && !desc.flags.proxyObject && desc.flags.writable)) { if (LLVM_UNLIKELY( setComputedSlotValue(selfHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } // Is it an accessor? if (LLVM_UNLIKELY(desc.flags.accessor)) { auto *accessor = vmcast( getComputedSlotValue(propObj.get(), runtime, desc)); // If it is a read-only accessor, fail. if (!accessor->setter) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( ""Cannot assign to property "", nameValPrimitiveHandle, "" which has only a getter""); } return false; } // Execute the accessor on this object. if (accessor->setter.get(runtime)->executeCall1( runtime->makeHandle(accessor->setter), runtime, receiver, valueHandle.get()) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return true; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { assert( !opFlags.getMustExist() && ""MustExist cannot be used with Proxy objects""); CallResult> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; CallResult setRes = JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver); if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*setRes && opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( TwineChar16(""Proxy trap returned false for property"")); } return setRes; } if (LLVM_UNLIKELY(!desc.flags.writable)) { if (desc.flags.staticBuiltin) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return raiseErrorForOverridingStaticBuiltin( selfHandle, runtime, runtime->makeHandle(id)); } if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( ""Cannot assign to read-only property "", nameValPrimitiveHandle, """"); } return false; } if (selfHandle == propObj && desc.flags.internalSetter) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return internalSetter( selfHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } } // The property does not exist as an conventional own property on // this object. MutableHandle receiverHandle{runtime, *selfHandle}; if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() || receiverHandle->isHostObject() || receiverHandle->isProxyObject()) { if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) { receiverHandle = dyn_vmcast(*receiver); } if (!receiverHandle) { return false; } CallResult descDefinedRes = getOwnComputedPrimitiveDescriptor( receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc); if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } DefinePropertyFlags dpf; if (*descDefinedRes) { if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) { return false; } if (LLVM_LIKELY( !desc.flags.internalSetter && !receiverHandle->isHostObject() && !receiverHandle->isProxyObject())) { if (LLVM_UNLIKELY( setComputedSlotValue( receiverHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } } if (LLVM_UNLIKELY( desc.flags.internalSetter || receiverHandle->isHostObject() || receiverHandle->isProxyObject())) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); if (desc.flags.internalSetter) { return internalSetter( receiverHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } else if (receiverHandle->isHostObject()) { return vmcast(receiverHandle.get())->set(id, *valueHandle); } assert( receiverHandle->isProxyObject() && ""descriptor flags are impossible""); if (*descDefinedRes) { dpf.setValue = 1; } else { dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); } return JSProxy::defineOwnProperty( receiverHandle, runtime, nameValPrimitiveHandle, dpf, valueHandle, opFlags); } } /// Can we add more properties? if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( ""cannot add a new property""); // TODO: better message. } return false; } // If we have indexed storage we must check whether the property is an index, // and if it is, store it in indexed storage. if (receiverHandle->flags_.indexedStorage) { OptValue arrayIndex; MutableHandle strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex); if (arrayIndex) { // Check whether we need to update array's "".length"" property. if (auto *array = dyn_vmcast(receiverHandle.get())) { if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) { auto cr = putNamed_RJS( receiverHandle, runtime, Predefined::getSymbolID(Predefined::length), runtime->makeHandle( HermesValue::encodeNumberValue(*arrayIndex + 1)), opFlags); if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_UNLIKELY(!*cr)) return false; } } auto result = setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError(""Cannot assign to read-only property""); } return false; } } SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); // Add a new named property. return addOwnProperty( receiverHandle, runtime, id, DefinePropertyFlags::getDefaultNewPropertyFlags(), valueHandle, opFlags); }",CWE-125,1 1,"static int irda_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_irda saddr; struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->dtsap_sel; saddr.sir_addr = self->daddr; } else { saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->stsap_sel; saddr.sir_addr = self->saddr; } IRDA_DEBUG(1, ""%s(), tsap_sel = %#x\n"", __func__, saddr.sir_lsap_sel); IRDA_DEBUG(1, ""%s(), addr = %08x\n"", __func__, saddr.sir_addr); /* uaddr_len come to us uninitialised */ *uaddr_len = sizeof (struct sockaddr_irda); memcpy(uaddr, &saddr, *uaddr_len); return 0; }",CWE-200,4 1,"PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector, MessageWriter *input, MessageReader *output) { int ret; UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance(); SgxParams *const sgx_params = reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams))); if (!TrustedPrimitives::IsOutsideEnclave(sgx_params, sizeof(SgxParams))) { TrustedPrimitives::BestEffortAbort( ""UntrustedCall: sgx_param should be in untrusted memory""); } Cleanup clean_up( [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); }); sgx_params->input_size = 0; sgx_params->input = nullptr; if (input) { sgx_params->input_size = input->MessageSize(); if (sgx_params->input_size > 0) { // Allocate and copy data to |input_buffer|. sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size); if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->input, sgx_params->input_size)) { TrustedPrimitives::BestEffortAbort( ""UntrustedCall: sgx_param input should be in untrusted memory""); } input->Serialize(const_cast(sgx_params->input)); } } sgx_params->output_size = 0; sgx_params->output = nullptr; CHECK_OCALL( ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params)); if (sgx_params->input) { untrusted_cache->Free(const_cast(sgx_params->input)); } if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output, sgx_params->output_size)) { TrustedPrimitives::BestEffortAbort( ""UntrustedCall: sgx_param output should be in untrusted memory""); } if (sgx_params->output) { // For the results obtained in |output_buffer|, copy them to |output| // before freeing the buffer. output->Deserialize(sgx_params->output, sgx_params->output_size); TrustedPrimitives::UntrustedLocalFree(sgx_params->output); } return PrimitiveStatus::OkStatus(); }",CWE-200,4 1,"static int vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q) { if ( !bcf_hdr_nsamples(h) ) return 0; static int extreme_val_warned = 0; char *r, *t; int j, l, m, g, overflow = 0; khint_t k; ks_tokaux_t aux1; vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID]; kstring_t *mem = (kstring_t*)&h->mem; fmt_aux_t fmt[MAX_N_FMT]; mem->l = 0; char *end = s->s + s->l; if ( q>=end ) { hts_log_error(""FORMAT column with no sample columns starting at %s:%""PRIhts_pos"""", bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_NCOLS; return -1; } v->n_fmt = 0; if ( p[0]=='.' && p[1]==0 ) // FORMAT field is empty ""."" { v->n_sample = bcf_hdr_nsamples(h); return 0; } // get format information from the dictionary for (j = 0, t = kstrtok(p, "":"", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) { if (j >= MAX_N_FMT) { v->errcode |= BCF_ERR_LIMITS; hts_log_error(""FORMAT column at %s:%""PRIhts_pos"" lists more identifiers than htslib can handle"", bcf_seqname_safe(h,v), v->pos+1); return -1; } *(char*)aux1.p = 0; k = kh_get(vdict, d, t); if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) { if ( t[0]=='.' && t[1]==0 ) { hts_log_error(""Invalid FORMAT tag name '.' at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_TAG_INVALID; return -1; } hts_log_warning(""FORMAT '%s' at %s:%""PRIhts_pos"" is not defined in the header, assuming Type=String"", t, bcf_seqname_safe(h,v), v->pos+1); kstring_t tmp = {0,0,0}; int l; ksprintf(&tmp, ""##FORMAT="", t); bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l); free(tmp.s); int res = hrec ? bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) : -1; if (res < 0) bcf_hrec_destroy(hrec); if (res > 0) res = bcf_hdr_sync((bcf_hdr_t*)h); k = kh_get(vdict, d, t); v->errcode = BCF_ERR_TAG_UNDEF; if (res || k == kh_end(d)) { hts_log_error(""Could not add dummy header for FORMAT '%s' at %s:%""PRIhts_pos, t, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_TAG_INVALID; return -1; } } fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0; fmt[j].key = kh_val(d, k).id; fmt[j].is_gt = !strcmp(t, ""GT""); fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT]; v->n_fmt++; } // compute max int n_sample_ori = -1; r = q + 1; // r: position in the format string l = 0, m = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles while ( rkeep_samples ) { n_sample_ori++; if ( !bit_array_test(h->keep_samples,n_sample_ori) ) { while ( *r!='\t' && ris_gt) g++; break; case '\t': *r = 0; // fall through case '\0': case ':': if (f->max_m < m) f->max_m = m; if (f->max_l < l) f->max_l = l; if (f->is_gt && f->max_g < g) f->max_g = g; l = 0, m = g = 1; if ( *r==':' ) { j++; f++; if ( j>=v->n_fmt ) { hts_log_error(""Incorrect number of FORMAT fields at %s:%""PRIhts_pos"""", h->id[BCF_DT_CTG][v->rid].key, v->pos+1); v->errcode |= BCF_ERR_NCOLS; return -1; } } else goto end_for; break; } if ( r>=end ) break; r++; l++; } end_for: v->n_sample++; if ( v->n_sample == bcf_hdr_nsamples(h) ) break; r++; } // allocate memory for arrays for (j = 0; j < v->n_fmt; ++j) { fmt_aux_t *f = &fmt[j]; if ( !f->max_m ) f->max_m = 1; // omitted trailing format field if ((f->y>>4&0xf) == BCF_HT_STR) { f->size = f->is_gt? f->max_g << 2 : f->max_l; } else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) { f->size = f->max_m << 2; } else { hts_log_error(""The format type %d at %s:%""PRIhts_pos"" is currently not supported"", f->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_TAG_INVALID; return -1; } if (align_mem(mem) < 0) { hts_log_error(""Memory allocation failure at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_LIMITS; return -1; } f->offset = mem->l; // Limit the total memory to ~2Gb per VCF row. This should mean // malformed VCF data is less likely to take excessive memory and/or // time. if (v->n_sample * (uint64_t)f->size > INT_MAX) { hts_log_error(""Excessive memory required by FORMAT fields at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_LIMITS; return -1; } if (ks_resize(mem, mem->l + v->n_sample * (size_t)f->size) < 0) { hts_log_error(""Memory allocation failure at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_LIMITS; return -1; } mem->l += v->n_sample * f->size; } for (j = 0; j < v->n_fmt; ++j) fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset; // fill the sample fields; at beginning of the loop, t points to the first char of a format n_sample_ori = -1; t = q + 1; m = 0; // m: sample id while ( tkeep_samples ) { n_sample_ori++; if ( !bit_array_test(h->keep_samples,n_sample_ori) ) { while ( *t && tbuf) { hts_log_error(""Memory allocation failure for FORMAT field type %d at %s:%""PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_LIMITS; return -1; } if ((z->y>>4&0xf) == BCF_HT_STR) { if (z->is_gt) { // genotypes int32_t is_phased = 0; uint32_t *x = (uint32_t*)(z->buf + z->size * (size_t)m); uint32_t unreadable = 0; uint32_t max = 0; overflow = 0; for (l = 0;; ++t) { if (*t == '.') { ++t, x[l++] = is_phased; } else { char *tt = t; uint32_t val = hts_str2uint(t, &t, sizeof(val) * CHAR_MAX - 2, &overflow); unreadable |= tt == t; if (max < val) max = val; x[l++] = (val + 1) << 1 | is_phased; } is_phased = (*t == '|'); if (*t != '|' && *t != '/') break; } // Possibly check max against v->n_allele instead? if (overflow || max > (INT32_MAX >> 1) - 1) { hts_log_error(""Couldn't read GT data: value too large at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); return -1; } if (unreadable) { hts_log_error(""Couldn't read GT data: value not a number or '.' at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); return -1; } if ( !l ) x[l++] = 0; // An empty field, insert missing value for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end; } else { char *x = (char*)z->buf + z->size * (size_t)m; for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t; for (; l < z->size; ++l) x[l] = 0; } } else if ((z->y>>4&0xf) == BCF_HT_INT) { int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m); for (l = 0;; ++t) { if (*t == '.') { x[l++] = bcf_int32_missing, ++t; // ++t to skip ""."" } else { overflow = 0; char *te; long int tmp_val = hts_str2int(t, &te, sizeof(tmp_val)*CHAR_BIT, &overflow); if ( te==t || overflow || tmp_valBCF_MAX_BT_INT32 ) { if ( !extreme_val_warned ) { hts_log_warning(""Extreme FORMAT/%s value encountered and set to missing at %s:%""PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname_safe(h,v), v->pos+1); extreme_val_warned = 1; } tmp_val = bcf_int32_missing; } x[l++] = tmp_val; t = te; } if (*t != ',') break; } if ( !l ) x[l++] = bcf_int32_missing; for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end; } else if ((z->y>>4&0xf) == BCF_HT_REAL) { float *x = (float*)(z->buf + z->size * (size_t)m); for (l = 0;; ++t) { if (*t == '.' && !isdigit_c(t[1])) { bcf_float_set_missing(x[l++]), ++t; // ++t to skip ""."" } else { overflow = 0; char *te; float tmp_val = hts_str2dbl(t, &te, &overflow); if ( (te==t || overflow) && !extreme_val_warned ) { hts_log_warning(""Extreme FORMAT/%s value encountered at %s:%""PRIhts_pos, h->id[BCF_DT_ID][fmt[j-1].key].key, bcf_seqname(h,v), v->pos+1); extreme_val_warned = 1; } x[l++] = tmp_val; t = te; } if (*t != ',') break; } if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]); } else { hts_log_error(""Unknown FORMAT field type %d at %s:%""PRIhts_pos, z->y>>4&0xf, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_TAG_INVALID; return -1; } if (*t == '\0') { break; } else if (*t == ':') { t++; } else { char buffer[8]; hts_log_error(""Invalid character %s in '%s' FORMAT field at %s:%""PRIhts_pos"""", hts_strprint(buffer, sizeof buffer, '\'', t, 1), h->id[BCF_DT_ID][z->key].key, bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_CHAR; return -1; } } for (; j < v->n_fmt; ++j) { // fill end-of-vector values fmt_aux_t *z = &fmt[j]; if ((z->y>>4&0xf) == BCF_HT_STR) { if (z->is_gt) { int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m); if (z->size) x[0] = bcf_int32_missing; for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end; } else { char *x = (char*)z->buf + z->size * (size_t)m; if ( z->size ) x[0] = '.'; for (l = 1; l < z->size; ++l) x[l] = 0; } } else if ((z->y>>4&0xf) == BCF_HT_INT) { int32_t *x = (int32_t*)(z->buf + z->size * (size_t)m); x[0] = bcf_int32_missing; for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end; } else if ((z->y>>4&0xf) == BCF_HT_REAL) { float *x = (float*)(z->buf + z->size * (size_t)m); bcf_float_set_missing(x[0]); for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]); } } m++; t++; } // write individual genotype information kstring_t *str = &v->indiv; int i; if (v->n_sample > 0) { for (i = 0; i < v->n_fmt; ++i) { fmt_aux_t *z = &fmt[i]; bcf_enc_int1(str, z->key); if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) { bcf_enc_size(str, z->size, BCF_BT_CHAR); kputsn((char*)z->buf, z->size * (size_t)v->n_sample, str); } else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) { bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2); } else { bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT); if (serialize_float_array(str, (z->size>>2) * (size_t)v->n_sample, (float *) z->buf) != 0) { v->errcode |= BCF_ERR_LIMITS; hts_log_error(""Out of memory at %s:%""PRIhts_pos, bcf_seqname_safe(h,v), v->pos+1); return -1; } } } } if ( v->n_sample!=bcf_hdr_nsamples(h) ) { hts_log_error(""Number of columns at %s:%""PRIhts_pos"" does not match the number of samples (%d vs %d)"", bcf_seqname_safe(h,v), v->pos+1, v->n_sample, bcf_hdr_nsamples(h)); v->errcode |= BCF_ERR_NCOLS; return -1; } if ( v->indiv.l > 0xffffffff ) { hts_log_error(""The FORMAT at %s:%""PRIhts_pos"" is too long"", bcf_seqname_safe(h,v), v->pos+1); v->errcode |= BCF_ERR_LIMITS; // Error recovery: return -1 if this is a critical error or 0 if we want to ignore the FORMAT and proceed v->n_fmt = 0; return -1; } return 0; }",CWE-787,16 1,"static Image *ReadHEICImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *profile; heif_item_id exif_id; Image *image; int count, stride_y, stride_cb, stride_cr; MagickBooleanType status; size_t length; ssize_t y; struct heif_context *heif_context; struct heif_decoding_options *decode_options; struct heif_error error; struct heif_image *heif_image; struct heif_image_handle *image_handle; const uint8_t *p_y, *p_cb, *p_cr; void *file_data; /* 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) return(DestroyImageList(image)); if (GetBlobSize(image) > (MagickSizeType) SSIZE_MAX) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); length=(size_t) GetBlobSize(image); file_data=AcquireMagickMemory(length); if (file_data == (void *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (ReadBlob(image,length,(unsigned char *) file_data) != (ssize_t) length) { file_data=RelinquishMagickMemory(file_data); ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); } /* Decode HEIF file */ heif_context=heif_context_alloc(); error=heif_context_read_from_memory_without_copy(heif_context,file_data, length,NULL); if (IsHeifSuccess(&error,image) == MagickFalse) { heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(DestroyImageList(image)); } image_handle=(struct heif_image_handle *) NULL; error=heif_context_get_primary_image_handle(heif_context,&image_handle); if (IsHeifSuccess(&error,image) == MagickFalse) { heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(DestroyImageList(image)); } #if LIBHEIF_NUMERIC_VERSION >= 0x01040000 length=heif_image_handle_get_raw_color_profile_size(image_handle); if (length > 0) { unsigned char *color_buffer; /* Read color profile. */ if ((MagickSizeType) length > GetBlobSize(image)) { heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); } color_buffer=(unsigned char *) AcquireMagickMemory(length); if (color_buffer != (unsigned char *) NULL) { error=heif_image_handle_get_raw_color_profile(image_handle, color_buffer); if (error.code == 0) { StringInfo *profile; profile=BlobToStringInfo(color_buffer,length); if (profile != (StringInfo*) NULL) { (void) SetImageProfile(image,""icc"",profile); profile=DestroyStringInfo(profile); } } } color_buffer=(unsigned char *) RelinquishMagickMemory(color_buffer); } #endif count=heif_image_handle_get_list_of_metadata_block_IDs(image_handle,""Exif"", &exif_id,1); if (count > 0) { size_t exif_size; unsigned char *exif_buffer; /* Read Exif profile. */ exif_size=heif_image_handle_get_metadata_size(image_handle,exif_id); if ((MagickSizeType) exif_size > GetBlobSize(image)) { heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); } exif_buffer=(unsigned char*) AcquireMagickMemory(exif_size); if (exif_buffer != (unsigned char*) NULL) { error=heif_image_handle_get_metadata(image_handle, exif_id,exif_buffer); if (error.code == 0) { StringInfo *profile; /* The first 4 byte should be skipped since they indicate the offset to the start of the TIFF header of the Exif data. */ profile=(StringInfo*) NULL; if (exif_size > 8) profile=BlobToStringInfo(exif_buffer+4,(size_t) exif_size-4); if (profile != (StringInfo*) NULL) { (void) SetImageProfile(image,""exif"",profile); profile=DestroyStringInfo(profile); } } } exif_buffer=(unsigned char *) RelinquishMagickMemory(exif_buffer); } /* Set image size. */ image->depth=8; image->columns=(size_t) heif_image_handle_get_width(image_handle); image->rows=(size_t) heif_image_handle_get_height(image_handle); if (image_info->ping != MagickFalse) { image->colorspace=YCbCrColorspace; heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(DestroyImageList(image)); } /* Copy HEIF image into ImageMagick data structures */ (void) SetImageColorspace(image,YCbCrColorspace); decode_options=(struct heif_decoding_options *) NULL; option=GetImageOption(image_info,""heic:preserve-orientation""); if (IsStringTrue(option) == MagickTrue) { decode_options=heif_decoding_options_alloc(); decode_options->ignore_transformations=1; } else (void) SetImageProperty(image,""exif:Orientation"",""1""); error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr, heif_chroma_420,NULL); if (IsHeifSuccess(&error,image) == MagickFalse) { heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(DestroyImageList(image)); } if (decode_options != (struct heif_decoding_options *) NULL) { /* Correct the width and height of the image. */ image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y); image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y); status=SetImageExtent(image,image->columns,image->rows); heif_decoding_options_free(decode_options); if (status == MagickFalse) { heif_image_release(heif_image); heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); return(DestroyImageList(image)); } } p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y); p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb); p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr); for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) p_y[y* stride_y+x])); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) p_cb[(y/2)* stride_cb+x/2])); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) p_cr[(y/2)* stride_cr+x/2])); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } heif_image_release(heif_image); heif_image_handle_release(image_handle); heif_context_free(heif_context); file_data=RelinquishMagickMemory(file_data); profile=GetImageProfile(image,""icc""); if (profile != (const StringInfo *) NULL) (void) TransformImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); }",CWE-125,1 0,"EmbeddedWorkerContextClient::ThreadSpecificInstance() { return g_worker_client_tls.Pointer()->Get(); } ",none,24 0,"WebString WebGraphicsContext3DDefaultImpl::getShaderInfoLog(WebGLId shader) { makeContextCurrent(); ShaderSourceMap::iterator result = m_shaderSourceMap.find(shader); if (result != m_shaderSourceMap.end()) { ShaderSourceEntry* entry = result->second; ASSERT(entry); if (!entry->isValid) { if (!entry->log) return WebString(); WebString res = WebString::fromUTF8(entry->log, strlen(entry->log)); return res; } } GLint logLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength <= 1) return WebString(); GLchar* log = 0; if (!tryFastMalloc(logLength * sizeof(GLchar)).getValue(log)) return WebString(); GLsizei returnedLogLength; glGetShaderInfoLog(shader, logLength, &returnedLogLength, log); ASSERT(logLength == returnedLogLength + 1); WebString res = WebString::fromUTF8(log, returnedLogLength); fastFree(log); return res; } ",none,24 0,"gfx::Size SoftwareFrameManager::GetCurrentFrameSizeInDIP() const { DCHECK(HasCurrentFrame()); return ConvertSizeToDIP(current_frame_->frame_device_scale_factor_, current_frame_->frame_size_pixels_); } ",none,24 1,"GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box) { u32 type, uuid_type, hdr_size; u64 size, start, payload_start, end; char uuid[16]; GF_Err e; GF_Box *newBox; Bool skip_logs = gf_bs_get_cookie(bs) ? GF_TRUE : GF_FALSE; Bool is_special = GF_TRUE; if ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM; *outBox = NULL; if (gf_bs_available(bs) < 8) { return GF_ISOM_INCOMPLETE_FILE; } start = gf_bs_get_position(bs); uuid_type = 0; size = (u64) gf_bs_read_u32(bs); hdr_size = 4; /*fix for some boxes found in some old hinted files*/ if ((size >= 2) && (size <= 4)) { size = 4; type = GF_ISOM_BOX_TYPE_VOID; } else { type = gf_bs_read_u32(bs); hdr_size += 4; /*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/ if (type == GF_ISOM_BOX_TYPE_TOTL) size = 12; if (!size) { if (is_root_box) { if (!skip_logs) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\n"", gf_4cc_to_str(type), type)); } size = gf_bs_available(bs) + 8; } else { if (!skip_logs) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Read Box type %s (0x%08X) at position ""LLU"" has size 0 but is not at root/file level, skipping\n"", gf_4cc_to_str(type), type, start)); } return GF_OK; // return GF_ISOM_INVALID_FILE; } } } /*handle uuid*/ memset(uuid, 0, 16); if (type == GF_ISOM_BOX_TYPE_UUID ) { if (gf_bs_available(bs) < 16) { return GF_ISOM_INCOMPLETE_FILE; } gf_bs_read_data(bs, uuid, 16); hdr_size += 16; uuid_type = gf_isom_solve_uuid_box(uuid); } //handle large box if (size == 1) { if (gf_bs_available(bs) < 8) { return GF_ISOM_INCOMPLETE_FILE; } size = gf_bs_read_u64(bs); hdr_size += 8; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[iso file] Read Box type %s size ""LLD"" start ""LLD""\n"", gf_4cc_to_str(type), LLD_CAST size, LLD_CAST start)); if ( size < hdr_size ) { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[iso file] Box size ""LLD"" less than box header size %d\n"", LLD_CAST size, hdr_size)); return GF_ISOM_INVALID_FILE; } //some special boxes (references and track groups) are handled by a single generic box with an associated ref/group type if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TREF)) { newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFT); if (!newBox) return GF_OUT_OF_MEM; ((GF_TrackReferenceTypeBox*)newBox)->reference_type = type; } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) { newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI); if (!newBox) return GF_OUT_OF_MEM; ((GF_ItemReferenceTypeBox*)newBox)->reference_type = type; } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) { newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT); if (!newBox) return GF_OUT_OF_MEM; ((GF_TrackGroupTypeBox*)newBox)->group_type = type; } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) { newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT); if (!newBox) return GF_OUT_OF_MEM; ((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type; } else { //OK, create the box based on the type is_special = GF_FALSE; newBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box); if (!newBox) return GF_OUT_OF_MEM; } //OK, init and read this box if (type==GF_ISOM_BOX_TYPE_UUID && !is_special) { memcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16); ((GF_UUIDBox *)newBox)->internal_4cc = uuid_type; } if (!newBox->type) newBox->type = type; payload_start = gf_bs_get_position(bs); retry_unknown_box: end = gf_bs_available(bs); if (size - hdr_size > end ) { newBox->size = size - hdr_size - end; *outBox = newBox; return GF_ISOM_INCOMPLETE_FILE; } newBox->size = size - hdr_size; if (newBox->size) { e = gf_isom_full_box_read(newBox, bs); if (!e) e = gf_isom_box_read(newBox, bs); newBox->size = size; end = gf_bs_get_position(bs); } else { newBox->size = size; //empty box e = GF_OK; end = gf_bs_get_position(bs); } if (e && (e != GF_ISOM_INCOMPLETE_FILE)) { gf_isom_box_del(newBox); *outBox = NULL; if (parent_type==GF_ISOM_BOX_TYPE_STSD) { newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_UNKNOWN); ((GF_UnknownBox *)newBox)->original_4cc = type; newBox->size = size; gf_bs_seek(bs, payload_start); goto retry_unknown_box; } if (!skip_logs) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Read Box \""%s\"" (start ""LLU"") failed (%s) - skipping\n"", gf_4cc_to_str(type), start, gf_error_to_string(e))); } //we don't try to reparse known boxes that have been failing (too dangerous) return e; } if (end-start > size) { if (!skip_logs) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] Box \""%s\"" size ""LLU"" (start ""LLU"") invalid (read ""LLU"")\n"", gf_4cc_to_str(type), LLU_CAST size, start, LLU_CAST (end-start) )); } /*let's still try to load the file since no error was notified*/ gf_bs_seek(bs, start+size); } else if (end-start < size) { u32 to_skip = (u32) (size-(end-start)); if (!skip_logs) { if ((to_skip!=4) || gf_bs_peek_bits(bs, 32, 0)) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[iso file] Box \""%s\"" (start ""LLU"") has %u extra bytes\n"", gf_4cc_to_str(type), start, to_skip)); } } gf_bs_skip_bytes(bs, to_skip); } *outBox = newBox; return e; }",CWE-476,12 0,"void WebGraphicsContext3DDefaultImpl::unmapTexSubImage2DCHROMIUM(const void* mem) { } ",none,24 0,"void SearchEngineTabHelper::OnPageHasOSDD( const GURL& page_url, const GURL& osdd_url, const search_provider::OSDDType& msg_provider_type) { if (!osdd_url.is_valid() || !osdd_url.SchemeIsHTTPOrHTTPS()) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); if (page_url != web_contents()->GetLastCommittedURL() || !TemplateURLFetcherFactory::GetForProfile(profile) || profile->IsOffTheRecord()) return; TemplateURLFetcher::ProviderType provider_type = (msg_provider_type == search_provider::AUTODETECTED_PROVIDER) ? TemplateURLFetcher::AUTODETECTED_PROVIDER : TemplateURLFetcher::EXPLICIT_PROVIDER; const NavigationController& controller = web_contents()->GetController(); const NavigationEntry* entry = controller.GetLastCommittedEntry(); for (int index = controller.GetLastCommittedEntryIndex(); (index > 0) && IsFormSubmit(entry); entry = controller.GetEntryAtIndex(index)) --index; if (!entry || IsFormSubmit(entry)) return; base::string16 keyword; if (provider_type == TemplateURLFetcher::AUTODETECTED_PROVIDER) { keyword = GenerateKeywordFromNavigationEntry( entry, profile->GetPrefs()->GetString(prefs::kAcceptLanguages)); if (keyword.empty()) return; } TemplateURLFetcherFactory::GetForProfile(profile)->ScheduleDownload( keyword, osdd_url, entry->GetFavicon().url, base::Bind(&AssociateURLFetcherWithWebContents, web_contents()), base::Bind(&SearchEngineTabHelper::OnDownloadedOSDD, weak_ptr_factory_.GetWeakPtr()), provider_type); } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::deleteTexture(unsigned texture) { makeContextCurrent(); glDeleteTextures(1, &texture); } ",none,24 1,"bool initiate_stratum(struct pool *pool) { char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; bool ret = false, recvd = false; json_error_t err; int n2size; if (!setup_stratum_curl(pool)) goto out; resend: if (pool->sessionid) sprintf(s, ""{\""id\"": %d, \""method\"": \""mining.subscribe\"", \""params\"": [\""%s\""]}"", swork_id++, pool->sessionid); else sprintf(s, ""{\""id\"": %d, \""method\"": \""mining.subscribe\"", \""params\"": []}"", swork_id++); if (!__stratum_send(pool, s, strlen(s))) { applog(LOG_DEBUG, ""Failed to send s in initiate_stratum""); goto out; } if (!socket_full(pool, true)) { applog(LOG_DEBUG, ""Timed out waiting for response in initiate_stratum""); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, ""JSON decode failed(%d): %s"", err.line, err.text); goto out; } res_val = json_object_get(val, ""result""); err_val = json_object_get(val, ""error""); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup(""(unknown reason)""); applog(LOG_INFO, ""JSON-RPC decode failed: %s"", ss); free(ss); goto out; } sessionid = json_array_string(json_array_get(res_val, 0), 1); if (!sessionid) { applog(LOG_INFO, ""Failed to get sessionid in initiate_stratum""); goto out; } nonce1 = json_array_string(res_val, 1); if (!nonce1) { applog(LOG_INFO, ""Failed to get nonce1 in initiate_stratum""); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (!n2size) { applog(LOG_INFO, ""Failed to get n2size in initiate_stratum""); free(sessionid); free(nonce1); goto out; } mutex_lock(&pool->pool_lock); pool->sessionid = sessionid; free(pool->nonce1); pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; pool->n2size = n2size; mutex_unlock(&pool->pool_lock); applog(LOG_DEBUG, ""Pool %d stratum session id: %s"", pool->pool_no, pool->sessionid); ret = true; out: if (val) json_decref(val); if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->swork.diff = 1; if (opt_protocol) { applog(LOG_DEBUG, ""Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d"", pool->pool_no, pool->nonce1, pool->n2size); } } else { if (recvd && pool->sessionid) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ mutex_lock(&pool->pool_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; mutex_unlock(&pool->pool_lock); applog(LOG_DEBUG, ""Failed to resume stratum, trying afresh""); goto resend; } applog(LOG_DEBUG, ""Initiate stratum failed""); if (pool->sock != INVSOCK) { shutdown(pool->sock, SHUT_RDWR); pool->sock = INVSOCK; } } return ret; }",CWE-787,16 1,"inline size_t codepoint_length(const char *s8, size_t l) { if (l) { auto b = static_cast(s8[0]); if ((b & 0x80) == 0) { return 1; } else if ((b & 0xE0) == 0xC0) { return 2; } else if ((b & 0xF0) == 0xE0) { return 3; } else if ((b & 0xF8) == 0xF0) { return 4; } } return 0; }",CWE-125,1 1," private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t count = m->str_range; int rv, oneed_separator; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, ""recursion nesting exceeded""); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, count) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, ""mget(type=%d, flag=%x, offset=%u, o=%zu, "" ""nbytes=%zu, count=%u)\n"", m->type, m->flag, offset, o, nbytes, count); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, ""indirect offs=%u\n"", off); } switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (nbytes < (offset + 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[0]<<8)| (p->hs[1])) & off; break; case FILE_OPOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[0]<<8)| (p->hs[1])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[0]<<8)| (p->hs[1])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[0]<<8)| (p->hs[1])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[0]<<8)| (p->hs[1])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[0]<<8)| (p->hs[1])) % off; break; } } else offset = (short)((p->hs[0]<<8)| (p->hs[1])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[1]<<8)| (p->hs[0])) & off; break; case FILE_OPOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[1]<<8)| (p->hs[0])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[1]<<8)| (p->hs[0])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[1]<<8)| (p->hs[0])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[1]<<8)| (p->hs[0])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[1]<<8)| (p->hs[0])) % off; break; } } else offset = (short)((p->hs[1]<<8)| (p->hs[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) % off; break; } } else offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) % off; break; } } else offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) % off; break; } } else offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; } switch (cvt_flip(m->in_type, flip)) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, ""indirect *zero* offset\n""); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, ""indirect +offs=%u\n"", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (nbytes < (offset + 1)) /* should alway be true */ return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (nbytes < (offset + 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (nbytes < (offset + 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (nbytes < (offset + m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, ""indirect @offs=%u[%d]\n"", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, m->desc, offset) == -1) return -1; if (file_printf(ms, ""%s"", rbuf) == -1) return -1; free(rbuf); } return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, ""cannot find entry `%s'"", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, ""%s"", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ default: break; } if (!mconvert(ms, m, flip)) return 0;",CWE-20,3 1,"void ocall_malloc(size_t size, uint8_t **ret) { *ret = static_cast(malloc(size)); }",CWE-787,16 0," void Stop() { EXPECT_CALL(*vc_impl_, StopCapture(capture_client())) .Times(1) .WillOnce(CaptureStopped(capture_client(), vc_impl_.get())); EXPECT_CALL(*vc_manager_, RemoveDevice(_, _)) .WillOnce(Return()); decoder_->Stop(media::NewExpectedClosure()); message_loop_->RunAllPending(); } ",none,24 0,"ACTION(DeleteDataBuffer) { delete[] arg0->memory_pointer; } ",none,24 1,"ms_escher_get_data (MSEscherState *state, gint offset, /* bytes from logical start of the stream */ gint num_bytes, /*how many bytes we want, NOT incl prefix */ gboolean * needs_free) { BiffQuery *q = state->q; guint8 *res; g_return_val_if_fail (offset >= state->start_offset, NULL); /* find the 1st containing record */ while (offset >= state->end_offset) { if (!ms_biff_query_next (q)) { g_warning (""unexpected end of stream;""); return NULL; } if (q->opcode != BIFF_MS_O_DRAWING && q->opcode != BIFF_MS_O_DRAWING_GROUP && q->opcode != BIFF_MS_O_DRAWING_SELECTION && q->opcode != BIFF_CHART_gelframe && q->opcode != BIFF_CONTINUE) { g_warning (""Unexpected record type 0x%x len=0x%x @ 0x%lx;"", q->opcode, q->length, (long)q->streamPos); return NULL; } d (1, g_printerr (""Target is 0x%x bytes at 0x%x, current = 0x%x..0x%x;\n"" ""Adding biff-0x%x of length 0x%x;\n"", num_bytes, offset, state->start_offset, state->end_offset, q->opcode, q->length);); state->start_offset = state->end_offset; state->end_offset += q->length; state->segment_len = q->length; } g_return_val_if_fail (offset >= state->start_offset, NULL); g_return_val_if_fail ((size_t)(offset - state->start_offset) < q->length, NULL); res = q->data + offset - state->start_offset; if ((*needs_free = ((offset + num_bytes) > state->end_offset))) { guint8 *buffer = g_malloc (num_bytes); guint8 *tmp = buffer; /* Setup front stub */ int len = q->length - (res - q->data); int counter = 0; d (1, g_printerr (""MERGE needed (%d) which is >= %d + %d;\n"", num_bytes, offset, state->end_offset);); do { d (1, g_printerr (""record %d) add %d bytes;\n"", ++counter, len);); /* copy necessary portion of current record */ memcpy (tmp, res, len); tmp += len; /* Get next record */ if (!ms_biff_query_next (q)) { g_warning (""unexpected end of stream;""); return NULL; } /* We should only see DRAW records now */ if (q->opcode != BIFF_MS_O_DRAWING && q->opcode != BIFF_MS_O_DRAWING_GROUP && q->opcode != BIFF_MS_O_DRAWING_SELECTION && q->opcode != BIFF_CHART_gelframe && q->opcode != BIFF_CONTINUE) { g_warning (""Unexpected record type 0x%x @ 0x%lx;"", q->opcode, (long)q->streamPos); return NULL; } state->start_offset = state->end_offset; state->end_offset += q->length; state->segment_len = q->length; res = q->data; len = q->length; } while ((num_bytes - (tmp - buffer)) > len); /* Copy back stub */ memcpy (tmp, res, num_bytes - (tmp-buffer)); d (1, g_printerr (""record %d) add %d bytes;\n"", ++counter, num_bytes - (int)(tmp-buffer));); return buffer; } return res; }",CWE-119,0 1,"xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) { xmlChar *encoding = NULL; SKIP_BLANKS; if (CMP8(CUR_PTR, 'e', 'n', 'c', 'o', 'd', 'i', 'n', 'g')) { SKIP(8); SKIP_BLANKS; if (RAW != '=') { xmlFatalErr(ctxt, XML_ERR_EQUAL_REQUIRED, NULL); return(NULL); } NEXT; SKIP_BLANKS; if (RAW == '""') { NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '""') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else if (RAW == '\''){ NEXT; encoding = xmlParseEncName(ctxt); if (RAW != '\'') { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_CLOSED, NULL); xmlFree((xmlChar *) encoding); return(NULL); } else NEXT; } else { xmlFatalErr(ctxt, XML_ERR_STRING_NOT_STARTED, NULL); } /* * Non standard parsing, allowing the user to ignore encoding */ if (ctxt->options & XML_PARSE_IGNORE_ENC) { xmlFree((xmlChar *) encoding); return(NULL); } /* * UTF-16 encoding stwich has already taken place at this stage, * more over the little-endian/big-endian selection is already done */ if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST ""UTF-16"")) || (!xmlStrcasecmp(encoding, BAD_CAST ""UTF16"")))) { /* * If no encoding was passed to the parser, that we are * using UTF-16 and no decoder is present i.e. the * document is apparently UTF-8 compatible, then raise an * encoding mismatch fatal error */ if ((ctxt->encoding == NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING, ""Document labelled UTF-16 but has UTF-8 content\n""); } if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } /* * UTF-8 encoding is handled natively */ else if ((encoding != NULL) && ((!xmlStrcasecmp(encoding, BAD_CAST ""UTF-8"")) || (!xmlStrcasecmp(encoding, BAD_CAST ""UTF8"")))) { if (ctxt->encoding != NULL) xmlFree((xmlChar *) ctxt->encoding); ctxt->encoding = encoding; } else if (encoding != NULL) { xmlCharEncodingHandlerPtr handler; if (ctxt->input->encoding != NULL) xmlFree((xmlChar *) ctxt->input->encoding); ctxt->input->encoding = encoding; handler = xmlFindCharEncodingHandler((const char *) encoding); if (handler != NULL) { xmlSwitchToEncoding(ctxt, handler); } else { xmlFatalErrMsgStr(ctxt, XML_ERR_UNSUPPORTED_ENCODING, ""Unsupported encoding %s\n"", encoding); return(NULL); } } } return(encoding); }",CWE-119,0 1,"multi_process_incoming_link(struct multi_context *m, struct multi_instance *instance, const unsigned int mpp_flags) { struct gc_arena gc = gc_new(); struct context *c; struct mroute_addr src, dest; unsigned int mroute_flags; struct multi_instance *mi; bool ret = true; bool floated = false; if (m->pending) { return true; } if (!instance) { #ifdef MULTI_DEBUG_EVENT_LOOP printf(""TCP/UDP -> TUN [%d]\n"", BLEN(&m->top.c2.buf)); #endif multi_set_pending(m, multi_get_create_instance_udp(m, &floated)); } else { multi_set_pending(m, instance); } if (m->pending) { set_prefix(m->pending); /* get instance context */ c = &m->pending->context; if (!instance) { /* transfer packet pointer from top-level context buffer to instance */ c->c2.buf = m->top.c2.buf; /* transfer from-addr from top-level context buffer to instance */ if (!floated) { c->c2.from = m->top.c2.from; } } if (BLEN(&c->c2.buf) > 0) { struct link_socket_info *lsi; const uint8_t *orig_buf; /* decrypt in instance context */ perf_push(PERF_PROC_IN_LINK); lsi = get_link_socket_info(c); orig_buf = c->c2.buf.data; if (process_incoming_link_part1(c, lsi, floated)) { if (floated) { multi_process_float(m, m->pending); } process_incoming_link_part2(c, lsi, orig_buf); } perf_pop(); if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TUN) { /* extract packet source and dest addresses */ mroute_flags = mroute_extract_addr_from_packet(&src, &dest, NULL, NULL, 0, &c->c2.to_tun, DEV_TYPE_TUN); /* drop packet if extract failed */ if (!(mroute_flags & MROUTE_EXTRACT_SUCCEEDED)) { c->c2.to_tun.len = 0; } /* make sure that source address is associated with this client */ else if (multi_get_instance_by_virtual_addr(m, &src, true) != m->pending) { /* IPv6 link-local address (fe80::xxx)? */ if ( (src.type & MR_ADDR_MASK) == MR_ADDR_IPV6 && IN6_IS_ADDR_LINKLOCAL(&src.v6.addr) ) { /* do nothing, for now. TODO: add address learning */ } else { msg(D_MULTI_DROPPED, ""MULTI: bad source address from client [%s], packet dropped"", mroute_addr_print(&src, &gc)); } c->c2.to_tun.len = 0; } /* client-to-client communication enabled? */ else if (m->enable_c2c) { /* multicast? */ if (mroute_flags & MROUTE_EXTRACT_MCAST) { /* for now, treat multicast as broadcast */ multi_bcast(m, &c->c2.to_tun, m->pending, NULL, 0); } else /* possible client to client routing */ { ASSERT(!(mroute_flags & MROUTE_EXTRACT_BCAST)); mi = multi_get_instance_by_virtual_addr(m, &dest, true); /* if dest addr is a known client, route to it */ if (mi) { #ifdef ENABLE_PF if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi, &mi->context.c2.pf, mi->context.c2.tls_multi, ""tun_c2c"")) { msg(D_PF_DROPPED, ""PF: client -> client[%s] packet dropped by TUN packet filter"", mi_prefix(mi)); } else #endif { multi_unicast(m, &c->c2.to_tun, mi); register_activity(c, BLEN(&c->c2.to_tun)); } c->c2.to_tun.len = 0; } } } #ifdef ENABLE_PF if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &dest, ""tun_dest_addr"")) { msg(D_PF_DROPPED, ""PF: client -> addr[%s] packet dropped by TUN packet filter"", mroute_addr_print_ex(&dest, MAPF_SHOW_ARP, &gc)); c->c2.to_tun.len = 0; } #endif } else if (TUNNEL_TYPE(m->top.c1.tuntap) == DEV_TYPE_TAP) { uint16_t vid = 0; #ifdef ENABLE_PF struct mroute_addr edest; mroute_addr_reset(&edest); #endif if (m->top.options.vlan_tagging) { if (vlan_is_tagged(&c->c2.to_tun)) { /* Drop VLAN-tagged frame. */ msg(D_VLAN_DEBUG, ""dropping incoming VLAN-tagged frame""); c->c2.to_tun.len = 0; } else { vid = c->options.vlan_pvid; } } /* extract packet source and dest addresses */ mroute_flags = mroute_extract_addr_from_packet(&src, &dest, NULL, #ifdef ENABLE_PF &edest, #else NULL, #endif vid, &c->c2.to_tun, DEV_TYPE_TAP); if (mroute_flags & MROUTE_EXTRACT_SUCCEEDED) { if (multi_learn_addr(m, m->pending, &src, 0) == m->pending) { /* check for broadcast */ if (m->enable_c2c) { if (mroute_flags & (MROUTE_EXTRACT_BCAST|MROUTE_EXTRACT_MCAST)) { multi_bcast(m, &c->c2.to_tun, m->pending, NULL, vid); } else /* try client-to-client routing */ { mi = multi_get_instance_by_virtual_addr(m, &dest, false); /* if dest addr is a known client, route to it */ if (mi) { #ifdef ENABLE_PF if (!pf_c2c_test(&c->c2.pf, c->c2.tls_multi, &mi->context.c2.pf, mi->context.c2.tls_multi, ""tap_c2c"")) { msg(D_PF_DROPPED, ""PF: client -> client[%s] packet dropped by TAP packet filter"", mi_prefix(mi)); } else #endif { multi_unicast(m, &c->c2.to_tun, mi); register_activity(c, BLEN(&c->c2.to_tun)); } c->c2.to_tun.len = 0; } } } #ifdef ENABLE_PF if (c->c2.to_tun.len && !pf_addr_test(&c->c2.pf, c, &edest, ""tap_dest_addr"")) { msg(D_PF_DROPPED, ""PF: client -> addr[%s] packet dropped by TAP packet filter"", mroute_addr_print_ex(&edest, MAPF_SHOW_ARP, &gc)); c->c2.to_tun.len = 0; } #endif } else { msg(D_MULTI_DROPPED, ""MULTI: bad source address from client [%s], packet dropped"", mroute_addr_print(&src, &gc)); c->c2.to_tun.len = 0; } } else { c->c2.to_tun.len = 0; } } } /* postprocess and set wakeup */ ret = multi_process_post(m, m->pending, mpp_flags); clear_prefix(); } gc_free(&gc); return ret; }",CWE-476,12 0,"SpeechSynthesisUtterance* SpeechSynthesis::currentSpeechUtterance() const { if (!m_utteranceQueue.isEmpty()) return m_utteranceQueue.first().get(); return 0; } ",none,24 1,"int setup_conds(THD *thd, TABLE_LIST *tables, List &leaves, COND **conds) { SELECT_LEX *select_lex= thd->lex->current_select; TABLE_LIST *table= NULL; // For HP compilers /* it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX which belong to LEX, i.e. most up SELECT) will be updated by INSERT/UPDATE/LOAD NOTE: using this condition helps to prevent call of prepare_check_option() from subquery of VIEW, because tables of subquery belongs to VIEW (see condition before prepare_check_option() call) */ bool it_is_update= (select_lex == thd->lex->first_select_lex()) && thd->lex->which_check_option_applicable(); bool save_is_item_list_lookup= select_lex->is_item_list_lookup; TABLE_LIST *derived= select_lex->master_unit()->derived; DBUG_ENTER(""setup_conds""); select_lex->is_item_list_lookup= 0; thd->column_usage= MARK_COLUMNS_READ; DBUG_PRINT(""info"", (""thd->column_usage: %d"", thd->column_usage)); select_lex->cond_count= 0; select_lex->between_count= 0; select_lex->max_equal_elems= 0; for (table= tables; table; table= table->next_local) { if (select_lex == thd->lex->first_select_lex() && select_lex->first_cond_optimization && table->merged_for_insert && table->prepare_where(thd, conds, FALSE)) goto err_no_arena; } if (*conds) { thd->where=""where clause""; DBUG_EXECUTE(""where"", print_where(*conds, ""WHERE in setup_conds"", QT_ORDINARY);); /* Wrap alone field in WHERE clause in case it will be outer field of subquery which need persistent pointer on it, but conds could be changed by optimizer */ if ((*conds)->type() == Item::FIELD_ITEM && !derived) wrap_ident(thd, conds); (*conds)->mark_as_condition_AND_part(NO_JOIN_NEST); if ((*conds)->fix_fields_if_needed_for_bool(thd, conds)) goto err_no_arena; } /* Apply fix_fields() to all ON clauses at all levels of nesting, including the ones inside view definitions. */ if (setup_on_expr(thd, tables, it_is_update)) goto err_no_arena; if (!thd->stmt_arena->is_conventional()) { /* We are in prepared statement preparation code => we should store WHERE clause changing for next executions. We do this ON -> WHERE transformation only once per PS/SP statement. */ select_lex->where= *conds; } thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup; DBUG_RETURN(thd->is_error()); err_no_arena: select_lex->is_item_list_lookup= save_is_item_list_lookup; DBUG_RETURN(1); }",CWE-416,10 1,"static struct wildmat *split_wildmats(char *str) { const char *prefix; char pattern[MAX_MAILBOX_BUFFER] = """", *p, *c; struct wildmat *wild = NULL; int n = 0; if ((prefix = config_getstring(IMAPOPT_NEWSPREFIX))) snprintf(pattern, sizeof(pattern), ""%s."", prefix); p = pattern + strlen(pattern); /* * split the list of wildmats * * we split them right to left because this is the order in which * we want to test them (per RFC3977 section 4.2) */ do { if ((c = strrchr(str, ','))) *c++ = '\0'; else c = str; if (!(n % 10)) /* alloc some more */ wild = xrealloc(wild, (n + 11) * sizeof(struct wildmat)); if (*c == '!') wild[n].not = 1; /* not */ else if (*c == '@') wild[n].not = -1; /* absolute not (feeding) */ else wild[n].not = 0; strcpy(p, wild[n].not ? c + 1 : c); wild[n++].pat = xstrdup(pattern); } while (c != str); wild[n].pat = NULL; return wild; }",CWE-119,0 1,"rleUncompress (int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -((int)*in++); inLength -= count + 1; if (0 > (maxLength -= count)) return 0; // check the input buffer is big enough to contain // 'count' bytes of remaining data if (inLength < 0) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *(char*)in, count+1); out += count+1; in++; } } return out - outStart; }",CWE-119,0 0,"void ContentSettingsStore::UnregisterExtension( const std::string& ext_id) { bool notify = false; bool notify_incognito = false; { base::AutoLock lock(lock_); ExtensionEntryMap::iterator i = FindEntry(ext_id); if (i == entries_.end()) return; notify = !i->second->settings.empty(); notify_incognito = !i->second->incognito_persistent_settings.empty() || !i->second->incognito_session_only_settings.empty(); delete i->second; entries_.erase(i); } if (notify) NotifyOfContentSettingChanged(ext_id, false); if (notify_incognito) NotifyOfContentSettingChanged(ext_id, true); } ",none,24 1,"static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, ""s#nO!s#s#"", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple""); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple of size 3""); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)""); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (underflow)""); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; }",CWE-787,16 1," void ValidateInputs(OpKernelContext* ctx, const CSRSparseMatrix& sparse_matrix, const Tensor& permutation_indices, int* batch_size, int64* num_rows) { OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum::value, errors::InvalidArgument( ""Asked for a CSRSparseMatrix of type "", DataTypeString(DataTypeToEnum::value), "" but saw dtype: "", DataTypeString(sparse_matrix.dtype()))); const Tensor& dense_shape = sparse_matrix.dense_shape(); const int rank = dense_shape.dim_size(0); OP_REQUIRES(ctx, rank == 2 || rank == 3, errors::InvalidArgument(""sparse matrix must have rank 2 or 3; "", ""but dense_shape has size "", rank)); const int row_dim = (rank == 2) ? 0 : 1; auto dense_shape_vec = dense_shape.vec(); *num_rows = dense_shape_vec(row_dim); const int64 num_cols = dense_shape_vec(row_dim + 1); OP_REQUIRES(ctx, *num_rows == num_cols, errors::InvalidArgument(""sparse matrix must be square; got: "", *num_rows, "" != "", num_cols)); const TensorShape& perm_shape = permutation_indices.shape(); OP_REQUIRES( ctx, perm_shape.dims() + 1 == rank, errors::InvalidArgument( ""sparse matrix must have the same rank as permutation; got: "", rank, "" != "", perm_shape.dims(), "" + 1."")); OP_REQUIRES( ctx, perm_shape.dim_size(rank - 2) == *num_rows, errors::InvalidArgument( ""permutation must have the same number of elements in each batch "" ""as the number of rows in sparse matrix; got: "", perm_shape.dim_size(rank - 2), "" != "", *num_rows)); *batch_size = sparse_matrix.batch_size(); if (*batch_size > 1) { OP_REQUIRES( ctx, perm_shape.dim_size(0) == *batch_size, errors::InvalidArgument(""permutation must have the same batch size "" ""as sparse matrix; got: "", perm_shape.dim_size(0), "" != "", *batch_size)); } }",CWE-476,12 1,"rndr_quote(struct buf *ob, const struct buf *text, void *opaque) { if (!text || !text->size) return 0; BUFPUTSL(ob, """"); bufput(ob, text->data, text->size); BUFPUTSL(ob, """"); return 1; }",CWE-79,17 0,"ContentSettingsStore::FindEntry(const std::string& ext_id) { ExtensionEntryMap::iterator i; for (i = entries_.begin(); i != entries_.end(); ++i) { if (i->second->id == ext_id) return i; } return entries_.end(); } ",none,24 1,"static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; }",CWE-125,1 0,"void WebGraphicsContext3DDefaultImpl::getIntegerv(unsigned long pname, int* value) { makeContextCurrent(); switch (pname) { case IMPLEMENTATION_COLOR_READ_FORMAT: *value = GL_RGB; break; case IMPLEMENTATION_COLOR_READ_TYPE: *value = GL_UNSIGNED_BYTE; break; case MAX_FRAGMENT_UNIFORM_VECTORS: glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, value); *value /= 4; break; case MAX_VERTEX_UNIFORM_VECTORS: glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, value); *value /= 4; break; case MAX_VARYING_VECTORS: glGetIntegerv(GL_MAX_VARYING_FLOATS, value); *value /= 4; break; default: glGetIntegerv(pname, value); } } ",none,24 1,"open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred) { SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; int n, finished = 0; X509_VERIFY_PARAM *param; uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode; if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method()))) { rfbClientLog(""Could not create new SSL context.\n""); return NULL; } param = X509_VERIFY_PARAM_new(); /* Setup verification if not anonymous */ if (!anonTLS) { if (cred->x509Credential.x509CACertFile) { if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL)) { rfbClientLog(""Failed to load CA certificate from %s.\n"", cred->x509Credential.x509CACertFile); goto error_free_ctx; } } else { rfbClientLog(""Using default paths for certificate verification.\n""); SSL_CTX_set_default_verify_paths (ssl_ctx); } if (cred->x509Credential.x509CACrlFile) { if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx)) { rfbClientLog(""CRLs could not be loaded.\n""); goto error_free_ctx; } if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll; } if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile) { if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1) { rfbClientLog(""Client certificate could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile, SSL_FILETYPE_PEM) != 1) { rfbClientLog(""Client private key could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_check_private_key(ssl_ctx) == 0) { rfbClientLog(""Client certificate and private key do not match.\n""); goto error_free_ctx; } } SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); if (verify_crls == rfbX509CrlVerifyClient) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK); else if (verify_crls == rfbX509CrlVerifyAll) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost))) { rfbClientLog(""Could not set server name for verification.\n""); goto error_free_ctx; } SSL_CTX_set1_param(ssl_ctx, param); } if (!(ssl = SSL_new (ssl_ctx))) { rfbClientLog(""Could not create a new SSL session.\n""); goto error_free_ctx; } /* TODO: finetune this list, take into account anonTLS bool */ SSL_set_cipher_list(ssl, ""ALL""); SSL_set_fd (ssl, sockfd); SSL_CTX_set_app_data (ssl_ctx, client); do { n = SSL_connect(ssl); if (n != 1) { if (wait_for_data(ssl, n, 1) != 1) { finished = 1; SSL_shutdown(ssl); goto error_free_ssl; } } } while( n != 1 && finished != 1 ); X509_VERIFY_PARAM_free(param); return ssl; error_free_ssl: SSL_free(ssl); error_free_ctx: X509_VERIFY_PARAM_free(param); SSL_CTX_free(ssl_ctx); return NULL; }",CWE-476,12 0,"void ContentSettingsStore::AddObserver(Observer* observer) { DCHECK(OnCorrectThread()); observers_.AddObserver(observer); } ",none,24 0,"void SpeechSynthesis::startSpeakingImmediately() { SpeechSynthesisUtterance* utterance = currentSpeechUtterance(); ASSERT(utterance); utterance->setStartTime(monotonicallyIncreasingTime()); m_isPaused = false; m_platformSpeechSynthesizer->speak(utterance->platformUtterance()); } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::activeTexture(unsigned long texture) { if (texture < GL_TEXTURE0 || texture > GL_TEXTURE0+32) return; makeContextCurrent(); glActiveTexture(texture); } ",none,24 1,"Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) { Sfdouble_t d; char *last; if (*str == 0) { if (ptr) *ptr = (char *)str; return 0; } errno = 0; d = number(str, &last, shp->inarith ? 0 : 10, NULL); if (*last) { if (*last != '.' || last[1] != '.') { d = strval(shp, str, &last, arith, mode); Varsubscript = true; } if (!ptr && *last && mode > 0) errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str); } else if (!d && *str == '-') { d = -0.0; } if (ptr) *ptr = last; return d; }",CWE-77,14 0,"static int createTextureObject(GLenum target) { GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(target, texture); glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); return texture; } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::isGLES2NPOTStrict() { return false; } ",none,24 1,"static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, ""Missing channel list.\n""); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, ""Compression %d"", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, ""Wrong or missing size information.\n""); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, ""recreating invalid scanline offset table\n""); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < s->ymin; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; }",CWE-787,16 1,"escape_xml(const char *text) { static char *escaped; static size_t escaped_size; char *out; size_t len; for (out=escaped, len=0; *text; ++len, ++out, ++text) { /* Make sure there's plenty of room for a quoted character */ if ((len + 8) > escaped_size) { char *bigger_escaped; escaped_size += 128; bigger_escaped = realloc(escaped, escaped_size); if (!bigger_escaped) { free(escaped); /* avoid leaking memory */ escaped = NULL; escaped_size = 0; /* Error string is cleverly chosen to fail XML validation */ return "">>> out of memory <<<""; } out = bigger_escaped + len; escaped = bigger_escaped; } switch (*text) { case '&': strcpy(out, ""&""); len += strlen(out) - 1; out = escaped + len; break; case '<': strcpy(out, ""<""); len += strlen(out) - 1; out = escaped + len; break; case '>': strcpy(out, "">""); len += strlen(out) - 1; out = escaped + len; break; default: *out = *text; break; } } *out = '\x0'; /* NUL terminate the string */ return escaped; }",CWE-476,12 0,"DataObjectItem* DataObjectItem::CreateFromString(const String& type, const String& data) { DataObjectItem* item = MakeGarbageCollected(kStringKind, type); item->data_ = data; return item; } ",none,24 1," size_t recv_body(char* buf, size_t max) override { auto& message = parser.get(); auto& body_remaining = message.body(); body_remaining.data = buf; body_remaining.size = max; while (body_remaining.size && !parser.is_done()) { boost::system::error_code ec; http::async_read_some(stream, buffer, parser, yield[ec]); if (ec == http::error::partial_message || ec == http::error::need_buffer) { break; } if (ec) { ldout(cct, 4) << ""failed to read body: "" << ec.message() << dendl; throw rgw::io::Exception(ec.value(), std::system_category()); } } return max - body_remaining.size; }",CWE-400,9 1,"static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { #ifndef PB_ENABLE_MALLOC PB_UNUSED(wire_type); PB_UNUSED(iter); PB_RETURN_ERROR(stream, ""no malloc support""); #else pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: case PB_HTYPE_ONEOF: if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && *(void**)iter->pData != NULL) { /* Duplicate field, have to release the old allocation first. */ pb_release_single_field(iter); } if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)iter->pSize = iter->pos->tag; } if (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES) { return func(stream, iter->pos, iter->pData); } else { if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) return false; initialize_pointer_field(*(void**)iter->pData, iter); return func(stream, iter->pos, *(void**)iter->pData); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; pb_size_t *size = (pb_size_t*)iter->pSize; size_t allocated_size = *size; void *pItem; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if ((size_t)*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ pItem = *(char**)iter->pData + iter->pos->data_size * (*size); initialize_pointer_field(pItem, iter); if (!func(&substream, iter->pos, pItem)) { status = false; break; } if (*size == PB_SIZE_MAX) { #ifndef PB_NO_ERRMSG stream->errmsg = ""too many array entries""; #endif status = false; break; } (*size)++; } if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Normal repeated field, i.e. only one item at a time. */ pb_size_t *size = (pb_size_t*)iter->pSize; void *pItem; if (*size == PB_SIZE_MAX) PB_RETURN_ERROR(stream, ""too many array entries""); (*size)++; if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size)) return false; pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1); initialize_pointer_field(pItem, iter); return func(stream, iter->pos, pItem); } default: PB_RETURN_ERROR(stream, ""invalid field type""); } #endif }",CWE-125,1 0,"int WebGraphicsContext3DDefaultImpl::sizeInBytes(int type) { switch (type) { case GL_BYTE: return sizeof(GLbyte); case GL_UNSIGNED_BYTE: return sizeof(GLubyte); case GL_SHORT: return sizeof(GLshort); case GL_UNSIGNED_SHORT: return sizeof(GLushort); case GL_INT: return sizeof(GLint); case GL_UNSIGNED_INT: return sizeof(GLuint); case GL_FLOAT: return sizeof(GLfloat); } return 0; } ",none,24 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); if (!dec->image->cmprof_) { jas_iccprof_destroy(iccprof); goto error; } 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) { if (!pclrd->numlutents) { goto error; } lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); if (!lutents) { goto error; } 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)); } #else /* suppress -Wunused-but-set-variable */ (void)cdefd; #endif } else { jas_eprintf(""error: invalid MTYP in CMAP box\n""); goto error; } } } /* 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->cdef->data.cdef.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,"void ContentSettingsStore::NotifyOfContentSettingChanged( const std::string& extension_id, bool incognito) { FOR_EACH_OBSERVER( ContentSettingsStore::Observer, observers_, OnContentSettingChanged(extension_id, incognito)); } ",none,24 1,"p11_rpc_buffer_get_byte_array (p11_buffer *buf, size_t *offset, const unsigned char **data, size_t *length) { size_t off = *offset; uint32_t len; if (!p11_rpc_buffer_get_uint32 (buf, &off, &len)) return false; if (len == 0xffffffff) { *offset = off; if (data) *data = NULL; if (length) *length = 0; return true; } else if (len >= 0x7fffffff) { p11_buffer_fail (buf); return false; } if (buf->len < len || *offset > buf->len - len) { p11_buffer_fail (buf); return false; } if (data) *data = (unsigned char *)buf->data + off; if (length) *length = len; *offset = off + len; return true; }",CWE-125,1 0,"bool DataObjectItem::HasFileSystemId() const { return kind_ == kFileKind && !file_system_id_.IsEmpty(); } ",none,24 1,"static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32) && (npages - i) >= HPAGE_PMD_NR) { for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while ((npages - i) >= HPAGE_PMD_NR) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); }",CWE-125,1 0," virtual ~EmbeddedWorkerBrowserTest() {} ",none,24 1,"static void gprinter_free(struct usb_function *f) { struct printer_dev *dev = func_to_printer(f); struct f_printer_opts *opts; opts = container_of(f->fi, struct f_printer_opts, func_inst); kfree(dev); mutex_lock(&opts->lock); --opts->refcnt; mutex_unlock(&opts->lock); }",CWE-416,10 1,"PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector, MessageWriter *input, MessageReader *output) { int ret; UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance(); SgxParams *const sgx_params = reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams))); Cleanup clean_up( [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); }); sgx_params->input_size = 0; sgx_params->input = nullptr; if (input) { sgx_params->input_size = input->MessageSize(); if (sgx_params->input_size > 0) { // Allocate and copy data to |input_buffer|. sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size); input->Serialize(const_cast(sgx_params->input)); } } sgx_params->output_size = 0; sgx_params->output = nullptr; CHECK_OCALL( ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params)); if (sgx_params->input) { untrusted_cache->Free(const_cast(sgx_params->input)); } if (sgx_params->output) { // For the results obtained in |output_buffer|, copy them to |output| // before freeing the buffer. output->Deserialize(sgx_params->output, sgx_params->output_size); TrustedPrimitives::UntrustedLocalFree(sgx_params->output); } return PrimitiveStatus::OkStatus(); }",CWE-125,1 1,"vq_endchains(struct virtio_vq_info *vq, int used_all_avail) { struct virtio_base *base; uint16_t event_idx, new_idx, old_idx; int intr; /* * Interrupt generation: if we're using EVENT_IDX, * interrupt if we've crossed the event threshold. * Otherwise interrupt is generated if we added ""used"" entries, * but suppressed by VRING_AVAIL_F_NO_INTERRUPT. * * In any case, though, if NOTIFY_ON_EMPTY is set and the * entire avail was processed, we need to interrupt always. */ atomic_thread_fence(); base = vq->base; old_idx = vq->save_used; vq->save_used = new_idx = vq->used->idx; if (used_all_avail && (base->negotiated_caps & (1 << VIRTIO_F_NOTIFY_ON_EMPTY))) intr = 1; else if (base->negotiated_caps & (1 << VIRTIO_RING_F_EVENT_IDX)) { event_idx = VQ_USED_EVENT_IDX(vq); /* * This calculation is per docs and the kernel * (see src/sys/dev/virtio/virtio_ring.h). */ intr = (uint16_t)(new_idx - event_idx - 1) < (uint16_t)(new_idx - old_idx); } else { intr = new_idx != old_idx && !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT); } if (intr) vq_interrupt(base, vq); }",CWE-476,12 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; 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) { ldout(s->cct, 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) { ldout(s->cct, 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); 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) { 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) { ldout(s->cct,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,"void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source TSRMLS_DC) { void **old_p, *retval; if (zend_hash_index_find(&xlat_table, (ulong)source, (void **)&old_p) == SUCCESS) { /* we already duplicated this pointer */ return *old_p; } retval = ZCG(mem);; ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { interned_efree((char*)source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; }",CWE-416,10 0,"void SpeechSynthesis::trace(Visitor* visitor) { visitor->trace(m_voiceList); visitor->trace(m_utteranceQueue); } ",none,24 1,"static int download(struct SPDBDownloader *pd) { SPDBDownloaderOpt *opt = pd->opt; char *curl_cmd = NULL; char *extractor_cmd = NULL; char *abspath_to_archive = NULL; char *abspath_to_file = NULL; char *archive_name = NULL; size_t archive_name_len = 0; char *symbol_store_path = NULL; char *dbg_file = NULL; char *guid = NULL; char *archive_name_escaped = NULL; char *user_agent = NULL; char *symbol_server = NULL; int res = 0; int cmd_ret; if (!opt->dbg_file || !*opt->dbg_file) { // no pdb debug file return 0; } if (!checkCurl ()) { return 0; } // dbg_file len is > 0 archive_name_len = strlen (opt->dbg_file); archive_name = malloc (archive_name_len + 1); if (!archive_name) { return 0; } memcpy (archive_name, opt->dbg_file, archive_name_len + 1); archive_name[archive_name_len - 1] = '_'; symbol_store_path = r_str_escape (opt->symbol_store_path); dbg_file = r_str_escape (opt->dbg_file); guid = r_str_escape (opt->guid); archive_name_escaped = r_str_escape (archive_name); user_agent = r_str_escape (opt->user_agent); symbol_server = r_str_escape (opt->symbol_server); abspath_to_archive = r_str_newf (""%s%s%s%s%s%s%s"", symbol_store_path, R_SYS_DIR, dbg_file, R_SYS_DIR, guid, R_SYS_DIR, archive_name_escaped); abspath_to_file = strdup (abspath_to_archive); abspath_to_file[strlen (abspath_to_file) - 1] = 'b'; if (r_file_exists (abspath_to_file)) { eprintf (""File already downloaded.\n""); R_FREE (user_agent); R_FREE (abspath_to_archive); R_FREE (archive_name_escaped); R_FREE (symbol_store_path); R_FREE (dbg_file); R_FREE (guid); R_FREE (archive_name); R_FREE (abspath_to_file); R_FREE (symbol_server); return 1; } if (checkExtract () || opt->extract == 0) { res = 1; curl_cmd = r_str_newf (""curl -sfLA \""%s\"" \""%s/%s/%s/%s\"" --create-dirs -o \""%s\"""", user_agent, symbol_server, dbg_file, guid, archive_name_escaped, abspath_to_archive); #if __WINDOWS__ const char *cabextractor = ""expand""; const char *format = ""%s %s %s""; // extractor_cmd -> %1 %2 %3 // %1 - 'expand' // %2 - absolute path to archive // %3 - absolute path to file that will be dearchive extractor_cmd = r_str_newf (format, cabextractor, abspath_to_archive, abspath_to_file); #else const char *cabextractor = ""cabextract""; const char *format = ""%s -d \""%s\"" \""%s\""""; char *abspath_to_dir = r_file_dirname (abspath_to_archive); // cabextract -d %1 %2 // %1 - path to directory where to extract all files from cab archive // %2 - absolute path to cab archive extractor_cmd = r_str_newf (format, cabextractor, abspath_to_dir, abspath_to_archive); R_FREE (abspath_to_dir); #endif eprintf (""Attempting to download compressed pdb in %s\n"", abspath_to_archive); if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) { eprintf(""curl exited with error %d\n"", cmd_ret); res = 0; } eprintf (""Attempting to decompress pdb\n""); if (opt->extract > 0) { if (res && ((cmd_ret = r_sys_cmd (extractor_cmd)) != 0)) { eprintf (""cab extractor exited with error %d\n"", cmd_ret); res = 0; } r_file_rm (abspath_to_archive); } R_FREE (curl_cmd); } if (res == 0) { eprintf (""Falling back to uncompressed pdb\n""); res = 1; archive_name_escaped[strlen (archive_name_escaped) - 1] = 'b'; curl_cmd = r_str_newf (""curl -sfLA \""%s\"" \""%s/%s/%s/%s\"" --create-dirs -o \""%s\"""", opt->user_agent, opt->symbol_server, opt->dbg_file, opt->guid, archive_name_escaped, abspath_to_file); eprintf (""Attempting to download uncompressed pdb in %s\n"", abspath_to_file); if ((cmd_ret = r_sys_cmd (curl_cmd) != 0)) { eprintf(""curl exited with error %d\n"", cmd_ret); res = 0; } R_FREE (curl_cmd); } R_FREE (abspath_to_archive); R_FREE (abspath_to_file); R_FREE (archive_name); R_FREE (extractor_cmd); R_FREE (symbol_store_path); R_FREE (dbg_file); R_FREE (guid); R_FREE (archive_name_escaped); R_FREE (user_agent); R_FREE (symbol_server); return res; }",CWE-78,15 1,"static void suboption(struct Curl_easy *data) { struct curl_slist *v; unsigned char temp[2048]; ssize_t bytes_written; size_t len; int err; char varname[128] = """"; char varval[128] = """"; struct TELNET *tn = data->req.p.telnet; struct connectdata *conn = data->conn; printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2); switch(CURL_SB_GET(tn)) { case CURL_TELOPT_TTYPE: len = strlen(tn->subopt_ttype) + 4 + 2; msnprintf((char *)temp, sizeof(temp), ""%c%c%c%c%s%c%c"", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE, CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE); bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,""Sending data failed (%d)"",err); } printsub(data, '>', &temp[2], len-2); break; case CURL_TELOPT_XDISPLOC: len = strlen(tn->subopt_xdisploc) + 4 + 2; msnprintf((char *)temp, sizeof(temp), ""%c%c%c%c%s%c%c"", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC, CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE); bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,""Sending data failed (%d)"",err); } printsub(data, '>', &temp[2], len-2); break; case CURL_TELOPT_NEW_ENVIRON: msnprintf((char *)temp, sizeof(temp), ""%c%c%c%c"", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON, CURL_TELQUAL_IS); len = 4; for(v = tn->telnet_vars; v; v = v->next) { size_t tmplen = (strlen(v->data) + 1); /* Add the variable only if it fits */ if(len + tmplen < (int)sizeof(temp)-6) { if(sscanf(v->data, ""%127[^,],%127s"", varname, varval)) { msnprintf((char *)&temp[len], sizeof(temp) - len, ""%c%s%c%s"", CURL_NEW_ENV_VAR, varname, CURL_NEW_ENV_VALUE, varval); len += tmplen; } } } msnprintf((char *)&temp[len], sizeof(temp) - len, ""%c%c"", CURL_IAC, CURL_SE); len += 2; bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,""Sending data failed (%d)"",err); } printsub(data, '>', &temp[2], len-2); break; } return; }",CWE-200,4 1,"_eddsa_hash (const struct ecc_modulo *m, mp_limb_t *rp, size_t digest_size, const uint8_t *digest) { mp_size_t nlimbs = (8*digest_size + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS; mpn_set_base256_le (rp, nlimbs, digest, digest_size); if (nlimbs > 2*m->size) { /* Special case for Ed448: reduce rp to 2*m->size limbs. After decoding rp from a hash of size 2*rn: rp = r2 || r1 || r0 where r0 and r1 have m->size limbs. Reduce this to: rp = r1' || r0 where r1' has m->size limbs. */ mp_limb_t hi = rp[2*m->size]; assert (nlimbs == 2*m->size + 1); hi = mpn_addmul_1 (rp + m->size, m->B, m->size, hi); assert (hi <= 1); hi = mpn_cnd_add_n (hi, rp + m->size, rp + m->size, m->B, m->size); assert (hi == 0); } m->mod (m, rp, rp); }",CWE-787,16 1,"int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char buf[512], *actual_alias = NULL, *p; phar_entry_info entry = {0}; size_t pos = 0, read, totalsize; tar_header *hdr; php_uint32 sum1, sum2, size, old; phar_archive_data *myphar, **actual; int last_was_longlink = 0; if (error) { *error = NULL; } php_stream_seek(fp, 0, SEEK_END); totalsize = php_stream_tell(fp); php_stream_seek(fp, 0, SEEK_SET); read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is not a tar file or is truncated"", fname); } php_stream_close(fp); return FAILURE; } hdr = (tar_header*)buf; old = (memcmp(hdr->magic, ""ustar"", sizeof(""ustar"")-1) != 0); myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); myphar->is_persistent = PHAR_G(persist); /* estimate number of entries, can't be certain with tar files */ zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11), zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); myphar->is_tar = 1; /* remember whether this entire phar was compressed with gz/bzip2 */ myphar->flags = compression; entry.is_tar = 1; entry.is_crc_checked = 1; entry.phar = myphar; pos += sizeof(buf); do { phar_entry_info *newentry; pos = php_stream_tell(fp); hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } memset(hdr->checksum, ' ', sizeof(hdr->checksum)); sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header)); size = entry.uncompressed_filesize = entry.compressed_filesize = phar_tar_number(hdr->size, sizeof(hdr->size)); /* skip global/file headers (pax) */ if (!old && (hdr->typeflag == TAR_GLOBAL_HDR || hdr->typeflag == TAR_FILE_HDR)) { size = (size+511)&~511; goto next; } if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof("".phar/signature.bin"")-1 && !strncmp(hdr->name, "".phar/signature.bin"", sizeof("".phar/signature.bin"")-1)) { off_t curloc; if (size > 511) { if (error) { spprintf(error, 4096, ""phar error: tar-based phar \""%s\"" has signature that is larger than 511 bytes, cannot process"", fname); } bail: php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } curloc = php_stream_tell(fp); read = php_stream_read(fp, buf, size); if (read != size) { if (error) { spprintf(error, 4096, ""phar error: tar-based phar \""%s\"" signature cannot be read"", fname); } goto bail; } #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer) \ (((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0])) #else # define PHAR_GET_32(buffer) (php_uint32) *(buffer) #endif myphar->sig_flags = PHAR_GET_32(buf); if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 4096, ""phar error: tar-based phar \""%s\"" signature cannot be verified: %s"", fname, save); efree(save); } goto bail; } php_stream_seek(fp, curloc + 512, SEEK_SET); /* signature checked out, let's ensure this is the last file in the phar */ if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, 512, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } if (error) { spprintf(error, 4096, ""phar error: \""%s\"" has entries after signature, invalid phar"", fname); } goto bail; } if (!last_was_longlink && hdr->typeflag == 'L') { last_was_longlink = 1; /* support the ././@LongLink system for storing long filenames */ entry.filename_len = entry.uncompressed_filesize; /* Check for overflow - bug 61065 */ if (entry.filename_len == UINT_MAX) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (invalid entry size)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent); read = php_stream_read(fp, entry.filename, entry.filename_len); if (read != entry.filename_len) { efree(entry.filename); if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename[entry.filename_len] = '\0'; /* skip blank stuff */ size = ((size+511)&~511) - size; /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { efree(entry.filename); if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { efree(entry.filename); if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } continue; } else if (!last_was_longlink && !old && hdr->prefix[0] != 0) { char name[256]; int i, j; for (i = 0; i < 155; i++) { name[i] = hdr->prefix[i]; if (name[i] == '\0') { break; } } name[i++] = '/'; for (j = 0; j < 100; j++) { name[i+j] = hdr->name[j]; if (name[i+j] == '\0') { break; } } entry.filename_len = i+j; if (name[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename_len--; } entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent); } else if (!last_was_longlink) { int i; /* calculate strlen, which can be no longer than 100 */ for (i = 0; i < 100; i++) { if (hdr->name[i] == '\0') { break; } } entry.filename_len = i; entry.filename = pestrndup(hdr->name, i, myphar->is_persistent); if (i > 0 && entry.filename[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename[entry.filename_len - 1] = '\0'; entry.filename_len--; } } last_was_longlink = 0; phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC); if (sum1 != sum2) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (checksum mismatch of file \""%s\"")"", fname, entry.filename); } pefree(entry.filename, myphar->is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag); entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */ entry.fp_type = PHAR_FP; entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK; entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime)); entry.is_persistent = myphar->is_persistent; #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) { entry.tar_type = TAR_DIR; } if (entry.tar_type == TAR_DIR) { entry.is_dir = 1; } else { entry.is_dir = 0; } entry.link = NULL; if (entry.tar_type == TAR_LINK) { if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file - hard link to non-existent file \""%s\"""", fname, hdr->linkname); } pefree(entry.filename, entry.is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.link = estrdup(hdr->linkname); } else if (entry.tar_type == TAR_SYMLINK) { entry.link = estrdup(hdr->linkname); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry); if (entry.is_persistent) { ++entry.manifest_pos; } if (entry.filename_len >= sizeof("".phar/.metadata"")-1 && !memcmp(entry.filename, "".phar/.metadata"", sizeof("".phar/.metadata"")-1)) { if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) { if (error) { spprintf(error, 4096, ""phar error: tar-based phar \""%s\"" has invalid metadata in magic file \""%s\"""", fname, entry.filename); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } if (!actual_alias && entry.filename_len == sizeof("".phar/alias.txt"")-1 && !strncmp(entry.filename, "".phar/alias.txt"", sizeof("".phar/alias.txt"")-1)) { /* found explicit alias */ if (size > 511) { if (error) { spprintf(error, 4096, ""phar error: tar-based phar \""%s\"" has alias that is larger than 511 bytes, cannot process"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, size); if (read == size) { buf[size] = '\0'; if (!phar_validate_alias(buf, size)) { if (size > 50) { buf[50] = '.'; buf[51] = '.'; buf[52] = '.'; buf[53] = '\0'; } if (error) { spprintf(error, 4096, ""phar error: invalid alias \""%s\"" in tar-based phar \""%s\"""", buf, fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } actual_alias = pestrndup(buf, size, myphar->is_persistent); myphar->alias = actual_alias; myphar->alias_len = size; php_stream_seek(fp, pos, SEEK_SET); } else { if (error) { spprintf(error, 4096, ""phar error: Unable to read alias from tar-based phar \""%s\"""", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } size = (size+511)&~511; if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { next: /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, ""phar error: \""%s\"" is a corrupted tar file (truncated)"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } while (read != 0); if (zend_hash_exists(&(myphar->manifest), "".phar/stub.php"", sizeof("".phar/stub.php"")-1)) { myphar->is_data = 0; } else { myphar->is_data = 1; } /* ensure signature set */ if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) { php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); if (error) { spprintf(error, 0, ""tar-based phar \""%s\"" does not have a signature"", fname); } return FAILURE; } myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(myphar->fname, fname_len); #endif myphar->fname_len = fname_len; myphar->fp = fp; p = strrchr(myphar->fname, '/'); if (p) { myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p); if (myphar->ext == p) { myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1); } if (myphar->ext) { myphar->ext_len = (myphar->fname + fname_len) - myphar->ext; } } phar_request_initialize(TSRMLS_C); if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) { if (error) { spprintf(error, 4096, ""phar error: Unable to add tar-based phar \""%s\"" to phar registry"", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } myphar = *actual; if (actual_alias) { phar_archive_data **fd_ptr; myphar->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, ""phar error: Unable to add tar-based phar \""%s\"", alias is already in use"", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, ""phar error: Unable to add tar-based phar \""%s\"", alias is already in use"", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent); myphar->alias_len = alias_len; } else { myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent); myphar->alias_len = fname_len; } myphar->is_temporary_alias = 1; } if (pphar) { *pphar = myphar; } return SUCCESS; }",CWE-119,0 1,"long keyctl_session_to_parent(void) { #ifdef TIF_NOTIFY_RESUME struct task_struct *me, *parent; const struct cred *mycred, *pcred; struct cred *cred, *oldcred; key_ref_t keyring_r; int ret; keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK); if (IS_ERR(keyring_r)) return PTR_ERR(keyring_r); /* our parent is going to need a new cred struct, a new tgcred struct * and new security data, so we allocate them here to prevent ENOMEM in * our parent */ ret = -ENOMEM; cred = cred_alloc_blank(); if (!cred) goto error_keyring; cred->tgcred->session_keyring = key_ref_to_ptr(keyring_r); keyring_r = NULL; me = current; write_lock_irq(&tasklist_lock); parent = me->real_parent; ret = -EPERM; /* the parent mustn't be init and mustn't be a kernel thread */ if (parent->pid <= 1 || !parent->mm) goto not_permitted; /* the parent must be single threaded */ if (!thread_group_empty(parent)) goto not_permitted; /* the parent and the child must have different session keyrings or * there's no point */ mycred = current_cred(); pcred = __task_cred(parent); if (mycred == pcred || mycred->tgcred->session_keyring == pcred->tgcred->session_keyring) goto already_same; /* the parent must have the same effective ownership and mustn't be * SUID/SGID */ if (pcred->uid != mycred->euid || pcred->euid != mycred->euid || pcred->suid != mycred->euid || pcred->gid != mycred->egid || pcred->egid != mycred->egid || pcred->sgid != mycred->egid) goto not_permitted; /* the keyrings must have the same UID */ if (pcred->tgcred->session_keyring->uid != mycred->euid || mycred->tgcred->session_keyring->uid != mycred->euid) goto not_permitted; /* if there's an already pending keyring replacement, then we replace * that */ oldcred = parent->replacement_session_keyring; /* the replacement session keyring is applied just prior to userspace * restarting */ parent->replacement_session_keyring = cred; cred = NULL; set_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME); write_unlock_irq(&tasklist_lock); if (oldcred) put_cred(oldcred); return 0; already_same: ret = 0; not_permitted: write_unlock_irq(&tasklist_lock); put_cred(cred); return ret; error_keyring: key_ref_put(keyring_r); return ret; #else /* !TIF_NOTIFY_RESUME */ /* * To be removed when TIF_NOTIFY_RESUME has been implemented on * m68k/xtensa */ #warning TIF_NOTIFY_RESUME not implemented return -EOPNOTSUPP; #endif /* !TIF_NOTIFY_RESUME */ }",CWE-476,12 0," MockVideoCaptureImpl(const media::VideoCaptureSessionId id, scoped_refptr ml_proxy, VideoCaptureMessageFilter* filter) : VideoCaptureImpl(id, ml_proxy, filter) { } ",none,24 1,"hivex_open (const char *filename, int flags) { hive_h *h = NULL; assert (sizeof (struct ntreg_header) == 0x1000); assert (offsetof (struct ntreg_header, csum) == 0x1fc); h = calloc (1, sizeof *h); if (h == NULL) goto error; h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK; const char *debug = getenv (""HIVEX_DEBUG""); if (debug && STREQ (debug, ""1"")) h->msglvl = 2; DEBUG (2, ""created handle %p"", h); h->writable = !!(flags & HIVEX_OPEN_WRITE); h->unsafe = !!(flags & HIVEX_OPEN_UNSAFE); h->filename = strdup (filename); if (h->filename == NULL) goto error; #ifdef O_CLOEXEC h->fd = open (filename, O_RDONLY | O_CLOEXEC | O_BINARY); #else h->fd = open (filename, O_RDONLY | O_BINARY); #endif if (h->fd == -1) goto error; #ifndef O_CLOEXEC fcntl (h->fd, F_SETFD, FD_CLOEXEC); #endif struct stat statbuf; if (fstat (h->fd, &statbuf) == -1) goto error; h->size = statbuf.st_size; if (h->size < 0x2000) { SET_ERRNO (EINVAL, ""%s: file is too small to be a Windows NT Registry hive file"", filename); goto error; } if (!h->writable) { h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0); if (h->addr == MAP_FAILED) goto error; DEBUG (2, ""mapped file at %p"", h->addr); } else { h->addr = malloc (h->size); if (h->addr == NULL) goto error; if (full_read (h->fd, h->addr, h->size) < h->size) goto error; /* We don't need the file descriptor along this path, since we * have read all the data. */ if (close (h->fd) == -1) goto error; h->fd = -1; } /* Check header. */ if (h->hdr->magic[0] != 'r' || h->hdr->magic[1] != 'e' || h->hdr->magic[2] != 'g' || h->hdr->magic[3] != 'f') { SET_ERRNO (ENOTSUP, ""%s: not a Windows NT Registry hive file"", filename); goto error; } /* Check major version. */ uint32_t major_ver = le32toh (h->hdr->major_ver); if (major_ver != 1) { SET_ERRNO (ENOTSUP, ""%s: hive file major version %"" PRIu32 "" (expected 1)"", filename, major_ver); goto error; } h->bitmap = calloc (1 + h->size / 32, 1); if (h->bitmap == NULL) goto error; /* Header checksum. */ uint32_t sum = header_checksum (h); if (sum != le32toh (h->hdr->csum)) { SET_ERRNO (EINVAL, ""%s: bad checksum in hive header"", filename); goto error; } for (int t=0; ticonv_cache[t].mutex); h->iconv_cache[t].handle = NULL; } /* Last modified time. */ h->last_modified = le64toh ((int64_t) h->hdr->last_modified); if (h->msglvl >= 2) { char *name = _hivex_recode (h, utf16le_to_utf8, h->hdr->name, 64, NULL); fprintf (stderr, ""hivex_open: header fields:\n"" "" file version %"" PRIu32 "".%"" PRIu32 ""\n"" "" sequence nos %"" PRIu32 "" %"" PRIu32 ""\n"" "" (sequences nos should match if hive was synched at shutdown)\n"" "" last modified %"" PRIi64 ""\n"" "" (Windows filetime, x 100 ns since 1601-01-01)\n"" "" original file name %s\n"" "" (only 32 chars are stored, name is probably truncated)\n"" "" root offset 0x%x + 0x1000\n"" "" end of last page 0x%x + 0x1000 (total file size 0x%zx)\n"" "" checksum 0x%x (calculated 0x%x)\n"", major_ver, le32toh (h->hdr->minor_ver), le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2), h->last_modified, name ? name : ""(conversion failed)"", le32toh (h->hdr->offset), le32toh (h->hdr->blocks), h->size, le32toh (h->hdr->csum), sum); free (name); } h->rootoffs = le32toh (h->hdr->offset) + 0x1000; h->endpages = le32toh (h->hdr->blocks) + 0x1000; DEBUG (2, ""root offset = 0x%zx"", h->rootoffs); /* We'll set this flag when we see a block with the root offset (ie. * the root block). */ int seen_root_block = 0, bad_root_block = 0; /* Collect some stats. */ size_t pages = 0; /* Number of hbin pages read. */ size_t smallest_page = SIZE_MAX, largest_page = 0; size_t blocks = 0; /* Total number of blocks found. */ size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0; size_t used_blocks = 0; /* Total number of used blocks found. */ size_t used_size = 0; /* Total size (bytes) of used blocks. */ /* Read the pages and blocks. The aim here is to be robust against * corrupt or malicious registries. So we make sure the loops * always make forward progress. We add the address of each block * we read to a hash table so pointers will only reference the start * of valid blocks. */ size_t off; struct ntreg_hbin_page *page; for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) { if (off >= h->endpages) break; page = (struct ntreg_hbin_page *) ((char *) h->addr + off); if (page->magic[0] != 'h' || page->magic[1] != 'b' || page->magic[2] != 'i' || page->magic[3] != 'n') { if (!h->unsafe) { SET_ERRNO (ENOTSUP, ""%s: trailing garbage at end of file "" ""(at 0x%zx, after %zu pages)"", filename, off, pages); goto error; } DEBUG (2, ""page not found at expected offset 0x%zx, "" ""seeking until one is found or EOF is reached"", off); int found = 0; while (off < h->size) { off += 0x1000; if (off >= h->endpages) break; page = (struct ntreg_hbin_page *) ((char *) h->addr + off); if (page->magic[0] == 'h' && page->magic[1] == 'b' && page->magic[2] == 'i' && page->magic[3] == 'n') { DEBUG (2, ""found next page by seeking at 0x%zx"", off); found = 1; break; } } if (!found) { DEBUG (2, ""page not found and end of pages section reached""); break; } } size_t page_size = le32toh (page->page_size); DEBUG (2, ""page at 0x%zx, size %zu"", off, page_size); pages++; if (page_size < smallest_page) smallest_page = page_size; if (page_size > largest_page) largest_page = page_size; if (page_size <= sizeof (struct ntreg_hbin_page) || (page_size & 0x0fff) != 0) { SET_ERRNO (ENOTSUP, ""%s: page size %zu at 0x%zx, bad registry"", filename, page_size, off); goto error; } if (off + page_size > h->size) { SET_ERRNO (ENOTSUP, ""%s: page size %zu at 0x%zx extends beyond end of file, bad registry"", filename, page_size, off); goto error; } size_t page_offset = le32toh(page->offset_first) + 0x1000; if (page_offset != off) { SET_ERRNO (ENOTSUP, ""%s: declared page offset (0x%zx) does not match computed "" ""offset (0x%zx), bad registry"", filename, page_offset, off); goto error; } /* Read the blocks in this page. */ size_t blkoff; struct ntreg_hbin_block *block; size_t seg_len; for (blkoff = off + 0x20; blkoff < off + page_size; blkoff += seg_len) { blocks++; int is_root = blkoff == h->rootoffs; if (is_root) seen_root_block = 1; block = (struct ntreg_hbin_block *) ((char *) h->addr + blkoff); int used; seg_len = block_len (h, blkoff, &used); /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78665 */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored ""-Wstrict-overflow"" if (seg_len <= 4 || (seg_len & 3) != 0) { #pragma GCC diagnostic pop if (is_root || !h->unsafe) { SET_ERRNO (ENOTSUP, ""%s, the block at 0x%zx has invalid size %"" PRIu32 "", bad registry"", filename, blkoff, le32toh (block->seg_len)); goto error; } else { DEBUG (2, ""%s: block at 0x%zx has invalid size %"" PRIu32 "", skipping"", filename, blkoff, le32toh (block->seg_len)); break; } } if (h->msglvl >= 2) { unsigned char *id = (unsigned char *) block->id; int id0 = id[0], id1 = id[1]; fprintf (stderr, ""%s: %s: "" ""%s block id %d,%d (%c%c) at 0x%zx size %zu%s\n"", ""hivex"", __func__, used ? ""used"" : ""free"", id0, id1, c_isprint (id0) ? id0 : '.', c_isprint (id1) ? id1 : '.', blkoff, seg_len, is_root ? "" (root)"" : """"); } blocks_bytes += seg_len; if (seg_len < smallest_block) smallest_block = seg_len; if (seg_len > largest_block) largest_block = seg_len; if (is_root && !used) bad_root_block = 1; if (used) { used_blocks++; used_size += seg_len; /* Root block must be an nk-block. */ if (is_root && (block->id[0] != 'n' || block->id[1] != 'k')) bad_root_block = 1; /* Note this blkoff is a valid address. */ BITMAP_SET (h->bitmap, blkoff); } } } if (!seen_root_block) { SET_ERRNO (ENOTSUP, ""%s: no root block found"", filename); goto error; } if (bad_root_block) { SET_ERRNO (ENOTSUP, ""%s: bad root block (free or not nk)"", filename); goto error; } DEBUG (1, ""successfully read Windows Registry hive file:\n"" "" pages: %zu [sml: %zu, lge: %zu]\n"" "" blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n"" "" blocks used: %zu\n"" "" bytes used: %zu"", pages, smallest_page, largest_page, blocks, smallest_block, blocks_bytes / blocks, largest_block, used_blocks, used_size); return h; error:; int err = errno; if (h) { free (h->bitmap); if (h->addr && h->size && h->addr != MAP_FAILED) { if (!h->writable) munmap (h->addr, h->size); else free (h->addr); } if (h->fd >= 0) close (h->fd); free (h->filename); free (h); } errno = err; return NULL; }",CWE-125,1 1,"static int ntlm_read_ntlm_v2_client_challenge(wStream* s, NTLMv2_CLIENT_CHALLENGE* challenge) { size_t size; Stream_Read_UINT8(s, challenge->RespType); Stream_Read_UINT8(s, challenge->HiRespType); Stream_Read_UINT16(s, challenge->Reserved1); Stream_Read_UINT32(s, challenge->Reserved2); Stream_Read(s, challenge->Timestamp, 8); Stream_Read(s, challenge->ClientChallenge, 8); Stream_Read_UINT32(s, challenge->Reserved3); size = Stream_Length(s) - Stream_GetPosition(s); if (size > UINT32_MAX) return -1; challenge->cbAvPairs = size; challenge->AvPairs = (NTLM_AV_PAIR*)malloc(challenge->cbAvPairs); if (!challenge->AvPairs) return -1; Stream_Read(s, challenge->AvPairs, size); return 1; }",CWE-125,1 0,"void* WebGraphicsContext3DDefaultImpl::mapTexSubImage2DCHROMIUM(unsigned target, int level, int xoffset, int yoffset, int width, int height, unsigned format, unsigned type, unsigned access) { return 0; } ",none,24 1,"int flb_gzip_compress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int flush; int status; int footer_start; uint8_t *pb; size_t out_size; void *out_buf; z_stream strm; mz_ulong crc; out_size = in_len + 32; out_buf = flb_malloc(out_size); if (!out_buf) { flb_errno(); flb_error(""[gzip] could not allocate outgoing buffer""); return -1; } /* Initialize streaming buffer context */ memset(&strm, '\0', sizeof(strm)); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in_data; strm.avail_in = in_len; strm.total_out = 0; /* Deflate mode */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY); /* * Miniz don't support GZip format directly, instead we will: * * - append manual GZip magic bytes * - deflate raw content * - append manual CRC32 data */ gzip_header(out_buf); /* Header offset */ pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET; flush = Z_NO_FLUSH; while (1) { strm.next_out = pb + strm.total_out; strm.avail_out = out_size - (pb - (uint8_t *) out_buf); if (strm.avail_in == 0) { flush = Z_FINISH; } status = deflate(&strm, flush); if (status == Z_STREAM_END) { break; } else if (status != Z_OK) { deflateEnd(&strm); return -1; } } if (deflateEnd(&strm) != Z_OK) { flb_free(out_buf); return -1; } *out_len = strm.total_out; /* Construct the gzip checksum (CRC32 footer) */ footer_start = FLB_GZIP_HEADER_OFFSET + *out_len; pb = (uint8_t *) out_buf + footer_start; crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len); *pb++ = crc & 0xFF; *pb++ = (crc >> 8) & 0xFF; *pb++ = (crc >> 16) & 0xFF; *pb++ = (crc >> 24) & 0xFF; *pb++ = in_len & 0xFF; *pb++ = (in_len >> 8) & 0xFF; *pb++ = (in_len >> 16) & 0xFF; *pb++ = (in_len >> 24) & 0xFF; /* Set the real buffer size for the caller */ *out_len += FLB_GZIP_HEADER_OFFSET + 8; *out_data = out_buf; return 0; }",CWE-787,16 0,"ACTION_P(ReturnBuffer, buffer) { arg0.Run(buffer); } ",none,24 1,"PHP_FUNCTION( msgfmt_parse_message ) { UChar *spattern = NULL; int spattern_len = 0; char *pattern = NULL; size_t pattern_len = 0; const char *slocale = NULL; size_t slocale_len = 0; char *source = NULL; size_t src_len = 0; MessageFormatter_object mf; MessageFormatter_object *mfo = &mf; /* Parse parameters. */ if( zend_parse_parameters( ZEND_NUM_ARGS(), ""sss"", &slocale, &slocale_len, &pattern, &pattern_len, &source, &src_len ) == FAILURE ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, ""msgfmt_parse_message: unable to parse input params"", 0 ); RETURN_FALSE; } memset(mfo, 0, sizeof(*mfo)); msgformat_data_init(&mfo->mf_data); if(pattern && pattern_len) { intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo)); if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, ""msgfmt_parse_message: error converting pattern to UTF-16"", 0 ); RETURN_FALSE; } } else { spattern_len = 0; spattern = NULL; } if(slocale_len == 0) { slocale = intl_locale_get_default(); } #ifdef MSG_FORMAT_QUOTE_APOS if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) { intl_error_set( NULL, U_INVALID_FORMAT_ERROR, ""msgfmt_parse_message: error converting pattern to quote-friendly format"", 0 ); RETURN_FALSE; } #endif /* Create an ICU message formatter. */ MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo)); if(spattern && spattern_len) { efree(spattern); } INTL_METHOD_CHECK_STATUS(mfo, ""Creating message formatter failed""); msgfmt_do_parse(mfo, source, src_len, return_value); /* drop the temporary formatter */ msgformat_data_free(&mfo->mf_data); }",CWE-119,0 0," StatisticsCB NewStatisticsCB() { return base::Bind(&MockStatisticsCB::OnStatistics, base::Unretained(&statistics_cb_)); } ",none,24 0,"const WillBeHeapVector >& SpeechSynthesis::getVoices() { if (m_voiceList.size()) return m_voiceList; const Vector >& platformVoices = m_platformSpeechSynthesizer->voiceList(); size_t voiceCount = platformVoices.size(); for (size_t k = 0; k < voiceCount; k++) m_voiceList.append(SpeechSynthesisVoice::create(platformVoices[k])); return m_voiceList; } ",none,24 0,"void DataObjectItem::Trace(blink::Visitor* visitor) { visitor->Trace(file_); } ",none,24 1,"int ecall_restore(const char *input, uint64_t input_len, char **output, uint64_t *output_len) { if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input, input_len) || !asylo::primitives::TrustedPrimitives::IsOutsideEnclave( output_len, sizeof(uint64_t))) { asylo::primitives::TrustedPrimitives::BestEffortAbort( ""ecall_restore: input/output found to not be in untrusted memory.""); } int result = 0; size_t tmp_output_len; try { result = asylo::Restore(input, static_cast(input_len), output, &tmp_output_len); } catch (...) { LOG(FATAL) << ""Uncaught exception in enclave""; } if (output_len) { *output_len = static_cast(tmp_output_len); } return result; }",CWE-787,16 1,"static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; }",CWE-787,16 1,"delete_buff_tail(buffheader_T *buf, int slen) { int len = (int)STRLEN(buf->bh_curr->b_str); if (len >= slen) { buf->bh_curr->b_str[len - slen] = NUL; buf->bh_space += slen; } }",CWE-125,1 0,"AudioInputStream* AudioManagerBase::MakeAudioInputStream( const AudioParameters& params, const std::string& device_id) { if (!params.IsValid() || (params.channels() > kMaxInputChannels) || device_id.empty()) { DLOG(ERROR) << ""Audio parameters are invalid for device "" << device_id; return NULL; } if (num_input_streams_ >= max_num_input_streams_) { DLOG(ERROR) << ""Number of opened input audio streams "" << num_input_streams_ << "" exceed the max allowed number "" << max_num_input_streams_; return NULL; } AudioInputStream* stream = NULL; if (params.format() == AudioParameters::AUDIO_MOCK) { stream = FakeAudioInputStream::MakeFakeStream(this, params); } else if (params.format() == AudioParameters::AUDIO_PCM_LINEAR) { stream = MakeLinearInputStream(params, device_id); } else if (params.format() == AudioParameters::AUDIO_PCM_LOW_LATENCY) { stream = MakeLowLatencyInputStream(params, device_id); } if (stream) ++num_input_streams_; return stream; } ",none,24 1,"static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = ""zip""; } else { ext = ""phar.zip""; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = ""tar.gz""; } else { ext = ""phar.tar.gz""; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = ""tar.bz2""; } else { ext = ""phar.tar.bz2""; } break; default: if (phar->is_data) { ext = ""tar""; } else { ext = ""phar.tar""; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = ""phar.gz""; break; case PHAR_FILE_COMPRESSED_BZ2: ext = ""phar.bz2""; break; default: ext = ""phar""; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""data phar converted from \""%s\"" has invalid extension %s"", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""phar converted from \""%s\"" has invalid extension %s"", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, ""%s.%s"", strtok(basename, "".""), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, ""%s%s"", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Unable to add newly converted phar \""%s\"" to the list of phars, new phar name is in phar.cache_list"", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Unable to add newly converted phar \""%s\"" to the list of phars, a phar with that name already exists"", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""phar \""%s\"" exists and must be unlinked prior to conversion"", newpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""phar \""%s\"" has invalid extension %s"", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""data phar \""%s\"" has invalid extension %s"", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Unable to add newly converted phar \""%s\"" to the list of phars"", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""%s"", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Unable to instantiate phar object when converting archive \""%s\"""", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, ""__construct"", NULL, &arg1); return ret; }",CWE-416,10 0,"void WebGraphicsContext3DDefaultImpl::copyTextureToParentTextureCHROMIUM(unsigned id, unsigned id2) { } ",none,24 1,"static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC) { int de, i=0, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""No maker note data found. Detected maker: %s (length = %d)"", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""check (%s,%s)"", maker_note->make?maker_note->make:"""", maker_note->model?maker_note->model:"""");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (maker_note->offset >= value_len) { /* Do not go past the value end */ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data too short: 0x%04X offset 0x%04X"", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Process %s @x%04X + 0x%04X=%d: %s"", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data too short: 0x%04X"", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Using automatic offset correction: 0x%04X"", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data bad offset: 0x%04X length 0x%04X"", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X"", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;detag_table TSRMLS_CC)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Subsection %s done"", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; }",CWE-125,1 1,"static int identity_count(void *v, const char *key, const char *val) { int *count = v; *count += strlen(key) * 3 + strlen(val) * 3 + 1; return 1; }",CWE-787,16 1,"static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size) { int i, j, ret; int64_t off; int val_1; int num_video; AVIOContext pb0, *pb = &pb0; ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL); ffio_read_varlen(pb); // track_header_len avio_r8(pb); // '1' val_1 = ffio_read_varlen(pb); for (i=0;iid = i; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_VP6; off = avio_tell(pb); off += ffio_read_varlen(pb); avio_r8(pb); // '3' avio_r8(pb); // val_7 num = avio_rl32(pb); // frame_time den = avio_rl32(pb); // time_base avpriv_set_pts_info(st, 64, num, den); st->nb_frames = avio_rl32(pb); // n frames st->codecpar->width = avio_rl16(pb); // width st->codecpar->height = avio_rl16(pb); // height avio_r8(pb); // val_8 avio_rl32(pb); // val_9 avio_seek(pb, off, SEEK_SET); } off = avio_tell(pb); off += ffio_read_varlen(pb); // val_10 avio_r8(pb); // '4' viv->num_audio = avio_r8(pb); avio_seek(pb, off, SEEK_SET); if (viv->num_audio != 1) av_log(s, AV_LOG_WARNING, ""number of audio tracks %d is not 1\n"", viv->num_audio); for(i=0;inum_audio;i++) { int q; AVStream *st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->id = num_video + i; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_VORBIS; off = avio_tell(pb); off += ffio_read_varlen(pb); // length avio_r8(pb); // '5' avio_r8(pb); //codec_id avio_rl16(pb); //codec_subid st->codecpar->channels = avio_rl16(pb); // channels st->codecpar->sample_rate = avio_rl32(pb); // sample_rate avio_seek(pb, 10, SEEK_CUR); // data_1 q = avio_r8(pb); avio_seek(pb, q, SEEK_CUR); // data_2 avio_r8(pb); // zeropad if (avio_tell(pb) < off) { int num_data; int xd_size = 0; int data_len[256]; int offset = 1; uint8_t *p; ffio_read_varlen(pb); // val_13 avio_r8(pb); // '19' ffio_read_varlen(pb); // len_3 num_data = avio_r8(pb); for (j = 0; j < num_data; j++) { uint64_t len = ffio_read_varlen(pb); if (len > INT_MAX/2 - xd_size) { return AVERROR_INVALIDDATA; } data_len[j] = len; xd_size += len; } ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255); if (ret < 0) return ret; p = st->codecpar->extradata; p[0] = 2; for (j = 0; j < num_data - 1; j++) { unsigned delta = av_xiphlacing(&p[offset], data_len[j]); if (delta > data_len[j]) { return AVERROR_INVALIDDATA; } offset += delta; } for (j = 0; j < num_data; j++) { int ret = avio_read(pb, &p[offset], data_len[j]); if (ret < data_len[j]) { st->codecpar->extradata_size = 0; av_freep(&st->codecpar->extradata); break; } offset += data_len[j]; } if (offset < st->codecpar->extradata_size) st->codecpar->extradata_size = offset; } } return 0; }",CWE-787,16 0,"DataObjectItem::DataObjectItem(ItemKind kind, const String& type) : source_(kInternalSource), kind_(kind), type_(type), sequence_number_(0) {} ",none,24 0,"void WebGraphicsContext3DDefaultImpl::shaderSource(WebGLId shader, const char* string) { makeContextCurrent(); GLint length = string ? strlen(string) : 0; ShaderSourceMap::iterator result = m_shaderSourceMap.find(shader); if (result != m_shaderSourceMap.end()) { ShaderSourceEntry* entry = result->second; ASSERT(entry); if (entry->source) { fastFree(entry->source); entry->source = 0; } if (!tryFastMalloc((length + 1) * sizeof(char)).getValue(entry->source)) return; // FIXME: generate an error? memcpy(entry->source, string, (length + 1) * sizeof(char)); } else glShaderSource(shader, 1, &string, &length); } ",none,24 0,"void RunAndQuit(const base::Closure& closure, const base::Closure& quit, base::MessageLoopProxy* original_message_loop) { closure.Run(); original_message_loop->PostTask(FROM_HERE, quit); } ",none,24 1,"read_attribute(cdk_stream_t inp, size_t pktlen, cdk_pkt_userid_t attr, int name_size) { const byte *p; byte *buf; size_t len, nread; cdk_error_t rc; if (!inp || !attr || !pktlen) return CDK_Inv_Value; if (DEBUG_PKT) _gnutls_write_log(""read_attribute: %d octets\n"", (int) pktlen); _gnutls_str_cpy(attr->name, name_size, ATTRIBUTE); attr->len = MIN(name_size, sizeof(ATTRIBUTE) - 1); buf = cdk_calloc(1, pktlen); if (!buf) return CDK_Out_Of_Core; rc = stream_read(inp, buf, pktlen, &nread); if (rc) { cdk_free(buf); return CDK_Inv_Packet; } p = buf; len = *p++; pktlen--; if (len == 255) { len = _cdk_buftou32(p); p += 4; pktlen -= 4; } else if (len >= 192) { if (pktlen < 2) { cdk_free(buf); return CDK_Inv_Packet; } len = ((len - 192) << 8) + *p + 192; p++; pktlen--; } if (*p != 1) { /* Currently only 1, meaning an image, is defined. */ cdk_free(buf); return CDK_Inv_Packet; } p++; len--; if (len >= pktlen) { cdk_free(buf); return CDK_Inv_Packet; } attr->attrib_img = cdk_calloc(1, len); if (!attr->attrib_img) { cdk_free(buf); return CDK_Out_Of_Core; } attr->attrib_len = len; memcpy(attr->attrib_img, p, len); cdk_free(buf); return rc; }",CWE-119,0 1," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const Tensor& input_min_tensor = ctx->input(1); const Tensor& input_max_tensor = ctx->input(2); int num_slices = 1; if (axis_ > -1) { num_slices = input.dim_size(axis_); } Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor float_output = need_cast_ ? tensorflow::Tensor(DT_FLOAT, input.shape()) : *output; if (num_slices == 1) { const float min_range = input_min_tensor.flat()(0); const float max_range = input_max_tensor.flat()(0); DequantizeTensor(ctx, input, min_range, max_range, &float_output); } else { OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST, errors::Unimplemented(""MIN_FIRST mode is not implemented for "" ""Dequantize with axis != -1."")); int64 pre_dim = 1, post_dim = 1; for (int i = 0; i < axis_; ++i) { pre_dim *= float_output.dim_size(i); } for (int i = axis_ + 1; i < float_output.dims(); ++i) { post_dim *= float_output.dim_size(i); } auto input_tensor = input.template bit_casted_shaped( {pre_dim, num_slices, post_dim}); auto output_tensor = float_output.flat_inner_outer_dims(axis_ - 1); auto min_ranges = input_min_tensor.vec(); auto max_ranges = input_max_tensor.vec(); for (int i = 0; i < num_slices; ++i) { DequantizeSlice(ctx->eigen_device(), ctx, input_tensor.template chip<1>(i), min_ranges(i), max_ranges(i), output_tensor.template chip<1>(i)); } } if (need_cast_) { S* out_ptr = output->flat().data(); float* in_ptr = float_output.flat().data(); for (int64 i = 0; i < float_output.NumElements(); ++i) { out_ptr[i] = static_cast(in_ptr[i]); } } }",CWE-20,3 1,"static int vt_disallocate(unsigned int vc_num) { struct vc_data *vc = NULL; int ret = 0; console_lock(); if (vt_busy(vc_num)) ret = -EBUSY; else if (vc_num) vc = vc_deallocate(vc_num); console_unlock(); if (vc && vc_num >= MIN_NR_CONSOLES) { tty_port_destroy(&vc->port); kfree(vc); } return ret; }",CWE-416,10 0,"void WebGraphicsContext3DDefaultImpl::renderbufferStorage(unsigned long target, unsigned long internalformat, unsigned long width, unsigned long height) { makeContextCurrent(); switch (internalformat) { case GL_DEPTH_STENCIL: internalformat = GL_DEPTH24_STENCIL8_EXT; break; case GL_DEPTH_COMPONENT16: internalformat = GL_DEPTH_COMPONENT; break; case GL_RGBA4: case GL_RGB5_A1: internalformat = GL_RGBA; break; case 0x8D62: // GL_RGB565 internalformat = GL_RGB; break; } glRenderbufferStorageEXT(target, internalformat, width, height); } ",none,24 0,"void TranslateManager::InitiateTranslation(TabContents* tab, const std::string& page_lang) { PrefService* prefs = tab->profile()->GetPrefs(); if (!prefs->GetBoolean(prefs::kEnableTranslate)) return; pref_change_registrar_.Init(prefs); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableTranslate)) return; NavigationEntry* entry = tab->controller().GetActiveEntry(); if (!entry) { return; } if (GetTranslateInfoBarDelegate(tab)) return; std::string target_lang = GetTargetLanguage(); if (target_lang.empty() || !IsSupportedLanguage(page_lang)) { return; } if (!IsTranslatableURL(entry->url()) || page_lang == target_lang || !TranslatePrefs::CanTranslate(prefs, page_lang, entry->url()) || IsAcceptLanguage(tab, page_lang)) { return; } std::string auto_target_lang; if (!tab->profile()->IsOffTheRecord() && TranslatePrefs::ShouldAutoTranslate(prefs, page_lang, &auto_target_lang)) { TranslatePage(tab, page_lang, auto_target_lang); return; } std::string auto_translate_to = tab->language_state().AutoTranslateTo(); if (!auto_translate_to.empty()) { TranslatePage(tab, page_lang, auto_translate_to); return; } tab->AddInfoBar(TranslateInfoBarDelegate::CreateDelegate( TranslateInfoBarDelegate::BEFORE_TRANSLATE, tab, page_lang, target_lang)); } ",none,24 1,"int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds, bool nonblock) { int error; int full_check = 0; struct fd f, tf; struct eventpoll *ep; struct epitem *epi; struct eventpoll *tep = NULL; error = -EBADF; f = fdget(epfd); if (!f.file) goto error_return; /* Get the ""struct file *"" for the target file */ tf = fdget(fd); if (!tf.file) goto error_fput; /* The target file descriptor must support poll */ error = -EPERM; if (!file_can_poll(tf.file)) goto error_tgt_fput; /* Check if EPOLLWAKEUP is allowed */ if (ep_op_has_event(op)) ep_take_care_of_epollwakeup(epds); /* * We have to check that the file structure underneath the file descriptor * the user passed to us _is_ an eventpoll file. And also we do not permit * adding an epoll file descriptor inside itself. */ error = -EINVAL; if (f.file == tf.file || !is_file_epoll(f.file)) goto error_tgt_fput; /* * epoll adds to the wakeup queue at EPOLL_CTL_ADD time only, * so EPOLLEXCLUSIVE is not allowed for a EPOLL_CTL_MOD operation. * Also, we do not currently supported nested exclusive wakeups. */ if (ep_op_has_event(op) && (epds->events & EPOLLEXCLUSIVE)) { if (op == EPOLL_CTL_MOD) goto error_tgt_fput; if (op == EPOLL_CTL_ADD && (is_file_epoll(tf.file) || (epds->events & ~EPOLLEXCLUSIVE_OK_BITS))) goto error_tgt_fput; } /* * At this point it is safe to assume that the ""private_data"" contains * our own data structure. */ ep = f.file->private_data; /* * When we insert an epoll file descriptor, inside another epoll file * descriptor, there is the change of creating closed loops, which are * better be handled here, than in more critical paths. While we are * checking for loops we also determine the list of files reachable * and hang them on the tfile_check_list, so we can check that we * haven't created too many possible wakeup paths. * * We do not need to take the global 'epumutex' on EPOLL_CTL_ADD when * the epoll file descriptor is attaching directly to a wakeup source, * unless the epoll file descriptor is nested. The purpose of taking the * 'epmutex' on add is to prevent complex toplogies such as loops and * deep wakeup paths from forming in parallel through multiple * EPOLL_CTL_ADD operations. */ error = epoll_mutex_lock(&ep->mtx, 0, nonblock); if (error) goto error_tgt_fput; if (op == EPOLL_CTL_ADD) { if (!list_empty(&f.file->f_ep_links) || is_file_epoll(tf.file)) { mutex_unlock(&ep->mtx); error = epoll_mutex_lock(&epmutex, 0, nonblock); if (error) goto error_tgt_fput; full_check = 1; if (is_file_epoll(tf.file)) { error = -ELOOP; if (ep_loop_check(ep, tf.file) != 0) { clear_tfile_check_list(); goto error_tgt_fput; } } else { get_file(tf.file); list_add(&tf.file->f_tfile_llink, &tfile_check_list); } error = epoll_mutex_lock(&ep->mtx, 0, nonblock); if (error) { out_del: list_del(&tf.file->f_tfile_llink); if (!is_file_epoll(tf.file)) fput(tf.file); goto error_tgt_fput; } if (is_file_epoll(tf.file)) { tep = tf.file->private_data; error = epoll_mutex_lock(&tep->mtx, 1, nonblock); if (error) { mutex_unlock(&ep->mtx); goto out_del; } } } } /* * Try to lookup the file inside our RB tree, Since we grabbed ""mtx"" * above, we can be sure to be able to use the item looked up by * ep_find() till we release the mutex. */ epi = ep_find(ep, tf.file, fd); error = -EINVAL; switch (op) { case EPOLL_CTL_ADD: if (!epi) { epds->events |= EPOLLERR | EPOLLHUP; error = ep_insert(ep, epds, tf.file, fd, full_check); } else error = -EEXIST; if (full_check) clear_tfile_check_list(); break; case EPOLL_CTL_DEL: if (epi) error = ep_remove(ep, epi); else error = -ENOENT; break; case EPOLL_CTL_MOD: if (epi) { if (!(epi->event.events & EPOLLEXCLUSIVE)) { epds->events |= EPOLLERR | EPOLLHUP; error = ep_modify(ep, epi, epds); } } else error = -ENOENT; break; } if (tep != NULL) mutex_unlock(&tep->mtx); mutex_unlock(&ep->mtx); error_tgt_fput: if (full_check) mutex_unlock(&epmutex); fdput(tf); error_fput: fdput(f); error_return: return error; }",CWE-416,10 0,"void WebGraphicsContext3DDefaultImpl::framebufferRenderbuffer(unsigned long target, unsigned long attachment, unsigned long renderbuffertarget, WebGLId buffer) { makeContextCurrent(); if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) { glFramebufferRenderbufferEXT(target, GL_DEPTH_ATTACHMENT, renderbuffertarget, buffer); glFramebufferRenderbufferEXT(target, GL_STENCIL_ATTACHMENT, renderbuffertarget, buffer); } else glFramebufferRenderbufferEXT(target, attachment, renderbuffertarget, buffer); } ",none,24 1,"tiff12_print_page(gx_device_printer * pdev, gp_file * file) { gx_device_tiff *const tfdev = (gx_device_tiff *)pdev; int code; /* open the TIFF device */ if (gdev_prn_file_is_new(pdev)) { tfdev->tif = tiff_from_filep(pdev, pdev->dname, file, tfdev->BigEndian, tfdev->UseBigTIFF); if (!tfdev->tif) return_error(gs_error_invalidfileaccess); } code = gdev_tiff_begin_page(tfdev, file); if (code < 0) return code; TIFFSetField(tfdev->tif, TIFFTAG_BITSPERSAMPLE, 4); tiff_set_rgb_fields(tfdev); TIFFCheckpointDirectory(tfdev->tif); /* Write the page data. */ { int y; int size = gdev_prn_raster(pdev); byte *data = gs_alloc_bytes(pdev->memory, size, ""tiff12_print_page""); if (data == 0) return_error(gs_error_VMerror); memset(data, 0, size); for (y = 0; y < pdev->height; ++y) { const byte *src; byte *dest; int x; code = gdev_prn_copy_scan_lines(pdev, y, data, size); if (code < 0) break; for (src = data, dest = data, x = 0; x < size; src += 6, dest += 3, x += 6 ) { dest[0] = (src[0] & 0xf0) | (src[1] >> 4); dest[1] = (src[2] & 0xf0) | (src[3] >> 4); dest[2] = (src[4] & 0xf0) | (src[5] >> 4); } TIFFWriteScanline(tfdev->tif, data, y, 0); } gs_free_object(pdev->memory, data, ""tiff12_print_page""); TIFFWriteDirectory(tfdev->tif); } return code; }",CWE-787,16 1," static int xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; int frame; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { xmlXPathObjectPtr tmp; if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else { if (xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode) < 0) { ctxt->error = XPATH_MEMORY_ERROR; goto evaluation_exit; } } frame = xmlXPathSetFrame(ctxt); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); tmp = valuePop(ctxt); xmlXPathPopFrame(ctxt, frame); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { while (tmp != contextObj) { /* * Free up the result * then pop off contextObj, which will be freed later */ xmlXPathReleaseObject(xpctxt, tmp); tmp = valuePop(ctxt); } goto evaluation_error; } /* push the result back onto the stack */ valuePush(ctxt, tmp); if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); }",CWE-416,10 0,"ACTION_P3(CreateDataBufferFromCapture, decoder, vc_impl, data_buffer_number) { for (int i = 0; i < data_buffer_number; i++) { media::VideoCapture::VideoFrameBuffer* buffer; buffer = new media::VideoCapture::VideoFrameBuffer(); buffer->width = arg1.width; buffer->height = arg1.height; int length = buffer->width * buffer->height * 3 / 2; buffer->memory_pointer = new uint8[length]; buffer->buffer_size = length; decoder->OnBufferReady(vc_impl, buffer); } } ",none,24 1,"search_memslots(struct kvm_memslots *slots, gfn_t gfn) { int start = 0, end = slots->used_slots; int slot = atomic_read(&slots->lru_slot); struct kvm_memory_slot *memslots = slots->memslots; if (gfn >= memslots[slot].base_gfn && gfn < memslots[slot].base_gfn + memslots[slot].npages) return &memslots[slot]; while (start < end) { slot = start + (end - start) / 2; if (gfn >= memslots[slot].base_gfn) end = slot; else start = slot + 1; } if (gfn >= memslots[start].base_gfn && gfn < memslots[start].base_gfn + memslots[start].npages) { atomic_set(&slots->lru_slot, start); return &memslots[start]; } return NULL; }",CWE-416,10 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())); } bool is_1d = shape.NumElements() == 1; int num_batches = is_1d ? 1 : shape.flat()(0); int num_values = values.NumElements(); 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; for (int idx = 0; idx < num_values; ++idx) { int batch = is_1d ? 0 : indices_values(idx, 0); 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-125,1 1,"int32_t *enc_untrusted_create_wait_queue() { MessageWriter input; MessageReader output; input.Push(sizeof(int32_t)); const auto status = NonSystemCallDispatcher( ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_create_wait_queue"", 2); int32_t *queue = reinterpret_cast(output.next()); int klinux_errno = output.next(); if (queue == nullptr) { errno = FromkLinuxErrorNumber(klinux_errno); } enc_untrusted_disable_waiting(queue); return queue; }",CWE-787,16 1,"static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg) { bool src_known = tnum_subreg_is_const(src_reg->var_off); bool dst_known = tnum_subreg_is_const(dst_reg->var_off); struct tnum var32_off = tnum_subreg(dst_reg->var_off); s32 smin_val = src_reg->smin_value; u32 umin_val = src_reg->umin_value; /* Assuming scalar64_min_max_or will be called so it is safe * to skip updating register for known case. */ if (src_known && dst_known) return; /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); dst_reg->u32_max_value = var32_off.value | var32_off.mask; if (dst_reg->s32_min_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->s32_min_value = S32_MIN; dst_reg->s32_max_value = S32_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->s32_min_value = dst_reg->umin_value; dst_reg->s32_max_value = dst_reg->umax_value; } }",CWE-787,16 1,"void LanLinkProvider::addLink(const QString& deviceId, QSslSocket* socket, NetworkPacket* receivedPacket, LanDeviceLink::ConnectionStarted connectionOrigin) { // Socket disconnection will now be handled by LanDeviceLink disconnect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater); LanDeviceLink* deviceLink; //Do we have a link for this device already? QMap< QString, LanDeviceLink* >::iterator linkIterator = m_links.find(deviceId); if (linkIterator != m_links.end()) { //qCDebug(KDECONNECT_CORE) << ""Reusing link to"" << deviceId; deviceLink = linkIterator.value(); deviceLink->reset(socket, connectionOrigin); } else { deviceLink = new LanDeviceLink(deviceId, this, socket, connectionOrigin); connect(deviceLink, &QObject::destroyed, this, &LanLinkProvider::deviceLinkDestroyed); m_links[deviceId] = deviceLink; if (m_pairingHandlers.contains(deviceId)) { //We shouldn't have a pairinghandler if we didn't have a link. //Crash if debug, recover if release (by setting the new devicelink to the old pairinghandler) Q_ASSERT(m_pairingHandlers.contains(deviceId)); m_pairingHandlers[deviceId]->setDeviceLink(deviceLink); } } Q_EMIT onConnectionReceived(*receivedPacket, deviceLink); }",CWE-400,9 1,"repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, ""schema2id: new schema\n""); #endif return data->nschemata++; }",CWE-125,1 0," void Initialize() { InitializeWithConfig(config_); } ",none,24 1,"exif_entry_get_value (ExifEntry *e, char *val, unsigned int maxlen) { unsigned int i, j, k; ExifShort v_short, v_short2, v_short3, v_short4; ExifByte v_byte; ExifRational v_rat; ExifSRational v_srat; char b[64]; const char *c; ExifByteOrder o; double d; ExifEntry *entry; static const struct { char label[5]; char major, minor; } versions[] = { {""0110"", 1, 1}, {""0120"", 1, 2}, {""0200"", 2, 0}, {""0210"", 2, 1}, {""0220"", 2, 2}, {""0221"", 2, 21}, {""0230"", 2, 3}, {"""" , 0, 0} }; (void) bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); if (!e || !e->parent || !e->parent->parent || !maxlen || !val) return val; /* make sure the returned string is zero terminated */ /* FIXME: this is inefficient in the case of long buffers and should * instead be taken care of on each write instead. */ memset (val, 0, maxlen); /* We need the byte order */ o = exif_data_get_byte_order (e->parent->parent); /* Sanity check */ if (e->size != e->components * exif_format_get_size (e->format)) { snprintf (val, maxlen, _(""Invalid size of entry (%i, "" ""expected %li x %i).""), e->size, e->components, exif_format_get_size (e->format)); return val; } switch (e->tag) { case EXIF_TAG_USER_COMMENT: /* * The specification says UNDEFINED, but some * manufacturers don't care and use ASCII. If this is the * case here, only refuse to read it if there is no chance * of finding readable data. */ if ((e->format != EXIF_FORMAT_ASCII) || (e->size <= 8) || ( memcmp (e->data, ""ASCII\0\0\0"" , 8) && memcmp (e->data, ""UNICODE\0"" , 8) && memcmp (e->data, ""JIS\0\0\0\0\0"", 8) && memcmp (e->data, ""\0\0\0\0\0\0\0\0"", 8))) CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); /* * Note that, according to the specification (V2.1, p 40), * the user comment field does not have to be * NULL terminated. */ if ((e->size >= 8) && !memcmp (e->data, ""ASCII\0\0\0"", 8)) { strncpy (val, (char *) e->data + 8, MIN (e->size - 8, maxlen-1)); break; } if ((e->size >= 8) && !memcmp (e->data, ""UNICODE\0"", 8)) { strncpy (val, _(""Unsupported UNICODE string""), maxlen-1); /* FIXME: use iconv to convert into the locale encoding. * EXIF 2.2 implies (but does not say) that this encoding is * UCS-2. */ break; } if ((e->size >= 8) && !memcmp (e->data, ""JIS\0\0\0\0\0"", 8)) { strncpy (val, _(""Unsupported JIS string""), maxlen-1); /* FIXME: use iconv to convert into the locale encoding */ break; } /* Check if there is really some information in the tag. */ for (i = 0; (i < e->size) && (!e->data[i] || (e->data[i] == ' ')); i++); if (i == e->size) break; /* * If we reach this point, the tag does not * comply with the standard but seems to contain data. * Print as much as possible. * Note: make sure we do not overwrite the final \0 at maxlen-1 */ exif_entry_log (e, EXIF_LOG_CODE_DEBUG, _(""Tag UserComment contains data but is "" ""against specification."")); for (j = 0; (i < e->size) && (j < maxlen-1); i++, j++) { exif_entry_log (e, EXIF_LOG_CODE_DEBUG, _(""Byte at position %i: 0x%02x""), i, e->data[i]); val[j] = isprint (e->data[i]) ? e->data[i] : '.'; } break; case EXIF_TAG_EXIF_VERSION: CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); CC (e, 4, val, maxlen); strncpy (val, _(""Unknown Exif Version""), maxlen-1); for (i = 0; *versions[i].label; i++) { if (!memcmp (e->data, versions[i].label, 4)) { snprintf (val, maxlen, _(""Exif Version %d.%d""), versions[i].major, versions[i].minor); break; } } break; case EXIF_TAG_FLASH_PIX_VERSION: CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); CC (e, 4, val, maxlen); if (!memcmp (e->data, ""0100"", 4)) strncpy (val, _(""FlashPix Version 1.0""), maxlen-1); else if (!memcmp (e->data, ""0101"", 4)) strncpy (val, _(""FlashPix Version 1.01""), maxlen-1); else strncpy (val, _(""Unknown FlashPix Version""), maxlen-1); break; case EXIF_TAG_COPYRIGHT: CF (e, EXIF_FORMAT_ASCII, val, maxlen); /* * First part: Photographer. * Some cameras store a string like "" "" here. Ignore it. * Remember that a corrupted tag might not be NUL-terminated */ if (e->size && e->data && match_repeated_char(e->data, ' ', e->size)) strncpy (val, (char *) e->data, MIN (maxlen-1, e->size)); else strncpy (val, _(""[None]""), maxlen-1); strncat (val, "" "", maxlen-1 - strlen (val)); strncat (val, _(""(Photographer)""), maxlen-1 - strlen (val)); /* Second part: Editor. */ strncat (val, "" - "", maxlen-1 - strlen (val)); k = 0; if (e->size && e->data) { const unsigned char *tagdata = memchr(e->data, 0, e->size); if (tagdata++) { unsigned int editor_ofs = tagdata - e->data; unsigned int remaining = e->size - editor_ofs; if (match_repeated_char(tagdata, ' ', remaining)) { strncat (val, (const char*)tagdata, MIN (maxlen-1 - strlen (val), remaining)); ++k; } } } if (!k) strncat (val, _(""[None]""), maxlen-1 - strlen (val)); strncat (val, "" "", maxlen-1 - strlen (val)); strncat (val, _(""(Editor)""), maxlen-1 - strlen (val)); break; case EXIF_TAG_FNUMBER: CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_rat.numerator / (double) v_rat.denominator; snprintf (val, maxlen, ""f/%.01f"", d); break; case EXIF_TAG_APERTURE_VALUE: case EXIF_TAG_MAX_APERTURE_VALUE: CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator || (0x80000000 == v_rat.numerator)) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_rat.numerator / (double) v_rat.denominator; snprintf (val, maxlen, _(""%.02f EV""), d); snprintf (b, sizeof (b), _("" (f/%.01f)""), pow (2, d / 2.)); strncat (val, b, maxlen-1 - strlen (val)); break; case EXIF_TAG_FOCAL_LENGTH: CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } /* * For calculation of the 35mm equivalent, * Minolta cameras need a multiplier that depends on the * camera model. */ d = 0.; entry = exif_content_get_entry ( e->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MAKE); if (entry && entry->data && entry->size >= 7 && !strncmp ((char *)entry->data, ""Minolta"", 7)) { entry = exif_content_get_entry ( e->parent->parent->ifd[EXIF_IFD_0], EXIF_TAG_MODEL); if (entry && entry->data && entry->size >= 8) { if (!strncmp ((char *)entry->data, ""DiMAGE 7"", 8)) d = 3.9; else if (!strncmp ((char *)entry->data, ""DiMAGE 5"", 8)) d = 4.9; } } if (d) snprintf (b, sizeof (b), _("" (35 equivalent: %.0f mm)""), (d * (double) v_rat.numerator / (double) v_rat.denominator)); else b[0] = 0; d = (double) v_rat.numerator / (double) v_rat.denominator; snprintf (val, maxlen, ""%.1f mm"", d); strncat (val, b, maxlen-1 - strlen (val)); break; case EXIF_TAG_SUBJECT_DISTANCE: CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_rat.numerator / (double) v_rat.denominator; snprintf (val, maxlen, ""%.1f m"", d); break; case EXIF_TAG_EXPOSURE_TIME: CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_rat.numerator / (double) v_rat.denominator; if (d < 1 && d) snprintf (val, maxlen, _(""1/%.0f""), 1. / d); else snprintf (val, maxlen, ""%.0f"", d); strncat (val, _("" sec.""), maxlen-1 - strlen (val)); break; case EXIF_TAG_SHUTTER_SPEED_VALUE: CF (e, EXIF_FORMAT_SRATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_srat = exif_get_srational (e->data, o); if (!v_srat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_srat.numerator / (double) v_srat.denominator; snprintf (val, maxlen, _(""%.02f EV""), d); if (pow (2, d)) d = 1. / pow (2, d); if (d < 1 && d) snprintf (b, sizeof (b), _("" (1/%.0f sec.)""), 1. / d); else snprintf (b, sizeof (b), _("" (%.0f sec.)""), d); strncat (val, b, maxlen-1 - strlen (val)); break; case EXIF_TAG_BRIGHTNESS_VALUE: CF (e, EXIF_FORMAT_SRATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_srat = exif_get_srational (e->data, o); if (!v_srat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_srat.numerator / (double) v_srat.denominator; snprintf (val, maxlen, _(""%.02f EV""), d); snprintf (b, sizeof (b), _("" (%.02f cd/m^2)""), 1. / (M_PI * 0.3048 * 0.3048) * pow (2, d)); strncat (val, b, maxlen-1 - strlen (val)); break; case EXIF_TAG_FILE_SOURCE: CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); CC (e, 1, val, maxlen); v_byte = e->data[0]; if (v_byte == 3) strncpy (val, _(""DSC""), maxlen-1); else snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_byte); break; case EXIF_TAG_COMPONENTS_CONFIGURATION: CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); CC (e, 4, val, maxlen); for (i = 0; i < 4; i++) { switch (e->data[i]) { case 0: c = _(""-""); break; case 1: c = _(""Y""); break; case 2: c = _(""Cb""); break; case 3: c = _(""Cr""); break; case 4: c = _(""R""); break; case 5: c = _(""G""); break; case 6: c = _(""B""); break; default: c = _(""Reserved""); break; } strncat (val, c, maxlen-1 - strlen (val)); if (i < 3) strncat (val, "" "", maxlen-1 - strlen (val)); } break; case EXIF_TAG_EXPOSURE_BIAS_VALUE: CF (e, EXIF_FORMAT_SRATIONAL, val, maxlen); CC (e, 1, val, maxlen); v_srat = exif_get_srational (e->data, o); if (!v_srat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_srat.numerator / (double) v_srat.denominator; snprintf (val, maxlen, _(""%.02f EV""), d); break; case EXIF_TAG_SCENE_TYPE: CF (e, EXIF_FORMAT_UNDEFINED, val, maxlen); CC (e, 1, val, maxlen); v_byte = e->data[0]; if (v_byte == 1) strncpy (val, _(""Directly photographed""), maxlen-1); else snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_byte); break; case EXIF_TAG_YCBCR_SUB_SAMPLING: CF (e, EXIF_FORMAT_SHORT, val, maxlen); CC (e, 2, val, maxlen); v_short = exif_get_short (e->data, o); v_short2 = exif_get_short ( e->data + exif_format_get_size (e->format), o); if ((v_short == 2) && (v_short2 == 1)) strncpy (val, _(""YCbCr4:2:2""), maxlen-1); else if ((v_short == 2) && (v_short2 == 2)) strncpy (val, _(""YCbCr4:2:0""), maxlen-1); else snprintf (val, maxlen, ""%u, %u"", v_short, v_short2); break; case EXIF_TAG_SUBJECT_AREA: CF (e, EXIF_FORMAT_SHORT, val, maxlen); switch (e->components) { case 2: v_short = exif_get_short (e->data, o); v_short2 = exif_get_short (e->data + 2, o); snprintf (val, maxlen, ""(x,y) = (%i,%i)"", v_short, v_short2); break; case 3: v_short = exif_get_short (e->data, o); v_short2 = exif_get_short (e->data + 2, o); v_short3 = exif_get_short (e->data + 4, o); snprintf (val, maxlen, _(""Within distance %i of "" ""(x,y) = (%i,%i)""), v_short3, v_short, v_short2); break; case 4: v_short = exif_get_short (e->data, o); v_short2 = exif_get_short (e->data + 2, o); v_short3 = exif_get_short (e->data + 4, o); v_short4 = exif_get_short (e->data + 6, o); snprintf (val, maxlen, _(""Within rectangle "" ""(width %i, height %i) around "" ""(x,y) = (%i,%i)""), v_short3, v_short4, v_short, v_short2); break; default: snprintf (val, maxlen, _(""Unexpected number "" ""of components (%li, expected 2, 3, or 4).""), e->components); } break; case EXIF_TAG_GPS_VERSION_ID: /* This is only valid in the GPS IFD */ CF (e, EXIF_FORMAT_BYTE, val, maxlen); CC (e, 4, val, maxlen); v_byte = e->data[0]; snprintf (val, maxlen, ""%u"", v_byte); for (i = 1; i < e->components; i++) { v_byte = e->data[i]; snprintf (b, sizeof (b), "".%u"", v_byte); strncat (val, b, maxlen-1 - strlen (val)); } break; case EXIF_TAG_INTEROPERABILITY_VERSION: /* a.k.a. case EXIF_TAG_GPS_LATITUDE: */ /* This tag occurs in EXIF_IFD_INTEROPERABILITY */ if (e->format == EXIF_FORMAT_UNDEFINED) { strncpy (val, (char *) e->data, MIN (maxlen-1, e->size)); break; } /* EXIF_TAG_GPS_LATITUDE is the same numerically as * EXIF_TAG_INTEROPERABILITY_VERSION but in EXIF_IFD_GPS */ exif_entry_format_value(e, val, maxlen); break; case EXIF_TAG_GPS_ALTITUDE_REF: /* This is only valid in the GPS IFD */ CF (e, EXIF_FORMAT_BYTE, val, maxlen); CC (e, 1, val, maxlen); v_byte = e->data[0]; if (v_byte == 0) strncpy (val, _(""Sea level""), maxlen-1); else if (v_byte == 1) strncpy (val, _(""Sea level reference""), maxlen-1); else snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_byte); break; case EXIF_TAG_GPS_TIME_STAMP: /* This is only valid in the GPS IFD */ CF (e, EXIF_FORMAT_RATIONAL, val, maxlen); CC (e, 3, val, maxlen); v_rat = exif_get_rational (e->data, o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } i = v_rat.numerator / v_rat.denominator; v_rat = exif_get_rational (e->data + exif_format_get_size (e->format), o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } j = v_rat.numerator / v_rat.denominator; v_rat = exif_get_rational (e->data + 2*exif_format_get_size (e->format), o); if (!v_rat.denominator) { exif_entry_format_value(e, val, maxlen); break; } d = (double) v_rat.numerator / (double) v_rat.denominator; snprintf (val, maxlen, ""%02u:%02u:%05.2f"", i, j, d); break; case EXIF_TAG_METERING_MODE: case EXIF_TAG_COMPRESSION: case EXIF_TAG_LIGHT_SOURCE: case EXIF_TAG_FOCAL_PLANE_RESOLUTION_UNIT: case EXIF_TAG_RESOLUTION_UNIT: case EXIF_TAG_EXPOSURE_PROGRAM: case EXIF_TAG_FLASH: case EXIF_TAG_SUBJECT_DISTANCE_RANGE: case EXIF_TAG_COLOR_SPACE: CF (e,EXIF_FORMAT_SHORT, val, maxlen); CC (e, 1, val, maxlen); v_short = exif_get_short (e->data, o); /* Search the tag */ for (i = 0; list2[i].tag && (list2[i].tag != e->tag); i++); if (!list2[i].tag) { snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_short); break; } /* Find the value */ for (j = 0; list2[i].elem[j].values[0] && (list2[i].elem[j].index < v_short); j++); if (list2[i].elem[j].index != v_short) { snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_short); break; } /* Find a short enough value */ memset (val, 0, maxlen); for (k = 0; list2[i].elem[j].values[k]; k++) { size_t l = strlen (_(list2[i].elem[j].values[k])); if ((maxlen > l) && (strlen (val) < l)) strncpy (val, _(list2[i].elem[j].values[k]), maxlen-1); } if (!val[0]) snprintf (val, maxlen, ""%i"", v_short); break; case EXIF_TAG_PLANAR_CONFIGURATION: case EXIF_TAG_SENSING_METHOD: case EXIF_TAG_ORIENTATION: case EXIF_TAG_YCBCR_POSITIONING: case EXIF_TAG_PHOTOMETRIC_INTERPRETATION: case EXIF_TAG_CUSTOM_RENDERED: case EXIF_TAG_EXPOSURE_MODE: case EXIF_TAG_WHITE_BALANCE: case EXIF_TAG_SCENE_CAPTURE_TYPE: case EXIF_TAG_GAIN_CONTROL: case EXIF_TAG_SATURATION: case EXIF_TAG_CONTRAST: case EXIF_TAG_SHARPNESS: CF (e, EXIF_FORMAT_SHORT, val, maxlen); CC (e, 1, val, maxlen); v_short = exif_get_short (e->data, o); /* Search the tag */ for (i = 0; list[i].tag && (list[i].tag != e->tag); i++); if (!list[i].tag) { snprintf (val, maxlen, _(""Internal error (unknown "" ""value %i)""), v_short); break; } /* Find the value */ for (j = 0; list[i].strings[j] && (j < v_short); j++); if (!list[i].strings[j]) snprintf (val, maxlen, ""%i"", v_short); else if (!*list[i].strings[j]) snprintf (val, maxlen, _(""Unknown value %i""), v_short); else strncpy (val, _(list[i].strings[j]), maxlen-1); break; case EXIF_TAG_XP_TITLE: case EXIF_TAG_XP_COMMENT: case EXIF_TAG_XP_AUTHOR: case EXIF_TAG_XP_KEYWORDS: case EXIF_TAG_XP_SUBJECT: { unsigned char *utf16; /* Sanity check the size to prevent overflow */ if (e->size+sizeof(uint16_t)+1 < e->size) break; /* The tag may not be U+0000-terminated , so make a local U+0000-terminated copy before converting it */ utf16 = exif_mem_alloc (e->priv->mem, e->size+sizeof(uint16_t)+1); if (!utf16) break; memcpy(utf16, e->data, e->size); /* NUL terminate the string. If the size is odd (which isn't possible * for a valid UTF16 string), then this will overwrite the high byte of * the final half word, plus add a full zero NUL word at the end. */ utf16[e->size] = 0; utf16[e->size+1] = 0; utf16[e->size+2] = 0; /* Warning! The texts are converted from UTF16 to UTF8 */ /* FIXME: use iconv to convert into the locale encoding */ exif_convert_utf16_to_utf8(val, utf16, maxlen); exif_mem_free(e->priv->mem, utf16); break; } default: /* Use a generic value formatting */ exif_entry_format_value(e, val, maxlen); } return val; }",CWE-787,16 1,"file_extension(const char *s) /* I - Filename or URL */ { const char *extension; /* Pointer to directory separator */ static char buf[1024]; /* Buffer for files with targets */ if (s == NULL) return (NULL); else if (!strncmp(s, ""data:image/bmp;"", 15)) return (""bmp""); else if (!strncmp(s, ""data:image/gif;"", 15)) return (""gif""); else if (!strncmp(s, ""data:image/jpeg;"", 16)) return (""jpg""); else if (!strncmp(s, ""data:image/png;"", 15)) return (""png""); else if ((extension = strrchr(s, '/')) != NULL) extension ++; else if ((extension = strrchr(s, '\\')) != NULL) extension ++; else extension = s; if ((extension = strrchr(extension, '.')) == NULL) return (""""); else extension ++; if (strchr(extension, '#') == NULL) return (extension); strlcpy(buf, extension, sizeof(buf)); *(char *)strchr(buf, '#') = '\0'; return (buf); }",CWE-476,12 0,"void TranslateManager::InitAcceptLanguages(PrefService* prefs) { std::string accept_langs_str = prefs->GetString(prefs::kAcceptLanguages); std::vector accept_langs_list; LanguageSet accept_langs_set; base::SplitString(accept_langs_str, ',', &accept_langs_list); std::vector::const_iterator iter; std::string ui_lang = GetLanguageCode(g_browser_process->GetApplicationLocale()); bool is_ui_english = StartsWithASCII(ui_lang, ""en-"", false); for (iter = accept_langs_list.begin(); iter != accept_langs_list.end(); ++iter) { std::string accept_lang(*iter); size_t index = iter->find(""-""); if (index != std::string::npos && *iter != ""zh-CN"" && *iter != ""zh-TW"") accept_lang = iter->substr(0, index); if (accept_lang != ""en"" || is_ui_english) accept_langs_set.insert(accept_lang); } accept_languages_[prefs] = accept_langs_set; } ",none,24 0,"void SpeechSynthesis::cancel() { m_utteranceQueue.clear(); m_platformSpeechSynthesizer->cancel(); } ",none,24 1,"TfLiteIntArray* TfLiteIntArrayCreate(int size) { TfLiteIntArray* ret = (TfLiteIntArray*)malloc(TfLiteIntArrayGetSizeInBytes(size)); ret->size = size; return ret; }",CWE-190,2 1,"int64_t OpLevelCostEstimator::CalculateTensorSize( const OpInfo::TensorProperties& tensor, bool* found_unknown_shapes) { int64_t count = CalculateTensorElementCount(tensor, found_unknown_shapes); int size = DataTypeSize(BaseType(tensor.dtype())); VLOG(2) << ""Count: "" << count << "" DataTypeSize: "" << size; return count * size; }",CWE-190,2 1,"int Jsi_ObjArraySizer(Jsi_Interp *interp, Jsi_Obj *obj, uint len) { int nsiz = len + 1, mod = ALLOC_MOD_SIZE; assert(obj->isarrlist); if (mod>1) nsiz = nsiz + ((mod-1) - (nsiz + mod - 1)%mod); if (nsiz > MAX_ARRAY_LIST) { Jsi_LogError(""array size too large""); return 0; } if (len >= obj->arrMaxSize) { int oldsz = (nsiz-obj->arrMaxSize); obj->arr = (Jsi_Value**)Jsi_Realloc(obj->arr, nsiz*sizeof(Jsi_Value*)); memset(obj->arr+obj->arrMaxSize, 0, oldsz*sizeof(Jsi_Value*)); obj->arrMaxSize = nsiz; } if (len>obj->arrCnt) obj->arrCnt = len; return nsiz; }",CWE-190,2 0," virtual void TearDownOnIOThread() {} ",none,24 1,"export_desktop_file (const char *app, const char *branch, const char *arch, GKeyFile *metadata, const char * const *previous_ids, int parent_fd, const char *name, struct stat *stat_buf, char **target, GCancellable *cancellable, GError **error) { gboolean ret = FALSE; glnx_autofd int desktop_fd = -1; g_autofree char *tmpfile_name = g_strdup_printf (""export-desktop-XXXXXX""); g_autoptr(GOutputStream) out_stream = NULL; g_autofree gchar *data = NULL; gsize data_len; g_autofree gchar *new_data = NULL; gsize new_data_len; g_autoptr(GKeyFile) keyfile = NULL; g_autofree gchar *old_exec = NULL; gint old_argc; g_auto(GStrv) old_argv = NULL; g_auto(GStrv) groups = NULL; GString *new_exec = NULL; g_autofree char *escaped_app = maybe_quote (app); g_autofree char *escaped_branch = maybe_quote (branch); g_autofree char *escaped_arch = maybe_quote (arch); int i; if (!flatpak_openat_noatime (parent_fd, name, &desktop_fd, cancellable, error)) goto out; if (!read_fd (desktop_fd, stat_buf, &data, &data_len, error)) goto out; keyfile = g_key_file_new (); if (!g_key_file_load_from_data (keyfile, data, data_len, G_KEY_FILE_KEEP_TRANSLATIONS, error)) goto out; if (g_str_has_suffix (name, "".service"")) { g_autofree gchar *dbus_name = NULL; g_autofree gchar *expected_dbus_name = g_strndup (name, strlen (name) - strlen ("".service"")); dbus_name = g_key_file_get_string (keyfile, ""D-BUS Service"", ""Name"", NULL); if (dbus_name == NULL || strcmp (dbus_name, expected_dbus_name) != 0) { return flatpak_fail_error (error, FLATPAK_ERROR_EXPORT_FAILED, _(""D-Bus service file '%s' has wrong name""), name); } } if (g_str_has_suffix (name, "".desktop"")) { gsize length; g_auto(GStrv) tags = g_key_file_get_string_list (metadata, ""Application"", ""tags"", &length, NULL); if (tags != NULL) { g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, ""X-Flatpak-Tags"", (const char * const *) tags, length); } /* Add a marker so consumers can easily find out that this launches a sandbox */ g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, ""X-Flatpak"", app); /* If the app has been renamed, add its old .desktop filename to * X-Flatpak-RenamedFrom in the new .desktop file, taking care not to * introduce duplicates. */ if (previous_ids != NULL) { const char *X_FLATPAK_RENAMED_FROM = ""X-Flatpak-RenamedFrom""; g_auto(GStrv) renamed_from = g_key_file_get_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, NULL, NULL); g_autoptr(GPtrArray) merged = g_ptr_array_new_with_free_func (g_free); g_autoptr(GHashTable) seen = g_hash_table_new (g_str_hash, g_str_equal); const char *new_suffix; for (i = 0; renamed_from != NULL && renamed_from[i] != NULL; i++) { if (!g_hash_table_contains (seen, renamed_from[i])) { gchar *copy = g_strdup (renamed_from[i]); g_hash_table_insert (seen, copy, copy); g_ptr_array_add (merged, g_steal_pointer (©)); } } /* If an app was renamed from com.example.Foo to net.example.Bar, and * the new version exports net.example.Bar-suffix.desktop, we assume the * old version exported com.example.Foo-suffix.desktop. * * This assertion is true because * flatpak_name_matches_one_wildcard_prefix() is called on all * exported files before we get here. */ g_assert (g_str_has_prefix (name, app)); /* "".desktop"" for the ""main"" desktop file; something like * ""-suffix.desktop"" for extra ones. */ new_suffix = name + strlen (app); for (i = 0; previous_ids[i] != NULL; i++) { g_autofree gchar *previous_desktop = g_strconcat (previous_ids[i], new_suffix, NULL); if (!g_hash_table_contains (seen, previous_desktop)) { g_hash_table_insert (seen, previous_desktop, previous_desktop); g_ptr_array_add (merged, g_steal_pointer (&previous_desktop)); } } if (merged->len > 0) { g_ptr_array_add (merged, NULL); g_key_file_set_string_list (keyfile, G_KEY_FILE_DESKTOP_GROUP, X_FLATPAK_RENAMED_FROM, (const char * const *) merged->pdata, merged->len - 1); } } } groups = g_key_file_get_groups (keyfile, NULL); for (i = 0; groups[i] != NULL; i++) { g_auto(GStrv) flatpak_run_opts = g_key_file_get_string_list (keyfile, groups[i], ""X-Flatpak-RunOptions"", NULL, NULL); g_autofree char *flatpak_run_args = format_flatpak_run_args_from_run_opts (flatpak_run_opts); g_key_file_remove_key (keyfile, groups[i], ""X-Flatpak-RunOptions"", NULL); g_key_file_remove_key (keyfile, groups[i], ""TryExec"", NULL); /* Remove this to make sure nothing tries to execute it outside the sandbox*/ g_key_file_remove_key (keyfile, groups[i], ""X-GNOME-Bugzilla-ExtraInfoScript"", NULL); new_exec = g_string_new (""""); g_string_append_printf (new_exec, FLATPAK_BINDIR ""/flatpak run --branch=%s --arch=%s"", escaped_branch, escaped_arch); if (flatpak_run_args != NULL) g_string_append_printf (new_exec, ""%s"", flatpak_run_args); old_exec = g_key_file_get_string (keyfile, groups[i], ""Exec"", NULL); if (old_exec && g_shell_parse_argv (old_exec, &old_argc, &old_argv, NULL) && old_argc >= 1) { int j; g_autofree char *command = maybe_quote (old_argv[0]); g_string_append_printf (new_exec, "" --command=%s"", command); for (j = 1; j < old_argc; j++) { if (strcasecmp (old_argv[j], ""%f"") == 0 || strcasecmp (old_argv[j], ""%u"") == 0) { g_string_append (new_exec, "" --file-forwarding""); break; } } g_string_append (new_exec, "" ""); g_string_append (new_exec, escaped_app); for (j = 1; j < old_argc; j++) { g_autofree char *arg = maybe_quote (old_argv[j]); if (strcasecmp (arg, ""%f"") == 0) g_string_append_printf (new_exec, "" @@ %s @@"", arg); else if (strcasecmp (arg, ""%u"") == 0) g_string_append_printf (new_exec, "" @@u %s @@"", arg); else if (g_str_has_prefix (arg, ""@@"")) g_print (_(""Skipping invalid Exec argument %s\n""), arg); else g_string_append_printf (new_exec, "" %s"", arg); } } else { g_string_append (new_exec, "" ""); g_string_append (new_exec, escaped_app); } g_key_file_set_string (keyfile, groups[i], G_KEY_FILE_DESKTOP_KEY_EXEC, new_exec->str); } new_data = g_key_file_to_data (keyfile, &new_data_len, error); if (new_data == NULL) goto out; if (!flatpak_open_in_tmpdir_at (parent_fd, 0755, tmpfile_name, &out_stream, cancellable, error)) goto out; if (!g_output_stream_write_all (out_stream, new_data, new_data_len, NULL, cancellable, error)) goto out; if (!g_output_stream_close (out_stream, cancellable, error)) goto out; if (target) *target = g_steal_pointer (&tmpfile_name); ret = TRUE; out: if (new_exec != NULL) g_string_free (new_exec, TRUE); return ret; }",CWE-94,23 1,"void LibRaw::parse_exif(int base) { unsigned entries, tag, type, len, save, c; double expo, ape; unsigned kodak = !strncmp(make, ""EASTMAN"", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, ""Hasselblad"", 10) && (tiff_nifds > 3) && (entries > 512)) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp, base); fseek(ifp, savepos, SEEK_SET); } switch (tag) { case 0xA005: // Interoperability IFD fseek(ifp, get4() + base, SEEK_SET); parse_exif_interop(base); break; case 0xA001: // ExifIFD.ColorSpace c = get2(); if (c == 1 && imgdata.color.ExifColorSpace == LIBRAW_COLORSPACE_Unknown) imgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_sRGB; else if (c == 2) imgdata.color.ExifColorSpace = LIBRAW_COLORSPACE_AdobeRGB; break; case 0x9400: imCommon.exifAmbientTemperature = getreal(type); if ((imCommon.CameraTemperature > -273.15f) && ((OlyID == OlyID_TG_5) || (OlyID == OlyID_TG_6)) ) imCommon.CameraTemperature += imCommon.exifAmbientTemperature; break; case 0x9401: imCommon.exifHumidity = getreal(type); break; case 0x9402: imCommon.exifPressure = getreal(type); break; case 0x9403: imCommon.exifWaterDepth = getreal(type); break; case 0x9404: imCommon.exifAcceleration = getreal(type); break; case 0x9405: imCommon.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); if (!strncmp(imgdata.lens.LensSerial, ""----"", 4)) imgdata.lens.LensSerial[0] = '\0'; break; case 0xa420: /* 42016, ImageUniqueID */ stmread(imgdata.color.ImageUniqueID, len, ifp); break; case 0xc65d: /* 50781, RawDataUniqueID */ imgdata.color.RawDataUniqueID[16] = 0; fread(imgdata.color.RawDataUniqueID, 1, 16, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xc68b: /* 50827, OriginalRawFileName */ stmread(imgdata.color.OriginalRawFileName, len, ifp); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, ""----"", 4)) imgdata.lens.Lens[0] = '\0'; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; case 0x829a: // 33434 tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 0x829d: // 33437, FNumber aperture = getreal(type); break; case 0x8827: // 34855 iso_speed = get2(); break; case 0x8831: // 34865 if (iso_speed == 0xffff && !strncasecmp(make, ""FUJI"", 4)) iso_speed = getreal(type); break; case 0x8832: // 34866 if (iso_speed == 0xffff && (!strncasecmp(make, ""SONY"", 4) || !strncasecmp(make, ""CANON"", 5))) iso_speed = getreal(type); break; case 0x9003: // 36867 case 0x9004: // 36868 get_timestamp(0); break; case 0x9201: // 37377 if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = libraw_powf64l(2.0, expo); break; case 0x9202: // 37378 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = libraw_powf64l(2.0, ape / 2); break; case 0x9209: // 37385 flash_used = getreal(type); break; case 0x920a: // 37386 focal_len = getreal(type); break; case 0x927c: // 37500 if (((make[0] == '\0') && !strncmp(model, ""ov5647"", 6)) || (!strncmp(make, ""RaspberryPi"", 11) && (!strncmp(model, ""RP_OV5647"", 9) || !strncmp(model, ""RP_imx219"", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len, 511), ifp); mn_text[511] = 0; pos = strstr(mn_text, ""gain_r=""); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, ""gain_b=""); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, ""ccm=""); if (pos) { pos += 4; char *pos2 = strstr(pos, "" ""); if (pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #ifdef LIBRAW_WIN32_CALLS // Win32 strtok is already thread-safe pos = strtok(ccms, "",""); #else char *last = 0; pos = strtok_r(ccms, "","", &last); #endif if (pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #ifdef LIBRAW_WIN32_CALLS pos = strtok(NULL, "",""); #else pos = strtok_r(NULL, "","", &last); #endif if (!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else if (!strncmp(make, ""SONY"", 4) && (!strncmp(model, ""DSC-V3"", 6) || !strncmp(model, ""DSC-F828"", 8))) { parseSonySRF(len); break; } else if ((len == 1) && !strncmp(make, ""NIKON"", 5)) { c = get4(); if (c) fseek(ifp, c, SEEK_SET); is_NikonTransfer = 1; } parse_makernote(base, 0); break; case 0xa002: // 40962 if (kodak) raw_width = get4(); break; case 0xa003: // 40963 if (kodak) raw_height = get4(); break; case 0xa302: // 41730 if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101U << c; } fseek(ifp, save, SEEK_SET); } }",CWE-787,16 0,"size_t imageSizeInBytes(unsigned width, unsigned height, unsigned format, unsigned type) { return width * height * bytesPerComponent(type) * componentsPerPixel(format, type); } ",none,24 1,"void luaD_callnoyield (lua_State *L, StkId func, int nResults) { incXCcalls(L); if (getCcalls(L) <= CSTACKERR) /* possible stack overflow? */ luaE_freeCI(L); luaD_call(L, func, nResults); decXCcalls(L); }",CWE-787,16 0," void Stop() { decoder_->Stop(NewExpectedClosure()); message_loop_.RunAllPending(); } ",none,24 0,"bool TranslateManager::IsAcceptLanguage(TabContents* tab, const std::string& language) { PrefService* pref_service = tab->profile()->GetPrefs(); PrefServiceLanguagesMap::const_iterator iter = accept_languages_.find(pref_service); if (iter == accept_languages_.end()) { InitAcceptLanguages(pref_service); notification_registrar_.Add(this, NotificationType::PROFILE_DESTROYED, Source(tab->profile())); pref_change_registrar_.Add(prefs::kAcceptLanguages, this); iter = accept_languages_.find(pref_service); } return iter->second.count(language) != 0; } ",none,24 1,"static int stszin(int size) { int cnt; uint32_t ofs; // version/flags u32in(); // Sample size u32in(); // Number of entries mp4config.frame.ents = u32in(); // fixme: check atom size mp4config.frame.data = malloc(sizeof(*mp4config.frame.data) * (mp4config.frame.ents + 1)); if (!mp4config.frame.data) return ERR_FAIL; ofs = 0; mp4config.frame.data[0] = ofs; for (cnt = 0; cnt < mp4config.frame.ents; cnt++) { uint32_t fsize = u32in(); ofs += fsize; if (mp4config.frame.maxsize < fsize) mp4config.frame.maxsize = fsize; mp4config.frame.data[cnt + 1] = ofs; if (ofs < mp4config.frame.data[cnt]) return ERR_FAIL; } return size; }",CWE-787,16 1,"GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth) { u32 i, sceneT, odT, descIndex, size, size64; GF_InitialObjectDescriptor *iod; GF_SLConfig slc; GF_ISOSample *samp; Bool remove_ocr; u8 *buffer; char buf64[5000], sdpLine[5100]; gf_isom_sdp_clean(file); if (bandwidth) { sprintf(buf64, ""b=AS:%d"", bandwidth); gf_isom_sdp_add_line(file, buf64); } //xtended attribute for copyright if (gf_sys_is_test_mode()) { sprintf(buf64, ""a=x-copyright: %s"", ""MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)""); } else { sprintf(buf64, ""a=x-copyright: MP4/3GP File hinted with GPAC %s - %s"", gf_gpac_version(), gf_gpac_copyright() ); } gf_isom_sdp_add_line(file, buf64); if (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK; odT = sceneT = 0; for (i=0; iESDescriptors)) { esd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0); gf_odf_desc_del((GF_Descriptor *) esd); gf_list_rem(iod->ESDescriptors, 0); } /*get OD esd, and embbed stream data if possible*/ if (odT) { esd = gf_isom_get_esd(file, odT, 1); if (gf_isom_get_sample_count(file, odT)==1) { samp = gf_isom_get_sample(file, odT, 1, &descIndex); if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) { InitSL_NULL(&slc); slc.predefined = 0; slc.hasRandomAccessUnitsOnlyFlag = 1; slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, odT, 1, &slc); size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, ""data:application/mpeg4-od-au;base64,%s"", buf64); esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; size64 = (u32) strlen(sdpLine)+1; esd->URLString = (char*)gf_malloc(sizeof(char) * size64); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_RTP, (""[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\n"")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; //OK, add this to our IOD gf_list_add(iod->ESDescriptors, esd); } esd = gf_isom_get_esd(file, sceneT, 1); if (gf_isom_get_sample_count(file, sceneT)==1) { samp = gf_isom_get_sample(file, sceneT, 1, &descIndex); if (gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) { slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, sceneT, 1, &slc); //encode in Base64 the sample size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, ""data:application/mpeg4-bifs-au;base64,%s"", buf64); esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; esd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1)); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, (""[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\n"")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; gf_list_add(iod->ESDescriptors, esd); if (is_ok) { u32 has_a, has_v, has_i_a, has_i_v; has_a = has_v = has_i_a = has_i_v = 0; for (i=0; idecoderConfig->streamType==GF_STREAM_VISUAL) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++; else has_v++; } else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++; else has_a++; } gf_odf_desc_del((GF_Descriptor *)esd); } /*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/ if (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) { sprintf(sdpLine, ""a=isma-compliance:1,1.0,1""); gf_isom_sdp_add_line(file, sdpLine); } } } //encode the IOD buffer = NULL; size = 0; gf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size); gf_odf_desc_del((GF_Descriptor *)iod); //encode in Base64 the iod size64 = gf_base64_encode(buffer, size, buf64, 2000); buf64[size64] = 0; gf_free(buffer); sprintf(sdpLine, ""a=mpeg4-iod:\""data:application/mpeg4-iod;base64,%s\"""", buf64); gf_isom_sdp_add_line(file, sdpLine); return GF_OK; }",CWE-476,12 1," void Compute(OpKernelContext* context) override { const Tensor& tensor_in = context->input(0); const Tensor& tensor_out = context->input(1); const Tensor& out_grad_backprop = context->input(2); // For maxpooling3d, tensor_in should have 5 dimensions. OP_REQUIRES(context, tensor_in.dims() == 5, errors::InvalidArgument(""tensor_in must be 5-dimensional"")); OP_REQUIRES(context, tensor_out.dims() == 5, errors::InvalidArgument(""tensor_out must be 5-dimensional"")); // For maxpooling3d, out_grad_backprop should have 5 dimensions. OP_REQUIRES( context, out_grad_backprop.dims() == 5, errors::InvalidArgument(""out_grad_backprop must be 5-dimensional"")); Pool3dParameters params{context, ksize_, stride_, padding_, data_format_, tensor_in.shape()}; Tensor* output = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {2}, 0, tensor_out.shape(), &output)); LaunchMaxPooling3dGradGradOp::launch( context, params, tensor_in, tensor_out, out_grad_backprop, output); }",CWE-476,12 1,"static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, UINT16 flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; UINT32 new_len; BYTE* new_data; CACHE_BITMAP_V3_ORDER* cache_bitmap_v3; if (!update || !s) return NULL; cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!cache_bitmap_v3) goto fail; cache_bitmap_v3->cacheId = flags & 0x00000003; cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; bitsPerPixelId = (flags & 0x00000078) >> 3; cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId]; if (Stream_GetRemainingLength(s) < 21) goto fail; Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ bitmapData = &cache_bitmap_v3->bitmapData; Stream_Read_UINT8(s, bitmapData->bpp); if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32)) { WLog_Print(update->log, WLOG_ERROR, ""invalid bpp value %"" PRIu32 """", bitmapData->bpp); goto fail; } Stream_Seek_UINT8(s); /* reserved1 (1 byte) */ Stream_Seek_UINT8(s); /* reserved2 (1 byte) */ Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Read_UINT32(s, new_len); /* length (4 bytes) */ if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len)) goto fail; new_data = (BYTE*)realloc(bitmapData->data, new_len); if (!new_data) goto fail; bitmapData->data = new_data; bitmapData->length = new_len; Stream_Read(s, bitmapData->data, bitmapData->length); return cache_bitmap_v3; fail: free_cache_bitmap_v3_order(update->context, cache_bitmap_v3); return NULL; }",CWE-125,1 1,"GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack) { u32 i; if (!nb_pack) nb_pack = 1; if (!stbl->SampleSize->sampleCount) { stbl->SampleSize->sampleSize = size; stbl->SampleSize->sampleCount += nb_pack; return GF_OK; } if (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) { stbl->SampleSize->sampleCount += nb_pack; return GF_OK; } if (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) { Bool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0; ALLOC_INC(stbl->SampleSize->alloc_size); if (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size) stbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack; stbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size); if (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM; memset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) ); if (init_table) { for (i=0; iSampleSize->sampleCount; i++) stbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize; } } stbl->SampleSize->sampleSize = 0; for (i=0; iSampleSize->sizes[stbl->SampleSize->sampleCount+i] = size; } stbl->SampleSize->sampleCount += nb_pack; if (size > stbl->SampleSize->max_size) stbl->SampleSize->max_size = size; stbl->SampleSize->total_size += size; stbl->SampleSize->total_samples += nb_pack; return GF_OK; }",CWE-787,16 1,"int ssl3_send_client_key_exchange(SSL *s) { unsigned char *p,*d; int n; unsigned long l; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX * bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { d=(unsigned char *)s->init_buf->data; p= &(d[4]); l=s->s3->tmp.new_cipher->algorithms; /* Fool emacs indentation */ if (0) {} #ifndef OPENSSL_NO_RSA else if (l & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa=s->session->sess_cert->peer_rsa_tmp; else { pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } rsa=pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; s->session->master_key_length=sizeof tmp_buf; q=p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p+=2; n=RSA_public_encrypt(sizeof tmp_buf, tmp_buf,p,rsa,RSA_PKCS1_PADDING); #ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; #endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n,q); n+=2; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf,sizeof tmp_buf); OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (l & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); #ifdef KSSL_DEBUG printf(""ssl3_send_client_key_exchange(%lx & %lx)\n"", l, SSL_kKRB5); #endif /* KSSL_DEBUG */ authp = NULL; #ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; #endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; #ifdef KSSL_DEBUG { printf(""kssl_cget_tkt rtn %d\n"", krb5rc); if (krb5rc && kssl_err.text) printf(""kssl_cget_tkt kssl_err=%s\n"", kssl_err.text); } #endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /* 20010406 VRS - Earlier versions used KRB5 AP_REQ ** in place of RFC 2712 KerberosWrapper, as in: ** ** Send ticket (copy to *p, set n = length) ** n = krb5_ap_req.length; ** memcpy(p, krb5_ap_req.data, krb5_ap_req.length); ** if (krb5_ap_req.data) ** kssl_krb5_free_data_contents(NULL,&krb5_ap_req); ** ** Now using real RFC 2712 KerberosWrapper ** (Thanks to Simon Wilkinson ) ** Note: 2712 ""opaque"" types are here replaced ** with a 2-byte length followed by the value. ** Example: ** KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms ** Where ""xx xx"" = length bytes. Shown here with ** optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length,p); memcpy(p, enc_ticket->data, enc_ticket->length); p+= enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length,p); memcpy(p, authp->data, authp->length); p+= authp->length; n+= authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0,p);/* null authenticator length */ n+=2; } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; /* 20010420 VRS. Tried it this way; failed. ** EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); ** EVP_CIPHER_CTX_set_key_length(&ciph_ctx, ** kssl_ctx->length); ** EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, kssl_ctx->key,iv); EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); outl += padl; if (outl > sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl,p); memcpy(p, epms, outl); p+=outl; n+=outl + 2; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) { DH *dh_srvr,*dh_clnt; if (s->session->sess_cert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } if (s->session->sess_cert->peer_dh_tmp != NULL) dh_srvr=s->session->sess_cert->peer_dh_tmp; else { /* we get them from the cert */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS); goto err; } /* generate a new random key */ if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } /* use the 'p' output buffer for the DH key, but * make sure to clear it out afterwards */ n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,n); /* clean up */ memset(p,0,n); /* send off the data */ n=BN_num_bytes(dh_clnt->pub_key); s2n(n,p); BN_bn2bin(dh_clnt->pub_key,p); n+=2; DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY*/ } #endif #ifndef OPENSSL_NO_ECDH else if ((l & SSL_kECDH) || (l & SSL_kECDHE)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; /* Did we send out the client's * ECDH share for use in premaster * computation as part of client certificate? * If so, set ecdh_clnt_cert to 1. */ if ((l & SSL_kECDH) && (s->cert != NULL)) { /* XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> \ sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* Reuse key info from our certificate * We only need our private key to perform * the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* use the 'p' output buffer for the ECDH key, but * make sure to clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc \ -> generate_master_secret(s, s->session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* First check the size of encoding and * allocate memory accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE; l2n3(n,d); s->state=SSL3_ST_CW_KEY_EXCH_B; /* number of bytes to write */ s->init_num=n+4; s->init_off=0; } /* SSL3_ST_CW_KEY_EXCH_B */ return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif return(-1); }",CWE-476,12 0,"base::ListValue* ContentSettingsStore::GetSettingsForExtension( const std::string& extension_id, ExtensionPrefsScope scope) const { base::AutoLock lock(lock_); const OriginIdentifierValueMap* map = GetValueMap(extension_id, scope); if (!map) return NULL; base::ListValue* settings = new base::ListValue(); OriginIdentifierValueMap::EntryMap::const_iterator it; for (it = map->begin(); it != map->end(); ++it) { scoped_ptr rule_iterator( map->GetRuleIterator(it->first.content_type, it->first.resource_identifier, NULL)); // We already hold the lock. while (rule_iterator->HasNext()) { const Rule& rule = rule_iterator->Next(); base::DictionaryValue* setting_dict = new base::DictionaryValue(); setting_dict->SetString(keys::kPrimaryPatternKey, rule.primary_pattern.ToString()); setting_dict->SetString(keys::kSecondaryPatternKey, rule.secondary_pattern.ToString()); setting_dict->SetString( keys::kContentSettingsTypeKey, helpers::ContentSettingsTypeToString(it->first.content_type)); setting_dict->SetString(keys::kResourceIdentifierKey, it->first.resource_identifier); ContentSetting content_setting = ValueToContentSetting(rule.value.get()); DCHECK_NE(CONTENT_SETTING_DEFAULT, content_setting); setting_dict->SetString( keys::kContentSettingKey, helpers::ContentSettingToString(content_setting)); settings->Append(setting_dict); } } return settings; } ",none,24 0,"void ContentSettingsStore::SetExtensionContentSettingFromList( const std::string& extension_id, const base::ListValue* list, ExtensionPrefsScope scope) { for (base::ListValue::const_iterator it = list->begin(); it != list->end(); ++it) { if ((*it)->GetType() != Value::TYPE_DICTIONARY) { NOTREACHED(); continue; } base::DictionaryValue* dict = static_cast(*it); std::string primary_pattern_str; dict->GetString(keys::kPrimaryPatternKey, &primary_pattern_str); ContentSettingsPattern primary_pattern = ContentSettingsPattern::FromString(primary_pattern_str); DCHECK(primary_pattern.IsValid()); std::string secondary_pattern_str; dict->GetString(keys::kSecondaryPatternKey, &secondary_pattern_str); ContentSettingsPattern secondary_pattern = ContentSettingsPattern::FromString(secondary_pattern_str); DCHECK(secondary_pattern.IsValid()); std::string content_settings_type_str; dict->GetString(keys::kContentSettingsTypeKey, &content_settings_type_str); ContentSettingsType content_settings_type = helpers::StringToContentSettingsType(content_settings_type_str); DCHECK_NE(CONTENT_SETTINGS_TYPE_DEFAULT, content_settings_type); std::string resource_identifier; dict->GetString(keys::kResourceIdentifierKey, &resource_identifier); std::string content_setting_string; dict->GetString(keys::kContentSettingKey, &content_setting_string); ContentSetting setting = CONTENT_SETTING_DEFAULT; bool result = helpers::StringToContentSetting(content_setting_string, &setting); DCHECK(result); SetExtensionContentSetting(extension_id, primary_pattern, secondary_pattern, content_settings_type, resource_identifier, setting, scope); } } ",none,24 0,"unsigned WebGraphicsContext3DDefaultImpl::createShader(unsigned long shaderType) { makeContextCurrent(); ASSERT(shaderType == GL_VERTEX_SHADER || shaderType == GL_FRAGMENT_SHADER); unsigned shader = glCreateShader(shaderType); if (shader) { ShaderSourceMap::iterator result = m_shaderSourceMap.find(shader); if (result != m_shaderSourceMap.end()) delete result->second; m_shaderSourceMap.set(shader, new ShaderSourceEntry(shaderType)); } return shader; } ",none,24 1,"spell_read_tree( FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, /* TRUE for the prefix tree */ int prefixcnt) /* when ""prefixtree"" is TRUE: prefix count */ { int len; int idx; char_u *bp; idx_T *ip; /* The tree size was computed when writing the file, so that we can * allocate it as one long block. */ len = get4c(fd); if (len < 0) return SP_TRUNCERROR; if (len > 0) { /* Allocate the byte array. */ bp = lalloc((long_u)len, TRUE); if (bp == NULL) return SP_OTHERERROR; *bytsp = bp; /* Allocate the index array. */ ip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE); if (ip == NULL) return SP_OTHERERROR; *idxsp = ip; /* Recursively read the tree and store it in the array. */ idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt); if (idx < 0) return idx; } return 0; }",CWE-190,2 1,"enum_func_status php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ DBG_ENTER(""php_mysqlnd_rowp_read_text_protocol_aux""); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF(""Directly creating zval""); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ unsigned long len = php_mysqlnd_net_field_length(&p); if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, ""%ld"", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS);",CWE-119,0 0,"void WebGraphicsContext3DDefaultImpl::drawElements(unsigned long mode, unsigned long count, unsigned long type, long offset) { makeContextCurrent(); glDrawElements(mode, count, type, reinterpret_cast(static_cast(offset))); } ",none,24 0,"unsigned long WebGraphicsContext3DDefaultImpl::getError() { if (m_syntheticErrors.size() > 0) { ListHashSet::iterator iter = m_syntheticErrors.begin(); unsigned long err = *iter; m_syntheticErrors.remove(iter); return err; } makeContextCurrent(); return glGetError(); } ",none,24 0,"void VideoRendererBase::SetPlaybackRate(float playback_rate) { base::AutoLock auto_lock(lock_); playback_rate_ = playback_rate; } ",none,24 1,"escape_xml(const char *text) { static char *escaped; static size_t escaped_size; char *out; size_t len; if (!strlen(text)) return ""empty string""; for (out=escaped, len=0; *text; ++len, ++out, ++text) { /* Make sure there's plenty of room for a quoted character */ if ((len + 8) > escaped_size) { char *bigger_escaped; escaped_size += 128; bigger_escaped = realloc(escaped, escaped_size); if (!bigger_escaped) { free(escaped); /* avoid leaking memory */ escaped = NULL; escaped_size = 0; /* Error string is cleverly chosen to fail XML validation */ return "">>> out of memory <<<""; } out = bigger_escaped + len; escaped = bigger_escaped; } switch (*text) { case '&': strcpy(out, ""&""); len += strlen(out) - 1; out = escaped + len; break; case '<': strcpy(out, ""<""); len += strlen(out) - 1; out = escaped + len; break; case '>': strcpy(out, "">""); len += strlen(out) - 1; out = escaped + len; break; default: *out = *text; break; } } *out = '\x0'; /* NUL terminate the string */ return escaped; }",CWE-476,12 0,"void WebGraphicsContext3DDefaultImpl::deleteRenderbuffer(unsigned renderbuffer) { makeContextCurrent(); glDeleteRenderbuffersEXT(1, &renderbuffer); } ",none,24 0,"void VideoRendererBase::AttemptFlush_Locked() { lock_.AssertAcquired(); DCHECK_EQ(kFlushing, state_); ready_frames_.clear(); if (!pending_paint_ && !pending_read_) { state_ = kFlushed; current_frame_ = NULL; base::ResetAndReturn(&flush_cb_).Run(); } } ",none,24 1,"slap_modrdn2mods( Operation *op, SlapReply *rs ) { int a_cnt, d_cnt; LDAPRDN old_rdn = NULL; LDAPRDN new_rdn = NULL; assert( !BER_BVISEMPTY( &op->oq_modrdn.rs_newrdn ) ); /* if requestDN is empty, silently reset deleteOldRDN */ if ( BER_BVISEMPTY( &op->o_req_dn ) ) op->orr_deleteoldrdn = 0; if ( ldap_bv2rdn_x( &op->oq_modrdn.rs_newrdn, &new_rdn, (char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: can't figure out "" ""type(s)/value(s) of newrdn\n"", op->o_log_prefix, 0, 0 ); rs->sr_err = LDAP_INVALID_DN_SYNTAX; rs->sr_text = ""unknown type(s)/value(s) used in RDN""; goto done; } if ( op->oq_modrdn.rs_deleteoldrdn ) { if ( ldap_bv2rdn_x( &op->o_req_dn, &old_rdn, (char **)&rs->sr_text, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx ) ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: can't figure out "" ""type(s)/value(s) of oldrdn\n"", op->o_log_prefix, 0, 0 ); rs->sr_err = LDAP_OTHER; rs->sr_text = ""cannot parse RDN from old DN""; goto done; } } rs->sr_text = NULL; /* Add new attribute values to the entry */ for ( a_cnt = 0; new_rdn[a_cnt]; a_cnt++ ) { AttributeDescription *desc = NULL; Modifications *mod_tmp; rs->sr_err = slap_bv2ad( &new_rdn[a_cnt]->la_attr, &desc, &rs->sr_text ); if ( rs->sr_err != LDAP_SUCCESS ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (new)\n"", op->o_log_prefix, rs->sr_text, new_rdn[ a_cnt ]->la_attr.bv_val ); goto done; } if ( !desc->ad_type->sat_equality ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (new)\n"", op->o_log_prefix, rs->sr_text, new_rdn[ a_cnt ]->la_attr.bv_val ); rs->sr_text = ""naming attribute has no equality matching rule""; rs->sr_err = LDAP_NAMING_VIOLATION; goto done; } /* Apply modification */ mod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) ); mod_tmp->sml_desc = desc; BER_BVZERO( &mod_tmp->sml_type ); mod_tmp->sml_numvals = 1; mod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); ber_dupbv( &mod_tmp->sml_values[0], &new_rdn[a_cnt]->la_value ); mod_tmp->sml_values[1].bv_val = NULL; if( desc->ad_type->sat_equality->smr_normalize) { mod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); rs->sr_err = desc->ad_type->sat_equality->smr_normalize( SLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, desc->ad_type->sat_syntax, desc->ad_type->sat_equality, &mod_tmp->sml_values[0], &mod_tmp->sml_nvalues[0], NULL ); if (rs->sr_err != LDAP_SUCCESS) { ch_free(mod_tmp->sml_nvalues); ch_free(mod_tmp->sml_values[0].bv_val); ch_free(mod_tmp->sml_values); ch_free(mod_tmp); goto done; } mod_tmp->sml_nvalues[1].bv_val = NULL; } else { mod_tmp->sml_nvalues = NULL; } mod_tmp->sml_op = SLAP_MOD_SOFTADD; mod_tmp->sml_flags = 0; mod_tmp->sml_next = op->orr_modlist; op->orr_modlist = mod_tmp; } /* Remove old rdn value if required */ if ( op->orr_deleteoldrdn ) { for ( d_cnt = 0; old_rdn[d_cnt]; d_cnt++ ) { AttributeDescription *desc = NULL; Modifications *mod_tmp; rs->sr_err = slap_bv2ad( &old_rdn[d_cnt]->la_attr, &desc, &rs->sr_text ); if ( rs->sr_err != LDAP_SUCCESS ) { Debug( LDAP_DEBUG_TRACE, ""%s slap_modrdn2mods: %s: %s (old)\n"", op->o_log_prefix, rs->sr_text, old_rdn[d_cnt]->la_attr.bv_val ); goto done; } /* Apply modification */ mod_tmp = ( Modifications * )ch_malloc( sizeof( Modifications ) ); mod_tmp->sml_desc = desc; BER_BVZERO( &mod_tmp->sml_type ); mod_tmp->sml_numvals = 1; mod_tmp->sml_values = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); ber_dupbv( &mod_tmp->sml_values[0], &old_rdn[d_cnt]->la_value ); mod_tmp->sml_values[1].bv_val = NULL; if( desc->ad_type->sat_equality->smr_normalize) { mod_tmp->sml_nvalues = ( BerVarray )ch_malloc( 2 * sizeof( struct berval ) ); (void) (*desc->ad_type->sat_equality->smr_normalize)( SLAP_MR_EQUALITY|SLAP_MR_VALUE_OF_ASSERTION_SYNTAX, desc->ad_type->sat_syntax, desc->ad_type->sat_equality, &mod_tmp->sml_values[0], &mod_tmp->sml_nvalues[0], NULL ); mod_tmp->sml_nvalues[1].bv_val = NULL; } else { mod_tmp->sml_nvalues = NULL; } mod_tmp->sml_op = LDAP_MOD_DELETE; mod_tmp->sml_flags = 0; mod_tmp->sml_next = op->orr_modlist; op->orr_modlist = mod_tmp; } } done: /* LDAP v2 supporting correct attribute handling. */ if ( rs->sr_err != LDAP_SUCCESS && op->orr_modlist != NULL ) { Modifications *tmp; for ( ; op->orr_modlist != NULL; op->orr_modlist = tmp ) { tmp = op->orr_modlist->sml_next; ch_free( op->orr_modlist ); } } if ( new_rdn != NULL ) { ldap_rdnfree_x( new_rdn, op->o_tmpmemctx ); } if ( old_rdn != NULL ) { ldap_rdnfree_x( old_rdn, op->o_tmpmemctx ); } return rs->sr_err; }",CWE-476,12 0," void BlobURLRequestJob::NotifySuccess() { int status_code = 0; std::string status_text; if (byte_range_set_ && byte_range_.IsValid()) { status_code = kHTTPPartialContent; status_text += kHTTPPartialContentText; } else { status_code = kHTTPOk; status_text = kHTTPOKText; } HeadersCompleted(status_code, status_text); } ",none,24 0,"std::unique_ptr ClipboardReader::Create( const String& mime_type) { if (mime_type == kMimeTypeImagePng) return std::make_unique(); if (mime_type == kMimeTypeTextPlain) return std::make_unique(); return nullptr; } ",none,24 0,"unsigned WebGraphicsContext3DDefaultImpl::createTexture() { makeContextCurrent(); GLuint o; glGenTextures(1, &o); return o; } ",none,24 1,"xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { zend_bool old; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; ctxt->sax->error = NULL; /*ctxt->sax->fatalError = NULL;*/ #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif old = php_libxml_disable_entity_loader(1); xmlParseDocument(ctxt); php_libxml_disable_entity_loader(old); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; }",CWE-200,4 1,"file_continue(i_ctx_t *i_ctx_p) { os_ptr op = osp; es_ptr pscratch = esp - 2; file_enum *pfen = r_ptr(esp - 1, file_enum); int devlen = esp[-3].value.intval; gx_io_device *iodev = r_ptr(esp - 4, gx_io_device); uint len = r_size(pscratch); uint code; if (len < devlen) return_error(gs_error_rangecheck); /* not even room for device len */ memcpy((char *)pscratch->value.bytes, iodev->dname, devlen); code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen, len - devlen); if (code == ~(uint) 0) { /* all done */ esp -= 5; /* pop proc, pfen, devlen, iodev , mark */ return o_pop_estack; } else if (code > len) /* overran string */ return_error(gs_error_rangecheck); else { push(1); ref_assign(op, pscratch); r_set_size(op, code + devlen); push_op_estack(file_continue); /* come again */ *++esp = pscratch[2]; /* proc */ return o_push_estack; } }",CWE-200,4 1,"static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; BYTE* next; BYTE orderType; UINT16 extraFlags; UINT16 orderLength; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpSecondaryUpdate* secondary = update->secondary; const char* name; if (Stream_GetRemainingLength(s) < 5) { WLog_Print(update->log, WLOG_ERROR, ""Stream_GetRemainingLength(s) < 5""); return FALSE; } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */ next = Stream_Pointer(s) + ((INT16)orderLength) + 7; name = secondary_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, ""Secondary Drawing Order %s"", name); if (!check_secondary_order_supported(update->log, settings, orderType, name)) return FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: { const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED); CACHE_BITMAP_ORDER* order = update_read_cache_bitmap_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order); free_cache_bitmap_order(context, order); } } break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: { const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2); CACHE_BITMAP_V2_ORDER* order = update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order); free_cache_bitmap_v2_order(context, order); } } break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: { CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order); free_cache_bitmap_v3_order(context, order); } } break; case ORDER_TYPE_CACHE_COLOR_TABLE: { CACHE_COLOR_TABLE_ORDER* order = update_read_cache_color_table_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order); free_cache_color_table_order(context, order); } } break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: { CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order); free_cache_glyph_order(context, order); } } break; case GLYPH_SUPPORT_ENCODE: { CACHE_GLYPH_V2_ORDER* order = update_read_cache_glyph_v2_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order); free_cache_glyph_v2_order(context, order); } } break; case GLYPH_SUPPORT_NONE: default: break; } } break; case ORDER_TYPE_CACHE_BRUSH: /* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */ { CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order); free_cache_brush_order(context, order); } } break; default: WLog_Print(update->log, WLOG_WARN, ""SECONDARY ORDER %s not supported"", name); break; } if (!rc) { WLog_Print(update->log, WLOG_ERROR, ""SECONDARY ORDER %s failed"", name); } Stream_SetPointer(s, next); return rc; }",CWE-125,1 0,"void WebGraphicsContext3DDefaultImpl::bindBuffer(unsigned long target, WebGLId buffer) { makeContextCurrent(); if (target == GL_ARRAY_BUFFER) m_boundArrayBuffer = buffer; glBindBuffer(target, buffer); } ",none,24 1,"static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies ""name"" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that ""sz"" and ""rawdata"" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, ""sz must be NULL""); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, ""rawdata must be NULL""); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for ""data"", and possibly ""method"". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, ""unknown compression method: %d"", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmpbase.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf(""%s/"", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, ""duplicate name: \""%s\"""", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; }",CWE-434,11 0,"WebGraphicsContext3DDefaultImpl::VertexAttribPointerState::VertexAttribPointerState() : enabled(false) , buffer(0) , indx(0) , size(0) , type(0) , normalized(false) , stride(0) , offset(0) { } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::reshape(int width, int height) { m_cachedWidth = width; m_cachedHeight = height; makeContextCurrent(); GLenum target = GL_TEXTURE_2D; if (!m_texture) { m_texture = createTextureObject(target); glGenFramebuffersEXT(1, &m_fbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); m_boundFBO = m_fbo; if (m_attributes.depth || m_attributes.stencil) glGenRenderbuffersEXT(1, &m_depthStencilBuffer); if (m_attributes.antialias) { glGenFramebuffersEXT(1, &m_multisampleFBO); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); m_boundFBO = m_multisampleFBO; glGenRenderbuffersEXT(1, &m_multisampleColorBuffer); if (m_attributes.depth || m_attributes.stencil) glGenRenderbuffersEXT(1, &m_multisampleDepthStencilBuffer); } } GLint internalColorFormat, colorFormat, internalDepthStencilFormat = 0; if (m_attributes.alpha) { internalColorFormat = GL_RGBA8; colorFormat = GL_RGBA; } else { internalColorFormat = GL_RGB8; colorFormat = GL_RGB; } if (m_attributes.stencil || m_attributes.depth) { if (m_attributes.stencil && m_attributes.depth) internalDepthStencilFormat = GL_DEPTH24_STENCIL8_EXT; else internalDepthStencilFormat = GL_DEPTH_COMPONENT; } bool mustRestoreFBO = false; if (m_attributes.antialias) { GLint maxSampleCount; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSampleCount); GLint sampleCount = std::min(8, maxSampleCount); if (m_boundFBO != m_multisampleFBO) { mustRestoreFBO = true; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); } glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleColorBuffer); glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalColorFormat, width, height); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, m_multisampleColorBuffer); if (m_attributes.stencil || m_attributes.depth) { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, sampleCount, internalDepthStencilFormat, width, height); if (m_attributes.stencil) glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); if (m_attributes.depth) glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_multisampleDepthStencilBuffer); } glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { printf(""GraphicsContext3D: multisampling framebuffer was incomplete\n""); notImplemented(); } } if (m_boundFBO != m_fbo) { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); mustRestoreFBO = true; } glBindTexture(target, m_texture); glTexImage2D(target, 0, internalColorFormat, width, height, 0, colorFormat, GL_UNSIGNED_BYTE, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, m_texture, 0); glBindTexture(target, 0); if (!m_attributes.antialias && (m_attributes.stencil || m_attributes.depth)) { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthStencilBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internalDepthStencilFormat, width, height); if (m_attributes.stencil) glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer); if (m_attributes.depth) glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthStencilBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); } GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { printf(""WebGraphicsContext3DDefaultImpl: framebuffer was incomplete\n""); notImplemented(); } if (m_attributes.antialias) { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_multisampleFBO); if (m_boundFBO == m_multisampleFBO) mustRestoreFBO = false; } GLboolean colorMask[] = {GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE}, depthMask = GL_TRUE, stencilMask = GL_TRUE; GLboolean isScissorEnabled = GL_FALSE; GLboolean isDitherEnabled = GL_FALSE; GLbitfield clearMask = GL_COLOR_BUFFER_BIT; glGetBooleanv(GL_COLOR_WRITEMASK, colorMask); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); if (m_attributes.depth) { glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); glDepthMask(GL_TRUE); clearMask |= GL_DEPTH_BUFFER_BIT; } if (m_attributes.stencil) { glGetBooleanv(GL_STENCIL_WRITEMASK, &stencilMask); glStencilMask(GL_TRUE); clearMask |= GL_STENCIL_BUFFER_BIT; } isScissorEnabled = glIsEnabled(GL_SCISSOR_TEST); glDisable(GL_SCISSOR_TEST); isDitherEnabled = glIsEnabled(GL_DITHER); glDisable(GL_DITHER); glClear(clearMask); glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); if (m_attributes.depth) glDepthMask(depthMask); if (m_attributes.stencil) glStencilMask(stencilMask); if (isScissorEnabled) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); if (isDitherEnabled) glEnable(GL_DITHER); else glDisable(GL_DITHER); if (mustRestoreFBO) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); #ifdef FLIP_FRAMEBUFFER_VERTICALLY if (m_scanline) { delete[] m_scanline; m_scanline = 0; } m_scanline = new unsigned char[width * 4]; #endif // FLIP_FRAMEBUFFER_VERTICALLY } ",none,24 0,"void BlobURLRequestJob::NotifyFailure(int error_code) { error_ = true; if (headers_set_) { NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, error_code)); return; } int status_code = 0; std::string status_txt; switch (error_code) { case net::ERR_ACCESS_DENIED: status_code = kHTTPNotAllowed; status_txt = kHTTPNotAllowedText; break; case net::ERR_FILE_NOT_FOUND: status_code = kHTTPNotFound; status_txt = kHTTPNotFoundText; break; case net::ERR_METHOD_NOT_SUPPORTED: status_code = kHTTPMethodNotAllow; status_txt = kHTTPMethodNotAllowText; break; case net::ERR_REQUEST_RANGE_NOT_SATISFIABLE: status_code = kHTTPRequestedRangeNotSatisfiable; status_txt = kHTTPRequestedRangeNotSatisfiableText; break; case net::ERR_FAILED: status_code = kHTTPInternalError; status_txt = kHTTPInternalErrorText; break; default: DCHECK(false); status_code = kHTTPInternalError; status_txt = kHTTPInternalErrorText; break; } HeadersCompleted(status_code, status_txt); } ",none,24 1,"void *UntrustedCacheMalloc::GetBuffer() { void **buffers = nullptr; void *buffer; bool is_pool_empty; { LockGuard spin_lock(&lock_); is_pool_empty = buffer_pool_.empty(); if (is_pool_empty) { buffers = primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize); for (int i = 0; i < kPoolIncrement; i++) { if (!buffers[i] || !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) { abort(); } buffer_pool_.push(buffers[i]); } } buffer = buffer_pool_.top(); buffer_pool_.pop(); busy_buffers_.insert(buffer); } if (is_pool_empty) { // Free memory held by the array of buffer pointers returned by // AllocateUntrustedBuffers. Free(buffers); } return buffer; }",CWE-200,4 0," void ServiceWorkerScriptContext::OnFetchEvent( const ServiceWorkerFetchRequest& request) { NOTIMPLEMENTED(); } ",none,24 1,"Pl_Count::write(unsigned char* buf, size_t len) { if (len) { this->m->count += QIntC::to_offset(len); getNext()->write(buf, len); this->m->last_char = buf[len - 1]; } }",CWE-787,16 0,"SpeechSynthesis::SpeechSynthesis(ExecutionContext* context) : ContextLifecycleObserver(context) , m_platformSpeechSynthesizer(PlatformSpeechSynthesizer::create(this)) , m_isPaused(false) { ScriptWrappable::init(this); } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::bindFramebuffer(unsigned long target, WebGLId framebuffer) { makeContextCurrent(); if (!framebuffer) framebuffer = (m_attributes.antialias ? m_multisampleFBO : m_fbo); if (framebuffer != m_boundFBO) { glBindFramebufferEXT(target, framebuffer); m_boundFBO = framebuffer; } } ",none,24 1,"ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) { unsigned int nbits; gpg_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t data_e = NULL; ECC_secret_key sk; gcry_mpi_t mpi_g = NULL; char *curvename = NULL; mpi_ec_t ec = NULL; mpi_point_struct kG; mpi_point_struct R; gcry_mpi_t r = NULL; int flags = 0; memset (&sk, 0, sizeof sk); point_init (&kG); point_init (&R); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, (nbits = ecc_get_nbits (keyparms))); /* Look for flags. */ l1 = sexp_find_token (keyparms, ""flags"", 0); if (l1) { rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); if (rc) goto leave; } sexp_release (l1); l1 = NULL; /* * Extract the data. */ rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); if (rc) goto leave; rc = sexp_extract_param (l1, NULL, ""e"", &data_e, NULL); if (rc) goto leave; if (DBG_CIPHER) log_printmpi (""ecc_decrypt d_e"", data_e); if (mpi_is_opaque (data_e)) { rc = GPG_ERR_INV_DATA; goto leave; } /* * Extract the key. */ rc = sexp_extract_param (keyparms, NULL, ""-p?a?b?g?n?h?+d"", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &sk.d, NULL); if (rc) goto leave; if (mpi_g) { point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (keyparms, ""curve"", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); if (rc) goto leave; } } /* Guess required fields if a curve parameter has not been given. */ if (!curvename) { sk.E.model = MPI_EC_WEIERSTRASS; sk.E.dialect = ECC_DIALECT_STANDARD; if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug (""ecc_decrypt info: %s/%s\n"", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect)); if (sk.E.name) log_debug (""ecc_decrypt name: %s\n"", sk.E.name); log_printmpi (""ecc_decrypt p"", sk.E.p); log_printmpi (""ecc_decrypt a"", sk.E.a); log_printmpi (""ecc_decrypt b"", sk.E.b); log_printpnt (""ecc_decrypt g"", &sk.E.G, NULL); log_printmpi (""ecc_decrypt n"", sk.E.n); log_printmpi (""ecc_decrypt h"", sk.E.h); if (!fips_mode ()) log_printmpi (""ecc_decrypt d"", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, sk.E.p, sk.E.a, sk.E.b); /* * Compute the plaintext. */ if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); else rc = _gcry_ecc_os2ec (&kG, data_e); if (rc) goto leave; if (DBG_CIPHER) log_printpnt (""ecc_decrypt kG"", &kG, NULL); if (!(flags & PUBKEY_FLAG_DJB_TWEAK) /* For X25519, by its definition, validation should not be done. */ && !_gcry_mpi_ec_curve_point (&kG, ec)) { rc = GPG_ERR_INV_DATA; goto leave; } /* R = dkG */ _gcry_mpi_ec_mul_point (&R, sk.d, &kG, ec); /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */ { gcry_mpi_t x, y; x = mpi_new (0); if (ec->model == MPI_EC_MONTGOMERY) y = NULL; else y = mpi_new (0); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { rc = GPG_ERR_INV_DATA; goto leave; /* * Note for X25519. * * By the definition of X25519, this is the case where X25519 * returns 0, mapping infinity to zero. However, we * deliberately let it return an error. * * For X25519 ECDH, comming here means that it might be * decrypted by anyone with the shared secret of 0 (the result * of this function could be always 0 by other scalar values, * other than the private key of SK.D). * * So, it looks like an encrypted message but it can be * decrypted by anyone, or at least something wrong * happens. Recipient should not proceed as if it were * properly encrypted message. * * This handling is needed for our major usage of GnuPG, * where it does the One-Pass Diffie-Hellman method, * C(1, 1, ECC CDH), with an ephemeral key. */ } if (y) r = _gcry_ecc_ec2os (x, y, sk.E.p); else { unsigned char *rawmpi; unsigned int rawmpilen; rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, &rawmpilen, NULL); if (!rawmpi) { rc = gpg_err_code_from_syserror (); goto leave; } else { rawmpi[0] = 0x40; rawmpilen++; r = mpi_new (0); mpi_set_opaque (r, rawmpi, rawmpilen*8); } } if (!r) rc = gpg_err_code_from_syserror (); else rc = 0; mpi_free (x); mpi_free (y); } if (DBG_CIPHER) log_printmpi (""ecc_decrypt res"", r); if (!rc) rc = sexp_build (r_plain, NULL, ""(value %m)"", r); leave: point_free (&R); point_free (&kG); _gcry_mpi_release (r); _gcry_mpi_release (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (sk.d); _gcry_mpi_release (data_e); xfree (curvename); sexp_release (l1); _gcry_mpi_ec_free (ec); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug (""ecc_decrypt => %s\n"", gpg_strerror (rc)); return rc; }",CWE-200,4 1,"static XMLSharedNodeList* find_impl(xmlXPathContext* ctxt, const string& xpath) { xmlXPathObject* result = xmlXPathEval((const xmlChar*)xpath.c_str(), ctxt); if (!result) { xmlXPathFreeContext(ctxt); xmlFreeDoc(ctxt->doc); throw XMLException(""Invalid XPath: "" + xpath); } if (result->type != XPATH_NODESET) { xmlXPathFreeObject(result); xmlXPathFreeContext(ctxt); xmlFreeDoc(ctxt->doc); throw XMLException(""Only nodeset result types are supported.""); } xmlNodeSet* nodeset = result->nodesetval; XMLSharedNodeList* nodes = new XMLSharedNodeList(); if (nodeset) { for (int i = 0; i < nodeset->nodeNr; ++i) { XMLNode* node = readnode(nodeset->nodeTab[i]); nodes->push_back(boost::shared_ptr(node)); } } else { // return empty set } xmlXPathFreeObject(result); return nodes; }",CWE-416,10 0,"int BlobURLRequestJob::GetResponseCode() const { if (!response_info_.get()) return -1; return response_info_->headers->response_code(); } ",none,24 1,"const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst, socklen_t size) { if (!src || !dst) { errno = EFAULT; return nullptr; } size_t src_size = 0; if (af == AF_INET) { src_size = sizeof(struct in_addr); } else if (af == AF_INET6) { src_size = sizeof(struct in6_addr); } else { errno = EAFNOSUPPORT; return nullptr; } MessageWriter input; input.Push(TokLinuxAfFamily(af)); input.PushByReference(Extent{reinterpret_cast(src), src_size}); input.Push(size); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kInetNtopHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_inet_ntop"", 2); auto result = output.next(); int klinux_errno = output.next(); if (result.empty()) { errno = FromkLinuxErrorNumber(klinux_errno); return nullptr; } memcpy(dst, result.data(), std::min(static_cast(size), static_cast(INET6_ADDRSTRLEN))); return dst; }",CWE-125,1 1,"TfLiteStatus Subgraph::AddNodeWithParameters( const std::vector& inputs, const std::vector& outputs, const std::vector& intermediates, const char* init_data, size_t init_data_size, void* builtin_data, const TfLiteRegistration* registration, int* node_index) { std::unique_ptr builtin_data_deleter(builtin_data, free); if (state_ == kStateInvokableAndImmutable) { ReportError(""AddNodeWithParameters is disallowed when graph is immutable.""); return kTfLiteError; } state_ = kStateUninvokable; TF_LITE_ENSURE_OK(&context_, CheckTensorIndices(""node inputs"", inputs.data(), inputs.size())); TF_LITE_ENSURE_OK( &context_, CheckTensorIndices(""node outputs"", outputs.data(), outputs.size())); int new_node_index = nodes_and_registration_.size(); if (node_index) *node_index = new_node_index; nodes_and_registration_.resize(nodes_and_registration_.size() + 1); auto& node_and_reg = nodes_and_registration_.back(); TfLiteNode& node = node_and_reg.first; if (node.inputs) TfLiteIntArrayFree(node.inputs); if (node.outputs) TfLiteIntArrayFree(node.outputs); if (node.intermediates) TfLiteIntArrayFree(node.intermediates); if (node.temporaries) TfLiteIntArrayFree(node.temporaries); // NOTE, here we are not using move semantics yet, since our internal // representation isn't std::vector, but in the future we would like to avoid // copies, so we want the interface to take r-value references now. node.inputs = ConvertVectorToTfLiteIntArray(inputs); node.outputs = ConvertVectorToTfLiteIntArray(outputs); node.intermediates = ConvertVectorToTfLiteIntArray(intermediates); node.temporaries = TfLiteIntArrayCreate(0); if (init_data) { node.user_data = OpInit(*registration, init_data, init_data_size); } else { node.user_data = OpInit( *registration, static_cast(builtin_data_deleter.get()), 0); } node.builtin_data = builtin_data_deleter.release(); // TODO(ycling): Filling `custom_initial_data` and `custom_initial_data_size` // properly for nodes generated by ReplaceNodeSubsetsWithDelegateKernels. if (registration->builtin_code == BuiltinOperator_CUSTOM) { // When it's a CUSTOM op, the `custom_options` field in the Flatbuffer // `Operator` table is passed in. node.custom_initial_data = init_data; node.custom_initial_data_size = init_data_size; } else { node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; } node.delegate = nullptr; // Copying of registration is required to support unresolved custom ops. node_and_reg.second = *registration; execution_plan_.push_back(new_node_index); return kTfLiteOk; }",CWE-787,16 1,"long keyctl_session_to_parent(void) { #ifdef TIF_NOTIFY_RESUME struct task_struct *me, *parent; const struct cred *mycred, *pcred; struct cred *cred, *oldcred; key_ref_t keyring_r; int ret; keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_LINK); if (IS_ERR(keyring_r)) return PTR_ERR(keyring_r); /* our parent is going to need a new cred struct, a new tgcred struct * and new security data, so we allocate them here to prevent ENOMEM in * our parent */ ret = -ENOMEM; cred = cred_alloc_blank(); if (!cred) goto error_keyring; cred->tgcred->session_keyring = key_ref_to_ptr(keyring_r); keyring_r = NULL; me = current; rcu_read_lock(); write_lock_irq(&tasklist_lock); parent = me->real_parent; ret = -EPERM; /* the parent mustn't be init and mustn't be a kernel thread */ if (parent->pid <= 1 || !parent->mm) goto not_permitted; /* the parent must be single threaded */ if (!thread_group_empty(parent)) goto not_permitted; /* the parent and the child must have different session keyrings or * there's no point */ mycred = current_cred(); pcred = __task_cred(parent); if (mycred == pcred || mycred->tgcred->session_keyring == pcred->tgcred->session_keyring) goto already_same; /* the parent must have the same effective ownership and mustn't be * SUID/SGID */ if (pcred->uid != mycred->euid || pcred->euid != mycred->euid || pcred->suid != mycred->euid || pcred->gid != mycred->egid || pcred->egid != mycred->egid || pcred->sgid != mycred->egid) goto not_permitted; /* the keyrings must have the same UID */ if (pcred->tgcred->session_keyring->uid != mycred->euid || mycred->tgcred->session_keyring->uid != mycred->euid) goto not_permitted; /* if there's an already pending keyring replacement, then we replace * that */ oldcred = parent->replacement_session_keyring; /* the replacement session keyring is applied just prior to userspace * restarting */ parent->replacement_session_keyring = cred; cred = NULL; set_ti_thread_flag(task_thread_info(parent), TIF_NOTIFY_RESUME); write_unlock_irq(&tasklist_lock); rcu_read_unlock(); if (oldcred) put_cred(oldcred); return 0; already_same: ret = 0; not_permitted: write_unlock_irq(&tasklist_lock); rcu_read_unlock(); put_cred(cred); return ret; error_keyring: key_ref_put(keyring_r); return ret; #else /* !TIF_NOTIFY_RESUME */ /* * To be removed when TIF_NOTIFY_RESUME has been implemented on * m68k/xtensa */ #warning TIF_NOTIFY_RESUME not implemented return -EOPNOTSUPP; #endif /* !TIF_NOTIFY_RESUME */ }",CWE-476,12 1," void Compute(OpKernelContext* context) override { // Get inputs const Tensor& input_tensor = context->input(0); const auto input_tensor_flat = input_tensor.flat(); const Tensor& input_splits = context->input(1); const auto input_splits_flat = input_splits.flat(); // Operation will treat first argument in input_splits as if it were zero // regardless of its actual value since splits should begin with zero and // end with the length of the input values vector. OP_REQUIRES( context, input_splits_flat(0) == 0, errors::InvalidArgument(""First value in input_splits must be zero."")); OP_REQUIRES(context, input_splits_flat(input_splits_flat.size() - 1) == input_tensor_flat.size(), errors::InvalidArgument(""Last value in input_splits must be "" ""equal to length of input_tensor."")); // Since we limit to a 2-D input (flat_values of rank 1 and a single splits // tensor), our output dimension will be 1 with it's size equal to the // number of splits (outer dimension or ragged tensor). TensorShape output_shape({input_splits.dim_size(0) - 1}); Tensor* output_tensor; OP_REQUIRES_OK(context, context->allocate_output(""output"", output_shape, &output_tensor)); auto output_tensor_flat = output_tensor->flat(); // Use a single index over the flattened input values tensor. int idx = 0; // Loop through our split dimension to create a new string at each split. for (int i = 1; i < input_splits_flat.size(); ++i) { icu::UnicodeString unicode_string; icu::UnicodeStringAppendable appendable_unicode_string(unicode_string); OP_REQUIRES( context, input_splits_flat(i - 1) <= input_splits_flat(i), errors::InvalidArgument( ""Values in input_splits must be equal or in ascending order."")); OP_REQUIRES( context, input_splits_flat(i) <= input_tensor_flat.size(), errors::InvalidArgument(""Values in input_splits must be less than or "" ""equal to input_tensor length."")); for (; idx < input_splits_flat(i); ++idx) { int32_t code_point = input_tensor_flat(idx); // Check for invalid code point if (!U_IS_UNICODE_CHAR(code_point)) { if (error_options_.error_on_malformatting) { context->CtxFailure(errors::InvalidArgument( ""Code point is out of range for Unicode, or a noncharacter."")); return; } else if (!error_options_.elide_replacement) { code_point = error_options_.subst; } } appendable_unicode_string.appendCodePoint(code_point); } // Encode our string and save in the output. tstring result; Encode(encoding_, unicode_string, &result); output_tensor_flat(i - 1) = std::move(result); } }",CWE-787,16 1,"check_tty(const char *tty) { /* Check that we're not being set up to take a fall. */ if ((tty == NULL) || (strlen(tty) == 0)) { return NULL; } /* Pull out the meaningful part of the tty's name. */ if (strchr(tty, '/') != NULL) { if (strncmp(tty, ""/dev/"", 5) != 0) { /* Make sure the device node is actually in /dev/, * noted by Michal Zalewski. */ return NULL; } tty = strrchr(tty, '/') + 1; } /* Make sure the tty wasn't actually a directory (no basename). */ if (strlen(tty) == 0) { return NULL; } return tty; }",CWE-22,5 1,"static int route4_change(struct net *net, struct sk_buff *in_skb, struct tcf_proto *tp, unsigned long base, u32 handle, struct nlattr **tca, void **arg, bool ovr, bool rtnl_held, struct netlink_ext_ack *extack) { struct route4_head *head = rtnl_dereference(tp->root); struct route4_filter __rcu **fp; struct route4_filter *fold, *f1, *pfp, *f = NULL; struct route4_bucket *b; struct nlattr *opt = tca[TCA_OPTIONS]; struct nlattr *tb[TCA_ROUTE4_MAX + 1]; unsigned int h, th; int err; bool new = true; if (opt == NULL) return handle ? -EINVAL : 0; err = nla_parse_nested_deprecated(tb, TCA_ROUTE4_MAX, opt, route4_policy, NULL); if (err < 0) return err; fold = *arg; if (fold && handle && fold->handle != handle) return -EINVAL; err = -ENOBUFS; f = kzalloc(sizeof(struct route4_filter), GFP_KERNEL); if (!f) goto errout; err = tcf_exts_init(&f->exts, net, TCA_ROUTE4_ACT, TCA_ROUTE4_POLICE); if (err < 0) goto errout; if (fold) { f->id = fold->id; f->iif = fold->iif; f->res = fold->res; f->handle = fold->handle; f->tp = fold->tp; f->bkt = fold->bkt; new = false; } err = route4_set_parms(net, tp, base, f, handle, head, tb, tca[TCA_RATE], new, ovr, extack); if (err < 0) goto errout; h = from_hash(f->handle >> 16); fp = &f->bkt->ht[h]; for (pfp = rtnl_dereference(*fp); (f1 = rtnl_dereference(*fp)) != NULL; fp = &f1->next) if (f->handle < f1->handle) break; tcf_block_netif_keep_dst(tp->chain->block); rcu_assign_pointer(f->next, f1); rcu_assign_pointer(*fp, f); if (fold && fold->handle && f->handle != fold->handle) { th = to_hash(fold->handle); h = from_hash(fold->handle >> 16); b = rtnl_dereference(head->table[th]); if (b) { fp = &b->ht[h]; for (pfp = rtnl_dereference(*fp); pfp; fp = &pfp->next, pfp = rtnl_dereference(*fp)) { if (pfp == f) { *fp = f->next; break; } } } } route4_reset_fastmap(head); *arg = f; if (fold) { tcf_unbind_filter(tp, &fold->res); tcf_exts_get_net(&fold->exts); tcf_queue_work(&fold->rwork, route4_delete_filter_work); } return 0; errout: if (f) tcf_exts_destroy(&f->exts); kfree(f); return err; }",CWE-200,4 1,"static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in) { int ret = 0, is_segment = 0, is_variant = 0; int64_t duration = 0; enum KeyType key_type = KEY_NONE; uint8_t iv[16] = """"; int has_iv = 0; char key[MAX_URL_SIZE] = """"; char line[MAX_URL_SIZE]; const char *ptr; int close_in = 0; int64_t seg_offset = 0; int64_t seg_size = -1; uint8_t *new_url = NULL; struct variant_info variant_info; char tmp_str[MAX_URL_SIZE]; struct segment *cur_init_section = NULL; if (!in) { #if 1 AVDictionary *opts = NULL; close_in = 1; /* Some HLS servers don't like being sent the range header */ av_dict_set(&opts, ""seekable"", ""0"", 0); // broker prior HTTP options that should be consistent across requests av_dict_set(&opts, ""user-agent"", c->user_agent, 0); av_dict_set(&opts, ""cookies"", c->cookies, 0); av_dict_set(&opts, ""headers"", c->headers, 0); ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts); av_dict_free(&opts); if (ret < 0) return ret; #else ret = open_in(c, &in, url); if (ret < 0) return ret; close_in = 1; #endif } if (av_opt_get(in, ""location"", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) url = new_url; read_chomp_line(in, line, sizeof(line)); if (strcmp(line, ""#EXTM3U"")) { ret = AVERROR_INVALIDDATA; goto fail; } if (pls) { free_segment_list(pls); pls->finished = 0; pls->type = PLS_TYPE_UNSPECIFIED; } while (!avio_feof(in)) { read_chomp_line(in, line, sizeof(line)); if (av_strstart(line, ""#EXT-X-STREAM-INF:"", &ptr)) { is_variant = 1; memset(&variant_info, 0, sizeof(variant_info)); ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args, &variant_info); } else if (av_strstart(line, ""#EXT-X-KEY:"", &ptr)) { struct key_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args, &info); key_type = KEY_NONE; has_iv = 0; if (!strcmp(info.method, ""AES-128"")) key_type = KEY_AES_128; if (!strcmp(info.method, ""SAMPLE-AES"")) key_type = KEY_SAMPLE_AES; if (!strncmp(info.iv, ""0x"", 2) || !strncmp(info.iv, ""0X"", 2)) { ff_hex_to_data(iv, info.iv + 2); has_iv = 1; } av_strlcpy(key, info.uri, sizeof(key)); } else if (av_strstart(line, ""#EXT-X-MEDIA:"", &ptr)) { struct rendition_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args, &info); new_rendition(c, &info, url); } else if (av_strstart(line, ""#EXT-X-TARGETDURATION:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->target_duration = atoi(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-MEDIA-SEQUENCE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->start_seq_no = atoi(ptr); } else if (av_strstart(line, ""#EXT-X-PLAYLIST-TYPE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; if (!strcmp(ptr, ""EVENT"")) pls->type = PLS_TYPE_EVENT; else if (!strcmp(ptr, ""VOD"")) pls->type = PLS_TYPE_VOD; } else if (av_strstart(line, ""#EXT-X-MAP:"", &ptr)) { struct init_section_info info = {{0}}; ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args, &info); cur_init_section = new_init_section(pls, &info, url); } else if (av_strstart(line, ""#EXT-X-ENDLIST"", &ptr)) { if (pls) pls->finished = 1; } else if (av_strstart(line, ""#EXTINF:"", &ptr)) { is_segment = 1; duration = atof(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-BYTERANGE:"", &ptr)) { seg_size = atoi(ptr); ptr = strchr(ptr, '@'); if (ptr) seg_offset = atoi(ptr+1); } else if (av_strstart(line, ""#"", NULL)) { continue; } else if (line[0]) { if (is_variant) { if (!new_variant(c, &variant_info, line, url)) { ret = AVERROR(ENOMEM); goto fail; } is_variant = 0; } if (is_segment) { struct segment *seg; if (!pls) { if (!new_variant(c, 0, url, NULL)) { ret = AVERROR(ENOMEM); goto fail; } pls = c->playlists[c->n_playlists - 1]; } seg = av_malloc(sizeof(struct segment)); if (!seg) { ret = AVERROR(ENOMEM); goto fail; } seg->duration = duration; seg->key_type = key_type; if (has_iv) { memcpy(seg->iv, iv, sizeof(iv)); } else { int seq = pls->start_seq_no + pls->n_segments; memset(seg->iv, 0, sizeof(seg->iv)); AV_WB32(seg->iv + 12, seq); } if (key_type != KEY_NONE) { ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key); seg->key = av_strdup(tmp_str); if (!seg->key) { av_free(seg); ret = AVERROR(ENOMEM); goto fail; } } else { seg->key = NULL; } ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line); seg->url = av_strdup(tmp_str); if (!seg->url) { av_free(seg->key); av_free(seg); ret = AVERROR(ENOMEM); goto fail; } dynarray_add(&pls->segments, &pls->n_segments, seg); is_segment = 0; seg->size = seg_size; if (seg_size >= 0) { seg->url_offset = seg_offset; seg_offset += seg_size; seg_size = -1; } else { seg->url_offset = 0; seg_offset = 0; } seg->init_section = cur_init_section; } } } if (pls) pls->last_load_time = av_gettime_relative(); fail: av_free(new_url); if (close_in) avio_close(in); return ret; }",CWE-416,10 1,"calculateNumTiles (int *numTiles, int numLevels, int min, int max, int size, LevelRoundingMode rmode) { for (int i = 0; i < numLevels; i++) { int l = levelSize (min, max, i, rmode); if (l > std::numeric_limits::max() - size + 1) throw IEX_NAMESPACE::ArgExc (""Invalid size.""); numTiles[i] = (l + size - 1) / size; } }",CWE-190,2 0,"WebGraphicsContext3D::Attributes WebGraphicsContext3DDefaultImpl::getContextAttributes() { return m_attributes; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::deleteFramebuffer(unsigned framebuffer) { makeContextCurrent(); glDeleteFramebuffersEXT(1, &framebuffer); } ",none,24 1,"GF_Err infe_box_read(GF_Box *s, GF_BitStream *bs) { char *buf; u32 buf_len, i, string_len, string_start; GF_ItemInfoEntryBox *ptr = (GF_ItemInfoEntryBox *)s; ISOM_DECREASE_SIZE(ptr, 4); ptr->item_ID = gf_bs_read_u16(bs); ptr->item_protection_index = gf_bs_read_u16(bs); if (ptr->version == 2) { ISOM_DECREASE_SIZE(ptr, 4); ptr->item_type = gf_bs_read_u32(bs); } buf_len = (u32) (ptr->size); buf = (char*)gf_malloc(buf_len); if (!buf) return GF_OUT_OF_MEM; if (buf_len != gf_bs_read_data(bs, buf, buf_len)) { gf_free(buf); return GF_ISOM_INVALID_FILE; } string_len = 1; string_start = 0; for (i = 0; i < buf_len; i++) { if (buf[i] == 0) { if (!ptr->item_name) { ptr->item_name = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->item_name) return GF_OUT_OF_MEM; memcpy(ptr->item_name, buf+string_start, string_len); } else if (!ptr->content_type) { ptr->content_type = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->content_type) return GF_OUT_OF_MEM; memcpy(ptr->content_type, buf+string_start, string_len); } else { ptr->content_encoding = (char*)gf_malloc(sizeof(char)*string_len); if (!ptr->content_encoding) return GF_OUT_OF_MEM; memcpy(ptr->content_encoding, buf+string_start, string_len); } string_start += string_len; string_len = 0; if (ptr->content_encoding && ptr->version == 1) { break; } } string_len++; } gf_free(buf); if (!ptr->item_name || (!ptr->content_type && ptr->version < 2)) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[isoff] Infe without name or content type !\n"")); } return GF_OK; }",CWE-787,16 1,"PHP_FUNCTION(enchant_broker_request_dict) { zval *broker; enchant_broker *pbroker; enchant_dict *dict; EnchantDict *d; char *tag; int taglen; int pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""rs"", &broker, &tag, &taglen) == FAILURE) { RETURN_FALSE; } PHP_ENCHANT_GET_BROKER; if (taglen == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Tag cannot be empty""); RETURN_FALSE; } d = enchant_broker_request_dict(pbroker->pbroker, (const char *)tag); if (d) { if (pbroker->dictcnt) { pbroker->dict = (enchant_dict **)erealloc(pbroker->dict, sizeof(enchant_dict *) * pbroker->dictcnt); pos = pbroker->dictcnt++; } else { pbroker->dict = (enchant_dict **)emalloc(sizeof(enchant_dict *)); pos = 0; pbroker->dictcnt++; } dict = pbroker->dict[pos] = (enchant_dict *)emalloc(sizeof(enchant_dict)); dict->id = pos; dict->pbroker = pbroker; dict->pdict = d; dict->prev = pos ? pbroker->dict[pos-1] : NULL; dict->next = NULL; pbroker->dict[pos] = dict; if (pos) { pbroker->dict[pos-1]->next = dict; } dict->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, dict, le_enchant_dict); zend_list_addref(pbroker->rsrc_id); } else { RETURN_FALSE; } }",CWE-119,0 1,"do_ed_script (char const *inname, char const *outname, bool *outname_needs_removal, FILE *ofp) { static char const editor_program[] = EDITOR_PROGRAM; file_offset beginning_of_this_line; size_t chars_read; FILE *tmpfp = 0; char const *tmpname; int tmpfd; pid_t pid; if (! dry_run && ! skip_rest_of_patch) { /* Write ed script to a temporary file. This causes ed to abort on invalid commands such as when line numbers or ranges exceed the number of available lines. When ed reads from a pipe, it rejects invalid commands and treats the next line as a new command, which can lead to arbitrary command execution. */ tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0); if (tmpfd == -1) pfatal (""Can't create temporary file %s"", quotearg (tmpname)); tmpfp = fdopen (tmpfd, ""w+b""); if (! tmpfp) pfatal (""Can't open stream for file %s"", quotearg (tmpname)); } for (;;) { char ed_command_letter; beginning_of_this_line = file_tell (pfp); chars_read = get_line (); if (! chars_read) { next_intuit_at(beginning_of_this_line,p_input_line); break; } ed_command_letter = get_ed_command_letter (buf); if (ed_command_letter) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (ed_command_letter != 'd' && ed_command_letter != 's') { p_pass_comments_through = true; while ((chars_read = get_line ()) != 0) { if (tmpfp) if (! fwrite (buf, sizeof *buf, chars_read, tmpfp)) write_fatal (); if (chars_read == 2 && strEQ (buf, "".\n"")) break; } p_pass_comments_through = false; } } else { next_intuit_at(beginning_of_this_line,p_input_line); break; } } if (!tmpfp) return; if (fwrite (""w\nq\n"", sizeof (char), (size_t) 4, tmpfp) == 0 || fflush (tmpfp) != 0) write_fatal (); if (lseek (tmpfd, 0, SEEK_SET) == -1) pfatal (""Can't rewind to the beginning of file %s"", quotearg (tmpname)); if (! dry_run && ! skip_rest_of_patch) { int exclusive = *outname_needs_removal ? 0 : O_EXCL; *outname_needs_removal = true; if (inerrno != ENOENT) { *outname_needs_removal = true; copy_file (inname, outname, 0, exclusive, instat.st_mode, true); } sprintf (buf, ""%s %s%s"", editor_program, verbosity == VERBOSE ? """" : ""- "", outname); fflush (stdout); pid = fork(); if (pid == -1) pfatal (""Can't fork""); else if (pid == 0) { dup2 (tmpfd, 0); execl (""/bin/sh"", ""sh"", ""-c"", buf, (char *) 0); _exit (2); } else { int wstatus; if (waitpid (pid, &wstatus, 0) == -1 || ! WIFEXITED (wstatus) || WEXITSTATUS (wstatus) != 0) fatal (""%s FAILED"", editor_program); } } fclose (tmpfp); safe_unlink (tmpname); if (ofp) { FILE *ifp = fopen (outname, binary_transput ? ""rb"" : ""r""); int c; if (!ifp) pfatal (""can't open '%s'"", outname); while ((c = getc (ifp)) != EOF) if (putc (c, ofp) == EOF) write_fatal (); if (ferror (ifp) || fclose (ifp) != 0) read_fatal (); } }",CWE-78,15 1,"vmod_append(VRT_CTX, VCL_HEADER hdr, VCL_STRANDS s) { struct http *hp; struct strands st[1]; const char *p[s->n + 2]; const char *b; CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC); /* prefix the strand with $hdr_name + space */ p[0] = hdr->what + 1; p[1] = "" ""; AN(memcpy(p + 2, s->p, s->n * sizeof *s->p)); st->n = s->n + 2; st->p = p; b = VRT_StrandsWS(ctx->ws, NULL, st); hp = VRT_selecthttp(ctx, hdr->where); http_SetHeader(hp, b); }",CWE-476,12 0,"void AudioManagerBase::IncreaseActiveInputStreamCount() { base::AtomicRefCountInc(&num_active_input_streams_); } ",none,24 0,"void ContentSettingsStore::SetExtensionContentSetting( const std::string& ext_id, const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType type, const content_settings::ResourceIdentifier& identifier, ContentSetting setting, ExtensionPrefsScope scope) { { base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); if (setting == CONTENT_SETTING_DEFAULT) { map->DeleteValue(primary_pattern, secondary_pattern, type, identifier); } else { map->SetValue(primary_pattern, secondary_pattern, type, identifier, base::Value::CreateIntegerValue(setting)); } } NotifyOfContentSettingChanged(ext_id, scope != kExtensionPrefsScopeRegular); } ",none,24 1," void Compute(OpKernelContext* context) override { // Get inputs const Tensor& input_tensor = context->input(0); const auto input_tensor_flat = input_tensor.flat(); const Tensor& input_splits = context->input(1); const auto input_splits_flat = input_splits.flat(); // Since we limit to a 2-D input (flat_values of rank 1 and a single splits // tensor), our output dimension will be 1 with it's size equal to the // number of splits (outer dimension or ragged tensor). TensorShape output_shape({input_splits.dim_size(0) - 1}); Tensor* output_tensor; OP_REQUIRES_OK(context, context->allocate_output(""output"", output_shape, &output_tensor)); auto output_tensor_flat = output_tensor->flat(); // Use a single index over the flattened input values tensor. int idx = 0; // Loop through our split dimension to create a new string at each split. for (int i = 1; i < input_splits_flat.size(); ++i) { icu::UnicodeString unicode_string; icu::UnicodeStringAppendable appendable_unicode_string(unicode_string); for (; idx < input_splits_flat(i); ++idx) { int32 code_point = input_tensor_flat(idx); // Check for invalid code point if (!U_IS_UNICODE_CHAR(code_point)) { if (error_options_.error_on_malformatting) { context->CtxFailure(errors::InvalidArgument( ""Code point is out of range for Unicode, or a noncharacter."")); return; } else if (!error_options_.elide_replacement) { code_point = error_options_.subst; } } appendable_unicode_string.appendCodePoint(code_point); } // Encode our string and save in the output. tstring result; Encode(encoding_, unicode_string, &result); output_tensor_flat(i - 1) = std::move(result); } }",CWE-787,16 1,"int ext4_group_add(struct super_block *sb, struct ext4_new_group_data *input) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int reserved_gdb = ext4_bg_has_super(sb, input->group) ? le16_to_cpu(es->s_reserved_gdt_blocks) : 0; struct buffer_head *primary = NULL; struct ext4_group_desc *gdp; struct inode *inode = NULL; handle_t *handle; int gdb_off, gdb_num; int num_grp_locked = 0; int err, err2; gdb_num = input->group / EXT4_DESC_PER_BLOCK(sb); gdb_off = input->group % EXT4_DESC_PER_BLOCK(sb); if (gdb_off == 0 && !EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER)) { ext4_warning(sb, __func__, ""Can't resize non-sparse filesystem further""); return -EPERM; } if (ext4_blocks_count(es) + input->blocks_count < ext4_blocks_count(es)) { ext4_warning(sb, __func__, ""blocks_count overflow""); return -EINVAL; } if (le32_to_cpu(es->s_inodes_count) + EXT4_INODES_PER_GROUP(sb) < le32_to_cpu(es->s_inodes_count)) { ext4_warning(sb, __func__, ""inodes_count overflow""); return -EINVAL; } if (reserved_gdb || gdb_off == 0) { if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_RESIZE_INODE) || !le16_to_cpu(es->s_reserved_gdt_blocks)) { ext4_warning(sb, __func__, ""No reserved GDT blocks, can't resize""); return -EPERM; } inode = ext4_iget(sb, EXT4_RESIZE_INO); if (IS_ERR(inode)) { ext4_warning(sb, __func__, ""Error opening resize inode""); return PTR_ERR(inode); } } if ((err = verify_group_input(sb, input))) goto exit_put; if ((err = setup_new_group_blocks(sb, input))) goto exit_put; /* * We will always be modifying at least the superblock and a GDT * block. If we are adding a group past the last current GDT block, * we will also modify the inode and the dindirect block. If we * are adding a group with superblock/GDT backups we will also * modify each of the reserved GDT dindirect blocks. */ handle = ext4_journal_start_sb(sb, ext4_bg_has_super(sb, input->group) ? 3 + reserved_gdb : 4); if (IS_ERR(handle)) { err = PTR_ERR(handle); goto exit_put; } lock_super(sb); if (input->group != sbi->s_groups_count) { ext4_warning(sb, __func__, ""multiple resizers run on filesystem!""); err = -EBUSY; goto exit_journal; } if ((err = ext4_journal_get_write_access(handle, sbi->s_sbh))) goto exit_journal; /* * We will only either add reserved group blocks to a backup group * or remove reserved blocks for the first group in a new group block. * Doing both would be mean more complex code, and sane people don't * use non-sparse filesystems anymore. This is already checked above. */ if (gdb_off) { primary = sbi->s_group_desc[gdb_num]; if ((err = ext4_journal_get_write_access(handle, primary))) goto exit_journal; if (reserved_gdb && ext4_bg_num_gdb(sb, input->group) && (err = reserve_backup_gdb(handle, inode, input))) goto exit_journal; } else if ((err = add_new_gdb(handle, inode, input, &primary))) goto exit_journal; /* * OK, now we've set up the new group. Time to make it active. * * Current kernels don't lock all allocations via lock_super(), * so we have to be safe wrt. concurrent accesses the group * data. So we need to be careful to set all of the relevant * group descriptor data etc. *before* we enable the group. * * The key field here is sbi->s_groups_count: as long as * that retains its old value, nobody is going to access the new * group. * * So first we update all the descriptor metadata for the new * group; then we update the total disk blocks count; then we * update the groups count to enable the group; then finally we * update the free space counts so that the system can start * using the new disk blocks. */ num_grp_locked = ext4_mb_get_buddy_cache_lock(sb, input->group); /* Update group descriptor block for new group */ gdp = (struct ext4_group_desc *)((char *)primary->b_data + gdb_off * EXT4_DESC_SIZE(sb)); ext4_block_bitmap_set(sb, gdp, input->block_bitmap); /* LV FIXME */ ext4_inode_bitmap_set(sb, gdp, input->inode_bitmap); /* LV FIXME */ ext4_inode_table_set(sb, gdp, input->inode_table); /* LV FIXME */ ext4_free_blks_set(sb, gdp, input->free_blocks_count); ext4_free_inodes_set(sb, gdp, EXT4_INODES_PER_GROUP(sb)); gdp->bg_flags |= cpu_to_le16(EXT4_BG_INODE_ZEROED); gdp->bg_checksum = ext4_group_desc_csum(sbi, input->group, gdp); /* * We can allocate memory for mb_alloc based on the new group * descriptor */ err = ext4_mb_add_groupinfo(sb, input->group, gdp); if (err) { ext4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked); goto exit_journal; } /* * Make the new blocks and inodes valid next. We do this before * increasing the group count so that once the group is enabled, * all of its blocks and inodes are already valid. * * We always allocate group-by-group, then block-by-block or * inode-by-inode within a group, so enabling these * blocks/inodes before the group is live won't actually let us * allocate the new space yet. */ ext4_blocks_count_set(es, ext4_blocks_count(es) + input->blocks_count); le32_add_cpu(&es->s_inodes_count, EXT4_INODES_PER_GROUP(sb)); /* * We need to protect s_groups_count against other CPUs seeing * inconsistent state in the superblock. * * The precise rules we use are: * * * Writers of s_groups_count *must* hold lock_super * AND * * Writers must perform a smp_wmb() after updating all dependent * data and before modifying the groups count * * * Readers must hold lock_super() over the access * OR * * Readers must perform an smp_rmb() after reading the groups count * and before reading any dependent data. * * NB. These rules can be relaxed when checking the group count * while freeing data, as we can only allocate from a block * group after serialising against the group count, and we can * only then free after serialising in turn against that * allocation. */ smp_wmb(); /* Update the global fs size fields */ sbi->s_groups_count++; ext4_mb_put_buddy_cache_lock(sb, input->group, num_grp_locked); ext4_handle_dirty_metadata(handle, NULL, primary); /* Update the reserved block counts only once the new group is * active. */ ext4_r_blocks_count_set(es, ext4_r_blocks_count(es) + input->reserved_blocks); /* Update the free space counts */ percpu_counter_add(&sbi->s_freeblocks_counter, input->free_blocks_count); percpu_counter_add(&sbi->s_freeinodes_counter, EXT4_INODES_PER_GROUP(sb)); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) { ext4_group_t flex_group; flex_group = ext4_flex_group(sbi, input->group); sbi->s_flex_groups[flex_group].free_blocks += input->free_blocks_count; sbi->s_flex_groups[flex_group].free_inodes += EXT4_INODES_PER_GROUP(sb); } ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh); sb->s_dirt = 1; exit_journal: unlock_super(sb); if ((err2 = ext4_journal_stop(handle)) && !err) err = err2; if (!err) { update_backups(sb, sbi->s_sbh->b_blocknr, (char *)es, sizeof(struct ext4_super_block)); update_backups(sb, primary->b_blocknr, primary->b_data, primary->b_size); } exit_put: iput(inode); return err; } /* ext4_group_add */",CWE-20,3 1,"gdImagePtr gdImageCreateFromGifCtx(gdIOCtxPtr fd) /* {{{ */ { int BitPixel; #if 0 int ColorResolution; int Background; int AspectRatio; #endif int Transparent = (-1); unsigned char buf[16]; unsigned char c; unsigned char ColorMap[3][MAXCOLORMAPSIZE]; unsigned char localColorMap[3][MAXCOLORMAPSIZE]; int imw, imh, screen_width, screen_height; int gif87a, useGlobalColormap; int bitPixel; int i; /*1.4//int imageCount = 0; */ int ZeroDataBlock = FALSE; int haveGlobalColormap; gdImagePtr im = 0; /*1.4//imageNumber = 1; */ if (! ReadOK(fd,buf,6)) { return 0; } if (strncmp((char *)buf,""GIF"",3) != 0) { return 0; } if (memcmp((char *)buf+3, ""87a"", 3) == 0) { gif87a = 1; } else if (memcmp((char *)buf+3, ""89a"", 3) == 0) { gif87a = 0; } else { return 0; } if (! ReadOK(fd,buf,7)) { return 0; } BitPixel = 2<<(buf[4]&0x07); #if 0 ColorResolution = (int) (((buf[4]&0x70)>>3)+1); Background = buf[5]; AspectRatio = buf[6]; #endif screen_width = imw = LM_to_uint(buf[0],buf[1]); screen_height = imh = LM_to_uint(buf[2],buf[3]); haveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */ if (haveGlobalColormap) { if (ReadColorMap(fd, BitPixel, ColorMap)) { return 0; } } for (;;) { int top, left; int width, height; if (! ReadOK(fd,&c,1)) { return 0; } if (c == ';') { /* GIF terminator */ goto terminated; } if (c == '!') { /* Extension */ if (! ReadOK(fd,&c,1)) { return 0; } DoExtension(fd, c, &Transparent, &ZeroDataBlock); continue; } if (c != ',') { /* Not a valid start character */ continue; } /*1.4//++imageCount; */ if (! ReadOK(fd,buf,9)) { return 0; } useGlobalColormap = ! BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1<<((buf[8]&0x07)+1); left = LM_to_uint(buf[0], buf[1]); top = LM_to_uint(buf[2], buf[3]); width = LM_to_uint(buf[4], buf[5]); height = LM_to_uint(buf[6], buf[7]); if (left + width > screen_width || top + height > screen_height) { if (VERBOSE) { printf(""Frame is not confined to screen dimension.\n""); } return 0; } if (!(im = gdImageCreate(width, height))) { return 0; } im->interlace = BitSet(buf[8], INTERLACE); if (!useGlobalColormap) { if (ReadColorMap(fd, bitPixel, localColorMap)) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, localColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } else { if (!haveGlobalColormap) { gdImageDestroy(im); return 0; } ReadImage(im, fd, width, height, ColorMap, BitSet(buf[8], INTERLACE), &ZeroDataBlock); } if (Transparent != (-1)) { gdImageColorTransparent(im, Transparent); } goto terminated; } terminated: /* Terminator before any image was declared! */ if (!im) { return 0; } if (!im->colorsTotal) { gdImageDestroy(im); return 0; } /* Check for open colors at the end, so we can reduce colorsTotal and ultimately BitsPerPixel */ for (i=((im->colorsTotal-1)); (i>=0); i--) { if (im->open[i]) { im->colorsTotal--; } else { break; } } return im; }",CWE-200,4 0,"WebString WebGraphicsContext3DDefaultImpl::getShaderSource(WebGLId shader) { makeContextCurrent(); ShaderSourceMap::iterator result = m_shaderSourceMap.find(shader); if (result != m_shaderSourceMap.end()) { ShaderSourceEntry* entry = result->second; ASSERT(entry); if (!entry->source) return WebString(); WebString res = WebString::fromUTF8(entry->source, strlen(entry->source)); return res; } GLint logLength = 0; glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &logLength); if (logLength <= 1) return WebString(); GLchar* log = 0; if (!tryFastMalloc(logLength * sizeof(GLchar)).getValue(log)) return WebString(); GLsizei returnedLogLength; glGetShaderSource(shader, logLength, &returnedLogLength, log); ASSERT(logLength == returnedLogLength + 1); WebString res = WebString::fromUTF8(log, returnedLogLength); fastFree(log); return res; } ",none,24 1,"GC_API GC_ATTR_MALLOC void * GC_CALL GC_calloc_explicitly_typed(size_t n, size_t lb, GC_descr d) { word *op; size_t lg; GC_descr simple_descr; complex_descriptor *complex_descr; int descr_type; struct LeafDescriptor leaf; GC_ASSERT(GC_explicit_typing_initialized); descr_type = GC_make_array_descriptor((word)n, (word)lb, d, &simple_descr, &complex_descr, &leaf); switch(descr_type) { case NO_MEM: return(0); case SIMPLE: return(GC_malloc_explicitly_typed(n*lb, simple_descr)); case LEAF: lb *= n; lb += sizeof(struct LeafDescriptor) + TYPD_EXTRA_BYTES; break; case COMPLEX: lb *= n; lb += TYPD_EXTRA_BYTES; break; } op = GC_malloc_kind(lb, GC_array_kind); if (EXPECT(NULL == op, FALSE)) return NULL; lg = SMALL_OBJ(lb) ? GC_size_map[lb] : BYTES_TO_GRANULES(GC_size(op)); if (descr_type == LEAF) { /* Set up the descriptor inside the object itself. */ volatile struct LeafDescriptor * lp = (struct LeafDescriptor *) (op + GRANULES_TO_WORDS(lg) - (BYTES_TO_WORDS(sizeof(struct LeafDescriptor)) + 1)); lp -> ld_tag = LEAF_TAG; lp -> ld_size = leaf.ld_size; lp -> ld_nelements = leaf.ld_nelements; lp -> ld_descriptor = leaf.ld_descriptor; ((volatile word *)op)[GRANULES_TO_WORDS(lg) - 1] = (word)lp; } else { # ifndef GC_NO_FINALIZATION size_t lw = GRANULES_TO_WORDS(lg); op[lw - 1] = (word)complex_descr; /* Make sure the descriptor is cleared once there is any danger */ /* it may have been collected. */ if (EXPECT(GC_general_register_disappearing_link( (void **)(op + lw - 1), op) == GC_NO_MEMORY, FALSE)) # endif { /* Couldn't register it due to lack of memory. Punt. */ /* This will probably fail too, but gives the recovery code */ /* a chance. */ return GC_malloc(lb); } } return op; }",CWE-119,0 1,"static int extractRDNSequence(struct ndpi_packet_struct *packet, u_int offset, char *buffer, u_int buffer_len, char *rdnSeqBuf, u_int *rdnSeqBuf_offset, u_int rdnSeqBuf_len, const char *label) { u_int8_t str_len = packet->payload[offset+4], is_printable = 1; char *str; u_int len, j; // packet is truncated... further inspection is not needed if((offset+4+str_len) >= packet->payload_packet_len) return(-1); str = (char*)&packet->payload[offset+5]; len = (u_int)ndpi_min(str_len, buffer_len-1); strncpy(buffer, str, len); buffer[len] = '\0'; // check string is printable for(j = 0; j < len; j++) { if(!ndpi_isprint(buffer[j])) { is_printable = 0; break; } } if(is_printable) { int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset], rdnSeqBuf_len-(*rdnSeqBuf_offset), ""%s%s=%s"", (*rdnSeqBuf_offset > 0) ? "", "" : """", label, buffer); if(rc > 0) (*rdnSeqBuf_offset) += rc; } return(is_printable); }",CWE-190,2 0," void DecodeIFrameThenTestFile(const std::string& test_file_name, size_t expected_width, size_t expected_height) { Initialize(); VideoDecoder::DecoderStatus status_a; VideoDecoder::DecoderStatus status_b; scoped_refptr video_frame_a; scoped_refptr video_frame_b; scoped_refptr buffer = ReadTestDataFile(test_file_name); EXPECT_CALL(*demuxer_, Read(_)) .WillOnce(ReturnBuffer(i_frame_buffer_)) .WillOnce(ReturnBuffer(buffer)) .WillRepeatedly(ReturnBuffer(end_of_stream_buffer_)); EXPECT_CALL(statistics_cb_, OnStatistics(_)) .Times(2); Read(&status_a, &video_frame_a); Read(&status_b, &video_frame_b); size_t original_width = static_cast(kVisibleRect.width()); size_t original_height = static_cast(kVisibleRect.height()); EXPECT_EQ(status_a, VideoDecoder::kOk); EXPECT_EQ(status_b, VideoDecoder::kOk); ASSERT_TRUE(video_frame_a); ASSERT_TRUE(video_frame_b); EXPECT_EQ(original_width, video_frame_a->width()); EXPECT_EQ(original_height, video_frame_a->height()); EXPECT_EQ(expected_width, video_frame_b->width()); EXPECT_EQ(expected_height, video_frame_b->height()); } ",none,24 1,"bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S') { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\""') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\""') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }",CWE-119,0 0,"bool SpeechSynthesis::speaking() const { return currentSpeechUtterance(); } ",none,24 0,"void BlobURLRequestJob::AdvanceItem() { CloseStream(); item_index_++; current_item_offset_ = 0; } ",none,24 0,"void AudioContext::addAutomaticPullNode(AudioNode* node) { ASSERT(isGraphOwner()); if (!m_automaticPullNodes.contains(node)) { m_automaticPullNodes.add(node); m_automaticPullNodesNeedUpdating = true; } } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::deleteProgram(unsigned program) { makeContextCurrent(); glDeleteProgram(program); } ",none,24 1,"static unsigned int xdr_set_page_base(struct xdr_stream *xdr, unsigned int base, unsigned int len) { unsigned int pgnr; unsigned int maxlen; unsigned int pgoff; unsigned int pgend; void *kaddr; maxlen = xdr->buf->page_len; if (base >= maxlen) { base = maxlen; maxlen = 0; } else maxlen -= base; if (len > maxlen) len = maxlen; xdr_stream_page_set_pos(xdr, base); base += xdr->buf->page_base; pgnr = base >> PAGE_SHIFT; xdr->page_ptr = &xdr->buf->pages[pgnr]; kaddr = page_address(*xdr->page_ptr); pgoff = base & ~PAGE_MASK; xdr->p = (__be32*)(kaddr + pgoff); pgend = pgoff + len; if (pgend > PAGE_SIZE) pgend = PAGE_SIZE; xdr->end = (__be32*)(kaddr + pgend); xdr->iov = NULL; return len; }",CWE-787,16 1,"int data_on_connection(int fd, callback_remove_handler remove) { int nread; char *network_packet; char network_line[8192]; char *p; unsigned long id; char string[1024]; unsigned long msg_id = UINT32_MAX; enum network_protocol version = network_client_get_version(fd); ioctl(fd, FIONREAD, &nread); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""new connection data = %d\n"",nread); if(nread == 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, ""%d failed, got 0 close connection to listener "", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); network_client_dump (); return 0; } if ( nread >= 8192 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, ""%d failed, more than 8192 close connection to listener "", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } /* read the whole package */ network_packet=malloc((nread+1) * sizeof(char)); read(fd, network_packet, nread); network_packet[nread]='\0'; memset(network_line, 0, 8192); p=network_packet; p_sem(sem_id); while ( get_network_line(p, network_line) ) { if ( strlen(network_line) > 0 ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""line = [%s]"",network_line); } if ( !strncmp(network_line, ""MSGID: "", strlen(""MSGID: "")) ) { /* read message id */ msg_id=strtoul(&(network_line[strlen(""MSGID: "")]), NULL, 10); p+=strlen(network_line); } else if ( !strncmp(network_line, ""Version: "", strlen(""Version: "")) ) { char *head = network_line, *end; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: VERSION""); version = strtoul(head + 9, &end, 10); if (!head[9] || *end) goto failed; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""VERSION=%d"", version); if (version < network_procotol_version) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, ""Forbidden VERSION=%d < %d, close connection to listener"", version, network_procotol_version); goto close; } else if (version >= PROTOCOL_LAST) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, ""Future VERSION=%d"", version); version = PROTOCOL_LAST - 1; } network_client_set_version(fd, version); /* reset message id */ msg_id = UINT32_MAX; p+=strlen(network_line); } else if ( !strncmp(network_line, ""Capabilities: "", strlen(""Capabilities: "")) ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: Capabilities""); if ( version > PROTOCOL_UNKNOWN ) { memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), ""Version: %d\nCapabilities: \n\n"", version); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""SEND: %s"", string); write(fd, string, strlen(string)); } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""Capabilities recv, but no version line""); } p+=strlen(network_line); } else if ( !strncmp(network_line, ""GET_DN "", strlen(""GET_DN "")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: GET_DN""); id=strtoul(&(network_line[strlen(""GET_DN "")]), NULL, 10); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""id: %ld"",id); if ( id <= notify_last_id.id) { char *dn_string = NULL; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""try to read %ld from cache"", id); /* try to read from cache */ if ( (dn_string = notifier_cache_get(id)) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""%ld not found in cache"", id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""%ld get one dn"", id); /* read from transaction file, because not in cache */ if( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""%ld failed "", id); /* TODO: maybe close connection? */ univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, ""%d failed, close connection to listener "", fd); close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; } } if ( dn_string != NULL ) { snprintf(string, sizeof(string), ""MSGID: %ld\n%s\n\n"",msg_id,dn_string); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""--> %d: [%s]"",fd, string); write(fd, string, strlen(string)); free(dn_string); } } else { /* set wanted id */ network_client_set_next_id(fd, id); network_client_set_msg_id(fd, msg_id); } p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if (!strncmp(p, ""WAIT_ID "", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) { char *head = network_line, *end; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: WAIT_ID""); id = strtoul(head + 8, &end, 10); if (!head[8] || *end) goto failed; univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""id: %ld"", id); if (id <= notify_last_id.id) { snprintf(string, sizeof(string), ""MSGID: %ld\n%ld\n\n"", msg_id, notify_last_id.id); write(fd, string, strlen(string)); } else { /* set wanted id */ network_client_set_next_id(fd, id); network_client_set_msg_id(fd, msg_id); } p += strlen(network_line) + 1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, ""GET_ID"", strlen(""GET_ID"")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: GET_ID""); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), ""MSGID: %ld\n%ld\n\n"",msg_id,notify_last_id.id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, ""GET_SCHEMA_ID"", strlen(""GET_SCHEMA_ID"")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: GET_SCHEMA_ID""); memset(string, 0, sizeof(string)); snprintf(string, sizeof(string), ""MSGID: %ld\n%ld\n\n"",msg_id,SCHEMA_ID); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""--> %d: [%s]"",fd, string); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else if ( !strncmp(network_line, ""ALIVE"", strlen(""ALIVE"")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""RECV: ALIVE""); snprintf(string, sizeof(string), ""MSGID: %ld\nOKAY\n\n"",msg_id); write(fd, string, strlen(string)); p+=strlen(network_line)+1; msg_id = UINT32_MAX; } else { p+=strlen(network_line); if (strlen(network_line) == 0 ) { p+=1; } else { univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, ""Drop package [%s]"", network_line); } } } v_sem(sem_id); univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, ""END Package""); network_client_dump (); return 0; failed: univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, ""Failed parsing [%s]"", p); close: close(fd); FD_CLR(fd, &readfds); remove(fd); return 0; }",CWE-200,4 0,"void VideoRendererBase::PutCurrentFrame(scoped_refptr frame) { base::AutoLock auto_lock(lock_); if (pending_paint_) { DCHECK_EQ(current_frame_, frame); DCHECK(!pending_paint_with_last_available_); pending_paint_ = false; } else if (pending_paint_with_last_available_) { DCHECK_EQ(last_available_frame_, frame); DCHECK(!pending_paint_); pending_paint_with_last_available_ = false; } else { DCHECK(!frame); } frame_available_.Signal(); if (state_ == kFlushingDecoder) return; if (state_ == kFlushing) { AttemptFlush_Locked(); return; } if (state_ == kError || state_ == kStopped) { DoStopOrError_Locked(); } } ",none,24 0,"float SoftwareFrameManager::GetCurrentFrameDeviceScaleFactor() const { DCHECK(HasCurrentFrame()); return current_frame_->frame_device_scale_factor_; } ",none,24 0,"void WebGraphicsContext3DDefaultImpl::copyTexSubImage2D(unsigned long target, long level, long xoffset, long yoffset, long x, long y, unsigned long width, unsigned long height) { makeContextCurrent(); bool needsResolve = (m_attributes.antialias && m_boundFBO == m_multisampleFBO); if (needsResolve) { resolveMultisampledFramebuffer(x, y, width, height); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); } glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); if (needsResolve) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_boundFBO); } ",none,24 1," Pong(const std::string& cookie, const std::string& server = """") : ClientProtocol::Message(""PONG"", ServerInstance->Config->GetServerName()) { PushParamRef(ServerInstance->Config->GetServerName()); if (!server.empty()) PushParamRef(server); PushParamRef(cookie); }",CWE-200,4 1,"pixReadFromTiffStream(TIFF *tif) { char *text; l_uint8 *linebuf, *data, *rowptr; l_uint16 spp, bps, photometry, tiffcomp, orientation, sample_fmt; l_uint16 *redmap, *greenmap, *bluemap; l_int32 d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval; l_int32 xres, yres, tiffbpl, packedbpl, halfsize; l_uint32 w, h, tiffword, read_oriented; l_uint32 *line, *ppixel, *tiffdata, *pixdata; PIX *pix, *pix1; PIXCMAP *cmap; PROCNAME(""pixReadFromTiffStream""); if (!tif) return (PIX *)ERROR_PTR(""tif not defined"", procName, NULL); read_oriented = 0; /* Only accept uint image data: * SAMPLEFORMAT_UINT = 1; * SAMPLEFORMAT_INT = 2; * SAMPLEFORMAT_IEEEFP = 3; * SAMPLEFORMAT_VOID = 4; */ TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt); if (sample_fmt != SAMPLEFORMAT_UINT) { L_ERROR(""sample format = %d is not uint\n"", procName, sample_fmt); return NULL; } /* Can't read tiff in tiled format. For what is involved, see, e.g: * https://www.cs.rochester.edu/~nelson/courses/vision/\ * resources/tiff/libtiff.html#Tiles * A tiled tiff can be converted to a normal (strip) tif: * tiffcp -s */ if (TIFFIsTiled(tif)) { L_ERROR(""tiled format is not supported\n"", procName); return NULL; } /* Old style jpeg is not supported. We tried supporting 8 bpp. * TIFFReadScanline() fails on this format, so we used RGBA * reading, which generates a 4 spp image, and pulled out the * red component. However, there were problems with double-frees * in cleanup. For RGB, tiffbpl is exactly half the size that * you would expect for the raster data in a scanline, which * is 3 * w. */ TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp); if (tiffcomp == COMPRESSION_OJPEG) { L_ERROR(""old style jpeg format is not supported\n"", procName); return NULL; } /* Use default fields for bps and spp */ TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp); if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) { L_ERROR(""invalid bps = %d\n"", procName, bps); return NULL; } if (spp == 2 && bps != 8) { L_WARNING(""for 2 spp, only handle 8 bps\n"", procName); return NULL; } if (spp == 1) d = bps; else if (spp == 2) /* gray plus alpha */ d = 32; /* will convert to RGBA */ else if (spp == 3 || spp == 4) d = 32; else return (PIX *)ERROR_PTR(""spp not in set {1,2,3,4}"", procName, NULL); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); if (w > MaxTiffWidth) { L_ERROR(""width = %d pixels; too large\n"", procName, w); return NULL; } if (h > MaxTiffHeight) { L_ERROR(""height = %d pixels; too large\n"", procName, h); return NULL; } /* The relation between the size of a byte buffer required to hold a raster of image pixels (packedbpl) and the size of the tiff buffer (tiffbuf) is either 1:1 or approximately 2:1, depending on how the data is stored and subsampled. Allow some slop when validating the relation between buffer size and the image parameters w, spp and bps. */ tiffbpl = TIFFScanlineSize(tif); packedbpl = (bps * spp * w + 7) / 8; halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8; #if 0 if (halfsize) L_INFO(""packedbpl = %d is approx. twice tiffbpl = %d\n"", procName, packedbpl, tiffbpl); #endif if (tiffbpl != packedbpl && !halfsize) { L_ERROR(""invalid tiffbpl: tiffbpl = %d, packedbpl = %d, "" ""bps = %d, spp = %d, w = %d\n"", procName, tiffbpl, packedbpl, bps, spp, w); return NULL; } if ((pix = pixCreate(w, h, d)) == NULL) return (PIX *)ERROR_PTR(""pix not made"", procName, NULL); pixSetInputFormat(pix, IFF_TIFF); data = (l_uint8 *)pixGetData(pix); wpl = pixGetWpl(pix); bpl = 4 * wpl; if (spp == 1) { linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8)); for (i = 0; i < h; i++) { if (TIFFReadScanline(tif, linebuf, i, 0) < 0) { LEPT_FREE(linebuf); pixDestroy(&pix); return (PIX *)ERROR_PTR(""line read fail"", procName, NULL); } memcpy(data, linebuf, tiffbpl); data += bpl; } if (bps <= 8) pixEndianByteSwap(pix); else /* bps == 16 */ pixEndianTwoByteSwap(pix); LEPT_FREE(linebuf); } else if (spp == 2 && bps == 8) { /* gray plus alpha */ L_INFO(""gray+alpha is not supported; converting to RGBA\n"", procName); pixSetSpp(pix, 4); linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8)); pixdata = pixGetData(pix); for (i = 0; i < h; i++) { if (TIFFReadScanline(tif, linebuf, i, 0) < 0) { LEPT_FREE(linebuf); pixDestroy(&pix); return (PIX *)ERROR_PTR(""line read fail"", procName, NULL); } rowptr = linebuf; ppixel = pixdata + i * wpl; for (j = k = 0; j < w; j++) { /* Copy gray value into r, g and b */ SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]); SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]); SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]); SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]); ppixel++; } } LEPT_FREE(linebuf); } else { /* rgb and rgba */ if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h, sizeof(l_uint32))) == NULL) { pixDestroy(&pix); return (PIX *)ERROR_PTR(""calloc fail for tiffdata"", procName, NULL); } /* TIFFReadRGBAImageOriented() converts to 8 bps */ if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata, ORIENTATION_TOPLEFT, 0)) { LEPT_FREE(tiffdata); pixDestroy(&pix); return (PIX *)ERROR_PTR(""failed to read tiffdata"", procName, NULL); } else { read_oriented = 1; } if (spp == 4) pixSetSpp(pix, 4); line = pixGetData(pix); for (i = 0; i < h; i++, line += wpl) { for (j = 0, ppixel = line; j < w; j++) { /* TIFFGet* are macros */ tiffword = tiffdata[i * w + j]; rval = TIFFGetR(tiffword); gval = TIFFGetG(tiffword); bval = TIFFGetB(tiffword); if (spp == 3) { composeRGBPixel(rval, gval, bval, ppixel); } else { /* spp == 4 */ aval = TIFFGetA(tiffword); composeRGBAPixel(rval, gval, bval, aval, ppixel); } ppixel++; } } LEPT_FREE(tiffdata); } if (getTiffStreamResolution(tif, &xres, &yres) == 0) { pixSetXRes(pix, xres); pixSetYRes(pix, yres); } /* Find and save the compression type */ comptype = getTiffCompressedFormat(tiffcomp); pixSetInputFormat(pix, comptype); if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) { /* Save the colormap as a pix cmap. Because the * tiff colormap components are 16 bit unsigned, * and go from black (0) to white (0xffff), the * the pix cmap takes the most significant byte. */ if (bps > 8) { pixDestroy(&pix); return (PIX *)ERROR_PTR(""colormap size > 256"", procName, NULL); } if ((cmap = pixcmapCreate(bps)) == NULL) { pixDestroy(&pix); return (PIX *)ERROR_PTR(""colormap not made"", procName, NULL); } ncolors = 1 << bps; for (i = 0; i < ncolors; i++) pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8, bluemap[i] >> 8); if (pixSetColormap(pix, cmap)) { pixDestroy(&pix); return (PIX *)ERROR_PTR(""invalid colormap"", procName, NULL); } /* Remove the colormap for 1 bpp. */ if (bps == 1) { pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC); pixDestroy(&pix); pix = pix1; } } else { /* No colormap: check photometry and invert if necessary */ if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) { /* Guess default photometry setting. Assume min_is_white * if compressed 1 bpp; min_is_black otherwise. */ if (tiffcomp == COMPRESSION_CCITTFAX3 || tiffcomp == COMPRESSION_CCITTFAX4 || tiffcomp == COMPRESSION_CCITTRLE || tiffcomp == COMPRESSION_CCITTRLEW) { photometry = PHOTOMETRIC_MINISWHITE; } else { photometry = PHOTOMETRIC_MINISBLACK; } } if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) || (d == 8 && photometry == PHOTOMETRIC_MINISWHITE)) pixInvert(pix, pix); } if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) { if (orientation >= 1 && orientation <= 8) { struct tiff_transform *transform = (read_oriented) ? &tiff_partial_orientation_transforms[orientation - 1] : &tiff_orientation_transforms[orientation - 1]; if (transform->vflip) pixFlipTB(pix, pix); if (transform->hflip) pixFlipLR(pix, pix); if (transform->rotate) { PIX *oldpix = pix; pix = pixRotate90(oldpix, transform->rotate); pixDestroy(&oldpix); } } } text = NULL; TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text); if (text) pixSetText(pix, text); return pix; }",CWE-125,1 1,"ins_comp_get_next_word_or_line( buf_T *ins_buf, // buffer being scanned pos_T *cur_match_pos, // current match position int *match_len, int *cont_s_ipos) // next ^X<> will set initial_pos { char_u *ptr; int len; *match_len = 0; ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) + cur_match_pos->col; if (ctrl_x_mode_line_or_eval()) { if (compl_status_adding()) { if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count) return NULL; ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE); if (!p_paste) ptr = skipwhite(ptr); } len = (int)STRLEN(ptr); } else { char_u *tmp_ptr = ptr; if (compl_status_adding()) { tmp_ptr += compl_length; // Skip if already inside a word. if (vim_iswordp(tmp_ptr)) return NULL; // Find start of next word. tmp_ptr = find_word_start(tmp_ptr); } // Find end of this word. tmp_ptr = find_word_end(tmp_ptr); len = (int)(tmp_ptr - ptr); if (compl_status_adding() && len == compl_length) { if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count) { // Try next line, if any. the new word will be // ""join"" as if the normal command ""J"" was used. // IOSIZE is always greater than // compl_length, so the next STRNCPY always // works -- Acevedo STRNCPY(IObuff, ptr, len); ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE); tmp_ptr = ptr = skipwhite(ptr); // Find start of next word. tmp_ptr = find_word_start(tmp_ptr); // Find end of next word. tmp_ptr = find_word_end(tmp_ptr); if (tmp_ptr > ptr) { if (*ptr != ')' && IObuff[len - 1] != TAB) { if (IObuff[len - 1] != ' ') IObuff[len++] = ' '; // IObuf =~ ""\k.* "", thus len >= 2 if (p_js && (IObuff[len - 2] == '.' || (vim_strchr(p_cpo, CPO_JOINSP) == NULL && (IObuff[len - 2] == '?' || IObuff[len - 2] == '!')))) IObuff[len++] = ' '; } // copy as much as possible of the new word if (tmp_ptr - ptr >= IOSIZE - len) tmp_ptr = ptr + IOSIZE - len - 1; STRNCPY(IObuff + len, ptr, tmp_ptr - ptr); len += (int)(tmp_ptr - ptr); *cont_s_ipos = TRUE; } IObuff[len] = NUL; ptr = IObuff; } if (len == compl_length) return NULL; } } *match_len = len; return ptr; }",CWE-787,16 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; 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) { ldout(s->cct, 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) { ldout(s->cct, 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); 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) { ldout(s->cct,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 0,"void ServiceWorkerScriptContext::DidHandleInstallEvent(int request_id) { Send(request_id, ServiceWorkerHostMsg_InstallEventFinished()); } ",none,24 0,"VideoRendererBase::VideoRendererBase(const base::Closure& paint_cb, const SetOpaqueCB& set_opaque_cb, bool drop_frames) : frame_available_(&lock_), state_(kUninitialized), thread_(base::kNullThreadHandle), pending_read_(false), pending_paint_(false), pending_paint_with_last_available_(false), drop_frames_(drop_frames), playback_rate_(0), paint_cb_(paint_cb), set_opaque_cb_(set_opaque_cb) { DCHECK(!paint_cb_.is_null()); } ",none,24 1,"void LibRaw::parseSonySRF(unsigned len) { if ((len > 0xfffff) || (len == 0)) return; INT64 save = ftell(ifp); INT64 offset = 0x0310c0 - save; /* for non-DNG this value normally is 0x8ddc */ if (len < offset || offset < 0) return; INT64 decrypt_len = offset >> 2; /* master key offset value is the next un-encrypted metadata field after SRF0 */ unsigned i, nWB; unsigned MasterKey, SRF2Key, RawDataKey; INT64 srf_offset, tag_offset, tag_data, tag_dataoffset; int tag_dataunitlen; uchar *srf_buf; short entries; unsigned tag_id, tag_type, tag_datalen; srf_buf = (uchar *)malloc(len); fread(srf_buf, len, 1, ifp); offset += srf_buf[offset] << 2; #define CHECKBUFFER_SGET4(offset) \ do \ { \ if ((((offset) + 4) > len) || ((offset) < 0)) \ goto restore_after_parseSonySRF; \ } while (0) #define CHECKBUFFER_SGET2(offset) \ do \ { \ if ( ((offset + 2) > len) || ((offset) < 0)) \ goto restore_after_parseSonySRF; \ } while (0) CHECKBUFFER_SGET4(offset); /* master key is stored in big endian */ MasterKey = ((unsigned)srf_buf[offset] << 24) | ((unsigned)srf_buf[offset + 1] << 16) | ((unsigned)srf_buf[offset + 2] << 8) | (unsigned)srf_buf[offset + 3]; /* skip SRF0 */ srf_offset = 0; CHECKBUFFER_SGET2(srf_offset); entries = sget2(srf_buf + srf_offset); if (entries > 1000) goto restore_after_parseSonySRF; offset = srf_offset + 2; CHECKBUFFER_SGET4(offset); CHECKBUFFER_SGET4(offset + 12 * entries); srf_offset = sget4(srf_buf + offset + 12 * entries) - save; /* SRF0 ends with SRF1 abs. position */ /* get SRF1, it has fixed 40 bytes length and contains keys to decode metadata * and raw data */ if (srf_offset < 0 || decrypt_len < srf_offset / 4) goto restore_after_parseSonySRF; sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4, 1, MasterKey); CHECKBUFFER_SGET2(srf_offset); entries = sget2(srf_buf + srf_offset); if (entries > 1000) goto restore_after_parseSonySRF; offset = srf_offset + 2; tag_offset = offset; while (entries--) { if (tiff_sget (save, srf_buf, len, &tag_offset, &tag_id, &tag_type, &tag_dataoffset, &tag_datalen, &tag_dataunitlen) == 0) { if (tag_id == 0x0000) { SRF2Key = sget4(srf_buf + tag_dataoffset); } else if (tag_id == 0x0001) { RawDataKey = sget4(srf_buf + tag_dataoffset); } } else goto restore_after_parseSonySRF; } offset = tag_offset; /* get SRF2 */ CHECKBUFFER_SGET4(offset); srf_offset = sget4(srf_buf + offset) - save; /* SRFn ends with SRFn+1 position */ if (srf_offset < 0 || decrypt_len < srf_offset / 4) goto restore_after_parseSonySRF; sony_decrypt((unsigned *)(srf_buf + srf_offset), decrypt_len - srf_offset / 4, 1, SRF2Key); CHECKBUFFER_SGET2(srf_offset); entries = sget2(srf_buf + srf_offset); if (entries > 1000) goto restore_after_parseSonySRF; offset = srf_offset + 2; tag_offset = offset; while (entries--) { if (tiff_sget (save, srf_buf, len, &tag_offset, &tag_id, &tag_type, &tag_dataoffset, &tag_datalen, &tag_dataunitlen) == 0) { if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) { i = (tag_id - 0x00c0) % 3; nWB = (tag_id - 0x00c0) / 3; icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset); if (i == 1) { icWBC[Sony_SRF_wb_list[nWB]][3] = icWBC[Sony_SRF_wb_list[nWB]][i]; } } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) { i = (tag_id - 0x00d0) % 3; cam_mul[i] = sget4(srf_buf + tag_dataoffset); if (i == 1) { cam_mul[3] = cam_mul[i]; } } else switch (tag_id) { /* 0x0002 SRF6Offset 0x0003 SRFDataOffset (?) 0x0004 RawDataOffset 0x0005 RawDataLength */ case 0x0043: ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset); break; case 0x0044: ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset); break; case 0x0045: ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset); break; case 0x0046: ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset); break; } } else goto restore_after_parseSonySRF; } offset = tag_offset; restore_after_parseSonySRF: free(srf_buf); fseek(ifp, save, SEEK_SET); #undef CHECKBUFFER_SGET4 #undef CHECKBUFFER_SGET2 }",CWE-125,1 1," void Compute(OpKernelContext* ctx) override { const Tensor* inputs; const Tensor* labels_indices; const Tensor* labels_values; const Tensor* seq_len; OP_REQUIRES_OK(ctx, ctx->input(""inputs"", &inputs)); OP_REQUIRES_OK(ctx, ctx->input(""labels_indices"", &labels_indices)); OP_REQUIRES_OK(ctx, ctx->input(""labels_values"", &labels_values)); OP_REQUIRES_OK(ctx, ctx->input(""sequence_length"", &seq_len)); OP_REQUIRES(ctx, inputs->shape().dims() == 3, errors::InvalidArgument(""inputs is not a 3-Tensor"")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(seq_len->shape()), errors::InvalidArgument(""sequence_length is not a vector"")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(labels_indices->shape()), errors::InvalidArgument(""labels_indices is not a matrix"")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(labels_values->shape()), errors::InvalidArgument(""labels_values is not a vector"")); const TensorShape& inputs_shape = inputs->shape(); const int64 max_time = inputs_shape.dim_size(0); const int64 batch_size = inputs_shape.dim_size(1); const int64 num_classes_raw = inputs_shape.dim_size(2); OP_REQUIRES( ctx, FastBoundsCheck(num_classes_raw, std::numeric_limits::max()), errors::InvalidArgument(""num_classes cannot exceed max int"")); const int num_classes = static_cast(num_classes_raw); OP_REQUIRES( ctx, batch_size == seq_len->dim_size(0), errors::InvalidArgument(""len(sequence_length) != batch_size. "", ""len(sequence_length): "", seq_len->dim_size(0), "" batch_size: "", batch_size)); auto seq_len_t = seq_len->vec(); OP_REQUIRES(ctx, labels_indices->dim_size(0) == labels_values->dim_size(0), errors::InvalidArgument( ""labels_indices and labels_values must contain the "" ""same number of rows, but saw shapes: "", labels_indices->shape().DebugString(), "" vs. "", labels_values->shape().DebugString())); OP_REQUIRES(ctx, batch_size != 0, errors::InvalidArgument(""batch_size must not be 0"")); // Figure out the maximum label length to use as sparse tensor dimension. auto labels_indices_t = labels_indices->matrix(); int64 max_label_len = 0; for (int i = 0; i < labels_indices->dim_size(0); i++) { max_label_len = std::max(max_label_len, labels_indices_t(i, 1) + 1); } TensorShape labels_shape({batch_size, max_label_len}); std::vector order{0, 1}; sparse::SparseTensor labels_sp; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create(*labels_indices, *labels_values, labels_shape, order, &labels_sp)); Status labels_sp_valid = labels_sp.IndicesValid(); OP_REQUIRES(ctx, labels_sp_valid.ok(), errors::InvalidArgument(""label SparseTensor is not valid: "", labels_sp_valid.error_message())); typename ctc::CTCLossCalculator::LabelSequences labels_t(batch_size); for (const auto& g : labels_sp.group({0})) { // iterate by batch const int64 batch_indices = g.group()[0]; OP_REQUIRES(ctx, FastBoundsCheck(batch_indices, batch_size), errors::InvalidArgument(""labels batch index must be between "", 0, "" and "", batch_size, "" but saw: "", batch_indices)); auto values = g.values(); std::vector* b_values = &labels_t[batch_indices]; b_values->resize(values.size()); for (int i = 0; i < values.size(); ++i) (*b_values)[i] = values(i); } OP_REQUIRES(ctx, static_cast(batch_size) == labels_t.size(), errors::InvalidArgument(""len(labels) != batch_size. "", ""len(labels): "", labels_t.size(), "" batch_size: "", batch_size)); for (int64 b = 0; b < batch_size; ++b) { OP_REQUIRES( ctx, seq_len_t(b) <= max_time, errors::InvalidArgument(""sequence_length("", b, "") <= "", max_time)); } Tensor* loss = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(""loss"", seq_len->shape(), &loss)); auto loss_t = loss->vec(); Tensor* gradient; OP_REQUIRES_OK(ctx, ctx->allocate_output(""gradient"", inputs_shape, &gradient)); auto gradient_t = gradient->tensor(); auto inputs_t = inputs->tensor(); std::vector gradient_list_t; std::vector input_list_t; for (std::size_t t = 0; t < max_time; ++t) { input_list_t.emplace_back(inputs_t.data() + t * batch_size * num_classes, batch_size, num_classes); gradient_list_t.emplace_back( gradient_t.data() + t * batch_size * num_classes, batch_size, num_classes); } gradient_t.setZero(); // Assumption: the blank index is num_classes - 1 ctc::CTCLossCalculator ctc_loss_calculator(num_classes - 1, 0); DeviceBase::CpuWorkerThreads workers = *ctx->device()->tensorflow_cpu_worker_threads(); OP_REQUIRES_OK(ctx, ctc_loss_calculator.CalculateLoss( seq_len_t, labels_t, input_list_t, preprocess_collapse_repeated_, ctc_merge_repeated_, ignore_longer_outputs_than_inputs_, &loss_t, &gradient_list_t, &workers)); }",CWE-190,2 0," media::VideoCapture::EventHandler* capture_client() { return static_cast(decoder_); } ",none,24 0," void DecodeSingleFrame(const scoped_refptr& buffer, VideoDecoder::DecoderStatus* status, scoped_refptr* video_frame) { EXPECT_CALL(*demuxer_, Read(_)) .WillOnce(ReturnBuffer(buffer)) .WillRepeatedly(ReturnBuffer(end_of_stream_buffer_)); EXPECT_CALL(statistics_cb_, OnStatistics(_)); Read(status, video_frame); } ",none,24 1,"static void vhost_vdpa_config_put(struct vhost_vdpa *v) { if (v->config_ctx) eventfd_ctx_put(v->config_ctx); }",CWE-416,10 1,"static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""No maker note data found. Detected maker: %s (length = %d)"", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""check (%s,%s)"", maker_note->make?maker_note->make:"""", maker_note->model?maker_note->model:"""");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data too short: 0x%04X offset 0x%04X"", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Process %s @x%04X + 0x%04X=%d: %s"", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data too short: 0x%04X"", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Using automatic offset correction: 0x%04X"", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""IFD data bad offset: 0x%04X length 0x%04X"", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X"", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;detag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, ""Subsection %s done"", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; }",CWE-125,1 1,"static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* 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); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,""NotAVIFFImage""); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); if (count != 512) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,""comment"",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=ReadBlobSignedLong(image); viff_info.y_offset=ReadBlobSignedLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) SetImageBackgroundColor(image); /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (number_pixels == 0) ThrowReaderException(CoderError,""ImageColumnOrRowSizeIsNotSupported""); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,""DataStorageTypeIsNotSupported""); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,""MapStorageTypeIsNotSupported""); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,""ColorspaceModelIsNotSupported""); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,""LocationTypeIsNotSupported""); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,""NumberOfImagesIsNotSupported""); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if ((MagickSizeType) (viff_info.map_rows*image->colors) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if ((MagickSizeType) viff_info.map_rows > GetBlobSize(image)) ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); if ((MagickSizeType) viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,""ColormapTypeNotSupported""); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Create bi-level colormap. */ image->colors=2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); image->colorspace=GRAYColorspace; } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) { if (HeapOverflowSanityCheck((image->columns+7UL) >> 3UL,image->rows) != MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); max_packets=((image->columns+7UL) >> 3UL)*image->rows; } else { if (HeapOverflowSanityCheck((size_t) number_pixels,viff_info.number_data_bands) != MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); max_packets=(size_t) (number_pixels*viff_info.number_data_bands); } if ((MagickSizeType) (bytes_per_pixel*max_packets) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); pixels=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( number_pixels,max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) memset(pixels,0,MagickMax(number_pixels,max_packets)* bytes_per_pixel*sizeof(*pixels)); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,(ssize_t) index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,(ssize_t) index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,(ssize_t) index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); 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; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count == 1) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }",CWE-400,9 1,"ds_fgetstr (FILE *f, dynamic_string *s, char eos) { int insize; /* Amount needed for line. */ int strsize; /* Amount allocated for S. */ int next_ch; /* Initialize. */ insize = 0; strsize = s->ds_length; /* Read the input string. */ next_ch = getc (f); while (next_ch != eos && next_ch != EOF) { if (insize >= strsize - 1) { ds_resize (s, strsize * 2 + 2); strsize = s->ds_length; } s->ds_string[insize++] = next_ch; next_ch = getc (f); } s->ds_string[insize++] = '\0'; if (insize == 1 && next_ch == EOF) return NULL; else return s->ds_string; }",CWE-190,2 1,"static MSUSB_PIPE_DESCRIPTOR** msusb_mspipes_read(wStream* s, UINT32 NumberOfPipes) { UINT32 pnum; MSUSB_PIPE_DESCRIPTOR** MsPipes; if (Stream_GetRemainingCapacity(s) < 12 * NumberOfPipes) return NULL; MsPipes = (MSUSB_PIPE_DESCRIPTOR**)calloc(NumberOfPipes, sizeof(MSUSB_PIPE_DESCRIPTOR*)); if (!MsPipes) return NULL; for (pnum = 0; pnum < NumberOfPipes; pnum++) { MSUSB_PIPE_DESCRIPTOR* MsPipe = msusb_mspipe_new(); if (!MsPipe) goto out_error; Stream_Read_UINT16(s, MsPipe->MaximumPacketSize); Stream_Seek(s, 2); Stream_Read_UINT32(s, MsPipe->MaximumTransferSize); Stream_Read_UINT32(s, MsPipe->PipeFlags); /* Already set to zero by memset MsPipe->PipeHandle = 0; MsPipe->bEndpointAddress = 0; MsPipe->bInterval = 0; MsPipe->PipeType = 0; MsPipe->InitCompleted = 0; */ MsPipes[pnum] = MsPipe; } return MsPipes; out_error: for (pnum = 0; pnum < NumberOfPipes; pnum++) free(MsPipes[pnum]); free(MsPipes); return NULL; }",CWE-190,2 1,"GF_Err stbl_GetSampleInfos(GF_SampleTableBox *stbl, u32 sampleNumber, u64 *offset, u32 *chunkNumber, u32 *descIndex, GF_StscEntry **out_ent) { GF_Err e; u32 i, k, offsetInChunk, size, chunk_num; GF_ChunkOffsetBox *stco; GF_ChunkLargeOffsetBox *co64; GF_StscEntry *ent; (*offset) = 0; (*chunkNumber) = (*descIndex) = 0; if (out_ent) (*out_ent) = NULL; if (!stbl || !sampleNumber) return GF_BAD_PARAM; if (!stbl->ChunkOffset || !stbl->SampleToChunk || !stbl->SampleSize) return GF_ISOM_INVALID_FILE; if (stbl->SampleSize && stbl->SampleToChunk->nb_entries == stbl->SampleSize->sampleCount) { ent = &stbl->SampleToChunk->entries[sampleNumber-1]; if (!ent) return GF_BAD_PARAM; (*descIndex) = ent->sampleDescriptionIndex; (*chunkNumber) = sampleNumber; if (out_ent) *out_ent = ent; if ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { stco = (GF_ChunkOffsetBox *)stbl->ChunkOffset; if (!stco->offsets) return GF_ISOM_INVALID_FILE; (*offset) = (u64) stco->offsets[sampleNumber - 1]; } else { co64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset; if (!co64->offsets) return GF_ISOM_INVALID_FILE; (*offset) = co64->offsets[sampleNumber - 1]; } return GF_OK; } //check our cache: if desired sample is at or above current cache entry, start from here if (stbl->SampleToChunk->firstSampleInCurrentChunk && (stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber)) { i = stbl->SampleToChunk->currentIndex; ent = &stbl->SampleToChunk->entries[stbl->SampleToChunk->currentIndex]; GetGhostNum(ent, i, stbl->SampleToChunk->nb_entries, stbl); k = stbl->SampleToChunk->currentChunk; } //otherwise start from first entry else { i = 0; stbl->SampleToChunk->currentIndex = 0; stbl->SampleToChunk->currentChunk = 1; stbl->SampleToChunk->ghostNumber = 1; stbl->SampleToChunk->firstSampleInCurrentChunk = 1; ent = &stbl->SampleToChunk->entries[0]; GetGhostNum(ent, 0, stbl->SampleToChunk->nb_entries, stbl); k = stbl->SampleToChunk->currentChunk; } //first get the chunk for (; i < stbl->SampleToChunk->nb_entries; i++) { assert(stbl->SampleToChunk->firstSampleInCurrentChunk <= sampleNumber); //corrupted file (less sample2chunk info than sample count if (k > stbl->SampleToChunk->ghostNumber) { return GF_ISOM_INVALID_FILE; } //check if sample is in current chunk u32 max_chunks_in_entry = stbl->SampleToChunk->ghostNumber - k; u32 nb_chunks_for_sample = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk; if (ent->samplesPerChunk) nb_chunks_for_sample /= ent->samplesPerChunk; if ( (nb_chunks_for_sample <= max_chunks_in_entry) && (stbl->SampleToChunk->firstSampleInCurrentChunk + (nb_chunks_for_sample+1) * ent->samplesPerChunk > sampleNumber) ) { stbl->SampleToChunk->firstSampleInCurrentChunk += nb_chunks_for_sample * ent->samplesPerChunk; stbl->SampleToChunk->currentChunk += nb_chunks_for_sample; goto sample_found; } max_chunks_in_entry += 1; stbl->SampleToChunk->firstSampleInCurrentChunk += max_chunks_in_entry * ent->samplesPerChunk; stbl->SampleToChunk->currentChunk += max_chunks_in_entry; //not in this entry, get the next entry if not the last one if (i+1 != stbl->SampleToChunk->nb_entries) { ent = &stbl->SampleToChunk->entries[i+1]; //update the GhostNumber GetGhostNum(ent, i+1, stbl->SampleToChunk->nb_entries, stbl); //update the entry in our cache stbl->SampleToChunk->currentIndex = i+1; stbl->SampleToChunk->currentChunk = 1; k = 1; } } //if we get here, gasp, the sample was not found return GF_ISOM_INVALID_FILE; sample_found: (*descIndex) = ent->sampleDescriptionIndex; (*chunkNumber) = chunk_num = ent->firstChunk + stbl->SampleToChunk->currentChunk - 1; if (out_ent) *out_ent = ent; if (! *chunkNumber) return GF_ISOM_INVALID_FILE; //ok, get the size of all the previous samples in the chunk offsetInChunk = 0; //constant size if (stbl->SampleSize && stbl->SampleSize->sampleSize) { u32 diff = sampleNumber - stbl->SampleToChunk->firstSampleInCurrentChunk; offsetInChunk += diff * stbl->SampleSize->sampleSize; } else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num == sampleNumber)) { offsetInChunk = stbl->r_last_offset_in_chunk; } else if ((stbl->r_last_chunk_num == chunk_num) && (stbl->r_last_sample_num + 1 == sampleNumber)) { e = stbl_GetSampleSize(stbl->SampleSize, stbl->r_last_sample_num, &size); if (e) return e; stbl->r_last_offset_in_chunk += size; stbl->r_last_sample_num = sampleNumber; offsetInChunk = stbl->r_last_offset_in_chunk; } else { //warning, firstSampleInChunk is at least 1 - not 0 for (i = stbl->SampleToChunk->firstSampleInCurrentChunk; i < sampleNumber; i++) { e = stbl_GetSampleSize(stbl->SampleSize, i, &size); if (e) return e; offsetInChunk += size; } stbl->r_last_chunk_num = chunk_num; stbl->r_last_sample_num = sampleNumber; stbl->r_last_offset_in_chunk = offsetInChunk; } //OK, that's the size of our offset in the chunk //now get the chunk if ( stbl->ChunkOffset->type == GF_ISOM_BOX_TYPE_STCO) { stco = (GF_ChunkOffsetBox *)stbl->ChunkOffset; if (stco->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE; (*offset) = (u64) stco->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk; } else { co64 = (GF_ChunkLargeOffsetBox *)stbl->ChunkOffset; if (co64->nb_entries < (*chunkNumber) ) return GF_ISOM_INVALID_FILE; (*offset) = co64->offsets[(*chunkNumber) - 1] + (u64) offsetInChunk; } return GF_OK; }",CWE-416,10 0,"SoftwareFrameManager::SoftwareFrameManager( base::WeakPtr client) : client_(client) {} ",none,24 1," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor num_bits_tensor; num_bits_tensor = ctx->input(3); int num_bits_val = num_bits_tensor.scalar()(); OP_REQUIRES( ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63), errors::InvalidArgument(""num_bits is out of range: "", num_bits_val, "" with signed_input_ "", signed_input_)); Tensor input_min_tensor; Tensor input_max_tensor; if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); if (axis_ == -1) { auto min_val = input_min_tensor.scalar()(); auto max_val = input_max_tensor.scalar()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument(""Invalid range: input_min "", min_val, "" > input_max "", max_val)); } else { OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_min_tensor has incorrect size, was "", input_min_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_min_tensor.shape())); OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_max_tensor has incorrect size, was "", input_max_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_max_tensor.shape())); } } else { auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth}); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_max_tensor)); } if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleFunctor f; f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_val, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, narrow_range_, output->flat()); } else { functor::QuantizeAndDequantizePerChannelFunctor f; f(ctx->eigen_device(), input.template flat_inner_outer_dims(axis_ - 1), signed_input_, num_bits_val, range_given_, &input_min_tensor, &input_max_tensor, ROUND_HALF_TO_EVEN, narrow_range_, output->template flat_inner_outer_dims(axis_ - 1)); } }",CWE-125,1 0,"bool WebGraphicsContext3DDefaultImpl::makeContextCurrent() { return m_glContext->MakeCurrent(); } ",none,24 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 (IHDR)\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 (BPCC)\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); if (!dec->image->cmprof_) { jas_iccprof_destroy(iccprof); goto error; } 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) { if (!pclrd->numlutents) { goto error; } lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); if (!lutents) { goto error; } 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)); } #else /* suppress -Wunused-but-set-variable */ (void)cdefd; #endif } else { jas_eprintf(""error: invalid MTYP in CMAP box\n""); goto error; } } } /* Ensure that the number of channels being used by the decoder matches the number of image components. */ if (dec->numchans != jas_image_numcmpts(dec->image)) { jas_eprintf(""error: mismatch in number of components (%d != %d)\n"", dec->numchans, jas_image_numcmpts(dec->image)); goto error; } /* 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->cdef->data.cdef.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,"void SearchEngineTabHelper::GenerateKeywordIfNecessary( const content::FrameNavigateParams& params) { if (!params.searchable_form_url.is_valid()) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); if (profile->IsOffTheRecord()) return; const NavigationController& controller = web_contents()->GetController(); int last_index = controller.GetLastCommittedEntryIndex(); if (last_index <= 0) return; base::string16 keyword(GenerateKeywordFromNavigationEntry( controller.GetEntryAtIndex(last_index - 1), profile->GetPrefs()->GetString(prefs::kAcceptLanguages))); if (keyword.empty()) return; TemplateURLService* url_service = TemplateURLServiceFactory::GetForProfile(profile); if (!url_service) return; if (!url_service->loaded()) { url_service->Load(); return; } TemplateURL* current_url; GURL url = params.searchable_form_url; if (!url_service->CanAddAutogeneratedKeyword(keyword, url, ¤t_url)) return; if (current_url) { if (current_url->originating_url().is_valid()) { return; } url_service->Remove(current_url); } TemplateURLData data; data.SetShortName(keyword); data.SetKeyword(keyword); data.SetURL(url.spec()); DCHECK(controller.GetLastCommittedEntry()); const GURL& current_favicon = controller.GetLastCommittedEntry()->GetFavicon().url; data.favicon_url = current_favicon.is_valid() ? current_favicon : TemplateURL::GenerateFaviconURL(params.referrer.url); data.safe_for_autoreplace = true; data.input_encodings.push_back(params.searchable_form_encoding); url_service->Add(new TemplateURL(data)); } ",none,24 1," Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) { const Tensor first_partition_tensor = context->input(kFirstPartitionInputIndex); const RowPartitionType first_partition_type = row_partition_types_[0]; switch (first_partition_type) { case RowPartitionType::FIRST_DIM_SIZE: *result = first_partition_tensor.scalar()(); return Status::OK(); case RowPartitionType::VALUE_ROWIDS: return errors::InvalidArgument( ""Cannot handle VALUE_ROWIDS in first dimension.""); case RowPartitionType::ROW_SPLITS: *result = first_partition_tensor.shape().dim_size(0) - 1; return Status::OK(); default: return errors::InvalidArgument( ""Cannot handle type "", RowPartitionTypeToString(first_partition_type)); } }",CWE-125,1 0,"void WebGraphicsContext3DDefaultImpl::compileShader(WebGLId shader) { makeContextCurrent(); ShaderSourceMap::iterator result = m_shaderSourceMap.find(shader); if (result == m_shaderSourceMap.end()) { glCompileShader(shader); return; } ShaderSourceEntry* entry = result->second; ASSERT(entry); if (!angleValidateShaderSource(*entry)) return; // Shader didn't validate, don't move forward with compiling translated source int shaderLength = entry->translatedSource ? strlen(entry->translatedSource) : 0; glShaderSource(shader, 1, const_cast(&entry->translatedSource), &shaderLength); glCompileShader(shader); #ifndef NDEBUG int compileStatus; glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus); ASSERT(compileStatus == GL_TRUE); #endif } ",none,24 1," bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '""': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }",CWE-125,1 1," explicit ReverseSequenceOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr(""batch_dim"", &batch_dim_)); OP_REQUIRES_OK(context, context->GetAttr(""seq_dim"", &seq_dim_)); }",CWE-787,16 0,"int VideoRendererBase::NumFrames_Locked() const { lock_.AssertAcquired(); int outstanding_frames = (current_frame_ ? 1 : 0) + (last_available_frame_ ? 1 : 0) + (current_frame_ && (current_frame_ == last_available_frame_) ? -1 : 0); return ready_frames_.size() + outstanding_frames; } ",none,24 1,"static int xbuf_format_converter(char **outbuf, const char *fmt, va_list ap) { register char *s = nullptr; char *q; int s_len; register int min_width = 0; int precision = 0; enum { LEFT, RIGHT } adjust; char pad_char; char prefix_char; double fp_num; wide_int i_num = (wide_int) 0; u_wide_int ui_num; char num_buf[NUM_BUF_SIZE]; char char_buf[2]; /* for printing %% and % */ #ifdef HAVE_LOCALE_H struct lconv *lconv = nullptr; #endif /* * Flag variables */ length_modifier_e modifier; boolean_e alternate_form; boolean_e print_sign; boolean_e print_blank; boolean_e adjust_precision; boolean_e adjust_width; int is_negative; int size = 240; char *result = (char *)malloc(size); int outpos = 0; while (*fmt) { if (*fmt != '%') { appendchar(&result, &outpos, &size, *fmt); } else { /* * Default variable settings */ adjust = RIGHT; alternate_form = print_sign = print_blank = NO; pad_char = ' '; prefix_char = NUL; fmt++; /* * Try to avoid checking for flags, width or precision */ if (isascii((int)*fmt) && !islower((int)*fmt)) { /* * Recognize flags: -, #, BLANK, + */ for (;; fmt++) { if (*fmt == '-') adjust = LEFT; else if (*fmt == '+') print_sign = YES; else if (*fmt == '#') alternate_form = YES; else if (*fmt == ' ') print_blank = YES; else if (*fmt == '0') pad_char = '0'; else break; } /* * Check if a width was specified */ if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, min_width); adjust_width = YES; } else if (*fmt == '*') { min_width = va_arg(ap, int); fmt++; adjust_width = YES; if (min_width < 0) { adjust = LEFT; min_width = -min_width; } } else adjust_width = NO; /* * Check if a precision was specified * * XXX: an unreasonable amount of precision may be specified * resulting in overflow of num_buf. Currently we * ignore this possibility. */ if (*fmt == '.') { adjust_precision = YES; fmt++; if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, precision); } else if (*fmt == '*') { precision = va_arg(ap, int); fmt++; if (precision < 0) precision = 0; } else precision = 0; } else adjust_precision = NO; } else adjust_precision = adjust_width = NO; /* * Modifier check */ switch (*fmt) { case 'L': fmt++; modifier = LM_LONG_DOUBLE; break; case 'I': fmt++; #if SIZEOF_LONG_LONG if (*fmt == '6' && *(fmt+1) == '4') { fmt += 2; modifier = LM_LONG_LONG; } else #endif if (*fmt == '3' && *(fmt+1) == '2') { fmt += 2; modifier = LM_LONG; } else { #ifdef _WIN64 modifier = LM_LONG_LONG; #else modifier = LM_LONG; #endif } break; case 'l': fmt++; #if SIZEOF_LONG_LONG if (*fmt == 'l') { fmt++; modifier = LM_LONG_LONG; } else #endif modifier = LM_LONG; break; case 'z': fmt++; modifier = LM_SIZE_T; break; case 'j': fmt++; #if SIZEOF_INTMAX_T modifier = LM_INTMAX_T; #else modifier = LM_SIZE_T; #endif break; case 't': fmt++; #if SIZEOF_PTRDIFF_T modifier = LM_PTRDIFF_T; #else modifier = LM_SIZE_T; #endif break; case 'h': fmt++; if (*fmt == 'h') { fmt++; } /* these are promoted to int, so no break */ default: modifier = LM_STD; break; } /* * Argument extraction and printing. * First we determine the argument type. * Then, we convert the argument to a string. * On exit from the switch, s points to the string that * must be printed, s_len has the length of the string * The precision requirements, if any, are reflected in s_len. * * NOTE: pad_char may be set to '0' because of the 0 flag. * It is reset to ' ' by non-numeric formats */ switch (*fmt) { case 'u': switch(modifier) { default: i_num = (wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: i_num = (wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: i_num = (wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: i_num = (wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: i_num = (wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: i_num = (wide_int) va_arg(ap, ptrdiff_t); break; #endif } /* * The rest also applies to other integer formats, so fall * into that case. */ case 'd': case 'i': /* * Get the arg if we haven't already. */ if ((*fmt) != 'u') { switch(modifier) { default: i_num = (wide_int) va_arg(ap, int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: i_num = (wide_int) va_arg(ap, long int); break; case LM_SIZE_T: #if SIZEOF_SSIZE_T i_num = (wide_int) va_arg(ap, ssize_t); #else i_num = (wide_int) va_arg(ap, size_t); #endif break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: i_num = (wide_int) va_arg(ap, wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: i_num = (wide_int) va_arg(ap, intmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: i_num = (wide_int) va_arg(ap, ptrdiff_t); break; #endif } } s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (*fmt != 'u') { if (is_negative) prefix_char = '-'; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; } break; case 'o': switch(modifier) { default: ui_num = (u_wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: ui_num = (u_wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: ui_num = (u_wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: ui_num = (u_wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: ui_num = (u_wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: ui_num = (u_wide_int) va_arg(ap, ptrdiff_t); break; #endif } s = ap_php_conv_p2(ui_num, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (alternate_form && *s != '0') { *--s = '0'; s_len++; } break; case 'x': case 'X': switch(modifier) { default: ui_num = (u_wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: ui_num = (u_wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: ui_num = (u_wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: ui_num = (u_wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: ui_num = (u_wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: ui_num = (u_wide_int) va_arg(ap, ptrdiff_t); break; #endif } s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (alternate_form && i_num != 0) { *--s = *fmt; /* 'x' or 'X' */ *--s = '0'; s_len += 2; } break; case 's': case 'v': s = va_arg(ap, char *); if (s != nullptr) { s_len = strlen(s); if (adjust_precision && precision < s_len) s_len = precision; } else { s = const_cast(s_null); s_len = S_NULL_LEN; } pad_char = ' '; break; case 'f': case 'F': case 'e': case 'E': switch(modifier) { case LM_LONG_DOUBLE: fp_num = (double) va_arg(ap, long double); break; case LM_STD: fp_num = va_arg(ap, double); break; default: goto fmt_error; } if (std::isnan(fp_num)) { s = const_cast(""nan""); s_len = 3; } else if (std::isinf(fp_num)) { s = const_cast(""inf""); s_len = 3; } else { #ifdef HAVE_LOCALE_H if (!lconv) { lconv = localeconv(); } #endif s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form, (adjust_precision == NO) ? FLOAT_DIGITS : precision, (*fmt == 'f')?LCONV_DECIMAL_POINT:'.', &is_negative, &num_buf[1], &s_len); if (is_negative) prefix_char = '-'; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; } break; case 'g': case 'k': case 'G': case 'H': switch(modifier) { case LM_LONG_DOUBLE: fp_num = (double) va_arg(ap, long double); break; case LM_STD: fp_num = va_arg(ap, double); break; default: goto fmt_error; } if (std::isnan(fp_num)) { s = const_cast(""NAN""); s_len = 3; break; } else if (std::isinf(fp_num)) { if (fp_num > 0) { s = const_cast(""INF""); s_len = 3; } else { s = const_cast(""-INF""); s_len = 4; } break; } if (adjust_precision == NO) precision = FLOAT_DIGITS; else if (precision == 0) precision = 1; /* * * We use &num_buf[ 1 ], so that we have room for the sign */ #ifdef HAVE_LOCALE_H if (!lconv) { lconv = localeconv(); } #endif s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]); if (*s == '-') prefix_char = *s++; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; s_len = strlen(s); if (alternate_form && (q = strchr(s, '.')) == nullptr) s[s_len++] = '.'; break; case 'c': char_buf[0] = (char) (va_arg(ap, int)); s = &char_buf[0]; s_len = 1; pad_char = ' '; break; case '%': char_buf[0] = '%'; s = &char_buf[0]; s_len = 1; pad_char = ' '; break; case 'n': *(va_arg(ap, int *)) = outpos; goto skip_output; /* * Always extract the argument as a ""char *"" pointer. We * should be using ""void *"" but there are still machines * that don't understand it. * If the pointer size is equal to the size of an unsigned * integer we convert the pointer to a hex number, otherwise * we print ""%p"" to indicate that we don't handle ""%p"". */ case 'p': if (sizeof(char *) <= sizeof(u_wide_int)) { ui_num = (u_wide_int)((size_t) va_arg(ap, char *)); s = ap_php_conv_p2(ui_num, 4, 'x', &num_buf[NUM_BUF_SIZE], &s_len); if (ui_num != 0) { *--s = 'x'; *--s = '0'; s_len += 2; } } else { s = const_cast(""%p""); s_len = 2; } pad_char = ' '; break; case NUL: /* * The last character of the format string was %. * We ignore it. */ continue; fmt_error: throw Exception(""Illegal length modifier specified '%c'"", *fmt); /* * The default case is for unrecognized %'s. * We print % to help the user identify what * option is not understood. * This is also useful in case the user wants to pass * the output of format_converter to another function * that understands some other % (like syslog). * Note that we can't point s inside fmt because the * unknown could be preceded by width etc. */ default: char_buf[0] = '%'; char_buf[1] = *fmt; s = char_buf; s_len = 2; pad_char = ' '; break; } if (prefix_char != NUL) { *--s = prefix_char; s_len++; } if (adjust_width && adjust == RIGHT && min_width > s_len) { if (pad_char == '0' && prefix_char != NUL) { appendchar(&result, &outpos, &size, *s); s++; s_len--; min_width--; } for (int i = 0; i < min_width - s_len; i++) { appendchar(&result, &outpos, &size, pad_char); } } /* * Print the (for now) non-null terminated string s. */ appendsimplestring(&result, &outpos, &size, s, s_len); if (adjust_width && adjust == LEFT && min_width > s_len) { for (int i = 0; i < min_width - s_len; i++) { appendchar(&result, &outpos, &size, pad_char); } } } skip_output: fmt++; } /* * Add the terminating null here since it wasn't added incrementally above * once the whole string has been composed. */ result[outpos] = NUL; *outbuf = result; return outpos; }",CWE-190,2 1,"void UncompressElementOp::Compute(OpKernelContext* ctx) { Tensor tensor = ctx->input(0); const Variant& variant = tensor.scalar()(); const CompressedElement* compressed = variant.get(); std::vector components; OP_REQUIRES_OK(ctx, UncompressElement(*compressed, &components)); OP_REQUIRES(ctx, components.size() == output_types_.size(), errors::FailedPrecondition(""Expected "", output_types_.size(), "" outputs from uncompress, but got "", components.size())); for (int i = 0; i < components.size(); ++i) { OP_REQUIRES( ctx, components[i].dtype() == output_types_[i], errors::FailedPrecondition(""Expected a tensor of type "", DataTypeString(output_types_[i]), "" but got a tensor of type "", DataTypeString(components[i].dtype()))); ctx->set_output(i, components[i]); } }",CWE-476,12 0,"scoped_refptr AudioManagerBase::GetMessageLoop() { base::AutoLock lock(audio_thread_lock_); return audio_thread_.get() ? audio_thread_->message_loop_proxy() : NULL; } ",none,24 1,"int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len) { buffer_verify(buffer); if (data == NULL) { return -1; } if (buffer->used + len < len) { return -1; } if (buffer->allocated < (buffer->used + len)) { if(buffer->pos > 0) buffer_shift(buffer); if (realloc_buffer(buffer, buffer->used + len) < 0) { return -1; } } memcpy(buffer->data+buffer->used, data, len); buffer->used+=len; buffer_verify(buffer); return 0; }",CWE-476,12 1,"void dmar_free_irte(const struct intr_source *intr_src, uint16_t index) { struct dmar_drhd_rt *dmar_unit; union dmar_ir_entry *ir_table, *ir_entry; union pci_bdf sid; if (intr_src->is_msi) { dmar_unit = device_to_dmaru((uint8_t)intr_src->src.msi.bits.b, intr_src->src.msi.fields.devfun); } else { dmar_unit = ioapic_to_dmaru(intr_src->src.ioapic_id, &sid); } if (is_dmar_unit_valid(dmar_unit, sid)) { ir_table = (union dmar_ir_entry *)hpa2hva(dmar_unit->ir_table_addr); ir_entry = ir_table + index; ir_entry->bits.remap.present = 0x0UL; iommu_flush_cache(ir_entry, sizeof(union dmar_ir_entry)); dmar_invalid_iec(dmar_unit, index, 0U, false); if (!is_irte_reserved(dmar_unit, index)) { spinlock_obtain(&dmar_unit->lock); bitmap_clear_nolock(index & 0x3FU, &dmar_unit->irte_alloc_bitmap[index >> 6U]); spinlock_release(&dmar_unit->lock); } } }",CWE-787,16 1,"static MagickBooleanType TIFFGetProfiles(TIFF *tiff,Image *image, ExceptionInfo *exception) { MagickBooleanType status; uint32 length = 0; unsigned char *profile = (unsigned char *) NULL; status=MagickTrue; #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) status=ReadProfile(image,""icc"",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) status=ReadProfile(image,""8bim"",profile,(ssize_t) length,exception); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); status=ReadProfile(image,""iptc"",profile,4L*length,exception); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { StringInfo *dng; status=ReadProfile(image,""xmp"",profile,(ssize_t) length,exception); dng=BlobToStringInfo(profile,length); if (dng != (StringInfo *) NULL) { const char *target = ""dc:format=\""image/dng\""""; if (strstr((char *) GetStringInfoDatum(dng),target) != (char *) NULL) (void) CopyMagickString(image->magick,""DNG"",MagickPathExtent); dng=DestroyStringInfo(dng); } } #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) status=ReadProfile(image,""tiff:34118"",profile,(ssize_t) length, exception); if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) status=ReadProfile(image,""tiff:37724"",profile,(ssize_t) length,exception); return(status); }",CWE-125,1 1,"static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; LOG_FUNC_CALLED(ctx); sc_log(ctx, ""TCOS3:%d PKCS1:%d\n"",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, ""APDU transmit failed""); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) { offset=2; while(offsetctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); }",CWE-787,16 0,"void VideoRendererBase::Pause(const base::Closure& callback) { base::AutoLock auto_lock(lock_); DCHECK(state_ != kUninitialized || state_ == kError); state_ = kPaused; callback.Run(); } ",none,24 0," void Read(VideoDecoder::DecoderStatus* status, scoped_refptr* video_frame) { EXPECT_CALL(*this, FrameReady(_, _)) .WillOnce(DoAll(SaveArg<0>(status), SaveArg<1>(video_frame))); decoder_->Read(read_cb_); message_loop_.RunAllPending(); } ",none,24 0,"void RunOnIOThread(const base::Closure& closure) { base::RunLoop run_loop; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&RunAndQuit, closure, run_loop.QuitClosure(), base::MessageLoopProxy::current())); run_loop.Run(); } ",none,24 0,"void SpeechSynthesis::fireEvent(const AtomicString& type, SpeechSynthesisUtterance* utterance, unsigned long charIndex, const String& name) { if (!executionContext()->activeDOMObjectsAreStopped()) utterance->dispatchEvent(SpeechSynthesisEvent::create(type, charIndex, (currentTime() - utterance->startTime()), name)); } ",none,24 1,"static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir, struct buffer_head **bh,struct dx_frame *frame, struct dx_hash_info *hinfo) { unsigned blocksize = dir->i_sb->s_blocksize; unsigned count, continued; struct buffer_head *bh2; ext4_lblk_t newblock; u32 hash2; struct dx_map_entry *map; char *data1 = (*bh)->b_data, *data2; unsigned split, move, size; struct ext4_dir_entry_2 *de = NULL, *de2; int csum_size = 0; int err = 0, i; if (ext4_has_metadata_csum(dir->i_sb)) csum_size = sizeof(struct ext4_dir_entry_tail); bh2 = ext4_append(handle, dir, &newblock); if (IS_ERR(bh2)) { brelse(*bh); *bh = NULL; return (struct ext4_dir_entry_2 *) bh2; } BUFFER_TRACE(*bh, ""get_write_access""); err = ext4_journal_get_write_access(handle, *bh); if (err) goto journal_error; BUFFER_TRACE(frame->bh, ""get_write_access""); err = ext4_journal_get_write_access(handle, frame->bh); if (err) goto journal_error; data2 = bh2->b_data; /* create map in the end of data2 block */ map = (struct dx_map_entry *) (data2 + blocksize); count = dx_make_map(dir, (struct ext4_dir_entry_2 *) data1, blocksize, hinfo, map); map -= count; dx_sort_map(map, count); /* Split the existing block in the middle, size-wise */ size = 0; move = 0; for (i = count-1; i >= 0; i--) { /* is more than half of this entry in 2nd half of the block? */ if (size + map[i].size/2 > blocksize/2) break; size += map[i].size; move++; } /* map index at which we will split */ split = count - move; hash2 = map[split].hash; continued = hash2 == map[split - 1].hash; dxtrace(printk(KERN_INFO ""Split block %lu at %x, %i/%i\n"", (unsigned long)dx_get_block(frame->at), hash2, split, count-split)); /* Fancy dance to stay within two buffers */ de2 = dx_move_dirents(data1, data2, map + split, count - split, blocksize); de = dx_pack_dirents(data1, blocksize); de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) - (char *) de, blocksize); de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) - (char *) de2, blocksize); if (csum_size) { ext4_initialize_dirent_tail(*bh, blocksize); ext4_initialize_dirent_tail(bh2, blocksize); } dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data1, blocksize, 1)); dxtrace(dx_show_leaf(dir, hinfo, (struct ext4_dir_entry_2 *) data2, blocksize, 1)); /* Which block gets the new entry? */ if (hinfo->hash >= hash2) { swap(*bh, bh2); de = de2; } dx_insert_block(frame, hash2 + continued, newblock); err = ext4_handle_dirty_dirblock(handle, dir, bh2); if (err) goto journal_error; err = ext4_handle_dirty_dx_node(handle, dir, frame->bh); if (err) goto journal_error; brelse(bh2); dxtrace(dx_show_index(""frame"", frame->entries)); return de; journal_error: brelse(*bh); brelse(bh2); *bh = NULL; ext4_std_error(dir->i_sb, err); return ERR_PTR(err); }",CWE-125,1 1,"void get_cmdln_options(int argc, char *argv[]) { int o; #if CONFIG_FILE && HAVE_GETPWUID static struct passwd *pwd_entry; char *str; #endif #ifdef LONG_OPTIONS int option_index = 0; static struct option long_options[] = { {""timeout"", 1, 0, 't'}, #ifdef PROC_NET_DEV {""procfile"",1,0,'f'}, #endif #ifdef PROC_DISKSTATS {""diskstatsfile"",1,0,1000}, {""partitionsfile"",1,0,1001}, #endif #if NETSTAT && ALLOW_NETSTATPATH {""netstat"",1,0,'n'}, #endif #if IOSERVICE_IN {""longdisknames"",0,0,1002}, #endif {""input"",1,0,'i'}, {""dynamic"",1,0,'d'}, {""help"", 0, 0, 'h'}, {""version"",0,0,'V'}, {""allif"",1,0,'a'}, {""unit"",1,0,'u'}, {""ansiout"",0,0,'N'}, #if EXTENDED_STATS {""type"",1,0,'T'}, {""avglength"",1,0,'A'}, #endif {""interfaces"",1,0,'I'}, {""sumhidden"",1,0,'S'}, {""output"",1,0,'o'}, #ifdef CSV {""csvchar"",1,0,'C'}, {""csvfile"",1,0,'F'}, #endif {""count"",1,0,'c'}, {""daemon"",1,0,'D'}, #ifdef HTML {""htmlrefresh"",1,0,'R'}, {""htmlheader"",1,0,'H'}, #endif {0,0,0,0} }; #endif #ifdef CONFIG_FILE /* loop till first non option argument */ opterr=0; while (1) { #ifdef LONG_OPTIONS o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index); #else o=getopt (argc,argv,SHORT_OPTIONS); #endif if (o==-1) break; } opterr=1; if (optind < argc) { read_config(argv[optind]); } else { read_config(""/etc/bwm-ng.conf""); #ifdef HAVE_GETPWUID pwd_entry=getpwuid(getuid()); if (pwd_entry!=NULL) { str=(char*)malloc(strlen(pwd_entry->pw_dir)+14); snprintf(str,strlen(pwd_entry->pw_dir)+14,""%s/.bwm-ng.conf"",pwd_entry->pw_dir); read_config(str); free(str); } #endif } /* reset getopt again */ optind=1; #endif /* get command line arguments, kinda ugly, wanna rewrite it? */ while (1) { #ifdef LONG_OPTIONS o=getopt_long (argc,argv,SHORT_OPTIONS,long_options, &option_index); #else o=getopt (argc,argv,SHORT_OPTIONS); #endif if (o==-1) break; switch (o) { case '?': printf(""unknown option: %s\n"",argv[optind-1]); exit(EXIT_FAILURE); break; /* ugly workaround to handle optional arguments for all platforms */ case ':': if (!strcmp(argv[optind-1],""-a"") || !strcasecmp(argv[optind-1],""--allif"")) show_all_if=1; else if (!strcmp(argv[optind-1],""-d"") || !strcasecmp(argv[optind-1],""--dynamic"")) dynamic=1; else if (!strcmp(argv[optind-1],""-D"") || !strcasecmp(argv[optind-1],""--daemon"")) daemonize=1; #ifdef HTML else if (!strcmp(argv[optind-1],""-H"") || !strcasecmp(argv[optind-1],""--htmlheader"")) html_header=1; #endif else if (!strcmp(argv[optind-1],""-S"") || !strcasecmp(argv[optind-1],""--sumhidden"")) sumhidden=1; else { printf(""%s requires an argument!\n"",argv[optind-1]); exit(EXIT_FAILURE); } break; #ifdef PROC_DISKSTATS case 1000: if (strlen(optarg)0) { html_refresh=atol(optarg); } break; case 'H': if (optarg) html_header=atoi(optarg); break; #endif case 'c': if (optarg) output_count=atol(optarg); break; #if CSV || HTML case 'F': if (optarg) { if (out_file) fclose(out_file); out_file=fopen(optarg,""a""); if (!out_file) deinit(1, ""failed to open outfile\n""); if (out_file_path) free(out_file_path); out_file_path=(char *)strdup(optarg); } break; #endif #ifdef CSV case 'C': if (optarg) csv_char=optarg[0]; break; #endif case 'h': cmdln_printhelp(); break; #ifdef PROC_NET_DEV case 'f': if (optarg && (strlen(optarg)0) { delay=atol(optarg); } break; #if EXTENDED_STATS case 'T': output_type=str2output_type(optarg); break; case 'A': if (optarg) avg_length=atoi(optarg)*1000; break; #endif case 'd': if (optarg) dynamic=atoi(optarg); break; case 'u': output_unit=str2output_unit(optarg); break; #if NETSTAT && ALLOW_NETSTATPATH case 'n': if (optarg && (strlen(optarg)=avg_length) deinit(1, ""avglength needs to be a least twice the value of timeout\n""); #endif if ((output_unit==ERRORS_OUT && !net_input_method(input_method)) || (output_unit==PACKETS_OUT && input_method==LIBSTATDISK_IN)) output_unit=BYTES_OUT; return; }",CWE-476,12 0," void EmbeddedWorkerContextClient::OnSendMessageToWorker( int thread_id, int embedded_worker_id, int request_id, const IPC::Message& message) { if (!script_context_) return; DCHECK_EQ(embedded_worker_id_, embedded_worker_id); script_context_->OnMessageReceived(request_id, message); } ",none,24 0,"void* SoftwareFrameManager::GetCurrentFramePixels() const { DCHECK(HasCurrentFrame()); DCHECK(base::SharedMemory::IsHandleValid( current_frame_->shared_memory_->handle())); return current_frame_->shared_memory_->memory(); } ",none,24 1,"INLINE void gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h) { *x = rect->left; *y = rect->top; *w = rect->right - rect->left + 1; *h = rect->bottom - rect->top + 1; }",CWE-190,2 1,"static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter) { #ifndef PB_ENABLE_MALLOC UNUSED(wire_type); UNUSED(iter); PB_RETURN_ERROR(stream, ""no malloc support""); #else pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && *(void**)iter->pData != NULL) { /* Duplicate field, have to release the old allocation first. */ pb_release_single_field(iter); } if (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES) { return func(stream, iter->pos, iter->pData); } else { if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) return false; initialize_pointer_field(*(void**)iter->pData, iter); return func(stream, iter->pos, *(void**)iter->pData); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; size_t *size = (size_t*)iter->pSize; size_t allocated_size = *size; void *pItem; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if (*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size); initialize_pointer_field(pItem, iter); if (!func(&substream, iter->pos, pItem)) { status = false; break; } (*size)++; } pb_close_string_substream(stream, &substream); return status; } else { /* Normal repeated field, i.e. only one item at a time. */ size_t *size = (size_t*)iter->pSize; void *pItem; (*size)++; if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size)) return false; pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1); initialize_pointer_field(pItem, iter); return func(stream, iter->pos, pItem); } default: PB_RETURN_ERROR(stream, ""invalid field type""); } #endif }",CWE-125,1 0,"void AudioManagerBase::ReleaseOutputStream(AudioOutputStream* stream) { DCHECK(stream); num_output_streams_--; delete stream; } ",none,24 1,"static int decode_attr_security_label(struct xdr_stream *xdr, uint32_t *bitmap, struct nfs4_label *label) { uint32_t pi = 0; uint32_t lfs = 0; __u32 len; __be32 *p; int status = 0; if (unlikely(bitmap[2] & (FATTR4_WORD2_SECURITY_LABEL - 1U))) return -EIO; if (likely(bitmap[2] & FATTR4_WORD2_SECURITY_LABEL)) { p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) return -EIO; lfs = be32_to_cpup(p++); p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) return -EIO; pi = be32_to_cpup(p++); p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) return -EIO; len = be32_to_cpup(p++); p = xdr_inline_decode(xdr, len); if (unlikely(!p)) return -EIO; if (len < NFS4_MAXLABELLEN) { if (label) { memcpy(label->label, p, len); label->len = len; label->pi = pi; label->lfs = lfs; status = NFS_ATTR_FATTR_V4_SECURITY_LABEL; } bitmap[2] &= ~FATTR4_WORD2_SECURITY_LABEL; } else printk(KERN_WARNING ""%s: label too long (%u)!\n"", __func__, len); } if (label && label->label) dprintk(""%s: label=%s, len=%d, PI=%d, LFS=%d\n"", __func__, (char *)label->label, label->len, label->pi, label->lfs); return status; }",CWE-787,16 1,"void CLua::init_libraries() { lua_stack_cleaner clean(state()); // Open Crawl bindings cluaopen_kills(_state); cluaopen_you(_state); cluaopen_item(_state); cluaopen_food(_state); cluaopen_crawl(_state); cluaopen_file(_state); cluaopen_moninf(_state); cluaopen_options(_state); cluaopen_travel(_state); cluaopen_view(_state); cluaopen_spells(_state); cluaopen_globals(_state); execfile(""dlua/macro.lua"", true, true); // All hook names must be chk_???? execstring(""chk_startgame = { }"", ""base""); lua_register(_state, ""loadfile"", _clua_loadfile); lua_register(_state, ""dofile"", _clua_dofile); lua_register(_state, ""crawl_require"", _clua_require); execfile(""dlua/util.lua"", true, true); execfile(""dlua/iter.lua"", true, true); execfile(""dlua/tags.lua"", true, true); execfile(""dlua/init.lua"", true, true); if (managed_vm) { lua_register(_state, ""pcall"", _clua_guarded_pcall); execfile(""dlua/userbase.lua"", true, true); execfile(""dlua/persist.lua"", true, true); } }",CWE-434,11 0,"DataObjectItem* DataObjectItem::CreateFromSharedBuffer( scoped_refptr buffer, const KURL& source_url, const String& filename_extension, const AtomicString& content_disposition) { DataObjectItem* item = MakeGarbageCollected( kFileKind, MIMETypeRegistry::GetWellKnownMIMETypeForExtension(filename_extension)); item->shared_buffer_ = std::move(buffer); item->filename_extension_ = filename_extension; item->title_ = content_disposition; item->base_url_ = source_url; return item; } ",none,24 0,"void VideoRendererBase::Play(const base::Closure& callback) { base::AutoLock auto_lock(lock_); DCHECK_EQ(kPrerolled, state_); state_ = kPlaying; callback.Run(); } ",none,24 1,"xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) { const xmlChar *cur = input; xmlChar *buffer = NULL; xmlChar *out = NULL; size_t buffer_size = 0; int html = 0; if (input == NULL) return(NULL); if (doc != NULL) html = (doc->type == XML_HTML_DOCUMENT_NODE); /* * allocate an translation buffer. */ buffer_size = 1000; buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar)); if (buffer == NULL) { xmlEntitiesErrMemory(""xmlEncodeEntities: malloc failed""); return(NULL); } out = buffer; while (*cur != '\0') { size_t indx = out - buffer; if (indx + 100 > buffer_size) { growBufferReentrant(); out = &buffer[indx]; } /* * By default one have to encode at least '<', '>', '""' and '&' ! */ if (*cur == '<') { const xmlChar *end; /* * Special handling of server side include in HTML attributes */ if (html && attr && (cur[1] == '!') && (cur[2] == '-') && (cur[3] == '-') && ((end = xmlStrstr(cur, BAD_CAST ""-->"")) != NULL)) { while (cur != end) { *out++ = *cur++; indx = out - buffer; if (indx + 100 > buffer_size) { growBufferReentrant(); out = &buffer[indx]; } } *out++ = *cur++; *out++ = *cur++; *out++ = *cur++; continue; } *out++ = '&'; *out++ = 'l'; *out++ = 't'; *out++ = ';'; } else if (*cur == '>') { *out++ = '&'; *out++ = 'g'; *out++ = 't'; *out++ = ';'; } else if (*cur == '&') { /* * Special handling of &{...} construct from HTML 4, see * http://www.w3.org/TR/html401/appendix/notes.html#h-B.7.1 */ if (html && attr && (cur[1] == '{') && (strchr((const char *) cur, '}'))) { while (*cur != '}') { *out++ = *cur++; indx = out - buffer; if (indx + 100 > buffer_size) { growBufferReentrant(); out = &buffer[indx]; } } *out++ = *cur++; continue; } *out++ = '&'; *out++ = 'a'; *out++ = 'm'; *out++ = 'p'; *out++ = ';'; } else if (((*cur >= 0x20) && (*cur < 0x80)) || (*cur == '\n') || (*cur == '\t') || ((html) && (*cur == '\r'))) { /* * default case, just copy ! */ *out++ = *cur; } else if (*cur >= 0x80) { if (((doc != NULL) && (doc->encoding != NULL)) || (html)) { /* * Bjørn Reese provided the patch xmlChar xc; xc = (*cur & 0x3F) << 6; if (cur[1] != 0) { xc += *(++cur) & 0x3F; *out++ = xc; } else */ *out++ = *cur; } else { /* * We assume we have UTF-8 input. */ char buf[11], *ptr; int val = 0, l = 1; if (*cur < 0xC0) { xmlEntitiesErr(XML_CHECK_NOT_UTF8, ""xmlEncodeEntities: input not UTF-8""); if (doc != NULL) doc->encoding = xmlStrdup(BAD_CAST ""ISO-8859-1""); snprintf(buf, sizeof(buf), ""&#%d;"", *cur); buf[sizeof(buf) - 1] = 0; ptr = buf; while (*ptr != 0) *out++ = *ptr++; cur++; continue; } else if (*cur < 0xE0) { val = (cur[0]) & 0x1F; val <<= 6; val |= (cur[1]) & 0x3F; l = 2; } else if (*cur < 0xF0) { val = (cur[0]) & 0x0F; val <<= 6; val |= (cur[1]) & 0x3F; val <<= 6; val |= (cur[2]) & 0x3F; l = 3; } else if (*cur < 0xF8) { val = (cur[0]) & 0x07; val <<= 6; val |= (cur[1]) & 0x3F; val <<= 6; val |= (cur[2]) & 0x3F; val <<= 6; val |= (cur[3]) & 0x3F; l = 4; } if ((l == 1) || (!IS_CHAR(val))) { xmlEntitiesErr(XML_ERR_INVALID_CHAR, ""xmlEncodeEntities: char out of range\n""); if (doc != NULL) doc->encoding = xmlStrdup(BAD_CAST ""ISO-8859-1""); snprintf(buf, sizeof(buf), ""&#%d;"", *cur); buf[sizeof(buf) - 1] = 0; ptr = buf; while (*ptr != 0) *out++ = *ptr++; cur++; continue; } /* * We could do multiple things here. Just save as a char ref */ snprintf(buf, sizeof(buf), ""&#x%X;"", val); buf[sizeof(buf) - 1] = 0; ptr = buf; while (*ptr != 0) *out++ = *ptr++; cur += l; continue; } } else if (IS_BYTE_CHAR(*cur)) { char buf[11], *ptr; snprintf(buf, sizeof(buf), ""&#%d;"", *cur); buf[sizeof(buf) - 1] = 0; ptr = buf; while (*ptr != 0) *out++ = *ptr++; } cur++; } *out = 0; return(buffer); mem_error: xmlEntitiesErrMemory(""xmlEncodeEntities: realloc failed""); xmlFree(buffer); return(NULL); }",CWE-787,16 1,"ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8* ptr; int framesize; int c, chunks, advance; int l, lines; int i, j, x = 0, y, ymax; /* If not even the chunk size is present, we'd better leave */ if (bytes < 4) return 0; /* We don't decode anything unless we have a full chunk in the input buffer (on the other hand, the Python part of the driver makes sure this is always the case) */ ptr = buf; framesize = I32(ptr); if (framesize < I32(ptr)) return 0; /* Make sure this is a frame chunk. The Python driver takes case of other chunk types. */ if (I16(ptr+4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } chunks = I16(ptr+6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { UINT8* data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; switch (I16(ptr+4)) { case 4: case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ lines = I16(data); data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { UINT8* buf = (UINT8*) im->image[y]; int p, packets; packets = I16(data); data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { y += 65536 - packets; /* skip lines */ if (y >= state->ysize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } buf = (UINT8*) im->image[y]; } else { /* store last byte (used if line width is odd) */ buf[state->xsize-1] = (UINT8) packets; } packets = I16(data); data += 2; } for (p = x = 0; p < packets; p++) { x += data[0]; /* pixel skip */ if (data[1] >= 128) { i = 256-data[1]; /* run */ if (x + i + i > state->xsize) break; for (j = 0; j < i; j++) { buf[x++] = data[2]; buf[x++] = data[3]; } data += 2 + 2; } else { i = 2 * (int) data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(buf + x, data + 2, i); data += 2 + i; x += i; } } if (p < packets) break; /* didn't process all packets */ } if (l < lines) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 12: /* FLI LC chunk (byte delta) */ y = I16(data); ymax = y + I16(data+2); data += 4; for (; y < ymax && y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { x += data[0]; /* skip pixels */ if (data[1] & 0x80) { i = 256-data[1]; /* run */ if (x + i > state->xsize) break; memset(out + x, data[2], i); data += 3; } else { i = data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(out + x, data + 2, i); data += i + 2; } } if (p < packets) break; /* didn't process all packets */ } if (y < ymax) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 13: /* FLI BLACK chunk */ for (y = 0; y < state->ysize; y++) memset(im->image[y], 0, state->xsize); break; case 15: /* FLI BRUN chunk */ for (y = 0; y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { if (data[0] & 0x80) { i = 256 - data[0]; if (x + i > state->xsize) break; /* safety first */ memcpy(out + x, data + 1, i); data += i + 1; } else { i = data[0]; if (x + i > state->xsize) break; /* safety first */ memset(out + x, data[1], i); data += 2; } } if (x != state->xsize) { /* didn't unpack whole line */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } } break; case 16: /* COPY chunk */ for (y = 0; y < state->ysize; y++) { UINT8* buf = (UINT8*) im->image[y]; memcpy(buf, data, state->xsize); data += state->xsize; } break; case 18: /* PSTAMP chunk */ break; /* ignored */ default: /* unknown chunk */ /* printf(""unknown FLI/FLC chunk: %d\n"", I16(ptr+4)); */ state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } advance = I32(ptr); ptr += advance; bytes -= advance; } return -1; /* end of frame */ }",CWE-787,16 0,"void BlobURLRequestJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_.get()) *info = *response_info_; } ",none,24 0,"void AudioManagerBase::GetAudioInputDeviceNames( media::AudioDeviceNames* device_names) { } ",none,24 1,"void stralgoLCS(client *c) { uint32_t i, j; long long minmatchlen = 0; sds a = NULL, b = NULL; int getlen = 0, getidx = 0, withmatchlen = 0; robj *obja = NULL, *objb = NULL; for (j = 2; j < (uint32_t)c->argc; j++) { char *opt = c->argv[j]->ptr; int moreargs = (c->argc-1) - j; if (!strcasecmp(opt,""IDX"")) { getidx = 1; } else if (!strcasecmp(opt,""LEN"")) { getlen = 1; } else if (!strcasecmp(opt,""WITHMATCHLEN"")) { withmatchlen = 1; } else if (!strcasecmp(opt,""MINMATCHLEN"") && moreargs) { if (getLongLongFromObjectOrReply(c,c->argv[j+1],&minmatchlen,NULL) != C_OK) goto cleanup; if (minmatchlen < 0) minmatchlen = 0; j++; } else if (!strcasecmp(opt,""STRINGS"") && moreargs > 1) { if (a != NULL) { addReplyError(c,""Either use STRINGS or KEYS""); goto cleanup; } a = c->argv[j+1]->ptr; b = c->argv[j+2]->ptr; j += 2; } else if (!strcasecmp(opt,""KEYS"") && moreargs > 1) { if (a != NULL) { addReplyError(c,""Either use STRINGS or KEYS""); goto cleanup; } obja = lookupKeyRead(c->db,c->argv[j+1]); objb = lookupKeyRead(c->db,c->argv[j+2]); if ((obja && obja->type != OBJ_STRING) || (objb && objb->type != OBJ_STRING)) { addReplyError(c, ""The specified keys must contain string values""); /* Don't cleanup the objects, we need to do that * only after calling getDecodedObject(). */ obja = NULL; objb = NULL; goto cleanup; } obja = obja ? getDecodedObject(obja) : createStringObject("""",0); objb = objb ? getDecodedObject(objb) : createStringObject("""",0); a = obja->ptr; b = objb->ptr; j += 2; } else { addReplyErrorObject(c,shared.syntaxerr); goto cleanup; } } /* Complain if the user passed ambiguous parameters. */ if (a == NULL) { addReplyError(c,""Please specify two strings: "" ""STRINGS or KEYS options are mandatory""); goto cleanup; } else if (getlen && getidx) { addReplyError(c, ""If you want both the length and indexes, please "" ""just use IDX.""); goto cleanup; } /* Compute the LCS using the vanilla dynamic programming technique of * building a table of LCS(x,y) substrings. */ uint32_t alen = sdslen(a); uint32_t blen = sdslen(b); /* Setup an uint32_t array to store at LCS[i,j] the length of the * LCS A0..i-1, B0..j-1. Note that we have a linear array here, so * we index it as LCS[j+(blen+1)*j] */ uint32_t *lcs = zmalloc((alen+1)*(blen+1)*sizeof(uint32_t)); #define LCS(A,B) lcs[(B)+((A)*(blen+1))] /* Start building the LCS table. */ for (uint32_t i = 0; i <= alen; i++) { for (uint32_t j = 0; j <= blen; j++) { if (i == 0 || j == 0) { /* If one substring has length of zero, the * LCS length is zero. */ LCS(i,j) = 0; } else if (a[i-1] == b[j-1]) { /* The len LCS (and the LCS itself) of two * sequences with the same final character, is the * LCS of the two sequences without the last char * plus that last char. */ LCS(i,j) = LCS(i-1,j-1)+1; } else { /* If the last character is different, take the longest * between the LCS of the first string and the second * minus the last char, and the reverse. */ uint32_t lcs1 = LCS(i-1,j); uint32_t lcs2 = LCS(i,j-1); LCS(i,j) = lcs1 > lcs2 ? lcs1 : lcs2; } } } /* Store the actual LCS string in ""result"" if needed. We create * it backward, but the length is already known, we store it into idx. */ uint32_t idx = LCS(alen,blen); sds result = NULL; /* Resulting LCS string. */ void *arraylenptr = NULL; /* Deffered length of the array for IDX. */ uint32_t arange_start = alen, /* alen signals that values are not set. */ arange_end = 0, brange_start = 0, brange_end = 0; /* Do we need to compute the actual LCS string? Allocate it in that case. */ int computelcs = getidx || !getlen; if (computelcs) result = sdsnewlen(SDS_NOINIT,idx); /* Start with a deferred array if we have to emit the ranges. */ uint32_t arraylen = 0; /* Number of ranges emitted in the array. */ if (getidx) { addReplyMapLen(c,2); addReplyBulkCString(c,""matches""); arraylenptr = addReplyDeferredLen(c); } i = alen, j = blen; while (computelcs && i > 0 && j > 0) { int emit_range = 0; if (a[i-1] == b[j-1]) { /* If there is a match, store the character and reduce * the indexes to look for a new match. */ result[idx-1] = a[i-1]; /* Track the current range. */ if (arange_start == alen) { arange_start = i-1; arange_end = i-1; brange_start = j-1; brange_end = j-1; } else { /* Let's see if we can extend the range backward since * it is contiguous. */ if (arange_start == i && brange_start == j) { arange_start--; brange_start--; } else { emit_range = 1; } } /* Emit the range if we matched with the first byte of * one of the two strings. We'll exit the loop ASAP. */ if (arange_start == 0 || brange_start == 0) emit_range = 1; idx--; i--; j--; } else { /* Otherwise reduce i and j depending on the largest * LCS between, to understand what direction we need to go. */ uint32_t lcs1 = LCS(i-1,j); uint32_t lcs2 = LCS(i,j-1); if (lcs1 > lcs2) i--; else j--; if (arange_start != alen) emit_range = 1; } /* Emit the current range if needed. */ uint32_t match_len = arange_end - arange_start + 1; if (emit_range) { if (minmatchlen == 0 || match_len >= minmatchlen) { if (arraylenptr) { addReplyArrayLen(c,2+withmatchlen); addReplyArrayLen(c,2); addReplyLongLong(c,arange_start); addReplyLongLong(c,arange_end); addReplyArrayLen(c,2); addReplyLongLong(c,brange_start); addReplyLongLong(c,brange_end); if (withmatchlen) addReplyLongLong(c,match_len); arraylen++; } } arange_start = alen; /* Restart at the next match. */ } } /* Signal modified key, increment dirty, ... */ /* Reply depending on the given options. */ if (arraylenptr) { addReplyBulkCString(c,""len""); addReplyLongLong(c,LCS(alen,blen)); setDeferredArrayLen(c,arraylenptr,arraylen); } else if (getlen) { addReplyLongLong(c,LCS(alen,blen)); } else { addReplyBulkSds(c,result); result = NULL; } /* Cleanup. */ sdsfree(result); zfree(lcs); cleanup: if (obja) decrRefCount(obja); if (objb) decrRefCount(objb); return; }",CWE-190,2 1,"ansicstr (string, len, flags, sawc, rlen) char *string; int len, flags, *sawc, *rlen; { int c, temp; char *ret, *r, *s; unsigned long v; if (string == 0 || *string == '\0') return ((char *)NULL); #if defined (HANDLE_MULTIBYTE) if (strstr (string, ""\\U"") != 0) ret = (char *)xmalloc (6*len + 1); else ret = (char *)xmalloc (4*len + 1); #else ret = (char *)xmalloc (2*len + 1); /* 2*len for possible CTLESC */ #endif for (r = ret, s = string; s && *s; ) { c = *s++; if (c != '\\' || *s == '\0') *r++ = c; else { switch (c = *s++) { #if defined (__STDC__) case 'a': c = '\a'; break; case 'v': c = '\v'; break; #else case 'a': c = (int) 0x07; break; case 'v': c = (int) 0x0B; break; #endif case 'b': c = '\b'; break; case 'e': case 'E': /* ESC -- non-ANSI */ c = ESC; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': #if 1 if (flags & 1) { *r++ = '\\'; break; } /*FALLTHROUGH*/ #endif case '0': /* If (FLAGS & 1), we're translating a string for echo -e (or the equivalent xpg_echo option), so we obey the SUSv3/ POSIX-2001 requirement and accept 0-3 octal digits after a leading `0'. */ temp = 2 + ((flags & 1) && (c == '0')); for (c -= '0'; ISOCTAL (*s) && temp--; s++) c = (c * 8) + OCTVALUE (*s); c &= 0xFF; break; case 'x': /* Hex digit -- non-ANSI */ if ((flags & 2) && *s == '{') { flags |= 16; /* internal flag value */ s++; } /* Consume at least two hex characters */ for (temp = 2, c = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++) c = (c * 16) + HEXVALUE (*s); /* DGK says that after a `\x{' ksh93 consumes ISXDIGIT chars until a non-xdigit or `}', so potentially more than two chars are consumed. */ if (flags & 16) { for ( ; ISXDIGIT ((unsigned char)*s); s++) c = (c * 16) + HEXVALUE (*s); flags &= ~16; if (*s == '}') s++; } /* \x followed by non-hex digits is passed through unchanged */ else if (temp == 2) { *r++ = '\\'; c = 'x'; } c &= 0xFF; break; #if defined (HANDLE_MULTIBYTE) case 'u': case 'U': temp = (c == 'u') ? 4 : 8; /* \uNNNN \UNNNNNNNN */ for (v = 0; ISXDIGIT ((unsigned char)*s) && temp--; s++) v = (v * 16) + HEXVALUE (*s); if (temp == ((c == 'u') ? 4 : 8)) { *r++ = '\\'; /* c remains unchanged */ break; } else if (v <= 0x7f) /* <= 0x7f translates directly */ { c = v; break; } else { temp = u32cconv (v, r); r += temp; continue; } #endif case '\\': break; case '\'': case '""': case '?': if (flags & 1) *r++ = '\\'; break; case 'c': if (sawc) { *sawc = 1; *r = '\0'; if (rlen) *rlen = r - ret; return ret; } else if ((flags & 1) == 0 && *s == 0) ; /* pass \c through */ else if ((flags & 1) == 0 && (c = *s)) { s++; if ((flags & 2) && c == '\\' && c == *s) s++; /* Posix requires $'\c\\' do backslash escaping */ c = TOCTRL(c); break; } /*FALLTHROUGH*/ default: if ((flags & 4) == 0) *r++ = '\\'; break; } if ((flags & 2) && (c == CTLESC || c == CTLNUL)) *r++ = CTLESC; *r++ = c; } } *r = '\0'; if (rlen) *rlen = r - ret; return ret; }",CWE-119,0 1," void Compute(OpKernelContext* context) override { const auto& input = context->input(0); auto flat_in = input.flat(); int fixed_length; const auto& length_input = context->input(1); OP_REQUIRES(context, TensorShapeUtils::IsScalar(length_input.shape()), errors::InvalidArgument(""k must be scalar, got shape "", length_input.shape().DebugString())); fixed_length = length_input.scalar()(); OP_REQUIRES( context, fixed_length % sizeof(T) == 0, errors::InvalidArgument( ""fixed_length ("", fixed_length, "") must be a multiple of the size of out_type ("", sizeof(T), "")"")); OP_REQUIRES(context, fixed_length > 0, errors::InvalidArgument(""fixed_length ("", fixed_length, "") must be greater than zero."")); int width = fixed_length / sizeof(T); TensorShape out_shape = input.shape(); out_shape.AddDim(width); Tensor* output_tensor = nullptr; OP_REQUIRES_OK( context, context->allocate_output(""output"", out_shape, &output_tensor)); if (flat_in.size() == 0) { // Empty input return; } auto out = output_tensor->flat_inner_dims(); T* out_data = out.data(); // Forcibly clear memory - we're going to copy variable length strings in, // and need to ensure that if we don't write to byte N when we copy, that // we're not getting random data. memset(out_data, 0, fixed_length * flat_in.size()); // If the data is already in the host's byte order, or if the width of the // output type is a single byte (meaning the ordering doesn't matter), we // can copy the memory directly. if (!convert_data_endianness_ || sizeof(T) == 1) { for (int64 i = 0; i < flat_in.size(); ++i) { const T* in_data = reinterpret_cast(flat_in(i).data()); if (flat_in(i).size() > fixed_length) { memcpy(out_data, in_data, fixed_length); } else { memcpy(out_data, in_data, flat_in(i).size()); } out_data += fixed_length; } } else { // Otherwise, the data is not in the host's byte order, and rather than a // direct copy, we need to reverse the byte ordering of each element. for (int64 i = 0; i < flat_in.size(); ++i) { const char* in_data_bytes = reinterpret_cast(flat_in(i).data()); char* out_data_bytes = reinterpret_cast(out_data); const char* p_in = in_data_bytes; char* p_out = out_data_bytes; for (; p_in < in_data_bytes + fixed_length; p_in += sizeof(T), p_out += sizeof(T)) { std::reverse_copy(p_in, p_in + sizeof(T), p_out); } out_data += fixed_length; } } }",CWE-787,16 1,"static BOOL clear_decompress_subcode_rlex(wStream* s, UINT32 bitmapDataByteCount, UINT32 width, UINT32 height, BYTE* pDstData, UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDstRel, UINT32 nYDstRel, UINT32 nDstWidth, UINT32 nDstHeight) { UINT32 x = 0, y = 0; UINT32 i; UINT32 pixelCount; UINT32 bitmapDataOffset; UINT32 pixelIndex; UINT32 numBits; BYTE startIndex; BYTE stopIndex; BYTE suiteIndex; BYTE suiteDepth; BYTE paletteCount; UINT32 palette[128] = { 0 }; if (Stream_GetRemainingLength(s) < bitmapDataByteCount) { WLog_ERR(TAG, ""stream short %"" PRIuz "" [%"" PRIu32 "" expected]"", Stream_GetRemainingLength(s), bitmapDataByteCount); return FALSE; } Stream_Read_UINT8(s, paletteCount); bitmapDataOffset = 1 + (paletteCount * 3); if ((paletteCount > 127) || (paletteCount < 1)) { WLog_ERR(TAG, ""paletteCount %"" PRIu8 """", paletteCount); return FALSE; } for (i = 0; i < paletteCount; i++) { BYTE r, g, b; Stream_Read_UINT8(s, b); Stream_Read_UINT8(s, g); Stream_Read_UINT8(s, r); palette[i] = FreeRDPGetColor(DstFormat, r, g, b, 0xFF); } pixelIndex = 0; pixelCount = width * height; numBits = CLEAR_LOG2_FLOOR[paletteCount - 1] + 1; while (bitmapDataOffset < bitmapDataByteCount) { UINT32 tmp; UINT32 color; UINT32 runLengthFactor; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, ""stream short %"" PRIuz "" [2 expected]"", Stream_GetRemainingLength(s)); return FALSE; } Stream_Read_UINT8(s, tmp); Stream_Read_UINT8(s, runLengthFactor); bitmapDataOffset += 2; suiteDepth = (tmp >> numBits) & CLEAR_8BIT_MASKS[(8 - numBits)]; stopIndex = tmp & CLEAR_8BIT_MASKS[numBits]; startIndex = stopIndex - suiteDepth; if (runLengthFactor >= 0xFF) { if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, ""stream short %"" PRIuz "" [2 expected]"", Stream_GetRemainingLength(s)); return FALSE; } Stream_Read_UINT16(s, runLengthFactor); bitmapDataOffset += 2; if (runLengthFactor >= 0xFFFF) { if (Stream_GetRemainingLength(s) < 4) { WLog_ERR(TAG, ""stream short %"" PRIuz "" [4 expected]"", Stream_GetRemainingLength(s)); return FALSE; } Stream_Read_UINT32(s, runLengthFactor); bitmapDataOffset += 4; } } if (startIndex >= paletteCount) { WLog_ERR(TAG, ""startIndex %"" PRIu8 "" > paletteCount %"" PRIu8 ""]"", startIndex, paletteCount); return FALSE; } if (stopIndex >= paletteCount) { WLog_ERR(TAG, ""stopIndex %"" PRIu8 "" > paletteCount %"" PRIu8 ""]"", stopIndex, paletteCount); return FALSE; } suiteIndex = startIndex; if (suiteIndex > 127) { WLog_ERR(TAG, ""suiteIndex %"" PRIu8 "" > 127]"", suiteIndex); return FALSE; } color = palette[suiteIndex]; if ((pixelIndex + runLengthFactor) > pixelCount) { WLog_ERR(TAG, ""pixelIndex %"" PRIu32 "" + runLengthFactor %"" PRIu32 "" > pixelCount %"" PRIu32 """", pixelIndex, runLengthFactor, pixelCount); return FALSE; } for (i = 0; i < runLengthFactor; i++) { BYTE* pTmpData = &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep]; if ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight)) WriteColor(pTmpData, DstFormat, color); if (++x >= width) { y++; x = 0; } } pixelIndex += runLengthFactor; if ((pixelIndex + (suiteDepth + 1)) > pixelCount) { WLog_ERR(TAG, ""pixelIndex %"" PRIu32 "" + suiteDepth %"" PRIu8 "" + 1 > pixelCount %"" PRIu32 """", pixelIndex, suiteDepth, pixelCount); return FALSE; } for (i = 0; i <= suiteDepth; i++) { BYTE* pTmpData = &pDstData[(nXDstRel + x) * GetBytesPerPixel(DstFormat) + (nYDstRel + y) * nDstStep]; UINT32 color = palette[suiteIndex]; if (suiteIndex > 127) { WLog_ERR(TAG, ""suiteIndex %"" PRIu8 "" > 127"", suiteIndex); return FALSE; } suiteIndex++; if ((nXDstRel + x < nDstWidth) && (nYDstRel + y < nDstHeight)) WriteColor(pTmpData, DstFormat, color); if (++x >= width) { y++; x = 0; } } pixelIndex += (suiteDepth + 1); } if (pixelIndex != pixelCount) { WLog_ERR(TAG, ""pixelIndex %"" PRIu32 "" != pixelCount %"" PRIu32 """", pixelIndex, pixelCount); return FALSE; } return TRUE; }",CWE-125,1 1,"static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, int oldproglen, struct jit_context *ctx, bool jmp_padding) { bool tail_call_reachable = bpf_prog->aux->tail_call_reachable; struct bpf_insn *insn = bpf_prog->insnsi; bool callee_regs_used[4] = {}; int insn_cnt = bpf_prog->len; bool tail_call_seen = false; bool seen_exit = false; u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY]; int i, cnt = 0, excnt = 0; int ilen, proglen = 0; u8 *prog = temp; int err; detect_reg_usage(insn, insn_cnt, callee_regs_used, &tail_call_seen); /* tail call's presence in current prog implies it is reachable */ tail_call_reachable |= tail_call_seen; emit_prologue(&prog, bpf_prog->aux->stack_depth, bpf_prog_was_classic(bpf_prog), tail_call_reachable, bpf_prog->aux->func_idx != 0); push_callee_regs(&prog, callee_regs_used); ilen = prog - temp; if (image) memcpy(image + proglen, temp, ilen); proglen += ilen; addrs[0] = proglen; prog = temp; for (i = 1; i <= insn_cnt; i++, insn++) { const s32 imm32 = insn->imm; u32 dst_reg = insn->dst_reg; u32 src_reg = insn->src_reg; u8 b2 = 0, b3 = 0; u8 *start_of_ldx; s64 jmp_offset; u8 jmp_cond; u8 *func; int nops; switch (insn->code) { /* ALU */ case BPF_ALU | BPF_ADD | BPF_X: case BPF_ALU | BPF_SUB | BPF_X: case BPF_ALU | BPF_AND | BPF_X: case BPF_ALU | BPF_OR | BPF_X: case BPF_ALU | BPF_XOR | BPF_X: case BPF_ALU64 | BPF_ADD | BPF_X: case BPF_ALU64 | BPF_SUB | BPF_X: case BPF_ALU64 | BPF_AND | BPF_X: case BPF_ALU64 | BPF_OR | BPF_X: case BPF_ALU64 | BPF_XOR | BPF_X: maybe_emit_mod(&prog, dst_reg, src_reg, BPF_CLASS(insn->code) == BPF_ALU64); b2 = simple_alu_opcodes[BPF_OP(insn->code)]; EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg)); break; case BPF_ALU64 | BPF_MOV | BPF_X: case BPF_ALU | BPF_MOV | BPF_X: emit_mov_reg(&prog, BPF_CLASS(insn->code) == BPF_ALU64, dst_reg, src_reg); break; /* neg dst */ case BPF_ALU | BPF_NEG: case BPF_ALU64 | BPF_NEG: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT2(0xF7, add_1reg(0xD8, dst_reg)); break; case BPF_ALU | BPF_ADD | BPF_K: case BPF_ALU | BPF_SUB | BPF_K: case BPF_ALU | BPF_AND | BPF_K: case BPF_ALU | BPF_OR | BPF_K: case BPF_ALU | BPF_XOR | BPF_K: case BPF_ALU64 | BPF_ADD | BPF_K: case BPF_ALU64 | BPF_SUB | BPF_K: case BPF_ALU64 | BPF_AND | BPF_K: case BPF_ALU64 | BPF_OR | BPF_K: case BPF_ALU64 | BPF_XOR | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); /* * b3 holds 'normal' opcode, b2 short form only valid * in case dst is eax/rax. */ switch (BPF_OP(insn->code)) { case BPF_ADD: b3 = 0xC0; b2 = 0x05; break; case BPF_SUB: b3 = 0xE8; b2 = 0x2D; break; case BPF_AND: b3 = 0xE0; b2 = 0x25; break; case BPF_OR: b3 = 0xC8; b2 = 0x0D; break; case BPF_XOR: b3 = 0xF0; b2 = 0x35; break; } if (is_imm8(imm32)) EMIT3(0x83, add_1reg(b3, dst_reg), imm32); else if (is_axreg(dst_reg)) EMIT1_off32(b2, imm32); else EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU64 | BPF_MOV | BPF_K: case BPF_ALU | BPF_MOV | BPF_K: emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64, dst_reg, imm32); break; case BPF_LD | BPF_IMM | BPF_DW: emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm); insn++; i++; break; /* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */ case BPF_ALU | BPF_MOD | BPF_X: case BPF_ALU | BPF_DIV | BPF_X: case BPF_ALU | BPF_MOD | BPF_K: case BPF_ALU | BPF_DIV | BPF_K: case BPF_ALU64 | BPF_MOD | BPF_X: case BPF_ALU64 | BPF_DIV | BPF_X: case BPF_ALU64 | BPF_MOD | BPF_K: case BPF_ALU64 | BPF_DIV | BPF_K: EMIT1(0x50); /* push rax */ EMIT1(0x52); /* push rdx */ if (BPF_SRC(insn->code) == BPF_X) /* mov r11, src_reg */ EMIT_mov(AUX_REG, src_reg); else /* mov r11, imm32 */ EMIT3_off32(0x49, 0xC7, 0xC3, imm32); /* mov rax, dst_reg */ EMIT_mov(BPF_REG_0, dst_reg); /* * xor edx, edx * equivalent to 'xor rdx, rdx', but one byte less */ EMIT2(0x31, 0xd2); if (BPF_CLASS(insn->code) == BPF_ALU64) /* div r11 */ EMIT3(0x49, 0xF7, 0xF3); else /* div r11d */ EMIT3(0x41, 0xF7, 0xF3); if (BPF_OP(insn->code) == BPF_MOD) /* mov r11, rdx */ EMIT3(0x49, 0x89, 0xD3); else /* mov r11, rax */ EMIT3(0x49, 0x89, 0xC3); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ /* mov dst_reg, r11 */ EMIT_mov(dst_reg, AUX_REG); break; case BPF_ALU | BPF_MUL | BPF_K: case BPF_ALU | BPF_MUL | BPF_X: case BPF_ALU64 | BPF_MUL | BPF_K: case BPF_ALU64 | BPF_MUL | BPF_X: { bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; if (dst_reg != BPF_REG_0) EMIT1(0x50); /* push rax */ if (dst_reg != BPF_REG_3) EMIT1(0x52); /* push rdx */ /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); if (BPF_SRC(insn->code) == BPF_X) emit_mov_reg(&prog, is64, BPF_REG_0, src_reg); else emit_mov_imm32(&prog, is64, BPF_REG_0, imm32); if (is64) EMIT1(add_1mod(0x48, AUX_REG)); else if (is_ereg(AUX_REG)) EMIT1(add_1mod(0x40, AUX_REG)); /* mul(q) r11 */ EMIT2(0xF7, add_1reg(0xE0, AUX_REG)); if (dst_reg != BPF_REG_3) EMIT1(0x5A); /* pop rdx */ if (dst_reg != BPF_REG_0) { /* mov dst_reg, rax */ EMIT_mov(dst_reg, BPF_REG_0); EMIT1(0x58); /* pop rax */ } break; } /* Shifts */ case BPF_ALU | BPF_LSH | BPF_K: case BPF_ALU | BPF_RSH | BPF_K: case BPF_ALU | BPF_ARSH | BPF_K: case BPF_ALU64 | BPF_LSH | BPF_K: case BPF_ALU64 | BPF_RSH | BPF_K: case BPF_ALU64 | BPF_ARSH | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); b3 = simple_alu_opcodes[BPF_OP(insn->code)]; if (imm32 == 1) EMIT2(0xD1, add_1reg(b3, dst_reg)); else EMIT3(0xC1, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU | BPF_LSH | BPF_X: case BPF_ALU | BPF_RSH | BPF_X: case BPF_ALU | BPF_ARSH | BPF_X: case BPF_ALU64 | BPF_LSH | BPF_X: case BPF_ALU64 | BPF_RSH | BPF_X: case BPF_ALU64 | BPF_ARSH | BPF_X: /* Check for bad case when dst_reg == rcx */ if (dst_reg == BPF_REG_4) { /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); dst_reg = AUX_REG; } if (src_reg != BPF_REG_4) { /* common case */ EMIT1(0x51); /* push rcx */ /* mov rcx, src_reg */ EMIT_mov(BPF_REG_4, src_reg); } /* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */ if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); b3 = simple_alu_opcodes[BPF_OP(insn->code)]; EMIT2(0xD3, add_1reg(b3, dst_reg)); if (src_reg != BPF_REG_4) EMIT1(0x59); /* pop rcx */ if (insn->dst_reg == BPF_REG_4) /* mov dst_reg, r11 */ EMIT_mov(insn->dst_reg, AUX_REG); break; case BPF_ALU | BPF_END | BPF_FROM_BE: switch (imm32) { case 16: /* Emit 'ror %ax, 8' to swap lower 2 bytes */ EMIT1(0x66); if (is_ereg(dst_reg)) EMIT1(0x41); EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8); /* Emit 'movzwl eax, ax' */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* Emit 'bswap eax' to swap lower 4 bytes */ if (is_ereg(dst_reg)) EMIT2(0x41, 0x0F); else EMIT1(0x0F); EMIT1(add_1reg(0xC8, dst_reg)); break; case 64: /* Emit 'bswap rax' to swap 8 bytes */ EMIT3(add_1mod(0x48, dst_reg), 0x0F, add_1reg(0xC8, dst_reg)); break; } break; case BPF_ALU | BPF_END | BPF_FROM_LE: switch (imm32) { case 16: /* * Emit 'movzwl eax, ax' to zero extend 16-bit * into 64 bit */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* Emit 'mov eax, eax' to clear upper 32-bits */ if (is_ereg(dst_reg)) EMIT1(0x45); EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg)); break; case 64: /* nop */ break; } break; /* ST: *(u8*)(dst_reg + off) = imm */ case BPF_ST | BPF_MEM | BPF_B: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC6); else EMIT1(0xC6); goto st; case BPF_ST | BPF_MEM | BPF_H: if (is_ereg(dst_reg)) EMIT3(0x66, 0x41, 0xC7); else EMIT2(0x66, 0xC7); goto st; case BPF_ST | BPF_MEM | BPF_W: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC7); else EMIT1(0xC7); goto st; case BPF_ST | BPF_MEM | BPF_DW: EMIT2(add_1mod(0x48, dst_reg), 0xC7); st: if (is_imm8(insn->off)) EMIT2(add_1reg(0x40, dst_reg), insn->off); else EMIT1_off32(add_1reg(0x80, dst_reg), insn->off); EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code))); break; /* STX: *(u8*)(dst_reg + off) = src_reg */ case BPF_STX | BPF_MEM | BPF_B: case BPF_STX | BPF_MEM | BPF_H: case BPF_STX | BPF_MEM | BPF_W: case BPF_STX | BPF_MEM | BPF_DW: emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off); break; /* LDX: dst_reg = *(u8*)(src_reg + off) */ case BPF_LDX | BPF_MEM | BPF_B: case BPF_LDX | BPF_PROBE_MEM | BPF_B: case BPF_LDX | BPF_MEM | BPF_H: case BPF_LDX | BPF_PROBE_MEM | BPF_H: case BPF_LDX | BPF_MEM | BPF_W: case BPF_LDX | BPF_PROBE_MEM | BPF_W: case BPF_LDX | BPF_MEM | BPF_DW: case BPF_LDX | BPF_PROBE_MEM | BPF_DW: if (BPF_MODE(insn->code) == BPF_PROBE_MEM) { /* test src_reg, src_reg */ maybe_emit_mod(&prog, src_reg, src_reg, true); /* always 1 byte */ EMIT2(0x85, add_2reg(0xC0, src_reg, src_reg)); /* jne start_of_ldx */ EMIT2(X86_JNE, 0); /* xor dst_reg, dst_reg */ emit_mov_imm32(&prog, false, dst_reg, 0); /* jmp byte_after_ldx */ EMIT2(0xEB, 0); /* populate jmp_offset for JNE above */ temp[4] = prog - temp - 5 /* sizeof(test + jne) */; start_of_ldx = prog; } emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off); if (BPF_MODE(insn->code) == BPF_PROBE_MEM) { struct exception_table_entry *ex; u8 *_insn = image + proglen; s64 delta; /* populate jmp_offset for JMP above */ start_of_ldx[-1] = prog - start_of_ldx; if (!bpf_prog->aux->extable) break; if (excnt >= bpf_prog->aux->num_exentries) { pr_err(""ex gen bug\n""); return -EFAULT; } ex = &bpf_prog->aux->extable[excnt++]; delta = _insn - (u8 *)&ex->insn; if (!is_simm32(delta)) { pr_err(""extable->insn doesn't fit into 32-bit\n""); return -EFAULT; } ex->insn = delta; delta = (u8 *)ex_handler_bpf - (u8 *)&ex->handler; if (!is_simm32(delta)) { pr_err(""extable->handler doesn't fit into 32-bit\n""); return -EFAULT; } ex->handler = delta; if (dst_reg > BPF_REG_9) { pr_err(""verifier error\n""); return -EFAULT; } /* * Compute size of x86 insn and its target dest x86 register. * ex_handler_bpf() will use lower 8 bits to adjust * pt_regs->ip to jump over this x86 instruction * and upper bits to figure out which pt_regs to zero out. * End result: x86 insn ""mov rbx, qword ptr [rax+0x14]"" * of 4 bytes will be ignored and rbx will be zero inited. */ ex->fixup = (prog - temp) | (reg2pt_regs[dst_reg] << 8); } break; case BPF_STX | BPF_ATOMIC | BPF_W: case BPF_STX | BPF_ATOMIC | BPF_DW: if (insn->imm == (BPF_AND | BPF_FETCH) || insn->imm == (BPF_OR | BPF_FETCH) || insn->imm == (BPF_XOR | BPF_FETCH)) { u8 *branch_target; bool is64 = BPF_SIZE(insn->code) == BPF_DW; u32 real_src_reg = src_reg; /* * Can't be implemented with a single x86 insn. * Need to do a CMPXCHG loop. */ /* Will need RAX as a CMPXCHG operand so save R0 */ emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0); if (src_reg == BPF_REG_0) real_src_reg = BPF_REG_AX; branch_target = prog; /* Load old value */ emit_ldx(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, insn->off); /* * Perform the (commutative) operation locally, * put the result in the AUX_REG. */ emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0); maybe_emit_mod(&prog, AUX_REG, real_src_reg, is64); EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)], add_2reg(0xC0, AUX_REG, real_src_reg)); /* Attempt to swap in new value */ err = emit_atomic(&prog, BPF_CMPXCHG, dst_reg, AUX_REG, insn->off, BPF_SIZE(insn->code)); if (WARN_ON(err)) return err; /* * ZF tells us whether we won the race. If it's * cleared we need to try again. */ EMIT2(X86_JNE, -(prog - branch_target) - 2); /* Return the pre-modification value */ emit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0); /* Restore R0 after clobbering RAX */ emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX); break; } err = emit_atomic(&prog, insn->imm, dst_reg, src_reg, insn->off, BPF_SIZE(insn->code)); if (err) return err; break; /* call */ case BPF_JMP | BPF_CALL: func = (u8 *) __bpf_call_base + imm32; if (tail_call_reachable) { EMIT3_off32(0x48, 0x8B, 0x85, -(bpf_prog->aux->stack_depth + 8)); if (!imm32 || emit_call(&prog, func, image + addrs[i - 1] + 7)) return -EINVAL; } else { if (!imm32 || emit_call(&prog, func, image + addrs[i - 1])) return -EINVAL; } break; case BPF_JMP | BPF_TAIL_CALL: if (imm32) emit_bpf_tail_call_direct(&bpf_prog->aux->poke_tab[imm32 - 1], &prog, addrs[i], image, callee_regs_used, bpf_prog->aux->stack_depth); else emit_bpf_tail_call_indirect(&prog, callee_regs_used, bpf_prog->aux->stack_depth); break; /* cond jump */ case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JNE | BPF_X: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JLT | BPF_X: case BPF_JMP | BPF_JGE | BPF_X: case BPF_JMP | BPF_JLE | BPF_X: case BPF_JMP | BPF_JSGT | BPF_X: case BPF_JMP | BPF_JSLT | BPF_X: case BPF_JMP | BPF_JSGE | BPF_X: case BPF_JMP | BPF_JSLE | BPF_X: case BPF_JMP32 | BPF_JEQ | BPF_X: case BPF_JMP32 | BPF_JNE | BPF_X: case BPF_JMP32 | BPF_JGT | BPF_X: case BPF_JMP32 | BPF_JLT | BPF_X: case BPF_JMP32 | BPF_JGE | BPF_X: case BPF_JMP32 | BPF_JLE | BPF_X: case BPF_JMP32 | BPF_JSGT | BPF_X: case BPF_JMP32 | BPF_JSLT | BPF_X: case BPF_JMP32 | BPF_JSGE | BPF_X: case BPF_JMP32 | BPF_JSLE | BPF_X: /* cmp dst_reg, src_reg */ maybe_emit_mod(&prog, dst_reg, src_reg, BPF_CLASS(insn->code) == BPF_JMP); EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_X: case BPF_JMP32 | BPF_JSET | BPF_X: /* test dst_reg, src_reg */ maybe_emit_mod(&prog, dst_reg, src_reg, BPF_CLASS(insn->code) == BPF_JMP); EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_K: case BPF_JMP32 | BPF_JSET | BPF_K: /* test dst_reg, imm32 */ if (BPF_CLASS(insn->code) == BPF_JMP) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32); goto emit_cond_jmp; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JNE | BPF_K: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JLT | BPF_K: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JLE | BPF_K: case BPF_JMP | BPF_JSGT | BPF_K: case BPF_JMP | BPF_JSLT | BPF_K: case BPF_JMP | BPF_JSGE | BPF_K: case BPF_JMP | BPF_JSLE | BPF_K: case BPF_JMP32 | BPF_JEQ | BPF_K: case BPF_JMP32 | BPF_JNE | BPF_K: case BPF_JMP32 | BPF_JGT | BPF_K: case BPF_JMP32 | BPF_JLT | BPF_K: case BPF_JMP32 | BPF_JGE | BPF_K: case BPF_JMP32 | BPF_JLE | BPF_K: case BPF_JMP32 | BPF_JSGT | BPF_K: case BPF_JMP32 | BPF_JSLT | BPF_K: case BPF_JMP32 | BPF_JSGE | BPF_K: case BPF_JMP32 | BPF_JSLE | BPF_K: /* test dst_reg, dst_reg to save one extra byte */ if (imm32 == 0) { maybe_emit_mod(&prog, dst_reg, dst_reg, BPF_CLASS(insn->code) == BPF_JMP); EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg)); goto emit_cond_jmp; } /* cmp dst_reg, imm8/32 */ if (BPF_CLASS(insn->code) == BPF_JMP) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); if (is_imm8(imm32)) EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32); else EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32); emit_cond_jmp: /* Convert BPF opcode to x86 */ switch (BPF_OP(insn->code)) { case BPF_JEQ: jmp_cond = X86_JE; break; case BPF_JSET: case BPF_JNE: jmp_cond = X86_JNE; break; case BPF_JGT: /* GT is unsigned '>', JA in x86 */ jmp_cond = X86_JA; break; case BPF_JLT: /* LT is unsigned '<', JB in x86 */ jmp_cond = X86_JB; break; case BPF_JGE: /* GE is unsigned '>=', JAE in x86 */ jmp_cond = X86_JAE; break; case BPF_JLE: /* LE is unsigned '<=', JBE in x86 */ jmp_cond = X86_JBE; break; case BPF_JSGT: /* Signed '>', GT in x86 */ jmp_cond = X86_JG; break; case BPF_JSLT: /* Signed '<', LT in x86 */ jmp_cond = X86_JL; break; case BPF_JSGE: /* Signed '>=', GE in x86 */ jmp_cond = X86_JGE; break; case BPF_JSLE: /* Signed '<=', LE in x86 */ jmp_cond = X86_JLE; break; default: /* to silence GCC warning */ return -EFAULT; } jmp_offset = addrs[i + insn->off] - addrs[i]; if (is_imm8(jmp_offset)) { if (jmp_padding) { /* To keep the jmp_offset valid, the extra bytes are * padded before the jump insn, so we substract the * 2 bytes of jmp_cond insn from INSN_SZ_DIFF. * * If the previous pass already emits an imm8 * jmp_cond, then this BPF insn won't shrink, so * ""nops"" is 0. * * On the other hand, if the previous pass emits an * imm32 jmp_cond, the extra 4 bytes(*) is padded to * keep the image from shrinking further. * * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond * is 2 bytes, so the size difference is 4 bytes. */ nops = INSN_SZ_DIFF - 2; if (nops != 0 && nops != 4) { pr_err(""unexpected jmp_cond padding: %d bytes\n"", nops); return -EFAULT; } cnt += emit_nops(&prog, nops); } EMIT2(jmp_cond, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset); } else { pr_err(""cond_jmp gen bug %llx\n"", jmp_offset); return -EFAULT; } break; case BPF_JMP | BPF_JA: if (insn->off == -1) /* -1 jmp instructions will always jump * backwards two bytes. Explicitly handling * this case avoids wasting too many passes * when there are long sequences of replaced * dead code. */ jmp_offset = -2; else jmp_offset = addrs[i + insn->off] - addrs[i]; if (!jmp_offset) { /* * If jmp_padding is enabled, the extra nops will * be inserted. Otherwise, optimize out nop jumps. */ if (jmp_padding) { /* There are 3 possible conditions. * (1) This BPF_JA is already optimized out in * the previous run, so there is no need * to pad any extra byte (0 byte). * (2) The previous pass emits an imm8 jmp, * so we pad 2 bytes to match the previous * insn size. * (3) Similarly, the previous pass emits an * imm32 jmp, and 5 bytes is padded. */ nops = INSN_SZ_DIFF; if (nops != 0 && nops != 2 && nops != 5) { pr_err(""unexpected nop jump padding: %d bytes\n"", nops); return -EFAULT; } cnt += emit_nops(&prog, nops); } break; } emit_jmp: if (is_imm8(jmp_offset)) { if (jmp_padding) { /* To avoid breaking jmp_offset, the extra bytes * are padded before the actual jmp insn, so * 2 bytes is substracted from INSN_SZ_DIFF. * * If the previous pass already emits an imm8 * jmp, there is nothing to pad (0 byte). * * If it emits an imm32 jmp (5 bytes) previously * and now an imm8 jmp (2 bytes), then we pad * (5 - 2 = 3) bytes to stop the image from * shrinking further. */ nops = INSN_SZ_DIFF - 2; if (nops != 0 && nops != 3) { pr_err(""unexpected jump padding: %d bytes\n"", nops); return -EFAULT; } cnt += emit_nops(&prog, INSN_SZ_DIFF - 2); } EMIT2(0xEB, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT1_off32(0xE9, jmp_offset); } else { pr_err(""jmp gen bug %llx\n"", jmp_offset); return -EFAULT; } break; case BPF_JMP | BPF_EXIT: if (seen_exit) { jmp_offset = ctx->cleanup_addr - addrs[i]; goto emit_jmp; } seen_exit = true; /* Update cleanup_addr */ ctx->cleanup_addr = proglen; pop_callee_regs(&prog, callee_regs_used); EMIT1(0xC9); /* leave */ EMIT1(0xC3); /* ret */ break; default: /* * By design x86-64 JIT should support all BPF instructions. * This error will be seen if new instruction was added * to the interpreter, but not to the JIT, or if there is * junk in bpf_prog. */ pr_err(""bpf_jit: unknown opcode %02x\n"", insn->code); return -EINVAL; } ilen = prog - temp; if (ilen > BPF_MAX_INSN_SIZE) { pr_err(""bpf_jit: fatal insn size error\n""); return -EFAULT; } if (image) { if (unlikely(proglen + ilen > oldproglen)) { pr_err(""bpf_jit: fatal error\n""); return -EFAULT; } memcpy(image + proglen, temp, ilen); } proglen += ilen; addrs[i] = proglen; prog = temp; } if (image && excnt != bpf_prog->aux->num_exentries) { pr_err(""extable is not populated\n""); return -EFAULT; } return proglen; }",CWE-77,14 0," void StartOnIOThread() { ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); worker_ = wrapper()->context()->embedded_worker_registry()->CreateWorker(); EXPECT_EQ(EmbeddedWorkerInstance::STOPPED, worker_->status()); worker_->AddObserver(this); AssociateRendererProcessToWorker(worker_.get()); const int64 service_worker_version_id = 33L; const GURL script_url = embedded_test_server()->GetURL( ""/service_worker/worker.js""); ServiceWorkerStatusCode status = worker_->Start( service_worker_version_id, script_url); last_worker_status_ = worker_->status(); EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_EQ(EmbeddedWorkerInstance::STARTING, last_worker_status_); if (status != SERVICE_WORKER_OK && !done_closure_.is_null()) done_closure_.Run(); } ",none,24 1,"hufUncompress (const char compressed[], int nCompressed, unsigned short raw[], int nRaw) { // // need at least 20 bytes for header // if (nCompressed < 20 ) { if (nRaw != 0) notEnoughData(); return; } int im = readUInt (compressed); int iM = readUInt (compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt (compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) invalidTableSize(); const char *ptr = compressed + 20; if ( ptr + (nBits+7 )/8 > compressed+nCompressed) { notEnoughData(); return; } // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // if (FastHufDecoder::enabled() && nBits > 128) { FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); } else { AutoArray freq; AutoArray hdec; hufClearDecTable (hdec); hufUnpackEncTable (&ptr, nCompressed - (ptr - compressed), im, iM, freq); try { if (nBits > 8 * (nCompressed - (ptr - compressed))) invalidNBits(); hufBuildDecTable (freq, im, iM, hdec); hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw); } catch (...) { hufFreeDecTable (hdec); throw; } hufFreeDecTable (hdec); } }",CWE-190,2 1,"static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int size_chk, err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say ""computer says no"". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } size_chk = chunk_size - headroom - XDP_PACKET_HEADROOM; if (size_chk < 0) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; }",CWE-416,10 1,"static void SpatialMaxPoolWithArgMaxHelper( OpKernelContext* context, Tensor* output, Tensor* output_arg_max, Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop, const PoolParameters& params, const bool include_batch_in_index) { if (input_backprop != nullptr) { OP_REQUIRES( context, include_batch_in_index, errors::Internal( ""SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index "" ""to be True when input_backprop != nullptr"")); OP_REQUIRES( context, (std::is_same::value), errors::Internal(""SpatialMaxPoolWithArgMaxHelper requires Targmax "" ""to be int64 when input_backprop != nullptr"")); } typedef Eigen::Map> ConstEigenMatrixMap; typedef Eigen::Map> EigenMatrixMap; typedef Eigen::Map> EigenIndexMatrixMap; ConstEigenMatrixMap in_mat( tensor_in.flat().data(), params.depth, params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch); EigenMatrixMap out_mat( output->flat().data(), params.depth, params.out_width * params.out_height * params.tensor_in_batch); EigenIndexMatrixMap out_arg_max_mat( output_arg_max->flat().data(), params.depth, params.out_width * params.out_height * params.tensor_in_batch); const DeviceBase::CpuWorkerThreads& worker_threads = *(context->device()->tensorflow_cpu_worker_threads()); // The following code basically does the following: // 1. Flattens the input and output tensors into two dimensional arrays. // tensor_in_as_matrix: // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch) // output_as_matrix: // depth by (out_width * out_height * tensor_in_batch) // // 2. Walks through the set of columns in the flattened tensor_in_as_matrix, // and updates the corresponding column(s) in output_as_matrix with the // max value. auto shard = [¶ms, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop, &output_arg_max, &out_backprop, include_batch_in_index](int64 start, int64 limit) { const int32 depth = params.depth; const int32 in_rows = params.tensor_in_rows; const int32 in_cols = params.tensor_in_cols; const int32 pad_top = params.pad_top; const int32 pad_left = params.pad_left; const int32 window_rows = params.window_rows; const int32 window_cols = params.window_cols; const int32 row_stride = params.row_stride; const int32 col_stride = params.col_stride; const int32 out_height = params.out_height; const int32 out_width = params.out_width; { // Initializes the output tensor with MIN. const int32 output_image_size = out_height * out_width * depth; EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1, (limit - start) * output_image_size); out_shard.setConstant(Eigen::NumTraits::lowest()); EigenIndexMatrixMap out_arg_max_shard( out_arg_max_mat.data() + start * output_image_size, 1, (limit - start) * output_image_size); out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex); } for (int64 b = start; b < limit; ++b) { for (int h = 0; h < in_rows; ++h) { for (int w = 0; w < in_cols; ++w) { // (h_start, h_end) * (w_start, w_end) is the range that the input // vector projects to. const int hpad = h + pad_top; const int wpad = w + pad_left; const int h_start = (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1; const int h_end = std::min(hpad / row_stride + 1, out_height); const int w_start = (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1; const int w_end = std::min(wpad / col_stride + 1, out_width); // compute elementwise max const int64 in_index = (b * in_rows + h) * in_cols + w; for (int ph = h_start; ph < h_end; ++ph) { const int64 out_index_base = (b * out_height + ph) * out_width; for (int pw = w_start; pw < w_end; ++pw) { const int64 out_index = out_index_base + pw; /// NOTES(zhengxq): not using the eigen matrix operation for /// now. for (int d = 0; d < depth; ++d) { const T& input_ref = in_mat.coeffRef(d, in_index); T& output_ref = out_mat.coeffRef(d, out_index); Targmax& out_arg_max_ref = out_arg_max_mat.coeffRef(d, out_index); if (output_ref < input_ref || out_arg_max_ref == kInvalidMaxPoolingIndex) { output_ref = input_ref; if (include_batch_in_index) { out_arg_max_ref = in_index * depth + d; } else { out_arg_max_ref = (h * in_cols + w) * depth + d; } } } } } } } } if (input_backprop != nullptr) { auto input_backprop_flat = input_backprop->flat(); auto out_arg_max_flat = output_arg_max->flat(); auto out_backprop_flat = out_backprop.flat(); // Initialize output to 0. const int64 in_size = in_rows * in_cols * depth; const int64 in_start = start * in_size; const int64 in_end = limit * in_size; EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1, in_end - in_start); in_shard.setConstant(T(0)); // Backpropagate. const int out_size = out_height * out_width * depth; const int out_start = start * out_size; const int out_end = limit * out_size; for (int index = out_start; index < out_end; ++index) { int input_backprop_index = out_arg_max_flat(index); // Although this check is in the inner loop, it is worth its value // so we don't end up with memory corruptions. Our benchmark shows that // the performance impact is quite small // CHECK(input_backprop_index >= in_start && input_backprop_index < // in_end) FastBoundsCheck(input_backprop_index - in_start, in_end - in_start); input_backprop_flat(input_backprop_index) += out_backprop_flat(index); } } }; const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols * params.depth * params.window_rows * params.window_cols; Shard(worker_threads.num_threads, worker_threads.workers, params.tensor_in_batch, shard_cost, shard); }",CWE-787,16 0,"bool ContentSettingsStore::OnCorrectThread() { return !BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI); } ",none,24 1," Status CalculateOutputIndex(OpKernelContext* context, int dimension, const vector& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector* result) { const RowPartitionTensor row_partition_tensor = GetRowPartitionTensor(context, dimension); auto partition_type = GetRowPartitionTypeByDimension(dimension); switch (partition_type) { case RowPartitionType::VALUE_ROWIDS: CalculateOutputIndexValueRowID( context, row_partition_tensor, parent_output_index, output_index_multiplier, output_size, result); return tensorflow::Status::OK(); case RowPartitionType::ROW_SPLITS: CalculateOutputIndexRowSplit( context, row_partition_tensor, parent_output_index, output_index_multiplier, output_size, result); return tensorflow::Status::OK(); default: return errors::InvalidArgument( ""Unsupported partition type:"", RowPartitionTypeToString(partition_type)); } }",CWE-125,1 1," static void launch(OpKernelContext* context, const PoolParameters& params, const Tensor& grad_in, const Tensor& argmax, Tensor* grad_out, const bool include_batch_in_index) { const DeviceBase::CpuWorkerThreads& worker_threads = *(context->device()->tensorflow_cpu_worker_threads()); auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index]( int64 start, int64 limit) { const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N'); const int64 output_size_per_batch = grad_out->NumElements() / batch_size; const int64 input_size_per_batch = grad_in.NumElements() / batch_size; { auto grad_out_flat = grad_out->flat(); auto argmax_flat = argmax.flat(); auto grad_in_flat = grad_in.flat(); const int64 output_start = start * output_size_per_batch; const int64 output_end = limit * output_size_per_batch; EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1, output_end - output_start); inputShard.setConstant(T(0)); const int input_start = start * input_size_per_batch; const int input_end = limit * input_size_per_batch; for (int64 index = input_start; index < input_end; index++) { int64 grad_out_index = argmax_flat(index); if (!include_batch_in_index) { const int64 cur_batch = index / input_size_per_batch; grad_out_index += cur_batch * output_size_per_batch; } CHECK(grad_out_index >= output_start && grad_out_index < output_end) << ""Invalid output gradient index: "" << grad_out_index << "", "" << output_start << "", "" << output_end; grad_out_flat(grad_out_index) += grad_in_flat(index); } } }; const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N'); const int64 shard_cost = grad_out->NumElements() / batch_size; Shard(worker_threads.num_threads, worker_threads.workers, batch_size, shard_cost, shard); }",CWE-125,1 0,"void CallWorkerContextDestroyedOnMainThread(int embedded_worker_id) { if (!RenderThreadImpl::current() || !RenderThreadImpl::current()->embedded_worker_dispatcher()) return; RenderThreadImpl::current()->embedded_worker_dispatcher()-> WorkerContextDestroyed(embedded_worker_id); } ",none,24 0,"bool WebGraphicsContext3DDefaultImpl::angleCreateCompilers() { if (!ShInitialize()) return false; ShBuiltInResources resources; ShInitBuiltInResources(&resources); getIntegerv(GL_MAX_VERTEX_ATTRIBS, &resources.MaxVertexAttribs); getIntegerv(MAX_VERTEX_UNIFORM_VECTORS, &resources.MaxVertexUniformVectors); getIntegerv(MAX_VARYING_VECTORS, &resources.MaxVaryingVectors); getIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &resources.MaxVertexTextureImageUnits); getIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &resources.MaxCombinedTextureImageUnits); getIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &resources.MaxTextureImageUnits); getIntegerv(MAX_FRAGMENT_UNIFORM_VECTORS, &resources.MaxFragmentUniformVectors); resources.MaxDrawBuffers = 1; m_fragmentCompiler = ShConstructCompiler(SH_FRAGMENT_SHADER, SH_WEBGL_SPEC, &resources); m_vertexCompiler = ShConstructCompiler(SH_VERTEX_SHADER, SH_WEBGL_SPEC, &resources); return (m_fragmentCompiler && m_vertexCompiler); } ",none,24 0,"AudioOutputStream* AudioManagerBase::MakeAudioOutputStream( const AudioParameters& params) { if (!params.IsValid()) { DLOG(ERROR) << ""Audio parameters are invalid""; return NULL; } if (num_output_streams_ >= max_num_output_streams_) { DLOG(ERROR) << ""Number of opened output audio streams "" << num_output_streams_ << "" exceed the max allowed number "" << max_num_output_streams_; return NULL; } AudioOutputStream* stream = NULL; if (params.format() == AudioParameters::AUDIO_MOCK) { stream = FakeAudioOutputStream::MakeFakeStream(this, params); } else if (params.format() == AudioParameters::AUDIO_PCM_LINEAR) { stream = MakeLinearOutputStream(params); } else if (params.format() == AudioParameters::AUDIO_PCM_LOW_LATENCY) { stream = MakeLowLatencyOutputStream(params); } if (stream) ++num_output_streams_; return stream; } ",none,24 1,"static PCRE2_SPTR SLJIT_FUNC do_extuni_no_utf(jit_arguments *args, PCRE2_SPTR cc) { PCRE2_SPTR start_subject = args->begin; PCRE2_SPTR end_subject = args->end; int lgb, rgb, ricount; PCRE2_SPTR bptr; uint32_t c; GETCHARINC(c, cc); lgb = UCD_GRAPHBREAK(c); while (cc < end_subject) { c = *cc; rgb = UCD_GRAPHBREAK(c); if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; /* Not breaking between Regional Indicators is allowed only if there are an even number of preceding RIs. */ if (lgb == ucp_gbRegionalIndicator && rgb == ucp_gbRegionalIndicator) { ricount = 0; bptr = cc - 1; /* bptr is pointing to the left-hand character */ while (bptr > start_subject) { bptr--; c = *bptr; if (UCD_GRAPHBREAK(c) != ucp_gbRegionalIndicator) break; ricount++; } if ((ricount & 1) != 0) break; /* Grapheme break required */ } /* If Extend or ZWJ follows Extended_Pictographic, do not update lgb; this allows any number of them before a following Extended_Pictographic. */ if ((rgb != ucp_gbExtend && rgb != ucp_gbZWJ) || lgb != ucp_gbExtended_Pictographic) lgb = rgb; cc++; } return cc; }",CWE-125,1 1,"static void io_async_task_func(struct callback_head *cb) { struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work); struct async_poll *apoll = req->apoll; struct io_ring_ctx *ctx = req->ctx; trace_io_uring_task_run(req->ctx, req->opcode, req->user_data); if (io_poll_rewait(req, &apoll->poll)) { spin_unlock_irq(&ctx->completion_lock); return; } /* If req is still hashed, it cannot have been canceled. Don't check. */ if (hash_hashed(&req->hash_node)) hash_del(&req->hash_node); io_poll_remove_double(req, apoll->double_poll); spin_unlock_irq(&ctx->completion_lock); if (!READ_ONCE(apoll->poll.canceled)) __io_req_task_submit(req); else __io_req_task_cancel(req, -ECANCELED); kfree(apoll->double_poll); kfree(apoll); }",CWE-416,10 1,"TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast(node->builtin_data); int axis = params->axis; int num_inputs = node->inputs->size; // The number of dimensions of the input tensors must match, and all // dimensions except 'axis' must be equal. const TfLiteTensor* t0; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0)); TfLiteType input_type = t0->type; if (axis < 0) axis += t0->dims->size; TF_LITE_ENSURE(context, axis >= 0); TF_LITE_ENSURE(context, axis < t0->dims->size); TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone); TF_LITE_ENSURE(context, input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 || input_type == kTfLiteInt8 || input_type == kTfLiteInt16 || input_type == kTfLiteInt32 || input_type == kTfLiteInt64 || input_type == kTfLiteBool); // Output dimensions will match input dimensions, except 'axis', which // will be the sum of inputs int sum_axis = t0->dims->data[axis]; for (int i = 1; i < num_inputs; ++i) { const TfLiteTensor* t; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t)); TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size); TF_LITE_ENSURE_EQ(context, t->type, input_type); for (int d = 0; d < t0->dims->size; ++d) { if (d == axis) { sum_axis += t->dims->data[axis]; } else { TF_LITE_ENSURE_EQ(context, t->dims->data[d], t0->dims->data[d]); } } } TfLiteIntArray* output_size = TfLiteIntArrayCreate(t0->dims->size); for (int d = 0; d < t0->dims->size; ++d) { output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d]; } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type); if (input_type == kTfLiteInt8) { // Make sure there is no re-scaling needed for Int8 quantized kernel. This // is a restriction we introduced to Int8 kernels. VectorOfTensors all_inputs(*context, *node->inputs); for (int i = 0; i < node->inputs->size; ++i) { const TfLiteTensor* t; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t)); TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale); TF_LITE_ENSURE_EQ(context, t->params.zero_point, output->params.zero_point); } } if (input_type == kTfLiteInt16) { // Make sure that all Int16 inputs have a null zero-point. for (int i = 0; i < node->inputs->size; ++i) { const TfLiteTensor* t = GetInput(context, node, i); TF_LITE_ENSURE_EQ(context, t->params.zero_point, 0); } TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } return context->ResizeTensor(context, output, output_size); }",CWE-476,12 0,"String DataObjectItem::FileSystemId() const { return file_system_id_; } ",none,24 0," void Reset() { decoder_->Reset(NewExpectedClosure()); message_loop_.RunAllPending(); } ",none,24 0,"bool AudioManagerBase::CanShowAudioInputSettings() { return false; } ",none,24 1,"static void ov511_mode_init_regs(struct sd *sd) { struct gspca_dev *gspca_dev = (struct gspca_dev *)sd; int hsegs, vsegs, packet_size, fps, needed; int interlaced = 0; struct usb_host_interface *alt; struct usb_interface *intf; intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface); alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt); if (!alt) { gspca_err(gspca_dev, ""Couldn't get altsetting\n""); sd->gspca_dev.usb_err = -EIO; return; } packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); reg_w(sd, R51x_FIFO_PSIZE, packet_size >> 5); reg_w(sd, R511_CAM_UV_EN, 0x01); reg_w(sd, R511_SNAP_UV_EN, 0x01); reg_w(sd, R511_SNAP_OPTS, 0x03); /* Here I'm assuming that snapshot size == image size. * I hope that's always true. --claudio */ hsegs = (sd->gspca_dev.pixfmt.width >> 3) - 1; vsegs = (sd->gspca_dev.pixfmt.height >> 3) - 1; reg_w(sd, R511_CAM_PXCNT, hsegs); reg_w(sd, R511_CAM_LNCNT, vsegs); reg_w(sd, R511_CAM_PXDIV, 0x00); reg_w(sd, R511_CAM_LNDIV, 0x00); /* YUV420, low pass filter on */ reg_w(sd, R511_CAM_OPTS, 0x03); /* Snapshot additions */ reg_w(sd, R511_SNAP_PXCNT, hsegs); reg_w(sd, R511_SNAP_LNCNT, vsegs); reg_w(sd, R511_SNAP_PXDIV, 0x00); reg_w(sd, R511_SNAP_LNDIV, 0x00); /******** Set the framerate ********/ if (frame_rate > 0) sd->frame_rate = frame_rate; switch (sd->sensor) { case SEN_OV6620: /* No framerate control, doesn't like higher rates yet */ sd->clockdiv = 3; break; /* Note once the FIXME's in mode_init_ov_sensor_regs() are fixed for more sensors we need to do this for them too */ case SEN_OV7620: case SEN_OV7620AE: case SEN_OV7640: case SEN_OV7648: case SEN_OV76BE: if (sd->gspca_dev.pixfmt.width == 320) interlaced = 1; /* Fall through */ case SEN_OV6630: case SEN_OV7610: case SEN_OV7670: switch (sd->frame_rate) { case 30: case 25: /* Not enough bandwidth to do 640x480 @ 30 fps */ if (sd->gspca_dev.pixfmt.width != 640) { sd->clockdiv = 0; break; } /* For 640x480 case */ /* fall through */ default: /* case 20: */ /* case 15: */ sd->clockdiv = 1; break; case 10: sd->clockdiv = 2; break; case 5: sd->clockdiv = 5; break; } if (interlaced) { sd->clockdiv = (sd->clockdiv + 1) * 2 - 1; /* Higher then 10 does not work */ if (sd->clockdiv > 10) sd->clockdiv = 10; } break; case SEN_OV8610: /* No framerate control ?? */ sd->clockdiv = 0; break; } /* Check if we have enough bandwidth to disable compression */ fps = (interlaced ? 60 : 30) / (sd->clockdiv + 1) + 1; needed = fps * sd->gspca_dev.pixfmt.width * sd->gspca_dev.pixfmt.height * 3 / 2; /* 1000 isoc packets/sec */ if (needed > 1000 * packet_size) { /* Enable Y and UV quantization and compression */ reg_w(sd, R511_COMP_EN, 0x07); reg_w(sd, R511_COMP_LUT_EN, 0x03); } else { reg_w(sd, R511_COMP_EN, 0x06); reg_w(sd, R511_COMP_LUT_EN, 0x00); } reg_w(sd, R51x_SYS_RESET, OV511_RESET_OMNICE); reg_w(sd, R51x_SYS_RESET, 0); }",CWE-476,12 0," void StopOnIOThread() { ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); EXPECT_EQ(EmbeddedWorkerInstance::RUNNING, worker_->status()); ServiceWorkerStatusCode status = worker_->Stop(); last_worker_status_ = worker_->status(); EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_EQ(EmbeddedWorkerInstance::STOPPING, last_worker_status_); if (status != SERVICE_WORKER_OK && !done_closure_.is_null()) done_closure_.Run(); } ",none,24 0,"SearchEngineTabHelper::~SearchEngineTabHelper() { } ",none,24