instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltFuncFunctionComp (xsltStylesheetPtr style, xmlNodePtr inst) { xmlChar *name, *prefix; xmlNsPtr ns; xmlHashTablePtr data; exsltFuncFunctionData *func; if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE)) return; { xmlChar *qname; qname = xmlGetProp(inst, (const xmlChar *) "name"); name = xmlSplitQName2 (qname, &prefix); xmlFree(qname); } if ((name == NULL) || (prefix == NULL)) { xsltGenericError(xsltGenericErrorContext, "func:function: not a QName\n"); if (name != NULL) xmlFree(name); return; } /* namespace lookup */ ns = xmlSearchNs (inst->doc, inst, prefix); if (ns == NULL) { xsltGenericError(xsltGenericErrorContext, "func:function: undeclared prefix %s\n", prefix); xmlFree(name); xmlFree(prefix); return; } xmlFree(prefix); xsltParseTemplateContent(style, inst); /* * Create function data */ func = exsltFuncNewFunctionData(); func->content = inst->children; while (IS_XSLT_ELEM(func->content) && IS_XSLT_NAME(func->content, "param")) { func->content = func->content->next; func->nargs++; } /* * Register the function data such that it can be retrieved * by exslFuncFunctionFunction */ #ifdef XSLT_REFACTORED /* * Ensure that the hash table will be stored in the *current* * stylesheet level in order to correctly evaluate the * import precedence. */ data = (xmlHashTablePtr) xsltStyleStylesheetLevelGetExtData(style, EXSLT_FUNCTIONS_NAMESPACE); #else data = (xmlHashTablePtr) xsltStyleGetExtData (style, EXSLT_FUNCTIONS_NAMESPACE); #endif if (data == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionComp: no stylesheet data\n"); xmlFree(name); return; } if (xmlHashAddEntry2 (data, ns->href, name, func) < 0) { xsltTransformError(NULL, style, inst, "Failed to register function {%s}%s\n", ns->href, name); style->errors++; } else { xsltGenericDebug(xsltGenericDebugContext, "exsltFuncFunctionComp: register {%s}%s\n", ns->href, name); } xmlFree(name); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltFuncFunctionComp (xsltStylesheetPtr style, xmlNodePtr inst) { xmlChar *name, *prefix; xmlNsPtr ns; xmlHashTablePtr data; exsltFuncFunctionData *func; if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE)) return; { xmlChar *qname; qname = xmlGetProp(inst, (const xmlChar *) "name"); name = xmlSplitQName2 (qname, &prefix); xmlFree(qname); } if ((name == NULL) || (prefix == NULL)) { xsltGenericError(xsltGenericErrorContext, "func:function: not a QName\n"); if (name != NULL) xmlFree(name); return; } /* namespace lookup */ ns = xmlSearchNs (inst->doc, inst, prefix); if (ns == NULL) { xsltGenericError(xsltGenericErrorContext, "func:function: undeclared prefix %s\n", prefix); xmlFree(name); xmlFree(prefix); return; } xmlFree(prefix); xsltParseTemplateContent(style, inst); /* * Create function data */ func = exsltFuncNewFunctionData(); if (func == NULL) { xmlFree(name); return; } func->content = inst->children; while (IS_XSLT_ELEM(func->content) && IS_XSLT_NAME(func->content, "param")) { func->content = func->content->next; func->nargs++; } /* * Register the function data such that it can be retrieved * by exslFuncFunctionFunction */ #ifdef XSLT_REFACTORED /* * Ensure that the hash table will be stored in the *current* * stylesheet level in order to correctly evaluate the * import precedence. */ data = (xmlHashTablePtr) xsltStyleStylesheetLevelGetExtData(style, EXSLT_FUNCTIONS_NAMESPACE); #else data = (xmlHashTablePtr) xsltStyleGetExtData (style, EXSLT_FUNCTIONS_NAMESPACE); #endif if (data == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionComp: no stylesheet data\n"); xmlFree(name); return; } if (xmlHashAddEntry2 (data, ns->href, name, func) < 0) { xsltTransformError(NULL, style, inst, "Failed to register function {%s}%s\n", ns->href, name); style->errors++; } else { xsltGenericDebug(xsltGenericDebugContext, "exsltFuncFunctionComp: register {%s}%s\n", ns->href, name); } xmlFree(name); }
173,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WorkerFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo& initiator_info) { probe::willSendRequest(global_scope_, identifier, nullptr, request, redirect_response, initiator_info); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void WorkerFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, Resource::Type resource_type, const FetchInitiatorInfo& initiator_info) { probe::willSendRequest(global_scope_, identifier, nullptr, request, redirect_response, initiator_info, resource_type); }
172,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: internalEntityProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { ENTITY *entity; const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; if (! openEntity) return XML_ERROR_UNEXPECTED_STATE; entity = openEntity->entity; textStart = ((char *)entity->textPtr) + entity->processed; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE); } else #endif /* XML_DTD */ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result != XML_ERROR_NONE) return result; else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - (char *)entity->textPtr); return result; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } #ifdef XML_DTD if (entity->is_param) { int tok; parser->m_processor = prologProcessor; tok = XmlPrologTok(parser->m_encoding, s, end, &next); return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } else #endif /* XML_DTD */ { parser->m_processor = contentProcessor; /* see externalEntityContentProcessor vs contentProcessor */ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
internalEntityProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { ENTITY *entity; const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; if (! openEntity) return XML_ERROR_UNEXPECTED_STATE; entity = openEntity->entity; textStart = ((char *)entity->textPtr) + entity->processed; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE, XML_TRUE); } else #endif /* XML_DTD */ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result != XML_ERROR_NONE) return result; else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - (char *)entity->textPtr); return result; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } #ifdef XML_DTD if (entity->is_param) { int tok; parser->m_processor = prologProcessor; tok = XmlPrologTok(parser->m_encoding, s, end, &next); return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); } else #endif /* XML_DTD */ { parser->m_processor = contentProcessor; /* see externalEntityContentProcessor vs contentProcessor */ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } }
169,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } fsize = st.st_size; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } Commit Message: - limit the number of program and section header number of sections to be processed to avoid excessive processing time. - if a bad note is found, return 0 to stop processing immediately. CWE ID: CWE-399
file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } fsize = st.st_size; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; }
169,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; unsigned long limit; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return 0; if (user_64bit_mode(regs) || v8086_mode(regs)) return -1L; if (!sel) return 0; desc = get_desc(sel); if (!desc) return 0; /* * If the granularity bit is set, the limit is given in multiples * of 4096. This also means that the 12 least significant bits are * not tested when checking the segment limits. In practice, * this means that the segment ends in (limit << 12) + 0xfff. */ limit = get_desc_limit(desc); if (desc->g) limit = (limit << 12) + 0xfff; return limit; } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct desc; unsigned long limit; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return 0; if (user_64bit_mode(regs) || v8086_mode(regs)) return -1L; if (!sel) return 0; if (!get_desc(&desc, sel)) return 0; /* * If the granularity bit is set, the limit is given in multiples * of 4096. This also means that the 12 least significant bits are * not tested when checking the segment limits. In practice, * this means that the segment ends in (limit << 12) + 0xfff. */ limit = get_desc_limit(&desc); if (desc.g) limit = (limit << 12) + 0xfff; return limit; }
169,608
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { u32 bmval0 = bmval[0]; u32 bmval1 = bmval[1]; u32 bmval2 = bmval[2]; struct kstat stat; struct svc_fh *tempfh = NULL; struct kstatfs statfs; __be32 *p; int starting_len = xdr->buf->len; int attrlen_offset; __be32 attrlen; u32 dummy; u64 dummy64; u32 rdattr_err = 0; __be32 status; int err; struct nfs4_acl *acl = NULL; void *context = NULL; int contextlen; bool contextsupport = false; struct nfsd4_compoundres *resp = rqstp->rq_resp; u32 minorversion = resp->cstate.minorversion; struct path path = { .mnt = exp->ex_path.mnt, .dentry = dentry, }; struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1); BUG_ON(!nfsd_attrs_supported(minorversion, bmval)); if (exp->ex_fslocs.migrated) { status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err); if (status) goto out; } err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); if (err) goto out_nfserr; if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE | FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) || (bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE | FATTR4_WORD1_SPACE_TOTAL))) { err = vfs_statfs(&path, &statfs); if (err) goto out_nfserr; } if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) { tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); status = nfserr_jukebox; if (!tempfh) goto out; fh_init(tempfh, NFS4_FHSIZE); status = fh_compose(tempfh, exp, dentry, NULL); if (status) goto out; fhp = tempfh; } if (bmval0 & FATTR4_WORD0_ACL) { err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl); if (err == -EOPNOTSUPP) bmval0 &= ~FATTR4_WORD0_ACL; else if (err == -EINVAL) { status = nfserr_attrnotsupp; goto out; } else if (err != 0) goto out_nfserr; } #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) || bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { if (exp->ex_flags & NFSEXP_SECURITY_LABEL) err = security_inode_getsecctx(d_inode(dentry), &context, &contextlen); else err = -EOPNOTSUPP; contextsupport = (err == 0); if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { if (err == -EOPNOTSUPP) bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL; else if (err) goto out_nfserr; } } #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2); if (status) goto out; attrlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; p++; /* to be backfilled later */ if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { u32 supp[3]; memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); if (!IS_POSIXACL(dentry->d_inode)) supp[0] &= ~FATTR4_WORD0_ACL; if (!contextsupport) supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL; if (!supp[2]) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); } else { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); *p++ = cpu_to_be32(supp[2]); } } if (bmval0 & FATTR4_WORD0_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; dummy = nfs4_file_type(stat.mode); if (dummy == NF4BAD) { status = nfserr_serverfault; goto out; } *p++ = cpu_to_be32(dummy); } if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; if (exp->ex_flags & NFSEXP_NOSUBTREECHECK) *p++ = cpu_to_be32(NFS4_FH_PERSISTENT); else *p++ = cpu_to_be32(NFS4_FH_PERSISTENT| NFS4_FH_VOL_RENAME); } if (bmval0 & FATTR4_WORD0_CHANGE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = encode_change(p, &stat, d_inode(dentry), exp); } if (bmval0 & FATTR4_WORD0_SIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.size); } if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_NAMED_ATTR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_FSID) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; if (exp->ex_fslocs.migrated) { p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR); p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR); } else switch(fsid_source(fhp)) { case FSIDSOURCE_FSID: p = xdr_encode_hyper(p, (u64)exp->ex_fsid); p = xdr_encode_hyper(p, (u64)0); break; case FSIDSOURCE_DEV: *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MAJOR(stat.dev)); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MINOR(stat.dev)); break; case FSIDSOURCE_UUID: p = xdr_encode_opaque_fixed(p, exp->ex_uuid, EX_UUID_LEN); break; } } if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_LEASE_TIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(nn->nfsd4_lease); } if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(rdattr_err); } if (bmval0 & FATTR4_WORD0_ACL) { struct nfs4_ace *ace; if (acl == NULL) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); goto out_acl; } p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(acl->naces); for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) { p = xdr_reserve_space(xdr, 4*3); if (!p) goto out_resource; *p++ = cpu_to_be32(ace->type); *p++ = cpu_to_be32(ace->flag); *p++ = cpu_to_be32(ace->access_mask & NFS4_ACE_MASK_ALL); status = nfsd4_encode_aclname(xdr, rqstp, ace); if (status) goto out; } } out_acl: if (bmval0 & FATTR4_WORD0_ACLSUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ? ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0); } if (bmval0 & FATTR4_WORD0_CANSETTIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_FILEHANDLE) { p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4); if (!p) goto out_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, fhp->fh_handle.fh_size); } if (bmval0 & FATTR4_WORD0_FILEID) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.ino); } if (bmval0 & FATTR4_WORD0_FILES_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_files); } if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) { status = nfsd4_encode_fs_locations(xdr, rqstp, exp); if (status) goto out; } if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_MAXFILESIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes); } if (bmval0 & FATTR4_WORD0_MAXLINK) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(255); } if (bmval0 & FATTR4_WORD0_MAXNAME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(statfs.f_namelen); } if (bmval0 & FATTR4_WORD0_MAXREAD) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval0 & FATTR4_WORD0_MAXWRITE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval1 & FATTR4_WORD1_MODE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.mode & S_IALLUGO); } if (bmval1 & FATTR4_WORD1_NO_TRUNC) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval1 & FATTR4_WORD1_NUMLINKS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.nlink); } if (bmval1 & FATTR4_WORD1_OWNER) { status = nfsd4_encode_user(xdr, rqstp, stat.uid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_OWNER_GROUP) { status = nfsd4_encode_group(xdr, rqstp, stat.gid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_RAWDEV) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32((u32) MAJOR(stat.rdev)); *p++ = cpu_to_be32((u32) MINOR(stat.rdev)); } if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_USED) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)stat.blocks << 9; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_TIME_ACCESS) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec); *p++ = cpu_to_be32(stat.atime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_DELTA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(0); } if (bmval1 & FATTR4_WORD1_TIME_METADATA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec); *p++ = cpu_to_be32(stat.ctime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_MODIFY) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec); *p++ = cpu_to_be32(stat.mtime.tv_nsec); } if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) { struct kstat parent_stat; u64 ino = stat.ino; p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; /* * Get parent's attributes if not ignoring crossmount * and this is the root of a cross-mounted filesystem. */ if (ignore_crossmnt == 0 && dentry == exp->ex_path.mnt->mnt_root) { err = get_parent_attributes(exp, &parent_stat); if (err) goto out_nfserr; ino = parent_stat.ino; } p = xdr_encode_hyper(p, ino); } #ifdef CONFIG_NFSD_PNFS if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.blksize); } #endif /* CONFIG_NFSD_PNFS */ if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) { status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0, NFSD_SUPPATTR_EXCLCREAT_WORD1, NFSD_SUPPATTR_EXCLCREAT_WORD2); if (status) goto out; } if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { status = nfsd4_encode_security_label(xdr, rqstp, context, contextlen); if (status) goto out; } attrlen = htonl(xdr->buf->len - attrlen_offset - 4); write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4); status = nfs_ok; out: #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (context) security_release_secctx(context, contextlen); #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ kfree(acl); if (tempfh) { fh_put(tempfh); kfree(tempfh); } if (status) xdr_truncate_encode(xdr, starting_len); return status; out_nfserr: status = nfserrno(err); goto out; out_resource: status = nfserr_resource; goto out; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry, u32 *bmval, struct svc_rqst *rqstp, int ignore_crossmnt) { u32 bmval0 = bmval[0]; u32 bmval1 = bmval[1]; u32 bmval2 = bmval[2]; struct kstat stat; struct svc_fh *tempfh = NULL; struct kstatfs statfs; __be32 *p; int starting_len = xdr->buf->len; int attrlen_offset; __be32 attrlen; u32 dummy; u64 dummy64; u32 rdattr_err = 0; __be32 status; int err; struct nfs4_acl *acl = NULL; void *context = NULL; int contextlen; bool contextsupport = false; struct nfsd4_compoundres *resp = rqstp->rq_resp; u32 minorversion = resp->cstate.minorversion; struct path path = { .mnt = exp->ex_path.mnt, .dentry = dentry, }; struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id); BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1); BUG_ON(!nfsd_attrs_supported(minorversion, bmval)); if (exp->ex_fslocs.migrated) { status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err); if (status) goto out; } err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); if (err) goto out_nfserr; if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE | FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) || (bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE | FATTR4_WORD1_SPACE_TOTAL))) { err = vfs_statfs(&path, &statfs); if (err) goto out_nfserr; } if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) { tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL); status = nfserr_jukebox; if (!tempfh) goto out; fh_init(tempfh, NFS4_FHSIZE); status = fh_compose(tempfh, exp, dentry, NULL); if (status) goto out; fhp = tempfh; } if (bmval0 & FATTR4_WORD0_ACL) { err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl); if (err == -EOPNOTSUPP) bmval0 &= ~FATTR4_WORD0_ACL; else if (err == -EINVAL) { status = nfserr_attrnotsupp; goto out; } else if (err != 0) goto out_nfserr; } #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) || bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { if (exp->ex_flags & NFSEXP_SECURITY_LABEL) err = security_inode_getsecctx(d_inode(dentry), &context, &contextlen); else err = -EOPNOTSUPP; contextsupport = (err == 0); if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { if (err == -EOPNOTSUPP) bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL; else if (err) goto out_nfserr; } } #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2); if (status) goto out; attrlen_offset = xdr->buf->len; p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; p++; /* to be backfilled later */ if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) { u32 supp[3]; memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); if (!IS_POSIXACL(dentry->d_inode)) supp[0] &= ~FATTR4_WORD0_ACL; if (!contextsupport) supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL; if (!supp[2]) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(2); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); } else { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; *p++ = cpu_to_be32(3); *p++ = cpu_to_be32(supp[0]); *p++ = cpu_to_be32(supp[1]); *p++ = cpu_to_be32(supp[2]); } } if (bmval0 & FATTR4_WORD0_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; dummy = nfs4_file_type(stat.mode); if (dummy == NF4BAD) { status = nfserr_serverfault; goto out; } *p++ = cpu_to_be32(dummy); } if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; if (exp->ex_flags & NFSEXP_NOSUBTREECHECK) *p++ = cpu_to_be32(NFS4_FH_PERSISTENT); else *p++ = cpu_to_be32(NFS4_FH_PERSISTENT| NFS4_FH_VOL_RENAME); } if (bmval0 & FATTR4_WORD0_CHANGE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = encode_change(p, &stat, d_inode(dentry), exp); } if (bmval0 & FATTR4_WORD0_SIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.size); } if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_NAMED_ATTR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_FSID) { p = xdr_reserve_space(xdr, 16); if (!p) goto out_resource; if (exp->ex_fslocs.migrated) { p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR); p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR); } else switch(fsid_source(fhp)) { case FSIDSOURCE_FSID: p = xdr_encode_hyper(p, (u64)exp->ex_fsid); p = xdr_encode_hyper(p, (u64)0); break; case FSIDSOURCE_DEV: *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MAJOR(stat.dev)); *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(MINOR(stat.dev)); break; case FSIDSOURCE_UUID: p = xdr_encode_opaque_fixed(p, exp->ex_uuid, EX_UUID_LEN); break; } } if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_LEASE_TIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(nn->nfsd4_lease); } if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(rdattr_err); } if (bmval0 & FATTR4_WORD0_ACL) { struct nfs4_ace *ace; if (acl == NULL) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); goto out_acl; } p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(acl->naces); for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) { p = xdr_reserve_space(xdr, 4*3); if (!p) goto out_resource; *p++ = cpu_to_be32(ace->type); *p++ = cpu_to_be32(ace->flag); *p++ = cpu_to_be32(ace->access_mask & NFS4_ACE_MASK_ALL); status = nfsd4_encode_aclname(xdr, rqstp, ace); if (status) goto out; } } out_acl: if (bmval0 & FATTR4_WORD0_ACLSUPPORT) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ? ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0); } if (bmval0 & FATTR4_WORD0_CANSETTIME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(0); } if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_FILEHANDLE) { p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4); if (!p) goto out_resource; p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base, fhp->fh_handle.fh_size); } if (bmval0 & FATTR4_WORD0_FILEID) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, stat.ino); } if (bmval0 & FATTR4_WORD0_FILES_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_ffree); } if (bmval0 & FATTR4_WORD0_FILES_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) statfs.f_files); } if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) { status = nfsd4_encode_fs_locations(xdr, rqstp, exp); if (status) goto out; } if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval0 & FATTR4_WORD0_MAXFILESIZE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes); } if (bmval0 & FATTR4_WORD0_MAXLINK) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(255); } if (bmval0 & FATTR4_WORD0_MAXNAME) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(statfs.f_namelen); } if (bmval0 & FATTR4_WORD0_MAXREAD) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval0 & FATTR4_WORD0_MAXWRITE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp)); } if (bmval1 & FATTR4_WORD1_MODE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.mode & S_IALLUGO); } if (bmval1 & FATTR4_WORD1_NO_TRUNC) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(1); } if (bmval1 & FATTR4_WORD1_NUMLINKS) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.nlink); } if (bmval1 & FATTR4_WORD1_OWNER) { status = nfsd4_encode_user(xdr, rqstp, stat.uid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_OWNER_GROUP) { status = nfsd4_encode_group(xdr, rqstp, stat.gid); if (status) goto out; } if (bmval1 & FATTR4_WORD1_RAWDEV) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; *p++ = cpu_to_be32((u32) MAJOR(stat.rdev)); *p++ = cpu_to_be32((u32) MINOR(stat.rdev)); } if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_FREE) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_SPACE_USED) { p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; dummy64 = (u64)stat.blocks << 9; p = xdr_encode_hyper(p, dummy64); } if (bmval1 & FATTR4_WORD1_TIME_ACCESS) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec); *p++ = cpu_to_be32(stat.atime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_DELTA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; *p++ = cpu_to_be32(0); *p++ = cpu_to_be32(1); *p++ = cpu_to_be32(0); } if (bmval1 & FATTR4_WORD1_TIME_METADATA) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec); *p++ = cpu_to_be32(stat.ctime.tv_nsec); } if (bmval1 & FATTR4_WORD1_TIME_MODIFY) { p = xdr_reserve_space(xdr, 12); if (!p) goto out_resource; p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec); *p++ = cpu_to_be32(stat.mtime.tv_nsec); } if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) { struct kstat parent_stat; u64 ino = stat.ino; p = xdr_reserve_space(xdr, 8); if (!p) goto out_resource; /* * Get parent's attributes if not ignoring crossmount * and this is the root of a cross-mounted filesystem. */ if (ignore_crossmnt == 0 && dentry == exp->ex_path.mnt->mnt_root) { err = get_parent_attributes(exp, &parent_stat); if (err) goto out_nfserr; ino = parent_stat.ino; } p = xdr_encode_hyper(p, ino); } #ifdef CONFIG_NFSD_PNFS if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) { status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types); if (status) goto out; } if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) { p = xdr_reserve_space(xdr, 4); if (!p) goto out_resource; *p++ = cpu_to_be32(stat.blksize); } #endif /* CONFIG_NFSD_PNFS */ if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) { u32 supp[3]; memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); supp[0] &= NFSD_SUPPATTR_EXCLCREAT_WORD0; supp[1] &= NFSD_SUPPATTR_EXCLCREAT_WORD1; supp[2] &= NFSD_SUPPATTR_EXCLCREAT_WORD2; status = nfsd4_encode_bitmap(xdr, supp[0], supp[1], supp[2]); if (status) goto out; } if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) { status = nfsd4_encode_security_label(xdr, rqstp, context, contextlen); if (status) goto out; } attrlen = htonl(xdr->buf->len - attrlen_offset - 4); write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4); status = nfs_ok; out: #ifdef CONFIG_NFSD_V4_SECURITY_LABEL if (context) security_release_secctx(context, contextlen); #endif /* CONFIG_NFSD_V4_SECURITY_LABEL */ kfree(acl); if (tempfh) { fh_put(tempfh); kfree(tempfh); } if (status) xdr_truncate_encode(xdr, starting_len); return status; out_nfserr: status = nfserrno(err); goto out; out_resource: status = nfserr_resource; goto out; }
168,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const { return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey(); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const
174,452
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; } Commit Message: add anti "../" and leading slash protection to chmextract CWE ID: CWE-22
int main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name(f[i]->filename); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; }
169,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init init_ext2_fs(void) { int err = init_ext2_xattr(); if (err) return err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); out1: exit_ext2_xattr(); return err; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
static int __init init_ext2_fs(void) { int err; err = init_inodecache(); if (err) return err; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); return err; }
169,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController::ExtensionTtsController() : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), current_utterance_(NULL), platform_impl_(NULL) { } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController::ExtensionTtsController()
170,376
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() { return brightness_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() {
170,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::string16 GetCertificateButtonTitle() const { PageInfoBubbleView* page_info_bubble_view = static_cast<PageInfoBubbleView*>( PageInfoBubbleView::GetPageInfoBubble()); return page_info_bubble_view->certificate_button_->title()->text(); } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311
base::string16 GetCertificateButtonTitle() const {
172,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; }
164,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { H264Picture::Vector::const_reverse_iterator rit; int i; for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); H264Picture::Vector::const_reverse_iterator rit; int i; for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; }
172,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } Commit Message: Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author. CWE ID: CWE-190
static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } }
170,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_cfg) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } Commit Message: add some boundary checks on gf_text_get_utf8_line (#1188) CWE ID: CWE-787
int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_url) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; }
169,787
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
BlockEntry::Kind SimpleBlock::GetKind() const
174,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } Commit Message: Pull entity fix from upstream. BUG=107128 Review URL: http://codereview.chromium.org/9072008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116175 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); }
170,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { /* * URGENT TODO: Normally inst->psvi Should never be reserved here, * BUT: since if we include the same stylesheet from * multiple imports, then the stylesheet will be parsed * again. We simply must not try to compute the stylesheet again. * TODO: Get to the point where we don't need to query the * namespace- and local-name of the node, but can evaluate this * using cctxt->style->inode->category; */ if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || (inst->psvi != NULL)) return; if (IS_XSLT_ELEM(inst)) { xsltStylePreCompPtr cur; if (IS_XSLT_NAME(inst, "apply-templates")) { xsltCheckInstructionElement(style, inst); xsltApplyTemplatesComp(style, inst); } else if (IS_XSLT_NAME(inst, "with-param")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "call-template"); xsltWithParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "value-of")) { xsltCheckInstructionElement(style, inst); xsltValueOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy")) { xsltCheckInstructionElement(style, inst); xsltCopyComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy-of")) { xsltCheckInstructionElement(style, inst); xsltCopyOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "if")) { xsltCheckInstructionElement(style, inst); xsltIfComp(style, inst); } else if (IS_XSLT_NAME(inst, "when")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltWhenComp(style, inst); } else if (IS_XSLT_NAME(inst, "choose")) { xsltCheckInstructionElement(style, inst); xsltChooseComp(style, inst); } else if (IS_XSLT_NAME(inst, "for-each")) { xsltCheckInstructionElement(style, inst); xsltForEachComp(style, inst); } else if (IS_XSLT_NAME(inst, "apply-imports")) { xsltCheckInstructionElement(style, inst); xsltApplyImportsComp(style, inst); } else if (IS_XSLT_NAME(inst, "attribute")) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->ns == NULL) || ((parent->ns != inst->ns) && (!xmlStrEqual(parent->ns->href, inst->ns->href))) || (!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) { xsltCheckInstructionElement(style, inst); } xsltAttributeComp(style, inst); } else if (IS_XSLT_NAME(inst, "element")) { xsltCheckInstructionElement(style, inst); xsltElementComp(style, inst); } else if (IS_XSLT_NAME(inst, "text")) { xsltCheckInstructionElement(style, inst); xsltTextComp(style, inst); } else if (IS_XSLT_NAME(inst, "sort")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "for-each"); xsltSortComp(style, inst); } else if (IS_XSLT_NAME(inst, "comment")) { xsltCheckInstructionElement(style, inst); xsltCommentComp(style, inst); } else if (IS_XSLT_NAME(inst, "number")) { xsltCheckInstructionElement(style, inst); xsltNumberComp(style, inst); } else if (IS_XSLT_NAME(inst, "processing-instruction")) { xsltCheckInstructionElement(style, inst); xsltProcessingInstructionComp(style, inst); } else if (IS_XSLT_NAME(inst, "call-template")) { xsltCheckInstructionElement(style, inst); xsltCallTemplateComp(style, inst); } else if (IS_XSLT_NAME(inst, "param")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "variable")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltVariableComp(style, inst); } else if (IS_XSLT_NAME(inst, "otherwise")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "template")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "output")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "preserve-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "strip-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if ((IS_XSLT_NAME(inst, "stylesheet")) || (IS_XSLT_NAME(inst, "transform"))) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { xsltTransformError(NULL, style, inst, "element %s only allowed only as root element\n", inst->name); style->errors++; } return; } else if (IS_XSLT_NAME(inst, "key")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "message")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "attribute-set")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "namespace-alias")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "include")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "import")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "decimal-format")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "fallback")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "document")) { xsltCheckInstructionElement(style, inst); inst->psvi = (void *) xsltDocumentComp(style, inst, (xsltTransformFunction) xsltDocumentElem); } else { xsltTransformError(NULL, style, inst, "xsltStylePreCompute: unknown xsl:%s\n", inst->name); if (style != NULL) style->warnings++; } cur = (xsltStylePreCompPtr) inst->psvi; /* * A ns-list is build for every XSLT item in the * node-tree. This is needed for XPath expressions. */ if (cur != NULL) { int i = 0; cur->nsList = xmlGetNsList(inst->doc, inst); if (cur->nsList != NULL) { while (cur->nsList[i] != NULL) i++; } cur->nsNr = i; } } else { inst->psvi = (void *) xsltPreComputeExtModuleElement(style, inst); /* * Unknown element, maybe registered at the context * level. Mark it for later recognition. */ if (inst->psvi == NULL) inst->psvi = (void *) xsltExtMarker; } } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { /* * URGENT TODO: Normally inst->psvi Should never be reserved here, * BUT: since if we include the same stylesheet from * multiple imports, then the stylesheet will be parsed * again. We simply must not try to compute the stylesheet again. * TODO: Get to the point where we don't need to query the * namespace- and local-name of the node, but can evaluate this * using cctxt->style->inode->category; */ if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || (inst->psvi != NULL)) return; if (IS_XSLT_ELEM(inst)) { xsltStylePreCompPtr cur; if (IS_XSLT_NAME(inst, "apply-templates")) { xsltCheckInstructionElement(style, inst); xsltApplyTemplatesComp(style, inst); } else if (IS_XSLT_NAME(inst, "with-param")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "call-template"); xsltWithParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "value-of")) { xsltCheckInstructionElement(style, inst); xsltValueOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy")) { xsltCheckInstructionElement(style, inst); xsltCopyComp(style, inst); } else if (IS_XSLT_NAME(inst, "copy-of")) { xsltCheckInstructionElement(style, inst); xsltCopyOfComp(style, inst); } else if (IS_XSLT_NAME(inst, "if")) { xsltCheckInstructionElement(style, inst); xsltIfComp(style, inst); } else if (IS_XSLT_NAME(inst, "when")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltWhenComp(style, inst); } else if (IS_XSLT_NAME(inst, "choose")) { xsltCheckInstructionElement(style, inst); xsltChooseComp(style, inst); } else if (IS_XSLT_NAME(inst, "for-each")) { xsltCheckInstructionElement(style, inst); xsltForEachComp(style, inst); } else if (IS_XSLT_NAME(inst, "apply-imports")) { xsltCheckInstructionElement(style, inst); xsltApplyImportsComp(style, inst); } else if (IS_XSLT_NAME(inst, "attribute")) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_ELEMENT_NODE) || (parent->ns == NULL) || ((parent->ns != inst->ns) && (!xmlStrEqual(parent->ns->href, inst->ns->href))) || (!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) { xsltCheckInstructionElement(style, inst); } xsltAttributeComp(style, inst); } else if (IS_XSLT_NAME(inst, "element")) { xsltCheckInstructionElement(style, inst); xsltElementComp(style, inst); } else if (IS_XSLT_NAME(inst, "text")) { xsltCheckInstructionElement(style, inst); xsltTextComp(style, inst); } else if (IS_XSLT_NAME(inst, "sort")) { xsltCheckParentElement(style, inst, BAD_CAST "apply-templates", BAD_CAST "for-each"); xsltSortComp(style, inst); } else if (IS_XSLT_NAME(inst, "comment")) { xsltCheckInstructionElement(style, inst); xsltCommentComp(style, inst); } else if (IS_XSLT_NAME(inst, "number")) { xsltCheckInstructionElement(style, inst); xsltNumberComp(style, inst); } else if (IS_XSLT_NAME(inst, "processing-instruction")) { xsltCheckInstructionElement(style, inst); xsltProcessingInstructionComp(style, inst); } else if (IS_XSLT_NAME(inst, "call-template")) { xsltCheckInstructionElement(style, inst); xsltCallTemplateComp(style, inst); } else if (IS_XSLT_NAME(inst, "param")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltParamComp(style, inst); } else if (IS_XSLT_NAME(inst, "variable")) { if (xsltCheckTopLevelElement(style, inst, 0) == 0) xsltCheckInstructionElement(style, inst); xsltVariableComp(style, inst); } else if (IS_XSLT_NAME(inst, "otherwise")) { xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL); xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "template")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "output")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "preserve-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "strip-space")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if ((IS_XSLT_NAME(inst, "stylesheet")) || (IS_XSLT_NAME(inst, "transform"))) { xmlNodePtr parent = inst->parent; if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { xsltTransformError(NULL, style, inst, "element %s only allowed only as root element\n", inst->name); style->errors++; } return; } else if (IS_XSLT_NAME(inst, "key")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "message")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "attribute-set")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "namespace-alias")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "include")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "import")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "decimal-format")) { xsltCheckTopLevelElement(style, inst, 1); return; } else if (IS_XSLT_NAME(inst, "fallback")) { xsltCheckInstructionElement(style, inst); return; } else if (IS_XSLT_NAME(inst, "document")) { xsltCheckInstructionElement(style, inst); inst->psvi = (void *) xsltDocumentComp(style, inst, (xsltTransformFunction) xsltDocumentElem); } else { xsltTransformError(NULL, style, inst, "xsltStylePreCompute: unknown xsl:%s\n", inst->name); if (style != NULL) style->warnings++; } cur = (xsltStylePreCompPtr) inst->psvi; /* * A ns-list is build for every XSLT item in the * node-tree. This is needed for XPath expressions. */ if (cur != NULL) { int i = 0; cur->nsList = xmlGetNsList(inst->doc, inst); if (cur->nsList != NULL) { while (cur->nsList[i] != NULL) i++; } cur->nsNr = i; } } else { inst->psvi = (void *) xsltPreComputeExtModuleElement(style, inst); /* * Unknown element, maybe registered at the context * level. Mark it for later recognition. */ if (inst->psvi == NULL) inst->psvi = (void *) xsltExtMarker; } }
173,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fd_read_body (const char *downloaded_filename, int fd, FILE *out, wgint toread, wgint startpos, wgint *qtyread, wgint *qtywritten, double *elapsed, int flags, FILE *out2) { int ret = 0; #undef max #define max(a,b) ((a) > (b) ? (a) : (b)) int dlbufsize = max (BUFSIZ, 8 * 1024); char *dlbuf = xmalloc (dlbufsize); struct ptimer *timer = NULL; double last_successful_read_tm = 0; /* The progress gauge, set according to the user preferences. */ void *progress = NULL; /* Non-zero if the progress gauge is interactive, i.e. if it can continually update the display. When true, smaller timeout values are used so that the gauge can update the display when data arrives slowly. */ bool progress_interactive = false; bool exact = !!(flags & rb_read_exactly); /* Used only by HTTP/HTTPS chunked transfer encoding. */ bool chunked = flags & rb_chunked_transfer_encoding; wgint skip = 0; /* How much data we've read/written. */ wgint sum_read = 0; wgint sum_written = 0; wgint remaining_chunk_size = 0; #ifdef HAVE_LIBZ /* try to minimize the number of calls to inflate() and write_data() per call to fd_read() */ unsigned int gzbufsize = dlbufsize * 4; char *gzbuf = NULL; z_stream gzstream; if (flags & rb_compressed_gzip) { gzbuf = xmalloc (gzbufsize); if (gzbuf != NULL) { gzstream.zalloc = zalloc; gzstream.zfree = zfree; gzstream.opaque = Z_NULL; gzstream.next_in = Z_NULL; gzstream.avail_in = 0; #define GZIP_DETECT 32 /* gzip format detection */ #define GZIP_WINDOW 15 /* logarithmic window size (default: 15) */ ret = inflateInit2 (&gzstream, GZIP_DETECT | GZIP_WINDOW); if (ret != Z_OK) { xfree (gzbuf); errno = (ret == Z_MEM_ERROR) ? ENOMEM : EINVAL; ret = -1; goto out; } } else { errno = ENOMEM; ret = -1; goto out; } } #endif if (flags & rb_skip_startpos) skip = startpos; if (opt.show_progress) { const char *filename_progress; /* If we're skipping STARTPOS bytes, pass 0 as the INITIAL argument to progress_create because the indicator doesn't (yet) know about "skipping" data. */ wgint start = skip ? 0 : startpos; if (opt.dir_prefix) filename_progress = downloaded_filename + strlen (opt.dir_prefix) + 1; else filename_progress = downloaded_filename; progress = progress_create (filename_progress, start, start + toread); progress_interactive = progress_interactive_p (progress); } if (opt.limit_rate) limit_bandwidth_reset (); /* A timer is needed for tracking progress, for throttling, and for tracking elapsed time. If either of these are requested, start the timer. */ if (progress || opt.limit_rate || elapsed) { timer = ptimer_new (); last_successful_read_tm = 0; } /* Use a smaller buffer for low requested bandwidths. For example, with --limit-rate=2k, it doesn't make sense to slurp in 16K of data and then sleep for 8s. With buffer size equal to the limit, we never have to sleep for more than one second. */ if (opt.limit_rate && opt.limit_rate < dlbufsize) dlbufsize = opt.limit_rate; /* Read from FD while there is data to read. Normally toread==0 means that it is unknown how much data is to arrive. However, if EXACT is set, then toread==0 means what it says: that no data should be read. */ while (!exact || (sum_read < toread)) { int rdsize; double tmout = opt.read_timeout; if (chunked) { if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); char *endl; if (line == NULL) { ret = -1; break; } else if (out2 != NULL) fwrite (line, 1, strlen (line), out2); remaining_chunk_size = strtol (line, &endl, 16); xfree (line); if (remaining_chunk_size == 0) { ret = 0; fwrite (line, 1, strlen (line), out2); xfree (line); } break; } } rdsize = MIN (remaining_chunk_size, dlbufsize); } else rdsize = exact ? MIN (toread - sum_read, dlbufsize) : dlbufsize; if (progress_interactive) { /* For interactive progress gauges, always specify a ~1s timeout, so that the gauge can be updated regularly even when the data arrives very slowly or stalls. */ tmout = 0.95; if (opt.read_timeout) { double waittm; waittm = ptimer_read (timer) - last_successful_read_tm; if (waittm + tmout > opt.read_timeout) { /* Don't let total idle time exceed read timeout. */ tmout = opt.read_timeout - waittm; if (tmout < 0) { /* We've already exceeded the timeout. */ ret = -1, errno = ETIMEDOUT; break; } } } } ret = fd_read (fd, dlbuf, rdsize, tmout); if (progress_interactive && ret < 0 && errno == ETIMEDOUT) ret = 0; /* interactive timeout, handled above */ else if (ret <= 0) break; /* EOF or read error */ if (progress || opt.limit_rate || elapsed) { ptimer_measure (timer); if (ret > 0) last_successful_read_tm = ptimer_read (timer); } if (ret > 0) { int write_res; sum_read += ret; #ifdef HAVE_LIBZ if (gzbuf != NULL) { int err; int towrite; gzstream.avail_in = ret; gzstream.next_in = (unsigned char *) dlbuf; do { gzstream.avail_out = gzbufsize; gzstream.next_out = (unsigned char *) gzbuf; err = inflate (&gzstream, Z_NO_FLUSH); switch (err) { case Z_MEM_ERROR: errno = ENOMEM; ret = -1; goto out; case Z_NEED_DICT: case Z_DATA_ERROR: errno = EINVAL; ret = -1; goto out; case Z_STREAM_END: if (exact && sum_read != toread) { DEBUGP(("zlib stream ended unexpectedly after " "%ld/%ld bytes\n", sum_read, toread)); } } towrite = gzbufsize - gzstream.avail_out; write_res = write_data (out, out2, gzbuf, towrite, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } while (gzstream.avail_out == 0); } else #endif { write_res = write_data (out, out2, dlbuf, ret, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } if (chunked) { remaining_chunk_size -= ret; if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); if (line == NULL) { ret = -1; break; } else { if (out2 != NULL) fwrite (line, 1, strlen (line), out2); xfree (line); } } } } if (opt.limit_rate) limit_bandwidth (ret, timer); if (progress) progress_update (progress, ret, ptimer_read (timer)); #ifdef WINDOWS if (toread > 0 && opt.show_progress) ws_percenttitle (100.0 * (startpos + sum_read) / (startpos + toread)); #endif } Commit Message: CWE ID: CWE-119
fd_read_body (const char *downloaded_filename, int fd, FILE *out, wgint toread, wgint startpos, wgint *qtyread, wgint *qtywritten, double *elapsed, int flags, FILE *out2) { int ret = 0; #undef max #define max(a,b) ((a) > (b) ? (a) : (b)) int dlbufsize = max (BUFSIZ, 8 * 1024); char *dlbuf = xmalloc (dlbufsize); struct ptimer *timer = NULL; double last_successful_read_tm = 0; /* The progress gauge, set according to the user preferences. */ void *progress = NULL; /* Non-zero if the progress gauge is interactive, i.e. if it can continually update the display. When true, smaller timeout values are used so that the gauge can update the display when data arrives slowly. */ bool progress_interactive = false; bool exact = !!(flags & rb_read_exactly); /* Used only by HTTP/HTTPS chunked transfer encoding. */ bool chunked = flags & rb_chunked_transfer_encoding; wgint skip = 0; /* How much data we've read/written. */ wgint sum_read = 0; wgint sum_written = 0; wgint remaining_chunk_size = 0; #ifdef HAVE_LIBZ /* try to minimize the number of calls to inflate() and write_data() per call to fd_read() */ unsigned int gzbufsize = dlbufsize * 4; char *gzbuf = NULL; z_stream gzstream; if (flags & rb_compressed_gzip) { gzbuf = xmalloc (gzbufsize); if (gzbuf != NULL) { gzstream.zalloc = zalloc; gzstream.zfree = zfree; gzstream.opaque = Z_NULL; gzstream.next_in = Z_NULL; gzstream.avail_in = 0; #define GZIP_DETECT 32 /* gzip format detection */ #define GZIP_WINDOW 15 /* logarithmic window size (default: 15) */ ret = inflateInit2 (&gzstream, GZIP_DETECT | GZIP_WINDOW); if (ret != Z_OK) { xfree (gzbuf); errno = (ret == Z_MEM_ERROR) ? ENOMEM : EINVAL; ret = -1; goto out; } } else { errno = ENOMEM; ret = -1; goto out; } } #endif if (flags & rb_skip_startpos) skip = startpos; if (opt.show_progress) { const char *filename_progress; /* If we're skipping STARTPOS bytes, pass 0 as the INITIAL argument to progress_create because the indicator doesn't (yet) know about "skipping" data. */ wgint start = skip ? 0 : startpos; if (opt.dir_prefix) filename_progress = downloaded_filename + strlen (opt.dir_prefix) + 1; else filename_progress = downloaded_filename; progress = progress_create (filename_progress, start, start + toread); progress_interactive = progress_interactive_p (progress); } if (opt.limit_rate) limit_bandwidth_reset (); /* A timer is needed for tracking progress, for throttling, and for tracking elapsed time. If either of these are requested, start the timer. */ if (progress || opt.limit_rate || elapsed) { timer = ptimer_new (); last_successful_read_tm = 0; } /* Use a smaller buffer for low requested bandwidths. For example, with --limit-rate=2k, it doesn't make sense to slurp in 16K of data and then sleep for 8s. With buffer size equal to the limit, we never have to sleep for more than one second. */ if (opt.limit_rate && opt.limit_rate < dlbufsize) dlbufsize = opt.limit_rate; /* Read from FD while there is data to read. Normally toread==0 means that it is unknown how much data is to arrive. However, if EXACT is set, then toread==0 means what it says: that no data should be read. */ while (!exact || (sum_read < toread)) { int rdsize; double tmout = opt.read_timeout; if (chunked) { if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); char *endl; if (line == NULL) { ret = -1; break; } else if (out2 != NULL) fwrite (line, 1, strlen (line), out2); remaining_chunk_size = strtol (line, &endl, 16); xfree (line); if (remaining_chunk_size < 0) { ret = -1; break; } if (remaining_chunk_size == 0) { ret = 0; fwrite (line, 1, strlen (line), out2); xfree (line); } break; } } rdsize = MIN (remaining_chunk_size, dlbufsize); } else rdsize = exact ? MIN (toread - sum_read, dlbufsize) : dlbufsize; if (progress_interactive) { /* For interactive progress gauges, always specify a ~1s timeout, so that the gauge can be updated regularly even when the data arrives very slowly or stalls. */ tmout = 0.95; if (opt.read_timeout) { double waittm; waittm = ptimer_read (timer) - last_successful_read_tm; if (waittm + tmout > opt.read_timeout) { /* Don't let total idle time exceed read timeout. */ tmout = opt.read_timeout - waittm; if (tmout < 0) { /* We've already exceeded the timeout. */ ret = -1, errno = ETIMEDOUT; break; } } } } ret = fd_read (fd, dlbuf, rdsize, tmout); if (progress_interactive && ret < 0 && errno == ETIMEDOUT) ret = 0; /* interactive timeout, handled above */ else if (ret <= 0) break; /* EOF or read error */ if (progress || opt.limit_rate || elapsed) { ptimer_measure (timer); if (ret > 0) last_successful_read_tm = ptimer_read (timer); } if (ret > 0) { int write_res; sum_read += ret; #ifdef HAVE_LIBZ if (gzbuf != NULL) { int err; int towrite; gzstream.avail_in = ret; gzstream.next_in = (unsigned char *) dlbuf; do { gzstream.avail_out = gzbufsize; gzstream.next_out = (unsigned char *) gzbuf; err = inflate (&gzstream, Z_NO_FLUSH); switch (err) { case Z_MEM_ERROR: errno = ENOMEM; ret = -1; goto out; case Z_NEED_DICT: case Z_DATA_ERROR: errno = EINVAL; ret = -1; goto out; case Z_STREAM_END: if (exact && sum_read != toread) { DEBUGP(("zlib stream ended unexpectedly after " "%ld/%ld bytes\n", sum_read, toread)); } } towrite = gzbufsize - gzstream.avail_out; write_res = write_data (out, out2, gzbuf, towrite, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } while (gzstream.avail_out == 0); } else #endif { write_res = write_data (out, out2, dlbuf, ret, &skip, &sum_written); if (write_res < 0) { ret = (write_res == -3) ? -3 : -2; goto out; } } if (chunked) { remaining_chunk_size -= ret; if (remaining_chunk_size == 0) { char *line = fd_read_line (fd); if (line == NULL) { ret = -1; break; } else { if (out2 != NULL) fwrite (line, 1, strlen (line), out2); xfree (line); } } } } if (opt.limit_rate) limit_bandwidth (ret, timer); if (progress) progress_update (progress, ret, ptimer_read (timer)); #ifdef WINDOWS if (toread > 0 && opt.show_progress) ws_percenttitle (100.0 * (startpos + sum_read) / (startpos + toread)); #endif }
164,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; } Commit Message: CWE ID: CWE-476
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score || crl_score == 0) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score && best_crl != NULL) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; }
164,940
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = " "; char buf[L_BUF_SIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = "xtractprotos"; if (argc == 1) { fprintf(stderr, "xtractprotos [-prestring=<string>] [-protos=<where>] " "[list of C files]\n" "where the prestring is prepended to each prototype, and \n" "protos can be either 'inline' or the name of an output " "prototype file\n"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], "-prestring", 10)) { nflags++; ret = sscanf(argv[i] + 1, "prestring=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for prestring\n"); return 1; } if ((len = strlen(buf)) > L_BUF_SIZE - 3) { L_WARNING("prestring too large; omitting!\n", mainName); } else { buf[len] = ' '; buf[len + 1] = '\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], "-protos", 7)) { nflags++; ret = sscanf(argv[i] + 1, "protos=%s", buf); if (ret != 1) { fprintf(stderr, "parse failure for protos\n"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, "inline", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, "no files specified!\n"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"/*", L_COPY); snprintf(buf, L_BUF_SIZE, " * These prototypes were autogen'd by xtractprotos, v. %s", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)" */", L_COPY); sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, "failure to make a writeable temp file\n"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, "cpp failure for %s; continuing\n", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, "parse failure for %s; continuing\n", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"}", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, "%s\n", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, "No protos found\n"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile("allheaders_top.txt"); if (!in_line) { snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, "w", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile("allheaders_bot.txt"); l_byteaJoin(ba, &ba2); l_byteaWrite("allheaders.h", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
int main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = " "; char buf[L_BUFSIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = "xtractprotos"; if (argc == 1) { fprintf(stderr, "xtractprotos [-prestring=<string>] [-protos=<where>] " "[list of C files]\n" "where the prestring is prepended to each prototype, and \n" "protos can be either 'inline' or the name of an output " "prototype file\n"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], "-prestring", 10)) { nflags++; ret = sscanf(argv[i] + 1, "prestring=%490s", buf); if (ret != 1) { fprintf(stderr, "parse failure for prestring\n"); return 1; } if ((len = strlen(buf)) > L_BUFSIZE - 3) { L_WARNING("prestring too large; omitting!\n", mainName); } else { buf[len] = ' '; buf[len + 1] = '\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], "-protos", 7)) { nflags++; ret = sscanf(argv[i] + 1, "protos=%490s", buf); if (ret != 1) { fprintf(stderr, "parse failure for protos\n"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, "inline", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, "no files specified!\n"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"/*", L_COPY); snprintf(buf, L_BUFSIZE, " * These prototypes were autogen'd by xtractprotos, v. %s", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)" */", L_COPY); sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, "failure to make a writeable temp file\n"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUFSIZE, "cpp -ansi -DNO_PROTOS %s %s", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, "cpp failure for %s; continuing\n", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, "parse failure for %s; continuing\n", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY); sarrayAddString(sa, (char *)"}", L_COPY); sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, "%s\n", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, "No protos found\n"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile("allheaders_top.txt"); if (!in_line) { snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, "w", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile("allheaders_bot.txt"); l_byteaJoin(ba, &ba2); l_byteaWrite("allheaders.h", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; }
169,322
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t nr) { const unsigned char *b = buf; DECLARE_WAITQUEUE(wait, current); int c; ssize_t retval = 0; /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */ if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) { retval = tty_check_change(tty); if (retval) return retval; } down_read(&tty->termios_rwsem); /* Write out any echoed characters that are still pending */ process_echoes(tty); add_wait_queue(&tty->write_wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) { retval = -ERESTARTSYS; break; } if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) { retval = -EIO; break; } if (O_OPOST(tty)) { while (nr > 0) { ssize_t num = process_output_block(tty, b, nr); if (num < 0) { if (num == -EAGAIN) break; retval = num; goto break_out; } b += num; nr -= num; if (nr == 0) break; c = *b; if (process_output(c, tty) < 0) break; b++; nr--; } if (tty->ops->flush_chars) tty->ops->flush_chars(tty); } else { while (nr > 0) { c = tty->ops->write(tty, b, nr); if (c < 0) { retval = c; goto break_out; } if (!c) break; b += c; nr -= c; } } if (!nr) break; if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } up_read(&tty->termios_rwsem); schedule(); down_read(&tty->termios_rwsem); } break_out: __set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (b - buf != nr && tty->fasync) set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); up_read(&tty->termios_rwsem); return (b - buf) ? b - buf : retval; } Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Jiri Slaby <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Alan Cox <[email protected]> Cc: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362
static ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t nr) { const unsigned char *b = buf; DECLARE_WAITQUEUE(wait, current); int c; ssize_t retval = 0; /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */ if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) { retval = tty_check_change(tty); if (retval) return retval; } down_read(&tty->termios_rwsem); /* Write out any echoed characters that are still pending */ process_echoes(tty); add_wait_queue(&tty->write_wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) { retval = -ERESTARTSYS; break; } if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) { retval = -EIO; break; } if (O_OPOST(tty)) { while (nr > 0) { ssize_t num = process_output_block(tty, b, nr); if (num < 0) { if (num == -EAGAIN) break; retval = num; goto break_out; } b += num; nr -= num; if (nr == 0) break; c = *b; if (process_output(c, tty) < 0) break; b++; nr--; } if (tty->ops->flush_chars) tty->ops->flush_chars(tty); } else { struct n_tty_data *ldata = tty->disc_data; while (nr > 0) { mutex_lock(&ldata->output_lock); c = tty->ops->write(tty, b, nr); mutex_unlock(&ldata->output_lock); if (c < 0) { retval = c; goto break_out; } if (!c) break; b += c; nr -= c; } } if (!nr) break; if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } up_read(&tty->termios_rwsem); schedule(); down_read(&tty->termios_rwsem); } break_out: __set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (b - buf != nr && tty->fasync) set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); up_read(&tty->termios_rwsem); return (b - buf) ? b - buf : retval; }
166,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScrollHitTestDisplayItem::ScrollHitTestDisplayItem( const DisplayItemClient& client, Type type, scoped_refptr<const TransformPaintPropertyNode> scroll_offset_node) : DisplayItem(client, type, sizeof(*this)), scroll_offset_node_(std::move(scroll_offset_node)) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); DCHECK(IsScrollHitTestType(type)); DCHECK(scroll_offset_node_->ScrollNode()); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
ScrollHitTestDisplayItem::ScrollHitTestDisplayItem( const DisplayItemClient& client, Type type, const TransformPaintPropertyNode& scroll_offset_node) : DisplayItem(client, type, sizeof(*this)), scroll_offset_node_(scroll_offset_node) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); DCHECK(IsScrollHitTestType(type)); DCHECK(scroll_offset_node_.ScrollNode()); }
171,842
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gamma_component_validate(PNG_CONST char *name, PNG_CONST validate_info *vi, PNG_CONST unsigned int id, PNG_CONST unsigned int od, PNG_CONST double alpha /* <0 for the alpha channel itself */, PNG_CONST double background /* component background value */) { PNG_CONST unsigned int isbit = id >> vi->isbit_shift; PNG_CONST unsigned int sbit_max = vi->sbit_max; PNG_CONST unsigned int outmax = vi->outmax; PNG_CONST int do_background = vi->do_background; double i; /* First check on the 'perfect' result obtained from the digitized input * value, id, and compare this against the actual digitized result, 'od'. * 'i' is the input result in the range 0..1: */ i = isbit; i /= sbit_max; /* Check for the fast route: if we don't do any background composition or if * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then * just use the gamma_correction field to correct to the final output gamma. */ if (alpha == 1 /* opaque pixel component */ || !do_background #ifdef PNG_READ_ALPHA_MODE_SUPPORTED || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG #endif || (alpha < 0 /* alpha channel */ #ifdef PNG_READ_ALPHA_MODE_SUPPORTED && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN #endif )) { /* Then get the gamma corrected version of 'i' and compare to 'od', any * error less than .5 is insignificant - just quantization of the output * value to the nearest digital value (nevertheless the error is still * recorded - it's interesting ;-) */ double encoded_sample = i; double encoded_error; /* alpha less than 0 indicates the alpha channel, which is always linear */ if (alpha >= 0 && vi->gamma_correction > 0) encoded_sample = pow(encoded_sample, vi->gamma_correction); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); if (encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total && encoded_error < vi->outlog) return i; } /* The slow route - attempt to do linear calculations. */ /* There may be an error, or background processing is required, so calculate * the actual sample values - unencoded light intensity values. Note that in * practice these are not completely unencoded because they include a * 'viewing correction' to decrease or (normally) increase the perceptual * contrast of the image. There's nothing we can do about this - we don't * know what it is - so assume the unencoded value is perceptually linear. */ { double input_sample = i; /* In range 0..1 */ double output, error, encoded_sample, encoded_error; double es_lo, es_hi; int compose = 0; /* Set to one if composition done */ int output_is_encoded; /* Set if encoded to screen gamma */ int log_max_error = 1; /* Check maximum error values */ png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */ /* Convert to linear light (with the above caveat.) The alpha channel is * already linear. */ if (alpha >= 0) { int tcompose; if (vi->file_inverse > 0) input_sample = pow(input_sample, vi->file_inverse); /* Handle the compose processing: */ tcompose = 0; input_sample = gamma_component_compose(do_background, input_sample, alpha, background, &tcompose); if (tcompose) compose = 1; } /* And similarly for the output value, but we need to check the background * handling to linearize it correctly. */ output = od; output /= outmax; output_is_encoded = vi->screen_gamma > 0; if (alpha < 0) /* The alpha channel */ { #ifdef PNG_READ_ALPHA_MODE_SUPPORTED if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN) #endif { /* In all other cases the output alpha channel is linear already, * don't log errors here, they are much larger in linear data. */ output_is_encoded = 0; log_max_error = 0; } } #ifdef PNG_READ_ALPHA_MODE_SUPPORTED else /* A component */ { if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED && alpha < 1) /* the optimized case - linear output */ { if (alpha > 0) log_max_error = 0; output_is_encoded = 0; } } #endif if (output_is_encoded) output = pow(output, vi->screen_gamma); /* Calculate (or recalculate) the encoded_sample value and repeat the * check above (unnecessary if we took the fast route, but harmless.) */ encoded_sample = input_sample; if (output_is_encoded) encoded_sample = pow(encoded_sample, vi->screen_inverse); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); /* Don't log errors in the alpha channel, or the 'optimized' case, * neither are significant to the overall perception. */ if (log_max_error && encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total) { if (encoded_error < vi->outlog) return i; /* Test passed but error is bigger than the log limit, record why the * test passed: */ pass = "less than maxout:\n"; } /* i: the original input value in the range 0..1 * * pngvalid calculations: * input_sample: linear result; i linearized and composed, range 0..1 * encoded_sample: encoded result; input_sample scaled to ouput bit depth * * libpng calculations: * output: linear result; od scaled to 0..1 and linearized * od: encoded result from libpng */ /* Now we have the numbers for real errors, both absolute values as as a * percentage of the correct value (output): */ error = fabs(input_sample-output); if (log_max_error && error > vi->dp->maxerrabs) vi->dp->maxerrabs = error; /* The following is an attempt to ignore the tendency of quantization to * dominate the percentage errors for lower result values: */ if (log_max_error && input_sample > .5) { double percentage_error = error/input_sample; if (percentage_error > vi->dp->maxerrpc) vi->dp->maxerrpc = percentage_error; } /* Now calculate the digitization limits for 'encoded_sample' using the * 'max' values. Note that maxout is in the encoded space but maxpc and * maxabs are in linear light space. * * First find the maximum error in linear light space, range 0..1: */ { double tmp = input_sample * vi->maxpc; if (tmp < vi->maxabs) tmp = vi->maxabs; /* If 'compose' is true the composition was done in linear space using * integer arithmetic. This introduces an extra error of +/- 0.5 (at * least) in the integer space used. 'maxcalc' records this, taking * into account the possibility that even for 16 bit output 8 bit space * may have been used. */ if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc; /* The 'maxout' value refers to the encoded result, to compare with * this encode input_sample adjusted by the maximum error (tmp) above. */ es_lo = encoded_sample - vi->maxout; if (es_lo > 0 && input_sample-tmp > 0) { double low_value = input_sample-tmp; if (output_is_encoded) low_value = pow(low_value, vi->screen_inverse); low_value *= outmax; if (low_value < es_lo) es_lo = low_value; /* Quantize this appropriately: */ es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant; } else es_lo = 0; es_hi = encoded_sample + vi->maxout; if (es_hi < outmax && input_sample+tmp < 1) { double high_value = input_sample+tmp; if (output_is_encoded) high_value = pow(high_value, vi->screen_inverse); high_value *= outmax; if (high_value > es_hi) es_hi = high_value; es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant; } else es_hi = outmax; } /* The primary test is that the final encoded value returned by the * library should be between the two limits (inclusive) that were * calculated above. */ if (od >= es_lo && od <= es_hi) { /* The value passes, but we may need to log the information anyway. */ if (encoded_error < vi->outlog) return i; if (pass == 0) pass = "within digitization limits:\n"; } { /* There has been an error in processing, or we need to log this * value. */ double is_lo, is_hi; /* pass is set at this point if either of the tests above would have * passed. Don't do these additional tests here - just log the * original [es_lo..es_hi] values. */ if (pass == 0 && vi->use_input_precision && vi->dp->sbit) { /* Ok, something is wrong - this actually happens in current libpng * 16-to-8 processing. Assume that the input value (id, adjusted * for sbit) can be anywhere between value-.5 and value+.5 - quite a * large range if sbit is low. * * NOTE: at present because the libpng gamma table stuff has been * changed to use a rounding algorithm to correct errors in 8-bit * calculations the precise sbit calculation (a shift) has been * lost. This can result in up to a +/-1 error in the presence of * an sbit less than the bit depth. */ # if PNG_LIBPNG_VER < 10700 # define SBIT_ERROR .5 # else # define SBIT_ERROR 1. # endif double tmp = (isbit - SBIT_ERROR)/sbit_max; if (tmp <= 0) tmp = 0; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; tmp = (isbit + SBIT_ERROR)/sbit_max; if (tmp >= 1) tmp = 1; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within input precision limits:\n"; } /* One last chance. If this is an alpha channel and the 16to8 * option has been used and 'inaccurate' scaling is used then the * bit reduction is obtained by simply using the top 8 bits of the * value. * * This is only done for older libpng versions when the 'inaccurate' * (chop) method of scaling was used. */ # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER < 10504 /* This may be required for other components in the future, * but at present the presence of gamma correction effectively * prevents the errors in the component scaling (I don't quite * understand why, but since it's better this way I care not * to ask, JB 20110419.) */ if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 && vi->sbit + vi->isbit_shift == 16) { tmp = ((id >> 8) - .5)/255; if (tmp > 0) { is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; } else is_lo = 0; tmp = ((id >> 8) + .5)/255; if (tmp < 1) { is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; } else is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within 8 bit limits:\n"; } } # endif # endif } else /* !use_input_precision */ is_lo = es_lo, is_hi = es_hi; /* Attempt to output a meaningful error/warning message: the message * output depends on the background/composite operation being performed * because this changes what parameters were actually used above. */ { size_t pos = 0; /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal * places. Just use outmax to work out which. */ int precision = (outmax >= 1000 ? 6 : 3); int use_input=1, use_background=0, do_compose=0; char msg[256]; if (pass != 0) pos = safecat(msg, sizeof msg, pos, "\n\t"); /* Set up the various flags, the output_is_encoded flag above * is also used below. do_compose is just a double check. */ switch (do_background) { # ifdef PNG_READ_BACKGROUND_SUPPORTED case PNG_BACKGROUND_GAMMA_SCREEN: case PNG_BACKGROUND_GAMMA_FILE: case PNG_BACKGROUND_GAMMA_UNIQUE: use_background = (alpha >= 0 && alpha < 1); /*FALL THROUGH*/ # endif # ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: # endif /* ALPHA_MODE_SUPPORTED */ do_compose = (alpha > 0 && alpha < 1); use_input = (alpha != 0); break; default: break; } /* Check the 'compose' flag */ if (compose != do_compose) png_error(vi->pp, "internal error (compose)"); /* 'name' is the component name */ pos = safecat(msg, sizeof msg, pos, name); pos = safecat(msg, sizeof msg, pos, "("); pos = safecatn(msg, sizeof msg, pos, id); if (use_input || pass != 0/*logging*/) { if (isbit != id) { /* sBIT has reduced the precision of the input: */ pos = safecat(msg, sizeof msg, pos, ", sbit("); pos = safecatn(msg, sizeof msg, pos, vi->sbit); pos = safecat(msg, sizeof msg, pos, "): "); pos = safecatn(msg, sizeof msg, pos, isbit); } pos = safecat(msg, sizeof msg, pos, "/"); /* The output is either "id/max" or "id sbit(sbit): isbit/max" */ pos = safecatn(msg, sizeof msg, pos, vi->sbit_max); } pos = safecat(msg, sizeof msg, pos, ")"); /* A component may have been multiplied (in linear space) by the * alpha value, 'compose' says whether this is relevant. */ if (compose || pass != 0) { /* If any form of composition is being done report our * calculated linear value here (the code above doesn't record * the input value before composition is performed, so what * gets reported is the value after composition.) */ if (use_input || pass != 0) { if (vi->file_inverse > 0) { pos = safecat(msg, sizeof msg, pos, "^"); pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2); } else pos = safecat(msg, sizeof msg, pos, "[linear]"); pos = safecat(msg, sizeof msg, pos, "*(alpha)"); pos = safecatd(msg, sizeof msg, pos, alpha, precision); } /* Now record the *linear* background value if it was used * (this function is not passed the original, non-linear, * value but it is contained in the test name.) */ if (use_background) { pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " "); pos = safecat(msg, sizeof msg, pos, "(background)"); pos = safecatd(msg, sizeof msg, pos, background, precision); pos = safecat(msg, sizeof msg, pos, "*"); pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision); } } /* Report the calculated value (input_sample) and the linearized * libpng value (output) unless this is just a component gamma * correction. */ if (compose || alpha < 0 || pass != 0) { pos = safecat(msg, sizeof msg, pos, pass != 0 ? " =\n\t" : " = "); pos = safecatd(msg, sizeof msg, pos, input_sample, precision); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatd(msg, sizeof msg, pos, output, precision); pos = safecat(msg, sizeof msg, pos, ")"); /* Finally report the output gamma encoding, if any. */ if (output_is_encoded) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2); pos = safecat(msg, sizeof msg, pos, "(to screen) ="); } else pos = safecat(msg, sizeof msg, pos, " [screen is linear] ="); } if ((!compose && alpha >= 0) || pass != 0) { if (pass != 0) /* logging */ pos = safecat(msg, sizeof msg, pos, "\n\t[overall:"); /* This is the non-composition case, the internal linear * values are irrelevant (though the log below will reveal * them.) Output a much shorter warning/error message and report * the overall gamma correction. */ if (vi->gamma_correction > 0) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2); pos = safecat(msg, sizeof msg, pos, "(gamma correction) ="); } else pos = safecat(msg, sizeof msg, pos, " [no gamma correction] ="); if (pass != 0) pos = safecat(msg, sizeof msg, pos, "]"); } /* This is our calculated encoded_sample which should (but does * not) match od: */ pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " "); pos = safecatd(msg, sizeof msg, pos, is_lo, 1); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatn(msg, sizeof msg, pos, od); pos = safecat(msg, sizeof msg, pos, ")"); pos = safecat(msg, sizeof msg, pos, "/"); pos = safecatn(msg, sizeof msg, pos, outmax); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, is_hi, 1); if (pass == 0) /* The error condition */ { # ifdef PNG_WARNINGS_SUPPORTED png_warning(vi->pp, msg); # else store_warning(vi->pp, msg); # endif } else /* logging this value */ store_verbose(&vi->dp->pm->this, vi->pp, pass, msg); } } } return i; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
gamma_component_validate(PNG_CONST char *name, PNG_CONST validate_info *vi, gamma_component_validate(const char *name, const validate_info *vi, const unsigned int id, const unsigned int od, const double alpha /* <0 for the alpha channel itself */, const double background /* component background value */) { const unsigned int isbit = id >> vi->isbit_shift; const unsigned int sbit_max = vi->sbit_max; const unsigned int outmax = vi->outmax; const int do_background = vi->do_background; double i; /* First check on the 'perfect' result obtained from the digitized input * value, id, and compare this against the actual digitized result, 'od'. * 'i' is the input result in the range 0..1: */ i = isbit; i /= sbit_max; /* Check for the fast route: if we don't do any background composition or if * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then * just use the gamma_correction field to correct to the final output gamma. */ if (alpha == 1 /* opaque pixel component */ || !do_background #ifdef PNG_READ_ALPHA_MODE_SUPPORTED || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG #endif || (alpha < 0 /* alpha channel */ #ifdef PNG_READ_ALPHA_MODE_SUPPORTED && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN #endif )) { /* Then get the gamma corrected version of 'i' and compare to 'od', any * error less than .5 is insignificant - just quantization of the output * value to the nearest digital value (nevertheless the error is still * recorded - it's interesting ;-) */ double encoded_sample = i; double encoded_error; /* alpha less than 0 indicates the alpha channel, which is always linear */ if (alpha >= 0 && vi->gamma_correction > 0) encoded_sample = pow(encoded_sample, vi->gamma_correction); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); if (encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total && encoded_error < vi->outlog) return i; } /* The slow route - attempt to do linear calculations. */ /* There may be an error, or background processing is required, so calculate * the actual sample values - unencoded light intensity values. Note that in * practice these are not completely unencoded because they include a * 'viewing correction' to decrease or (normally) increase the perceptual * contrast of the image. There's nothing we can do about this - we don't * know what it is - so assume the unencoded value is perceptually linear. */ { double input_sample = i; /* In range 0..1 */ double output, error, encoded_sample, encoded_error; double es_lo, es_hi; int compose = 0; /* Set to one if composition done */ int output_is_encoded; /* Set if encoded to screen gamma */ int log_max_error = 1; /* Check maximum error values */ png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */ /* Convert to linear light (with the above caveat.) The alpha channel is * already linear. */ if (alpha >= 0) { int tcompose; if (vi->file_inverse > 0) input_sample = pow(input_sample, vi->file_inverse); /* Handle the compose processing: */ tcompose = 0; input_sample = gamma_component_compose(do_background, input_sample, alpha, background, &tcompose); if (tcompose) compose = 1; } /* And similarly for the output value, but we need to check the background * handling to linearize it correctly. */ output = od; output /= outmax; output_is_encoded = vi->screen_gamma > 0; if (alpha < 0) /* The alpha channel */ { #ifdef PNG_READ_ALPHA_MODE_SUPPORTED if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN) #endif { /* In all other cases the output alpha channel is linear already, * don't log errors here, they are much larger in linear data. */ output_is_encoded = 0; log_max_error = 0; } } #ifdef PNG_READ_ALPHA_MODE_SUPPORTED else /* A component */ { if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED && alpha < 1) /* the optimized case - linear output */ { if (alpha > 0) log_max_error = 0; output_is_encoded = 0; } } #endif if (output_is_encoded) output = pow(output, vi->screen_gamma); /* Calculate (or recalculate) the encoded_sample value and repeat the * check above (unnecessary if we took the fast route, but harmless.) */ encoded_sample = input_sample; if (output_is_encoded) encoded_sample = pow(encoded_sample, vi->screen_inverse); encoded_sample *= outmax; encoded_error = fabs(od-encoded_sample); /* Don't log errors in the alpha channel, or the 'optimized' case, * neither are significant to the overall perception. */ if (log_max_error && encoded_error > vi->dp->maxerrout) vi->dp->maxerrout = encoded_error; if (encoded_error < vi->maxout_total) { if (encoded_error < vi->outlog) return i; /* Test passed but error is bigger than the log limit, record why the * test passed: */ pass = "less than maxout:\n"; } /* i: the original input value in the range 0..1 * * pngvalid calculations: * input_sample: linear result; i linearized and composed, range 0..1 * encoded_sample: encoded result; input_sample scaled to ouput bit depth * * libpng calculations: * output: linear result; od scaled to 0..1 and linearized * od: encoded result from libpng */ /* Now we have the numbers for real errors, both absolute values as as a * percentage of the correct value (output): */ error = fabs(input_sample-output); if (log_max_error && error > vi->dp->maxerrabs) vi->dp->maxerrabs = error; /* The following is an attempt to ignore the tendency of quantization to * dominate the percentage errors for lower result values: */ if (log_max_error && input_sample > .5) { double percentage_error = error/input_sample; if (percentage_error > vi->dp->maxerrpc) vi->dp->maxerrpc = percentage_error; } /* Now calculate the digitization limits for 'encoded_sample' using the * 'max' values. Note that maxout is in the encoded space but maxpc and * maxabs are in linear light space. * * First find the maximum error in linear light space, range 0..1: */ { double tmp = input_sample * vi->maxpc; if (tmp < vi->maxabs) tmp = vi->maxabs; /* If 'compose' is true the composition was done in linear space using * integer arithmetic. This introduces an extra error of +/- 0.5 (at * least) in the integer space used. 'maxcalc' records this, taking * into account the possibility that even for 16 bit output 8 bit space * may have been used. */ if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc; /* The 'maxout' value refers to the encoded result, to compare with * this encode input_sample adjusted by the maximum error (tmp) above. */ es_lo = encoded_sample - vi->maxout; if (es_lo > 0 && input_sample-tmp > 0) { double low_value = input_sample-tmp; if (output_is_encoded) low_value = pow(low_value, vi->screen_inverse); low_value *= outmax; if (low_value < es_lo) es_lo = low_value; /* Quantize this appropriately: */ es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant; } else es_lo = 0; es_hi = encoded_sample + vi->maxout; if (es_hi < outmax && input_sample+tmp < 1) { double high_value = input_sample+tmp; if (output_is_encoded) high_value = pow(high_value, vi->screen_inverse); high_value *= outmax; if (high_value > es_hi) es_hi = high_value; es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant; } else es_hi = outmax; } /* The primary test is that the final encoded value returned by the * library should be between the two limits (inclusive) that were * calculated above. */ if (od >= es_lo && od <= es_hi) { /* The value passes, but we may need to log the information anyway. */ if (encoded_error < vi->outlog) return i; if (pass == 0) pass = "within digitization limits:\n"; } { /* There has been an error in processing, or we need to log this * value. */ double is_lo, is_hi; /* pass is set at this point if either of the tests above would have * passed. Don't do these additional tests here - just log the * original [es_lo..es_hi] values. */ if (pass == 0 && vi->use_input_precision && vi->dp->sbit) { /* Ok, something is wrong - this actually happens in current libpng * 16-to-8 processing. Assume that the input value (id, adjusted * for sbit) can be anywhere between value-.5 and value+.5 - quite a * large range if sbit is low. * * NOTE: at present because the libpng gamma table stuff has been * changed to use a rounding algorithm to correct errors in 8-bit * calculations the precise sbit calculation (a shift) has been * lost. This can result in up to a +/-1 error in the presence of * an sbit less than the bit depth. */ # if PNG_LIBPNG_VER < 10700 # define SBIT_ERROR .5 # else # define SBIT_ERROR 1. # endif double tmp = (isbit - SBIT_ERROR)/sbit_max; if (tmp <= 0) tmp = 0; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; tmp = (isbit + SBIT_ERROR)/sbit_max; if (tmp >= 1) tmp = 1; else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1) tmp = pow(tmp, vi->file_inverse); tmp = gamma_component_compose(do_background, tmp, alpha, background, NULL); if (output_is_encoded && tmp > 0 && tmp < 1) tmp = pow(tmp, vi->screen_inverse); is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within input precision limits:\n"; } /* One last chance. If this is an alpha channel and the 16to8 * option has been used and 'inaccurate' scaling is used then the * bit reduction is obtained by simply using the top 8 bits of the * value. * * This is only done for older libpng versions when the 'inaccurate' * (chop) method of scaling was used. */ # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER < 10504 /* This may be required for other components in the future, * but at present the presence of gamma correction effectively * prevents the errors in the component scaling (I don't quite * understand why, but since it's better this way I care not * to ask, JB 20110419.) */ if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 && vi->sbit + vi->isbit_shift == 16) { tmp = ((id >> 8) - .5)/255; if (tmp > 0) { is_lo = ceil(outmax * tmp - vi->maxout_total); if (is_lo < 0) is_lo = 0; } else is_lo = 0; tmp = ((id >> 8) + .5)/255; if (tmp < 1) { is_hi = floor(outmax * tmp + vi->maxout_total); if (is_hi > outmax) is_hi = outmax; } else is_hi = outmax; if (!(od < is_lo || od > is_hi)) { if (encoded_error < vi->outlog) return i; pass = "within 8 bit limits:\n"; } } # endif # endif } else /* !use_input_precision */ is_lo = es_lo, is_hi = es_hi; /* Attempt to output a meaningful error/warning message: the message * output depends on the background/composite operation being performed * because this changes what parameters were actually used above. */ { size_t pos = 0; /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal * places. Just use outmax to work out which. */ int precision = (outmax >= 1000 ? 6 : 3); int use_input=1, use_background=0, do_compose=0; char msg[256]; if (pass != 0) pos = safecat(msg, sizeof msg, pos, "\n\t"); /* Set up the various flags, the output_is_encoded flag above * is also used below. do_compose is just a double check. */ switch (do_background) { # ifdef PNG_READ_BACKGROUND_SUPPORTED case PNG_BACKGROUND_GAMMA_SCREEN: case PNG_BACKGROUND_GAMMA_FILE: case PNG_BACKGROUND_GAMMA_UNIQUE: use_background = (alpha >= 0 && alpha < 1); /*FALL THROUGH*/ # endif # ifdef PNG_READ_ALPHA_MODE_SUPPORTED case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD: case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN: case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED: # endif /* ALPHA_MODE_SUPPORTED */ do_compose = (alpha > 0 && alpha < 1); use_input = (alpha != 0); break; default: break; } /* Check the 'compose' flag */ if (compose != do_compose) png_error(vi->pp, "internal error (compose)"); /* 'name' is the component name */ pos = safecat(msg, sizeof msg, pos, name); pos = safecat(msg, sizeof msg, pos, "("); pos = safecatn(msg, sizeof msg, pos, id); if (use_input || pass != 0/*logging*/) { if (isbit != id) { /* sBIT has reduced the precision of the input: */ pos = safecat(msg, sizeof msg, pos, ", sbit("); pos = safecatn(msg, sizeof msg, pos, vi->sbit); pos = safecat(msg, sizeof msg, pos, "): "); pos = safecatn(msg, sizeof msg, pos, isbit); } pos = safecat(msg, sizeof msg, pos, "/"); /* The output is either "id/max" or "id sbit(sbit): isbit/max" */ pos = safecatn(msg, sizeof msg, pos, vi->sbit_max); } pos = safecat(msg, sizeof msg, pos, ")"); /* A component may have been multiplied (in linear space) by the * alpha value, 'compose' says whether this is relevant. */ if (compose || pass != 0) { /* If any form of composition is being done report our * calculated linear value here (the code above doesn't record * the input value before composition is performed, so what * gets reported is the value after composition.) */ if (use_input || pass != 0) { if (vi->file_inverse > 0) { pos = safecat(msg, sizeof msg, pos, "^"); pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2); } else pos = safecat(msg, sizeof msg, pos, "[linear]"); pos = safecat(msg, sizeof msg, pos, "*(alpha)"); pos = safecatd(msg, sizeof msg, pos, alpha, precision); } /* Now record the *linear* background value if it was used * (this function is not passed the original, non-linear, * value but it is contained in the test name.) */ if (use_background) { pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " "); pos = safecat(msg, sizeof msg, pos, "(background)"); pos = safecatd(msg, sizeof msg, pos, background, precision); pos = safecat(msg, sizeof msg, pos, "*"); pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision); } } /* Report the calculated value (input_sample) and the linearized * libpng value (output) unless this is just a component gamma * correction. */ if (compose || alpha < 0 || pass != 0) { pos = safecat(msg, sizeof msg, pos, pass != 0 ? " =\n\t" : " = "); pos = safecatd(msg, sizeof msg, pos, input_sample, precision); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatd(msg, sizeof msg, pos, output, precision); pos = safecat(msg, sizeof msg, pos, ")"); /* Finally report the output gamma encoding, if any. */ if (output_is_encoded) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2); pos = safecat(msg, sizeof msg, pos, "(to screen) ="); } else pos = safecat(msg, sizeof msg, pos, " [screen is linear] ="); } if ((!compose && alpha >= 0) || pass != 0) { if (pass != 0) /* logging */ pos = safecat(msg, sizeof msg, pos, "\n\t[overall:"); /* This is the non-composition case, the internal linear * values are irrelevant (though the log below will reveal * them.) Output a much shorter warning/error message and report * the overall gamma correction. */ if (vi->gamma_correction > 0) { pos = safecat(msg, sizeof msg, pos, " ^"); pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2); pos = safecat(msg, sizeof msg, pos, "(gamma correction) ="); } else pos = safecat(msg, sizeof msg, pos, " [no gamma correction] ="); if (pass != 0) pos = safecat(msg, sizeof msg, pos, "]"); } /* This is our calculated encoded_sample which should (but does * not) match od: */ pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " "); pos = safecatd(msg, sizeof msg, pos, is_lo, 1); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1); pos = safecat(msg, sizeof msg, pos, " (libpng: "); pos = safecatn(msg, sizeof msg, pos, od); pos = safecat(msg, sizeof msg, pos, ")"); pos = safecat(msg, sizeof msg, pos, "/"); pos = safecatn(msg, sizeof msg, pos, outmax); pos = safecat(msg, sizeof msg, pos, " < "); pos = safecatd(msg, sizeof msg, pos, is_hi, 1); if (pass == 0) /* The error condition */ { # ifdef PNG_WARNINGS_SUPPORTED png_warning(vi->pp, msg); # else store_warning(vi->pp, msg); # endif } else /* logging this value */ store_verbose(&vi->dp->pm->this, vi->pp, pass, msg); } } } return i; }
173,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; } Commit Message: CWE ID: CWE-787
static void esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); assert (s->cmdlen <= sizeof(s->cmdbuf) && len <= sizeof(s->cmdbuf) - s->cmdlen); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; }
164,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Horizontal_Sweep_Span( RAS_ARGS Short y, FT_F26Dot6 x1, FT_F26Dot6 x2, PProfile left, PProfile right ) { FT_UNUSED( left ); FT_UNUSED( right ); if ( x2 - x1 < ras.precision ) { Long e1, e2; e1 = CEILING( x1 ); e2 = FLOOR ( x2 ); if ( e1 == e2 ) { Byte f1; PByte bits; bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); e1 = TRUNC( e1 ); if ( e1 >= 0 && e1 < ras.target.rows ) { PByte p; p = bits - e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) p += ( ras.target.rows - 1 ) * ras.target.pitch; p[0] |= f1; } } } } Commit Message: CWE ID: CWE-119
Horizontal_Sweep_Span( RAS_ARGS Short y, FT_F26Dot6 x1, FT_F26Dot6 x2, PProfile left, PProfile right ) { FT_UNUSED( left ); FT_UNUSED( right ); if ( x2 - x1 < ras.precision ) { Long e1, e2; e1 = CEILING( x1 ); e2 = FLOOR ( x2 ); if ( e1 == e2 ) { Byte f1; PByte bits; bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); e1 = TRUNC( e1 ); if ( e1 >= 0 && (ULong)e1 < ras.target.rows ) { PByte p; p = bits - e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) p += ( ras.target.rows - 1 ) * ras.target.pitch; p[0] |= f1; } } } }
164,853
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GDataEntry* GDataFile::FromDocumentEntry( GDataDirectory* parent, DocumentEntry* doc, GDataDirectoryService* directory_service) { DCHECK(doc->is_hosted_document() || doc->is_file()); GDataFile* file = new GDataFile(parent, directory_service); file->title_ = UTF16ToUTF8(doc->title()); if (doc->is_file()) { file->file_info_.size = doc->file_size(); file->file_md5_ = doc->file_md5(); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_EDIT_MEDIA); if (upload_link) file->upload_url_ = upload_link->href(); } else { file->document_extension_ = doc->GetHostedDocumentExtension(); file->file_info_.size = 0; } file->kind_ = doc->kind(); const Link* edit_link = doc->GetLinkByType(Link::EDIT); if (edit_link) file->edit_url_ = edit_link->href(); file->content_url_ = doc->content_url(); file->content_mime_type_ = doc->content_mime_type(); file->resource_id_ = doc->resource_id(); file->is_hosted_document_ = doc->is_hosted_document(); file->file_info_.last_modified = doc->updated_time(); file->file_info_.last_accessed = doc->updated_time(); file->file_info_.creation_time = doc->published_time(); file->deleted_ = doc->deleted(); const Link* parent_link = doc->GetLinkByType(Link::PARENT); if (parent_link) file->parent_resource_id_ = ExtractResourceId(parent_link->href()); file->SetBaseNameFromTitle(); const Link* thumbnail_link = doc->GetLinkByType(Link::THUMBNAIL); if (thumbnail_link) file->thumbnail_url_ = thumbnail_link->href(); const Link* alternate_link = doc->GetLinkByType(Link::ALTERNATE); if (alternate_link) file->alternate_url_ = alternate_link->href(); return file; } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GDataEntry* GDataFile::FromDocumentEntry( void GDataFile::InitFromDocumentEntry(DocumentEntry* doc) { GDataEntry::InitFromDocumentEntry(doc); if (doc->is_file()) { file_info_.size = doc->file_size(); file_md5_ = doc->file_md5(); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_EDIT_MEDIA); if (upload_link) upload_url_ = upload_link->href(); } else { document_extension_ = doc->GetHostedDocumentExtension(); file_info_.size = 0; } kind_ = doc->kind(); content_mime_type_ = doc->content_mime_type(); is_hosted_document_ = doc->is_hosted_document(); SetBaseNameFromTitle(); const Link* thumbnail_link = doc->GetLinkByType(Link::THUMBNAIL); if (thumbnail_link) thumbnail_url_ = thumbnail_link->href(); const Link* alternate_link = doc->GetLinkByType(Link::ALTERNATE); if (alternate_link) alternate_url_ = alternate_link->href(); }
171,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } Commit Message: fix #6872 CWE ID: CWE-476
static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } if (p4 <= 0) { return; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); }
168,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } Commit Message: a-a-i-d-to-abrt-cache: make own random temporary directory The set-user-ID wrapper must use own new temporary directory in order to avoid security issues with unpacking specially crafted debuginfo packages that might be used to create files or symlinks anywhere on the file system as the abrt user. Withot the forking code the temporary directory would remain on the filesystem in the case where all debuginfo data are already available. This is caused by the fact that the underlying libreport functionality accepts path to a desired temporary directory and creates it only if necessary. Otherwise, the directory is not touched at all. This commit addresses CVE-2015-5273 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59
int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } char tmp_directory[] = LARGE_DATA_TMP_DIR"/abrt-tmp-debuginfo.XXXXXX"; if (mkdtemp(tmp_directory) == NULL) perror_msg_and_die("Failed to create working directory"); log_info("Created working directory: %s", tmp_directory); /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, -t, PATH, --, NULL */ const char *args[13]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--tmpdir"; args[i++] = tmp_directory; args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } pid_t pid = fork(); if (pid < 0) perror_msg_and_die("fork"); if (pid == 0) { execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } int status; if (safe_waitpid(pid, &status, 0) < 0) perror_msg_and_die("waitpid"); if (rmdir(tmp_directory) >= 0) log_info("Removed working directory: %s", tmp_directory); else if (errno != ENOENT) perror_msg("Failed to remove working directory"); /* Normal execution should exit here. */ if (WIFEXITED(status)) return WEXITSTATUS(status); if (WIFSIGNALED(status)) error_msg_and_die("Child terminated with signal %d", WTERMSIG(status)); error_msg_and_die("Child exit failed"); }
166,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_venc::component_deinit(OMX_IN OMX_HANDLETYPE hComp) { (void) hComp; OMX_U32 i = 0; DEBUG_PRINT_HIGH("omx_venc(): Inside component_deinit()"); if (OMX_StateLoaded != m_state) { DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\ m_state); } if (m_out_mem_ptr) { DEBUG_PRINT_LOW("Freeing the Output Memory"); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++ ) { free_output_buffer (&m_out_mem_ptr[i]); } free(m_out_mem_ptr); m_out_mem_ptr = NULL; } /*Check if the input buffers have to be cleaned up*/ if (m_inp_mem_ptr #ifdef _ANDROID_ICS_ && !meta_mode_enable #endif ) { DEBUG_PRINT_LOW("Freeing the Input Memory"); for (i=0; i<m_sInPortDef.nBufferCountActual; i++ ) { free_input_buffer (&m_inp_mem_ptr[i]); } free(m_inp_mem_ptr); m_inp_mem_ptr = NULL; } m_ftb_q.m_size=0; m_cmd_q.m_size=0; m_etb_q.m_size=0; m_ftb_q.m_read = m_ftb_q.m_write =0; m_cmd_q.m_read = m_cmd_q.m_write =0; m_etb_q.m_read = m_etb_q.m_write =0; #ifdef _ANDROID_ DEBUG_PRINT_HIGH("Calling m_heap_ptr.clear()"); m_heap_ptr.clear(); #endif // _ANDROID_ DEBUG_PRINT_HIGH("Calling venc_close()"); if (handle) { handle->venc_close(); DEBUG_PRINT_HIGH("Deleting HANDLE[%p]", handle); delete (handle); handle = NULL; } DEBUG_PRINT_INFO("Component Deinit"); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Add safety checks to free only as many buffers were allocated. Fixes: Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVenc problem) Bug: 27532497 Change-Id: I31e576ef9dc542df73aa6b0ea113d72724b50fc6 CWE ID: CWE-119
OMX_ERRORTYPE omx_venc::component_deinit(OMX_IN OMX_HANDLETYPE hComp) { (void) hComp; OMX_U32 i = 0; DEBUG_PRINT_HIGH("omx_venc(): Inside component_deinit()"); if (OMX_StateLoaded != m_state) { DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\ m_state); } if (m_out_mem_ptr) { DEBUG_PRINT_LOW("Freeing the Output Memory"); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++ ) { if (BITMASK_PRESENT(&m_out_bm_count, i)) { BITMASK_CLEAR(&m_out_bm_count, i); free_output_buffer (&m_out_mem_ptr[i]); } if (release_output_done()) { break; } } free(m_out_mem_ptr); m_out_mem_ptr = NULL; } /*Check if the input buffers have to be cleaned up*/ if (m_inp_mem_ptr #ifdef _ANDROID_ICS_ && !meta_mode_enable #endif ) { DEBUG_PRINT_LOW("Freeing the Input Memory"); for (i=0; i<m_sInPortDef.nBufferCountActual; i++ ) { if (BITMASK_PRESENT(&m_inp_bm_count, i)) { BITMASK_CLEAR(&m_inp_bm_count, i); free_input_buffer (&m_inp_mem_ptr[i]); } if (release_input_done()) { break; } } free(m_inp_mem_ptr); m_inp_mem_ptr = NULL; } m_ftb_q.m_size=0; m_cmd_q.m_size=0; m_etb_q.m_size=0; m_ftb_q.m_read = m_ftb_q.m_write =0; m_cmd_q.m_read = m_cmd_q.m_write =0; m_etb_q.m_read = m_etb_q.m_write =0; #ifdef _ANDROID_ DEBUG_PRINT_HIGH("Calling m_heap_ptr.clear()"); m_heap_ptr.clear(); #endif // _ANDROID_ DEBUG_PRINT_HIGH("Calling venc_close()"); if (handle) { handle->venc_close(); DEBUG_PRINT_HIGH("Deleting HANDLE[%p]", handle); delete (handle); handle = NULL; } DEBUG_PRINT_INFO("Component Deinit"); return OMX_ErrorNone; }
173,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: magic_getparam(struct magic_set *ms, int param, void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: *(size_t *)val = ms->indir_max; return 0; case MAGIC_PARAM_NAME_MAX: *(size_t *)val = ms->name_max; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: *(size_t *)val = ms->elf_phnum_max; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: *(size_t *)val = ms->elf_shnum_max; return 0; default: errno = EINVAL; return -1; } } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
magic_getparam(struct magic_set *ms, int param, void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: *(size_t *)val = ms->indir_max; return 0; case MAGIC_PARAM_NAME_MAX: *(size_t *)val = ms->name_max; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: *(size_t *)val = ms->elf_phnum_max; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: *(size_t *)val = ms->elf_shnum_max; return 0; case MAGIC_PARAM_ELF_NOTES_MAX: *(size_t *)val = ms->elf_notes_max; return 0; default: errno = EINVAL; return -1; } }
166,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (target == GL_PROGRAM_COMPLETION_QUERY_CHROMIUM) { linking_program_service_id_ = 0u; } if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; }
172,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_set_sec_context_option( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; ret = gss_set_sec_context_option(minor_status, context_handle, desired_object, value); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_set_sec_context_option( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)*context_handle; /* There are no SPNEGO-specific OIDs for this function, and we cannot * construct an empty SPNEGO context with it. */ if (sc == NULL || sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_UNAVAILABLE); ret = gss_set_sec_context_option(minor_status, &sc->ctx_handle, desired_object, value); return (ret); }
166,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind( &CoordinatorImpl::OnChromeMemoryDumpResponse, base::Unretained(this)); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, base::Unretained(this), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, base::Unretained(this), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, base::Unretained(this), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, base::Unretained(this), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind(&CoordinatorImpl::OnChromeMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr()); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr(), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, weak_ptr_factory_.GetWeakPtr(), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); }
173,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cms_copy_content(BIO *out, BIO *in, unsigned int flags) { unsigned char buf[4096]; int r = 0, i; BIO *tmpout = NULL; if (out == NULL) tmpout = BIO_new(BIO_s_null()); else if (flags & CMS_TEXT) { tmpout = BIO_new(BIO_s_mem()); BIO_set_mem_eof_return(tmpout, 0); } else tmpout = out; if(!tmpout) { CMSerr(CMS_F_CMS_COPY_CONTENT,ERR_R_MALLOC_FAILURE); goto err; } /* Read all content through chain to process digest, decrypt etc */ for (;;) { i=BIO_read(in,buf,sizeof(buf)); if (i <= 0) { if (BIO_method_type(in) == BIO_TYPE_CIPHER) { if (!BIO_get_cipher_status(in)) goto err; } if (i < 0) goto err; break; } if (tmpout && (BIO_write(tmpout, buf, i) != i)) goto err; } if(flags & CMS_TEXT) { if(!SMIME_text(tmpout, out)) { CMSerr(CMS_F_CMS_COPY_CONTENT,CMS_R_SMIME_TEXT_ERROR); goto err; } } r = 1; err: if (tmpout && (tmpout != out)) BIO_free(tmpout); return r; } Commit Message: Canonicalise input in CMS_verify. If content is detached and not binary mode translate the input to CRLF format. Before this change the input was verified verbatim which lead to a discrepancy between sign and verify. CWE ID: CWE-399
static int cms_copy_content(BIO *out, BIO *in, unsigned int flags) static BIO *cms_get_text_bio(BIO *out, unsigned int flags) { BIO *rbio; if (out == NULL) rbio = BIO_new(BIO_s_null()); else if (flags & CMS_TEXT) { rbio = BIO_new(BIO_s_mem()); BIO_set_mem_eof_return(rbio, 0); } else rbio = out; return rbio; } static int cms_copy_content(BIO *out, BIO *in, unsigned int flags) { unsigned char buf[4096]; int r = 0, i; BIO *tmpout; tmpout = cms_get_text_bio(out, flags); if(!tmpout) { CMSerr(CMS_F_CMS_COPY_CONTENT,ERR_R_MALLOC_FAILURE); goto err; } /* Read all content through chain to process digest, decrypt etc */ for (;;) { i=BIO_read(in,buf,sizeof(buf)); if (i <= 0) { if (BIO_method_type(in) == BIO_TYPE_CIPHER) { if (!BIO_get_cipher_status(in)) goto err; } if (i < 0) goto err; break; } if (tmpout && (BIO_write(tmpout, buf, i) != i)) goto err; } if(flags & CMS_TEXT) { if(!SMIME_text(tmpout, out)) { CMSerr(CMS_F_CMS_COPY_CONTENT,CMS_R_SMIME_TEXT_ERROR); goto err; } } r = 1; err: if (tmpout && (tmpout != out)) BIO_free(tmpout); return r; }
166,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, 1, &sample, regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, &sample, regs); }
165,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t hash_str(const void *ptr) { const char *str = (const char *)ptr; size_t hash = 5381; size_t c; while((c = (size_t)*str)) { hash = ((hash << 5) + hash) + c; str++; } return hash; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static size_t hash_str(const void *ptr) extern volatile uint32_t hashtable_seed; /* Implementation of the hash function */ #include "lookup3.h"
166,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint8_t* input() const { return input_ + BorderTop() * kOuterBlockSize + BorderLeft(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
uint8_t* input() const { uint8_t *input() const { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { return input_ + BorderTop() * kOuterBlockSize + BorderLeft(); } else { return CONVERT_TO_BYTEPTR(input16_ + BorderTop() * kOuterBlockSize + BorderLeft()); } #else return input_ + BorderTop() * kOuterBlockSize + BorderLeft(); #endif }
174,510
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: verify_client_san(krb5_context context, pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_const_principal client, int *valid_san) { krb5_error_code retval; krb5_principal *princs = NULL; krb5_principal *upns = NULL; int i; #ifdef DEBUG_SAN_INFO char *client_string = NULL, *san_string; #endif *valid_san = 0; retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &princs, plgctx->opts->allow_upn ? &upns : NULL, NULL); if (retval == ENOENT) { TRACE_PKINIT_SERVER_NO_SAN(context); goto out; } else if (retval) { pkiDebug("%s: error from retrieve_certificate_sans()\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } /* XXX Verify this is consistent with client side XXX */ #if 0 retval = call_san_checking_plugins(context, plgctx, reqctx, princs, upns, NULL, &plugin_decision, &ignore); pkiDebug("%s: call_san_checking_plugins() returned retval %d\n", __FUNCTION__); if (retval) { retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } pkiDebug("%s: call_san_checking_plugins() returned decision %d\n", __FUNCTION__, plugin_decision); if (plugin_decision != NO_DECISION) { retval = plugin_decision; goto out; } #endif #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, client, &client_string); #endif pkiDebug("%s: Checking pkinit sans\n", __FUNCTION__); for (i = 0; princs != NULL && princs[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, princs[i], &san_string); pkiDebug("%s: Comparing client '%s' to pkinit san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, princs[i])) { TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no pkinit san match found\n", __FUNCTION__); /* * XXX if cert has names but none match, should we * be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here? */ if (upns == NULL) { pkiDebug("%s: no upn sans (or we wouldn't accept them anyway)\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } pkiDebug("%s: Checking upn sans\n", __FUNCTION__); for (i = 0; upns[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, upns[i], &san_string); pkiDebug("%s: Comparing client '%s' to upn san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, upns[i])) { TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no upn san match found\n", __FUNCTION__); /* We found no match */ if (princs != NULL || upns != NULL) { *valid_san = 0; /* XXX ??? If there was one or more name in the cert, but * none matched the client name, then return mismatch? */ retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; } retval = 0; out: if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } #ifdef DEBUG_SAN_INFO if (client_string != NULL) krb5_free_unparsed_name(context, client_string); #endif pkiDebug("%s: returning retval %d, valid_san %d\n", __FUNCTION__, retval, *valid_san); return retval; } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 CWE ID: CWE-287
verify_client_san(krb5_context context, pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_const_principal client, int *valid_san) { krb5_error_code retval; krb5_principal *princs = NULL; krb5_principal *upns = NULL; int i; #ifdef DEBUG_SAN_INFO char *client_string = NULL, *san_string; #endif *valid_san = 0; retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &princs, plgctx->opts->allow_upn ? &upns : NULL, NULL); if (retval) { pkiDebug("%s: error from retrieve_certificate_sans()\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } if (princs == NULL && upns == NULL) { TRACE_PKINIT_SERVER_NO_SAN(context); retval = ENOENT; goto out; } /* XXX Verify this is consistent with client side XXX */ #if 0 retval = call_san_checking_plugins(context, plgctx, reqctx, princs, upns, NULL, &plugin_decision, &ignore); pkiDebug("%s: call_san_checking_plugins() returned retval %d\n", __FUNCTION__); if (retval) { retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } pkiDebug("%s: call_san_checking_plugins() returned decision %d\n", __FUNCTION__, plugin_decision); if (plugin_decision != NO_DECISION) { retval = plugin_decision; goto out; } #endif #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, client, &client_string); #endif pkiDebug("%s: Checking pkinit sans\n", __FUNCTION__); for (i = 0; princs != NULL && princs[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, princs[i], &san_string); pkiDebug("%s: Comparing client '%s' to pkinit san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, princs[i])) { TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no pkinit san match found\n", __FUNCTION__); /* * XXX if cert has names but none match, should we * be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here? */ if (upns == NULL) { pkiDebug("%s: no upn sans (or we wouldn't accept them anyway)\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } pkiDebug("%s: Checking upn sans\n", __FUNCTION__); for (i = 0; upns[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, upns[i], &san_string); pkiDebug("%s: Comparing client '%s' to upn san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, upns[i])) { TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no upn san match found\n", __FUNCTION__); /* We found no match */ if (princs != NULL || upns != NULL) { *valid_san = 0; /* XXX ??? If there was one or more name in the cert, but * none matched the client name, then return mismatch? */ retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; } retval = 0; out: if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } #ifdef DEBUG_SAN_INFO if (client_string != NULL) krb5_free_unparsed_name(context, client_string); #endif pkiDebug("%s: returning retval %d, valid_san %d\n", __FUNCTION__, retval, *valid_san); return retval; }
170,175
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tap_if_up(const char *devname, const bt_bdaddr_t *addr) { struct ifreq ifr; int sk, err; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1); err = ioctl(sk, SIOCGIFHWADDR, &ifr); if (err < 0) { BTIF_TRACE_ERROR("Could not get network hardware for interface:%s, errno:%s", devname, strerror(errno)); close(sk); return -1; } strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1); memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6); /* The IEEE has specified that the most significant bit of the most significant byte is used to * determine a multicast address. If its a 1, that means multicast, 0 means unicast. * Kernel returns an error if we try to set a multicast address for the tun-tap ethernet interface. * Mask this bit to avoid any issue with auto generated address. */ if (ifr.ifr_hwaddr.sa_data[0] & 0x01) { BTIF_TRACE_WARNING("Not a unicast MAC address, force multicast bit flipping"); ifr.ifr_hwaddr.sa_data[0] &= ~0x01; } err = ioctl(sk, SIOCSIFHWADDR, (caddr_t)&ifr); if (err < 0) { BTIF_TRACE_ERROR("Could not set bt address for interface:%s, errno:%s", devname, strerror(errno)); close(sk); return -1; } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags |= IFF_UP; ifr.ifr_flags |= IFF_MULTICAST; err = ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); if (err < 0) { BTIF_TRACE_ERROR("Could not bring up network interface:%s, errno:%d", devname, errno); close(sk); return -1; } close(sk); BTIF_TRACE_DEBUG("network interface: %s is up", devname); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int tap_if_up(const char *devname, const bt_bdaddr_t *addr) { struct ifreq ifr; int sk, err; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1); err = TEMP_FAILURE_RETRY(ioctl(sk, SIOCGIFHWADDR, &ifr)); if (err < 0) { BTIF_TRACE_ERROR("Could not get network hardware for interface:%s, errno:%s", devname, strerror(errno)); close(sk); return -1; } strncpy(ifr.ifr_name, devname, IFNAMSIZ - 1); memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6); /* The IEEE has specified that the most significant bit of the most significant byte is used to * determine a multicast address. If its a 1, that means multicast, 0 means unicast. * Kernel returns an error if we try to set a multicast address for the tun-tap ethernet interface. * Mask this bit to avoid any issue with auto generated address. */ if (ifr.ifr_hwaddr.sa_data[0] & 0x01) { BTIF_TRACE_WARNING("Not a unicast MAC address, force multicast bit flipping"); ifr.ifr_hwaddr.sa_data[0] &= ~0x01; } err = TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFHWADDR, (caddr_t)&ifr)); if (err < 0) { BTIF_TRACE_ERROR("Could not set bt address for interface:%s, errno:%s", devname, strerror(errno)); close(sk); return -1; } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags |= IFF_UP; ifr.ifr_flags |= IFF_MULTICAST; err = TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr)); if (err < 0) { BTIF_TRACE_ERROR("Could not bring up network interface:%s, errno:%d", devname, errno); close(sk); return -1; } close(sk); BTIF_TRACE_DEBUG("network interface: %s is up", devname); return 0; }
173,449
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_string( cJSON *item, const char *str ) { const char *ptr = str + 1; char *ptr2; char *out; int len = 0; unsigned uc, uc2; if ( *str != '\"' ) { /* Not a string! */ ep = str; return 0; } /* Skip escaped quotes. */ while ( *ptr != '\"' && *ptr && ++len ) if ( *ptr++ == '\\' ) ptr++; if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) ) return 0; ptr = str + 1; ptr2 = out; while ( *ptr != '\"' && *ptr ) { if ( *ptr != '\\' ) *ptr2++ = *ptr++; else { ptr++; switch ( *ptr ) { case 'b': *ptr2++ ='\b'; break; case 'f': *ptr2++ ='\f'; break; case 'n': *ptr2++ ='\n'; break; case 'r': *ptr2++ ='\r'; break; case 't': *ptr2++ ='\t'; break; case 'u': /* Transcode utf16 to utf8. */ /* Get the unicode char. */ sscanf( ptr + 1,"%4x", &uc ); ptr += 4; /* Check for invalid. */ if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 ) break; /* UTF16 surrogate pairs. */ if ( uc >= 0xD800 && uc <= 0xDBFF ) { if ( ptr[1] != '\\' || ptr[2] != 'u' ) /* Missing second-half of surrogate. */ break; sscanf( ptr + 3, "%4x", &uc2 ); ptr += 6; if ( uc2 < 0xDC00 || uc2 > 0xDFFF ) /* Invalid second-half of surrogate. */ break; uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF ); } len = 4; if ( uc < 0x80 ) len = 1; else if ( uc < 0x800 ) len = 2; else if ( uc < 0x10000 ) len = 3; ptr2 += len; switch ( len ) { case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 1: *--ptr2 = ( uc | firstByteMark[len] ); } ptr2 += len; break; default: *ptr2++ = *ptr; break; } ++ptr; } } *ptr2 = 0; if ( *ptr == '\"' ) ++ptr; item->valuestring = out; item->type = cJSON_String; return ptr; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static const char *parse_string( cJSON *item, const char *str ) static const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; return ptr; }
167,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DeleteSymlink(const FilePath& file_path) { const bool deleted = HANDLE_EINTR(unlink(file_path.value().c_str())) == 0; return deleted; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool DeleteSymlink(const FilePath& file_path) {
170,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Track::GetNext(const BlockEntry* pCurrEntry, const BlockEntry*& pNextEntry) const { assert(pCurrEntry); assert(!pCurrEntry->EOS()); //? const Block* const pCurrBlock = pCurrEntry->GetBlock(); assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) return -1; const Cluster* pCluster = pCurrEntry->GetCluster(); assert(pCluster); assert(!pCluster->EOS()); long status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; for (int i = 0;;) { while (pNextEntry) { const Block* const pNextBlock = pNextEntry->GetBlock(); assert(pNextBlock); if (pNextBlock->GetTrackNumber() == m_info.number) return 0; pCurrEntry = pNextEntry; status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; } pCluster = m_pSegment->GetNext(pCluster); if (pCluster == NULL) { pNextEntry = GetEOS(); return 1; } if (pCluster->EOS()) { #if 0 if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded { pNextEntry = GetEOS(); return 1; } #else if (m_pSegment->DoneParsing()) { pNextEntry = GetEOS(); return 1; } #endif pNextEntry = NULL; return E_BUFFER_NOT_FULL; } status = pCluster->GetFirst(pNextEntry); if (status < 0) // error return status; if (pNextEntry == NULL) // empty cluster continue; ++i; if (i >= 100) break; } pNextEntry = GetEOS(); // so we can return a non-NULL value return 1; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Track::GetNext(const BlockEntry* pCurrEntry, const BlockEntry*& pNextEntry) const { assert(pCurrEntry); assert(!pCurrEntry->EOS()); //? const Block* const pCurrBlock = pCurrEntry->GetBlock(); assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) return -1; const Cluster* pCluster = pCurrEntry->GetCluster(); assert(pCluster); assert(!pCluster->EOS()); long status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; for (int i = 0;;) { while (pNextEntry) { const Block* const pNextBlock = pNextEntry->GetBlock(); assert(pNextBlock); if (pNextBlock->GetTrackNumber() == m_info.number) return 0; pCurrEntry = pNextEntry; status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; } pCluster = m_pSegment->GetNext(pCluster); if (pCluster == NULL) { pNextEntry = GetEOS(); return 1; } if (pCluster->EOS()) { if (m_pSegment->DoneParsing()) { pNextEntry = GetEOS(); return 1; } pNextEntry = NULL; return E_BUFFER_NOT_FULL; } status = pCluster->GetFirst(pNextEntry); if (status < 0) // error return status; if (pNextEntry == NULL) // empty cluster continue; ++i; if (i >= 100) break; } pNextEntry = GetEOS(); // so we can return a non-NULL value return 1; }
173,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXResQueryResourceBytes (ClientPtr client) { REQUEST(xXResQueryResourceBytesReq); int rc; ConstructResourceBytesCtx ctx; REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq); REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq, stuff->numSpecs * sizeof(ctx.specs[0])); (void*) ((char*) stuff + sz_xXResQueryResourceBytesReq))) { return BadAlloc; } rc = ConstructResourceBytes(stuff->client, &ctx); if (rc == Success) { xXResQueryResourceBytesReply rep = { .type = X_Reply, .sequenceNumber = client->sequence, .length = bytes_to_int32(ctx.resultBytes), .numSizes = ctx.numSizes }; if (client->swapped) { swaps (&rep.sequenceNumber); swapl (&rep.length); swapl (&rep.numSizes); SwapXResQueryResourceBytes(&ctx.response); } WriteToClient(client, sizeof(rep), &rep); WriteFragmentsToClient(client, &ctx.response); } DestroyConstructResourceBytesCtx(&ctx); return rc; } Commit Message: CWE ID: CWE-20
ProcXResQueryResourceBytes (ClientPtr client) { REQUEST(xXResQueryResourceBytesReq); int rc; ConstructResourceBytesCtx ctx; REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq); if (stuff->numSpecs > UINT32_MAX / sizeof(ctx.specs[0])) return BadLength; REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq, stuff->numSpecs * sizeof(ctx.specs[0])); (void*) ((char*) stuff + sz_xXResQueryResourceBytesReq))) { return BadAlloc; } rc = ConstructResourceBytes(stuff->client, &ctx); if (rc == Success) { xXResQueryResourceBytesReply rep = { .type = X_Reply, .sequenceNumber = client->sequence, .length = bytes_to_int32(ctx.resultBytes), .numSizes = ctx.numSizes }; if (client->swapped) { swaps (&rep.sequenceNumber); swapl (&rep.length); swapl (&rep.numSizes); SwapXResQueryResourceBytes(&ctx.response); } WriteToClient(client, sizeof(rep), &rep); WriteFragmentsToClient(client, &ctx.response); } DestroyConstructResourceBytesCtx(&ctx); return rc; }
165,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Cues::~Cues() { const long n = m_count + m_preload_count; CuePoint** p = m_cue_points; CuePoint** const q = p + n; while (p != q) { CuePoint* const pCP = *p++; assert(pCP); delete pCP; } delete[] m_cue_points; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Cues::~Cues() return m_count; // TODO: really ignore preload count? } bool Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } void Cues::Init() const { if (m_cue_points) return; assert(m_count == 0); assert(m_preload_count == 0); IMkvReader* const pReader = m_pSegment->m_pReader; const long long stop = m_start + m_size; long long pos = m_start; long cue_points_size = 0; while (pos < stop) { const long long idpos = pos; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x3B) // CuePoint ID PreloadCuePoint(cue_points_size, idpos); pos += size; // consume payload assert(pos <= stop); } } void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new CuePoint* [n]; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; }
174,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::GetNext(const Cluster* pCurr) { assert(pCurr); assert(pCurr != &m_eos); assert(m_clusters); long idx = pCurr->m_index; if (idx >= 0) { assert(m_clusterCount > 0); assert(idx < m_clusterCount); assert(pCurr == m_clusters[idx]); ++idx; if (idx >= m_clusterCount) return &m_eos; // caller will LoadCluster as desired Cluster* const pNext = m_clusters[idx]; assert(pNext); assert(pNext->m_index >= 0); assert(pNext->m_index == idx); return pNext; } assert(m_clusterPreloadCount > 0); long long pos = pCurr->m_element_start; assert(m_size >= 0); // TODO const long long stop = m_start + m_size; // end of segment { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long id = ReadUInt(m_pReader, pos, len); assert(id == 0x0F43B675); // Cluster ID if (id != 0x0F43B675) return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size > 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO pos += size; // consume payload } long long off_next = 0; while (pos < stop) { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long idpos = pos; // pos of next (potential) cluster const long long id = ReadUInt(m_pReader, idpos, len); assert(id > 0); // TODO pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size >= 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO if (size == 0) // weird continue; if (id == 0x0F43B675) { // Cluster ID const long long off_next_ = idpos - m_start; long long pos_; long len_; const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_); assert(status >= 0); if (status > 0) { off_next = off_next_; break; } } pos += size; // consume payload } if (off_next <= 0) return 0; Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else return pNext; } assert(i == j); Cluster* const pNext = Cluster::Create(this, -1, off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; // insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); return pNext; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const Cluster* Segment::GetNext(const Cluster* pCurr) { assert(pCurr); assert(pCurr != &m_eos); assert(m_clusters); long idx = pCurr->m_index; if (idx >= 0) { assert(m_clusterCount > 0); assert(idx < m_clusterCount); assert(pCurr == m_clusters[idx]); ++idx; if (idx >= m_clusterCount) return &m_eos; // caller will LoadCluster as desired Cluster* const pNext = m_clusters[idx]; assert(pNext); assert(pNext->m_index >= 0); assert(pNext->m_index == idx); return pNext; } assert(m_clusterPreloadCount > 0); long long pos = pCurr->m_element_start; assert(m_size >= 0); // TODO const long long stop = m_start + m_size; // end of segment { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long id = ReadID(m_pReader, pos, len); if (id != 0x0F43B675) // Cluster ID return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size > 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO pos += size; // consume payload } long long off_next = 0; while (pos < stop) { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long idpos = pos; // pos of next (potential) cluster const long long id = ReadID(m_pReader, idpos, len); if (id < 0) return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size >= 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO if (size == 0) // weird continue; if (id == 0x0F43B675) { // Cluster ID const long long off_next_ = idpos - m_start; long long pos_; long len_; const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_); assert(status >= 0); if (status > 0) { off_next = off_next_; break; } } pos += size; // consume payload } if (off_next <= 0) return 0; Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else return pNext; } assert(i == j); Cluster* const pNext = Cluster::Create(this, -1, off_next); if (pNext == NULL) return NULL; const ptrdiff_t idx_next = i - m_clusters; // insertion position if (!PreloadCluster(pNext, idx_next)) { delete pNext; return NULL; } assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); return pNext; }
173,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; // Can't call BadMessage as we're no longer on the IO thread. So ignore. if (connection_->GetTransaction(transaction_id)) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); }
172,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Init_ossl_cipher(void) { #if 0 mOSSL = rb_define_module("OpenSSL"); eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError); #endif /* Document-class: OpenSSL::Cipher * * Provides symmetric algorithms for encryption and decryption. The * algorithms that are available depend on the particular version * of OpenSSL that is installed. * * === Listing all supported algorithms * * A list of supported algorithms can be obtained by * * puts OpenSSL::Cipher.ciphers * * === Instantiating a Cipher * * There are several ways to create a Cipher instance. Generally, a * Cipher algorithm is categorized by its name, the key length in bits * and the cipher mode to be used. The most generic way to create a * Cipher is the following * * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>') * * That is, a string consisting of the hyphenated concatenation of the * individual components name, key length and mode. Either all uppercase * or all lowercase strings may be used, for example: * * cipher = OpenSSL::Cipher.new('AES-128-CBC') * * For each algorithm supported, there is a class defined under the * Cipher class that goes by the name of the cipher, e.g. to obtain an * instance of AES, you could also use * * # these are equivalent * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher = OpenSSL::Cipher::AES.new(128, 'CBC') * cipher = OpenSSL::Cipher::AES.new('128-CBC') * * Finally, due to its wide-spread use, there are also extra classes * defined for the different key sizes of AES * * cipher = OpenSSL::Cipher::AES128.new(:CBC) * cipher = OpenSSL::Cipher::AES192.new(:CBC) * cipher = OpenSSL::Cipher::AES256.new(:CBC) * * === Choosing either encryption or decryption mode * * Encryption and decryption are often very similar operations for * symmetric algorithms, this is reflected by not having to choose * different classes for either operation, both can be done using the * same class. Still, after obtaining a Cipher instance, we need to * tell the instance what it is that we intend to do with it, so we * need to call either * * cipher.encrypt * * or * * cipher.decrypt * * on the Cipher instance. This should be the first call after creating * the instance, otherwise configuration that has already been set could * get lost in the process. * * === Choosing a key * * Symmetric encryption requires a key that is the same for the encrypting * and for the decrypting party and after initial key establishment should * be kept as private information. There are a lot of ways to create * insecure keys, the most notable is to simply take a password as the key * without processing the password further. A simple and secure way to * create a key for a particular Cipher is * * cipher = OpenSSL::AES256.new(:CFB) * cipher.encrypt * key = cipher.random_key # also sets the generated key on the Cipher * * If you absolutely need to use passwords as encryption keys, you * should use Password-Based Key Derivation Function 2 (PBKDF2) by * generating the key with the help of the functionality provided by * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac. * * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and * it should only be used in legacy applications because it does not use * the newer PKCS#5 v2 algorithms. * * === Choosing an IV * * The cipher modes CBC, CFB, OFB and CTR all need an "initialization * vector", or short, IV. ECB mode is the only mode that does not require * an IV, but there is almost no legitimate use case for this mode * because of the fact that it does not sufficiently hide plaintext * patterns. Therefore * * <b>You should never use ECB mode unless you are absolutely sure that * you absolutely need it</b> * * Because of this, you will end up with a mode that explicitly requires * an IV in any case. Note that for backwards compatibility reasons, * setting an IV is not explicitly mandated by the Cipher API. If not * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the * character). Although the IV can be seen as public information, i.e. * it may be transmitted in public once generated, it should still stay * unpredictable to prevent certain kinds of attacks. Therefore, ideally * * <b>Always create a secure random IV for every encryption of your * Cipher</b> * * A new, random IV should be created for every encryption of data. Think * of the IV as a nonce (number used once) - it's public but random and * unpredictable. A secure random IV can be created as follows * * cipher = ... * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv # also sets the generated IV on the Cipher * * Although the key is generally a random value, too, it is a bad choice * as an IV. There are elaborate ways how an attacker can take advantage * of such an IV. As a general rule of thumb, exposing the key directly * or indirectly should be avoided at all cost and exceptions only be * made with good reason. * * === Calling Cipher#final * * ECB (which should not be used) and CBC are both block-based modes. * This means that unlike for the other streaming-based modes, they * operate on fixed-size blocks of data, and therefore they require a * "finalization" step to produce or correctly decrypt the last block of * data by appropriately handling some form of padding. Therefore it is * essential to add the output of OpenSSL::Cipher#final to your * encryption/decryption buffer or you will end up with decryption errors * or truncated data. * * Although this is not really necessary for streaming-mode ciphers, it is * still recommended to apply the same pattern of adding the output of * Cipher#final there as well - it also enables you to switch between * modes more easily in the future. * * === Encrypting and decrypting some data * * data = "Very, very confidential data" * * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv * * encrypted = cipher.update(data) + cipher.final * ... * decipher = OpenSSL::Cipher::AES.new(128, :CBC) * decipher.decrypt * decipher.key = key * decipher.iv = iv * * plain = decipher.update(encrypted) + decipher.final * * puts data == plain #=> true * * === Authenticated Encryption and Associated Data (AEAD) * * If the OpenSSL version used supports it, an Authenticated Encryption * mode (such as GCM or CCM) should always be preferred over any * unauthenticated mode. Currently, OpenSSL supports AE only in combination * with Associated Data (AEAD) where additional associated data is included * in the encryption process to compute a tag at the end of the encryption. * This tag will also be used in the decryption process and by verifying * its validity, the authenticity of a given ciphertext is established. * * This is superior to unauthenticated modes in that it allows to detect * if somebody effectively changed the ciphertext after it had been * encrypted. This prevents malicious modifications of the ciphertext that * could otherwise be exploited to modify ciphertexts in ways beneficial to * potential attackers. * * An associated data is used where there is additional information, such as * headers or some metadata, that must be also authenticated but not * necessarily need to be encrypted. If no associated data is needed for * encryption and later decryption, the OpenSSL library still requires a * value to be set - "" may be used in case none is available. * * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+, * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the * security gurantees of GCM mode. * * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt * cipher.key = key * cipher.iv = nonce * cipher.auth_data = auth_data * * encrypted = cipher.update(data) + cipher.final * tag = cipher.auth_tag # produces 16 bytes tag by default * * Now you are the receiver. You know the +key+ and have received +nonce+, * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may * additionally need to check that the received tag has the correct length, * or you allow attackers to forge a valid single byte tag for the tampered * ciphertext with a probability of 1/256. * * raise "tag is truncated!" unless tag.bytesize == 16 * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt * decipher.key = key * decipher.iv = nonce * decipher.auth_tag = tag * decipher.auth_data = auth_data * * decrypted = decipher.update(encrypted) + decipher.final * * puts data == decrypted #=> true */ cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject); eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError); rb_define_alloc_func(cCipher, ossl_cipher_alloc); rb_define_copy_func(cCipher, ossl_cipher_copy); rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0); rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1); rb_define_method(cCipher, "reset", ossl_cipher_reset, 0); rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1); rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1); rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1); rb_define_method(cCipher, "update", ossl_cipher_update, -1); rb_define_method(cCipher, "final", ossl_cipher_final, 0); rb_define_method(cCipher, "name", ossl_cipher_name, 0); rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1); rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1); rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1); rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1); rb_define_method(cCipher, "auth_tag_len=", ossl_cipher_set_auth_tag_len, 1); rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0); rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1); rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0); rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1); rb_define_method(cCipher, "iv_len=", ossl_cipher_set_iv_length, 1); rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0); rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0); rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1); id_auth_tag_len = rb_intern_const("auth_tag_len"); } Commit Message: cipher: don't set dummy encryption key in Cipher#initialize Remove the encryption key initialization from Cipher#initialize. This is effectively a revert of r32723 ("Avoid possible SEGV from AES encryption/decryption", 2011-07-28). r32723, which added the key initialization, was a workaround for Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate() before setting an encryption key caused segfault. It was not a problem until OpenSSL implemented GCM mode - the encryption key could be overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the case for AES-GCM ciphers. Setting a key, an IV, a key, in this order causes the IV to be reset to an all-zero IV. The problem of Bug #2768 persists on the current versions of OpenSSL. So, make Cipher#update raise an exception if a key is not yet set by the user. Since encrypting or decrypting without key does not make any sense, this should not break existing applications. Users can still call Cipher#key= and Cipher#iv= multiple times with their own responsibility. Reference: https://bugs.ruby-lang.org/issues/2768 Reference: https://bugs.ruby-lang.org/issues/8221 Reference: https://github.com/ruby/openssl/issues/49 CWE ID: CWE-310
Init_ossl_cipher(void) { #if 0 mOSSL = rb_define_module("OpenSSL"); eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError); #endif /* Document-class: OpenSSL::Cipher * * Provides symmetric algorithms for encryption and decryption. The * algorithms that are available depend on the particular version * of OpenSSL that is installed. * * === Listing all supported algorithms * * A list of supported algorithms can be obtained by * * puts OpenSSL::Cipher.ciphers * * === Instantiating a Cipher * * There are several ways to create a Cipher instance. Generally, a * Cipher algorithm is categorized by its name, the key length in bits * and the cipher mode to be used. The most generic way to create a * Cipher is the following * * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>') * * That is, a string consisting of the hyphenated concatenation of the * individual components name, key length and mode. Either all uppercase * or all lowercase strings may be used, for example: * * cipher = OpenSSL::Cipher.new('AES-128-CBC') * * For each algorithm supported, there is a class defined under the * Cipher class that goes by the name of the cipher, e.g. to obtain an * instance of AES, you could also use * * # these are equivalent * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher = OpenSSL::Cipher::AES.new(128, 'CBC') * cipher = OpenSSL::Cipher::AES.new('128-CBC') * * Finally, due to its wide-spread use, there are also extra classes * defined for the different key sizes of AES * * cipher = OpenSSL::Cipher::AES128.new(:CBC) * cipher = OpenSSL::Cipher::AES192.new(:CBC) * cipher = OpenSSL::Cipher::AES256.new(:CBC) * * === Choosing either encryption or decryption mode * * Encryption and decryption are often very similar operations for * symmetric algorithms, this is reflected by not having to choose * different classes for either operation, both can be done using the * same class. Still, after obtaining a Cipher instance, we need to * tell the instance what it is that we intend to do with it, so we * need to call either * * cipher.encrypt * * or * * cipher.decrypt * * on the Cipher instance. This should be the first call after creating * the instance, otherwise configuration that has already been set could * get lost in the process. * * === Choosing a key * * Symmetric encryption requires a key that is the same for the encrypting * and for the decrypting party and after initial key establishment should * be kept as private information. There are a lot of ways to create * insecure keys, the most notable is to simply take a password as the key * without processing the password further. A simple and secure way to * create a key for a particular Cipher is * * cipher = OpenSSL::AES256.new(:CFB) * cipher.encrypt * key = cipher.random_key # also sets the generated key on the Cipher * * If you absolutely need to use passwords as encryption keys, you * should use Password-Based Key Derivation Function 2 (PBKDF2) by * generating the key with the help of the functionality provided by * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac. * * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and * it should only be used in legacy applications because it does not use * the newer PKCS#5 v2 algorithms. * * === Choosing an IV * * The cipher modes CBC, CFB, OFB and CTR all need an "initialization * vector", or short, IV. ECB mode is the only mode that does not require * an IV, but there is almost no legitimate use case for this mode * because of the fact that it does not sufficiently hide plaintext * patterns. Therefore * * <b>You should never use ECB mode unless you are absolutely sure that * you absolutely need it</b> * * Because of this, you will end up with a mode that explicitly requires * an IV in any case. Note that for backwards compatibility reasons, * setting an IV is not explicitly mandated by the Cipher API. If not * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the * character). Although the IV can be seen as public information, i.e. * it may be transmitted in public once generated, it should still stay * unpredictable to prevent certain kinds of attacks. Therefore, ideally * * <b>Always create a secure random IV for every encryption of your * Cipher</b> * * A new, random IV should be created for every encryption of data. Think * of the IV as a nonce (number used once) - it's public but random and * unpredictable. A secure random IV can be created as follows * * cipher = ... * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv # also sets the generated IV on the Cipher * * Although the key is generally a random value, too, it is a bad choice * as an IV. There are elaborate ways how an attacker can take advantage * of such an IV. As a general rule of thumb, exposing the key directly * or indirectly should be avoided at all cost and exceptions only be * made with good reason. * * === Calling Cipher#final * * ECB (which should not be used) and CBC are both block-based modes. * This means that unlike for the other streaming-based modes, they * operate on fixed-size blocks of data, and therefore they require a * "finalization" step to produce or correctly decrypt the last block of * data by appropriately handling some form of padding. Therefore it is * essential to add the output of OpenSSL::Cipher#final to your * encryption/decryption buffer or you will end up with decryption errors * or truncated data. * * Although this is not really necessary for streaming-mode ciphers, it is * still recommended to apply the same pattern of adding the output of * Cipher#final there as well - it also enables you to switch between * modes more easily in the future. * * === Encrypting and decrypting some data * * data = "Very, very confidential data" * * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv * * encrypted = cipher.update(data) + cipher.final * ... * decipher = OpenSSL::Cipher::AES.new(128, :CBC) * decipher.decrypt * decipher.key = key * decipher.iv = iv * * plain = decipher.update(encrypted) + decipher.final * * puts data == plain #=> true * * === Authenticated Encryption and Associated Data (AEAD) * * If the OpenSSL version used supports it, an Authenticated Encryption * mode (such as GCM or CCM) should always be preferred over any * unauthenticated mode. Currently, OpenSSL supports AE only in combination * with Associated Data (AEAD) where additional associated data is included * in the encryption process to compute a tag at the end of the encryption. * This tag will also be used in the decryption process and by verifying * its validity, the authenticity of a given ciphertext is established. * * This is superior to unauthenticated modes in that it allows to detect * if somebody effectively changed the ciphertext after it had been * encrypted. This prevents malicious modifications of the ciphertext that * could otherwise be exploited to modify ciphertexts in ways beneficial to * potential attackers. * * An associated data is used where there is additional information, such as * headers or some metadata, that must be also authenticated but not * necessarily need to be encrypted. If no associated data is needed for * encryption and later decryption, the OpenSSL library still requires a * value to be set - "" may be used in case none is available. * * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+, * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the * security gurantees of GCM mode. * * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt * cipher.key = key * cipher.iv = nonce * cipher.auth_data = auth_data * * encrypted = cipher.update(data) + cipher.final * tag = cipher.auth_tag # produces 16 bytes tag by default * * Now you are the receiver. You know the +key+ and have received +nonce+, * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may * additionally need to check that the received tag has the correct length, * or you allow attackers to forge a valid single byte tag for the tampered * ciphertext with a probability of 1/256. * * raise "tag is truncated!" unless tag.bytesize == 16 * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt * decipher.key = key * decipher.iv = nonce * decipher.auth_tag = tag * decipher.auth_data = auth_data * * decrypted = decipher.update(encrypted) + decipher.final * * puts data == decrypted #=> true */ cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject); eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError); rb_define_alloc_func(cCipher, ossl_cipher_alloc); rb_define_copy_func(cCipher, ossl_cipher_copy); rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0); rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1); rb_define_method(cCipher, "reset", ossl_cipher_reset, 0); rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1); rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1); rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1); rb_define_method(cCipher, "update", ossl_cipher_update, -1); rb_define_method(cCipher, "final", ossl_cipher_final, 0); rb_define_method(cCipher, "name", ossl_cipher_name, 0); rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1); rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1); rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1); rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1); rb_define_method(cCipher, "auth_tag_len=", ossl_cipher_set_auth_tag_len, 1); rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0); rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1); rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0); rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1); rb_define_method(cCipher, "iv_len=", ossl_cipher_set_iv_length, 1); rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0); rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0); rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1); id_auth_tag_len = rb_intern_const("auth_tag_len"); id_key_set = rb_intern_const("key_set"); }
168,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsSmartVirtualKeyboardEnabled() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( keyboard::switches::kEnableVirtualKeyboard)) { return false; } return !base::CommandLine::ForCurrentProcess()->HasSwitch( keyboard::switches::kDisableSmartVirtualKeyboard); } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} CWE ID: CWE-399
bool IsSmartVirtualKeyboardEnabled() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( keyboard::switches::kEnableVirtualKeyboard)) { return false; } return keyboard::IsSmartDeployEnabled(); }
171,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial) { struct sc_context *ctx = card->ctx; struct sc_iin *iin = &card->serialnr.iin; struct sc_apdu apdu; unsigned char rbuf[0xC0]; size_t ii, offs; int rv; LOG_FUNC_CALLED(ctx); if (card->serialnr.len) goto end; memset(&card->serialnr, 0, sizeof(card->serialnr)); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0); apdu.le = sizeof(rbuf); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed"); if (rbuf[0] != ISO7812_PAN_SN_TAG) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error"); iin->mii = (rbuf[2] >> 4) & 0x0F; iin->country = 0; for (ii=5; ii<8; ii++) { iin->country *= 10; iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F; } iin->issuer_id = 0; for (ii=8; ii<10; ii++) { iin->issuer_id *= 10; iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F; } offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0; if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { /* 5A 0A 92 50 00 20 10 10 25 00 01 3F */ /* 00 02 01 01 02 50 00 13 */ for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4) + ((rbuf[ii + offs + 2] & 0xF0) >> 4) ; card->serialnr.len = ii; } else { for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = rbuf[ii + offs + 2]; card->serialnr.len = ii; } do { char txt[0x200]; for (ii=0;ii<card->serialnr.len;ii++) sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii)); sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id); } while(0); end: if (serial) memcpy(serial, &card->serialnr, sizeof(*serial)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial) { struct sc_context *ctx = card->ctx; struct sc_iin *iin = &card->serialnr.iin; struct sc_apdu apdu; unsigned char rbuf[0xC0]; size_t ii, offs; int rv; LOG_FUNC_CALLED(ctx); if (card->serialnr.len) goto end; memset(&card->serialnr, 0, sizeof(card->serialnr)); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0); apdu.le = sizeof(rbuf); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed"); if (rbuf[0] != ISO7812_PAN_SN_TAG) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error"); iin->mii = (rbuf[2] >> 4) & 0x0F; iin->country = 0; for (ii=5; ii<8; ii++) { iin->country *= 10; iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F; } iin->issuer_id = 0; for (ii=8; ii<10; ii++) { iin->issuer_id *= 10; iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F; } offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0; if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { /* 5A 0A 92 50 00 20 10 10 25 00 01 3F */ /* 00 02 01 01 02 50 00 13 */ for (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++) *(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4) + ((rbuf[ii + offs + 2] & 0xF0) >> 4) ; card->serialnr.len = ii; } else { for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = rbuf[ii + offs + 2]; card->serialnr.len = ii; } do { char txt[0x200]; for (ii=0;ii<card->serialnr.len;ii++) sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii)); sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id); } while(0); end: if (serial) memcpy(serial, &card->serialnr, sizeof(*serial)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); }
169,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitIdentity *ret; guint32 uid; ret = NULL; if (POLKIT_IS_UNIX_PROCESS (subject)) { uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if ((gint) uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } ret = polkit_unix_user_new (uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); } else if (POLKIT_IS_UNIX_SESSION (subject)) { if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); } out: return ret; } if (!tmp_process) goto out; process = tmp_process; } Commit Message: CWE ID: CWE-200
polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, gboolean *result_matches, GError **error) { PolkitIdentity *ret; gboolean matches; ret = NULL; matches = FALSE; if (POLKIT_IS_UNIX_PROCESS (subject)) { gint subject_uid, current_uid; GError *local_error; subject_uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if (subject_uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } local_error = NULL; current_uid = polkit_unix_process_get_racy_uid__ (POLKIT_UNIX_PROCESS (subject), &local_error); if (local_error != NULL) { g_propagate_error (error, local_error); goto out; } ret = polkit_unix_user_new (subject_uid); matches = (subject_uid == current_uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); matches = TRUE; } else if (POLKIT_IS_UNIX_SESSION (subject)) { uid_t uid; if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); matches = TRUE; } out: if (result_matches != NULL) { *result_matches = matches; } return ret; } if (!tmp_process) goto out; process = tmp_process; }
165,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; msg->msg_namelen = sizeof(*sipx); if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; msg->msg_namelen = sizeof(*sipx); } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; }
166,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rd_build_device_space(struct rd_dev *rd_dev) { u32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); struct rd_dev_sg_table *sg_table; struct page *pg; struct scatterlist *sg; if (rd_dev->rd_page_count <= 0) { pr_err("Illegal page count: %u for Ramdisk device\n", rd_dev->rd_page_count); return -EINVAL; } /* Don't need backing pages for NULLIO */ if (rd_dev->rd_flags & RDF_NULLIO) return 0; total_sg_needed = rd_dev->rd_page_count; sg_tables = (total_sg_needed / max_sg_per_table) + 1; sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL); if (!sg_table) { pr_err("Unable to allocate memory for Ramdisk" " scatterlist tables\n"); return -ENOMEM; } rd_dev->sg_table_array = sg_table; rd_dev->sg_table_count = sg_tables; while (total_sg_needed) { sg_per_table = (total_sg_needed > max_sg_per_table) ? max_sg_per_table : total_sg_needed; sg = kzalloc(sg_per_table * sizeof(struct scatterlist), GFP_KERNEL); if (!sg) { pr_err("Unable to allocate scatterlist array" " for struct rd_dev\n"); return -ENOMEM; } sg_init_table(sg, sg_per_table); sg_table[i].sg_table = sg; sg_table[i].rd_sg_count = sg_per_table; sg_table[i].page_start_offset = page_offset; sg_table[i++].page_end_offset = (page_offset + sg_per_table) - 1; for (j = 0; j < sg_per_table; j++) { pg = alloc_pages(GFP_KERNEL, 0); if (!pg) { pr_err("Unable to allocate scatterlist" " pages for struct rd_dev_sg_table\n"); return -ENOMEM; } sg_assign_page(&sg[j], pg); sg[j].length = PAGE_SIZE; } page_offset += sg_per_table; total_sg_needed -= sg_per_table; } pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of" " %u pages in %u tables\n", rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, rd_dev->rd_page_count, rd_dev->sg_table_count); return 0; } Commit Message: target/rd: Refactor rd_build_device_space + rd_release_device_space This patch refactors rd_build_device_space() + rd_release_device_space() into rd_allocate_sgl_table() + rd_release_device_space() so that they may be used seperatly for setup + release of protection information scatterlists. Also add explicit memset of pages within rd_allocate_sgl_table() based upon passed 'init_payload' value. v2 changes: - Drop unused sg_table from rd_release_device_space (Wei) Cc: Martin K. Petersen <[email protected]> Cc: Christoph Hellwig <[email protected]> Cc: Hannes Reinecke <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: Or Gerlitz <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-264
static int rd_build_device_space(struct rd_dev *rd_dev) static int rd_allocate_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table, u32 total_sg_needed, unsigned char init_payload) { u32 i = 0, j, page_offset = 0, sg_per_table; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); struct page *pg; struct scatterlist *sg; unsigned char *p; while (total_sg_needed) { sg_per_table = (total_sg_needed > max_sg_per_table) ? max_sg_per_table : total_sg_needed; sg = kzalloc(sg_per_table * sizeof(struct scatterlist), GFP_KERNEL); if (!sg) { pr_err("Unable to allocate scatterlist array" " for struct rd_dev\n"); return -ENOMEM; } sg_init_table(sg, sg_per_table); sg_table[i].sg_table = sg; sg_table[i].rd_sg_count = sg_per_table; sg_table[i].page_start_offset = page_offset; sg_table[i++].page_end_offset = (page_offset + sg_per_table) - 1; for (j = 0; j < sg_per_table; j++) { pg = alloc_pages(GFP_KERNEL, 0); if (!pg) { pr_err("Unable to allocate scatterlist" " pages for struct rd_dev_sg_table\n"); return -ENOMEM; } sg_assign_page(&sg[j], pg); sg[j].length = PAGE_SIZE; p = kmap(pg); memset(p, init_payload, PAGE_SIZE); kunmap(pg); } page_offset += sg_per_table; total_sg_needed -= sg_per_table; } return 0; } static int rd_build_device_space(struct rd_dev *rd_dev) { struct rd_dev_sg_table *sg_table; u32 sg_tables, total_sg_needed; u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE / sizeof(struct scatterlist)); int rc; if (rd_dev->rd_page_count <= 0) { pr_err("Illegal page count: %u for Ramdisk device\n", rd_dev->rd_page_count); return -EINVAL; } /* Don't need backing pages for NULLIO */ if (rd_dev->rd_flags & RDF_NULLIO) return 0; total_sg_needed = rd_dev->rd_page_count; sg_tables = (total_sg_needed / max_sg_per_table) + 1; sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL); if (!sg_table) { pr_err("Unable to allocate memory for Ramdisk" " scatterlist tables\n"); return -ENOMEM; } rd_dev->sg_table_array = sg_table; rd_dev->sg_table_count = sg_tables; rc = rd_allocate_sgl_table(rd_dev, sg_table, total_sg_needed, 0x00); if (rc) return rc; pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of" " %u pages in %u tables\n", rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, rd_dev->rd_page_count, rd_dev->sg_table_count); return 0; }
166,315
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < CHDLC_HDRLEN) { ND_PRINT((ndo, "[|chdlc]")); return (caplen); } return (chdlc_print(ndo, p,length)); } Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks. Prevent a possible buffer overread in chdlc_print() and replace the custom check in chdlc_if_print() with a standard check in chdlc_print() so that the latter certainly does not over-read even when reached via juniper_chdlc_print(). Add length checks. CWE ID: CWE-125
chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { return chdlc_print(ndo, p, h->len); }
170,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: QTN2QT(QTNode *in) { TSQuery out; int len; int sumlen = 0, nnode = 0; QTN2QTState state; cntsize(in, &sumlen, &nnode); len = COMPUTESIZE(nnode, sumlen); out = (TSQuery) palloc0(len); SET_VARSIZE(out, len); out->size = nnode; state.curitem = GETQUERY(out); state.operand = state.curoperand = GETOPERAND(out); fillQT(&state, in); return out; } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
QTN2QT(QTNode *in) { TSQuery out; int len; int sumlen = 0, nnode = 0; QTN2QTState state; cntsize(in, &sumlen, &nnode); if (TSQUERY_TOO_BIG(nnode, sumlen)) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("tsquery is too large"))); len = COMPUTESIZE(nnode, sumlen); out = (TSQuery) palloc0(len); SET_VARSIZE(out, len); out->size = nnode; state.curitem = GETQUERY(out); state.operand = state.curoperand = GETOPERAND(out); fillQT(&state, in); return out; }
166,414
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } }
167,956
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebMediaPlayerImpl::DidPassCORSAccessCheck() const { if (data_source_) return data_source_->DidPassCORSAccessCheck(); return false; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
bool WebMediaPlayerImpl::DidPassCORSAccessCheck() const { bool WebMediaPlayerImpl::WouldTaintOrigin() const { if (!HasSingleSecurityOrigin()) { // When the resource is redirected to another origin we think it as // tainted. This is actually not specified, and is under discussion. // See https://github.com/whatwg/fetch/issues/737. return true; } return data_source_ && data_source_->IsCorsCrossOrigin(); }
172,631
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: setup_arch (char **cmdline_p) { unw_init(); ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist); *cmdline_p = __va(ia64_boot_param->command_line); strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE); efi_init(); io_port_init(); #ifdef CONFIG_IA64_GENERIC /* machvec needs to be parsed from the command line * before parse_early_param() is called to ensure * that ia64_mv is initialised before any command line * settings may cause console setup to occur */ machvec_init_from_cmdline(*cmdline_p); #endif parse_early_param(); if (early_console_setup(*cmdline_p) == 0) mark_bsp_online(); #ifdef CONFIG_ACPI /* Initialize the ACPI boot-time table parser */ acpi_table_init(); # ifdef CONFIG_ACPI_NUMA acpi_numa_init(); per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ? 32 : cpus_weight(early_cpu_possible_map)), additional_cpus); # endif #else # ifdef CONFIG_SMP smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */ # endif #endif /* CONFIG_APCI_BOOT */ find_memory(); /* process SAL system table: */ ia64_sal_init(__va(efi.sal_systab)); #ifdef CONFIG_SMP cpu_physical_id(0) = hard_smp_processor_id(); #endif cpu_init(); /* initialize the bootstrap CPU */ mmu_context_init(); /* initialize context_id bitmap */ check_sal_cache_flush(); #ifdef CONFIG_ACPI acpi_boot_init(); #endif #ifdef CONFIG_VT if (!conswitchp) { # if defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; # endif # if defined(CONFIG_VGA_CONSOLE) /* * Non-legacy systems may route legacy VGA MMIO range to system * memory. vga_con probes the MMIO hole, so memory looks like * a VGA device to it. The EFI memory map can tell us if it's * memory so we can avoid this problem. */ if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY) conswitchp = &vga_con; # endif } #endif /* enable IA-64 Machine Check Abort Handling unless disabled */ if (!nomca) ia64_mca_init(); platform_setup(cmdline_p); paging_init(); } Commit Message: [IA64] Workaround for RSE issue Problem: An application violating the architectural rules regarding operation dependencies and having specific Register Stack Engine (RSE) state at the time of the violation, may result in an illegal operation fault and invalid RSE state. Such faults may initiate a cascade of repeated illegal operation faults within OS interruption handlers. The specific behavior is OS dependent. Implication: An application causing an illegal operation fault with specific RSE state may result in a series of illegal operation faults and an eventual OS stack overflow condition. Workaround: OS interruption handlers that switch to kernel backing store implement a check for invalid RSE state to avoid the series of illegal operation faults. The core of the workaround is the RSE_WORKAROUND code sequence inserted into each invocation of the SAVE_MIN_WITH_COVER and SAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded constants that depend on the number of stacked physical registers being 96. The rest of this patch consists of code to disable this workaround should this not be the case (with the presumption that if a future Itanium processor increases the number of registers, it would also remove the need for this patch). Move the start of the RBS up to a mod32 boundary to avoid some corner cases. The dispatch_illegal_op_fault code outgrew the spot it was squatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y Move it out to the end of the ivt. Signed-off-by: Tony Luck <[email protected]> CWE ID: CWE-119
setup_arch (char **cmdline_p) { unw_init(); ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist); *cmdline_p = __va(ia64_boot_param->command_line); strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE); efi_init(); io_port_init(); #ifdef CONFIG_IA64_GENERIC /* machvec needs to be parsed from the command line * before parse_early_param() is called to ensure * that ia64_mv is initialised before any command line * settings may cause console setup to occur */ machvec_init_from_cmdline(*cmdline_p); #endif parse_early_param(); if (early_console_setup(*cmdline_p) == 0) mark_bsp_online(); #ifdef CONFIG_ACPI /* Initialize the ACPI boot-time table parser */ acpi_table_init(); # ifdef CONFIG_ACPI_NUMA acpi_numa_init(); per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ? 32 : cpus_weight(early_cpu_possible_map)), additional_cpus); # endif #else # ifdef CONFIG_SMP smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */ # endif #endif /* CONFIG_APCI_BOOT */ find_memory(); /* process SAL system table: */ ia64_sal_init(__va(efi.sal_systab)); #ifdef CONFIG_ITANIUM ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist); #else { u64 num_phys_stacked; if (ia64_pal_rse_info(&num_phys_stacked, 0) == 0 && num_phys_stacked > 96) ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist); } #endif #ifdef CONFIG_SMP cpu_physical_id(0) = hard_smp_processor_id(); #endif cpu_init(); /* initialize the bootstrap CPU */ mmu_context_init(); /* initialize context_id bitmap */ check_sal_cache_flush(); #ifdef CONFIG_ACPI acpi_boot_init(); #endif #ifdef CONFIG_VT if (!conswitchp) { # if defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; # endif # if defined(CONFIG_VGA_CONSOLE) /* * Non-legacy systems may route legacy VGA MMIO range to system * memory. vga_con probes the MMIO hole, so memory looks like * a VGA device to it. The EFI memory map can tell us if it's * memory so we can avoid this problem. */ if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY) conswitchp = &vga_con; # endif } #endif /* enable IA-64 Machine Check Abort Handling unless disabled */ if (!nomca) ia64_mca_init(); platform_setup(cmdline_p); paging_init(); }
168,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate, OnQueryKnownToValidate) IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate, OnSetKnownToValidate) #if defined(OS_WIN) IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler, OnAttachDebugExceptionHandler) #endif IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelCreated, OnPpapiChannelCreated) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate, OnQueryKnownToValidate) IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate, OnSetKnownToValidate) #if defined(OS_WIN) IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClProcessMsg_AttachDebugExceptionHandler, OnAttachDebugExceptionHandler) #endif IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; }
170,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_warning_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", name); return 0; } else if (r < 0) return log_warning_errno(r, "Failed to verify kbdmode on %s: %m", name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; }
169,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GLSurfaceEGLSurfaceControl::SwapBuffersAsync( SwapCompletionCallback completion_callback, PresentationCallback presentation_callback) { CommitPendingTransaction(std::move(completion_callback), std::move(presentation_callback)); } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
void GLSurfaceEGLSurfaceControl::SwapBuffersAsync( gfx::SwapResult GLSurfaceEGLSurfaceControl::CommitOverlayPlanes( PresentationCallback callback) { NOTREACHED(); return gfx::SwapResult::SWAP_FAILED; }
172,113
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); } Commit Message: issue #54: fix potential out-of-bounds heap read CWE ID: CWE-125
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }
168,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit, const ContentSecurityPolicy* previous_document_csp) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else { if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); } } if (!policy_to_inherit) policy_to_inherit = previous_document_csp; if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void Document::InitContentSecurityPolicy( void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp, const Document* origin_document) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); ContentSecurityPolicy* policy_to_inherit = nullptr; if (origin_document) policy_to_inherit = origin_document->GetContentSecurityPolicy(); // We should inherit the navigation initiator CSP if the document is loaded // using a local-scheme url. if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (IsPluginDocument()) { // TODO(andypaicu): This should inherit the origin document's plugin types // but because this could be a OOPIF document it might not have access. // In this situation we fallback on using the parent/opener. if (origin_document) { GetContentSecurityPolicy()->CopyPluginTypesFrom( origin_document->GetContentSecurityPolicy()); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); GetContentSecurityPolicy()->CopyPluginTypesFrom( inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); } } } }
173,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CSSDefaultStyleSheets::loadFullDefaultStyle() { if (simpleDefaultStyleSheet) { ASSERT(defaultStyle); ASSERT(defaultPrintStyle == defaultStyle); delete defaultStyle; simpleDefaultStyleSheet->deref(); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); simpleDefaultStyleSheet = 0; } else { ASSERT(!defaultStyle); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); defaultQuirksStyle = RuleSet::create().leakPtr(); } String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet(); defaultStyleSheet = parseUASheet(defaultRules); defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval()); String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet(); quirksStyleSheet = parseUASheet(quirksRules); defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval()); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void CSSDefaultStyleSheets::loadFullDefaultStyle() void CSSDefaultStyleSheets::loadDefaultStyle() { ASSERT(!defaultStyle); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); defaultQuirksStyle = RuleSet::create().leakPtr(); String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet(); defaultStyleSheet = parseUASheet(defaultRules); defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval()); String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet(); quirksStyleSheet = parseUASheet(quirksRules); defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval()); }
171,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t StreamingProcessor::processRecordingFrame() { ATRACE_CALL(); status_t res; sp<Camera2Heap> recordingHeap; size_t heapIdx = 0; nsecs_t timestamp; sp<Camera2Client> client = mClient.promote(); if (client == 0) { BufferItem imgBuffer; res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0); if (res != OK) { if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) { ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)", __FUNCTION__, mId, strerror(-res), res); } return res; } mRecordingConsumer->releaseBuffer(imgBuffer); return OK; } { /* acquire SharedParameters before mMutex so we don't dead lock with Camera2Client code calling into StreamingProcessor */ SharedParameters::Lock l(client->getParameters()); Mutex::Autolock m(mMutex); BufferItem imgBuffer; res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0); if (res != OK) { if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) { ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)", __FUNCTION__, mId, strerror(-res), res); } return res; } timestamp = imgBuffer.mTimestamp; mRecordingFrameCount++; ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount); if (l.mParameters.state != Parameters::RECORD && l.mParameters.state != Parameters::VIDEO_SNAPSHOT) { ALOGV("%s: Camera %d: Discarding recording image buffers " "received after recording done", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return INVALID_OPERATION; } if (mRecordingHeap == 0) { size_t payloadSize = sizeof(VideoNativeMetadata); ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of " "size %zu bytes", __FUNCTION__, mId, mRecordingHeapCount, payloadSize); mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount, "Camera2Client::RecordingHeap"); if (mRecordingHeap->mHeap->getSize() == 0) { ALOGE("%s: Camera %d: Unable to allocate memory for recording", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return NO_MEMORY; } for (size_t i = 0; i < mRecordingBuffers.size(); i++) { if (mRecordingBuffers[i].mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT) { ALOGE("%s: Camera %d: Non-empty recording buffers list!", __FUNCTION__, mId); } } mRecordingBuffers.clear(); mRecordingBuffers.setCapacity(mRecordingHeapCount); mRecordingBuffers.insertAt(0, mRecordingHeapCount); mRecordingHeapHead = 0; mRecordingHeapFree = mRecordingHeapCount; } if (mRecordingHeapFree == 0) { ALOGE("%s: Camera %d: No free recording buffers, dropping frame", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return NO_MEMORY; } heapIdx = mRecordingHeapHead; mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount; mRecordingHeapFree--; ALOGVV("%s: Camera %d: Timestamp %lld", __FUNCTION__, mId, timestamp); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset, &size); VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); payload->eType = kMetadataBufferTypeANWBuffer; payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer(); payload->nFenceFd = -1; ALOGVV("%s: Camera %d: Sending out ANWBuffer %p", __FUNCTION__, mId, payload->pBuffer); mRecordingBuffers.replaceAt(imgBuffer, heapIdx); recordingHeap = mRecordingHeap; } Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks); if (l.mRemoteCallback != 0) { l.mRemoteCallback->dataCallbackTimestamp(timestamp, CAMERA_MSG_VIDEO_FRAME, recordingHeap->mBuffers[heapIdx]); } else { ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId); } return OK; } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
status_t StreamingProcessor::processRecordingFrame() { ATRACE_CALL(); status_t res; sp<Camera2Heap> recordingHeap; size_t heapIdx = 0; nsecs_t timestamp; sp<Camera2Client> client = mClient.promote(); if (client == 0) { BufferItem imgBuffer; res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0); if (res != OK) { if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) { ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)", __FUNCTION__, mId, strerror(-res), res); } return res; } mRecordingConsumer->releaseBuffer(imgBuffer); return OK; } { /* acquire SharedParameters before mMutex so we don't dead lock with Camera2Client code calling into StreamingProcessor */ SharedParameters::Lock l(client->getParameters()); Mutex::Autolock m(mMutex); BufferItem imgBuffer; res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0); if (res != OK) { if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) { ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)", __FUNCTION__, mId, strerror(-res), res); } return res; } timestamp = imgBuffer.mTimestamp; mRecordingFrameCount++; ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount); if (l.mParameters.state != Parameters::RECORD && l.mParameters.state != Parameters::VIDEO_SNAPSHOT) { ALOGV("%s: Camera %d: Discarding recording image buffers " "received after recording done", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return INVALID_OPERATION; } if (mRecordingHeap == 0) { size_t payloadSize = sizeof(VideoNativeMetadata); ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of " "size %zu bytes", __FUNCTION__, mId, mRecordingHeapCount, payloadSize); mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount, "Camera2Client::RecordingHeap"); if (mRecordingHeap->mHeap->getSize() == 0) { ALOGE("%s: Camera %d: Unable to allocate memory for recording", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return NO_MEMORY; } for (size_t i = 0; i < mRecordingBuffers.size(); i++) { if (mRecordingBuffers[i].mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT) { ALOGE("%s: Camera %d: Non-empty recording buffers list!", __FUNCTION__, mId); } } mRecordingBuffers.clear(); mRecordingBuffers.setCapacity(mRecordingHeapCount); mRecordingBuffers.insertAt(0, mRecordingHeapCount); mRecordingHeapHead = 0; mRecordingHeapFree = mRecordingHeapCount; } if (mRecordingHeapFree == 0) { ALOGE("%s: Camera %d: No free recording buffers, dropping frame", __FUNCTION__, mId); mRecordingConsumer->releaseBuffer(imgBuffer); return NO_MEMORY; } heapIdx = mRecordingHeapHead; mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount; mRecordingHeapFree--; ALOGVV("%s: Camera %d: Timestamp %lld", __FUNCTION__, mId, timestamp); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset, &size); VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); payload->eType = kMetadataBufferTypeANWBuffer; payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer(); // b/28466701 payload->pBuffer = (ANativeWindowBuffer*)((uint8_t*)payload->pBuffer - ICameraRecordingProxy::getCommonBaseAddress()); payload->nFenceFd = -1; ALOGVV("%s: Camera %d: Sending out ANWBuffer %p", __FUNCTION__, mId, payload->pBuffer); mRecordingBuffers.replaceAt(imgBuffer, heapIdx); recordingHeap = mRecordingHeap; } Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks); if (l.mRemoteCallback != 0) { l.mRemoteCallback->dataCallbackTimestamp(timestamp, CAMERA_MSG_VIDEO_FRAME, recordingHeap->mBuffers[heapIdx]); } else { ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId); } return OK; }
173,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) continue; next = zap_pte_range(tlb, vma, pmd, addr, next, details); cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264
static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next - addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) goto next; /* fall through */ } /* * Here there can be other concurrent MADV_DONTNEED or * trans huge page faults running, and if the pmd is * none or trans huge it can change under us. This is * because MADV_DONTNEED holds the mmap_sem in read * mode. */ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) goto next; next = zap_pte_range(tlb, vma, pmd, addr, next, details); next: cond_resched(); } while (pmd++, addr = next, addr != end); return addr; }
165,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Factory(mojo::ScopedSharedBufferMapping mapping, std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm, const PlatformSensorProviderBase::CreateSensorCallback& callback, PlatformSensorProvider* provider) : fusion_algorithm_(std::move(fusion_algorithm)), result_callback_(std::move(callback)), mapping_(std::move(mapping)), provider_(provider) { const auto& types = fusion_algorithm_->source_types(); DCHECK(!types.empty()); DCHECK(std::adjacent_find(types.begin(), types.end()) == types.end()); DCHECK(result_callback_); DCHECK(mapping_); DCHECK(provider_); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
Factory(mojo::ScopedSharedBufferMapping mapping, Factory(SensorReadingSharedBuffer* reading_buffer, std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm, const PlatformSensorProviderBase::CreateSensorCallback& callback, PlatformSensorProvider* provider) : fusion_algorithm_(std::move(fusion_algorithm)), result_callback_(std::move(callback)), reading_buffer_(reading_buffer), provider_(provider) { const auto& types = fusion_algorithm_->source_types(); DCHECK(!types.empty()); DCHECK(std::adjacent_find(types.begin(), types.end()) == types.end()); DCHECK(result_callback_); DCHECK(reading_buffer_); DCHECK(provider_); }
172,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GDataEntry::GDataEntry(GDataDirectory* parent, GDataDirectoryService* directory_service) : directory_service_(directory_service), deleted_(false) { SetParent(parent); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GDataEntry::GDataEntry(GDataDirectory* parent, GDataEntry::GDataEntry(GDataDirectoryService* directory_service) : parent_(NULL), directory_service_(directory_service), deleted_(false) { }
171,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; } Commit Message: Bluetooth: L2CAP - Fix info leak via getsockname() The L2CAP code fails to initialize the l2_bdaddr_type member of struct sockaddr_l2 and the padding byte added for alignment. It that for leaks two bytes kernel stack via the getsockname() syscall. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); memset(la, 0, sizeof(struct sockaddr_l2)); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; }
169,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp) { struct sem_undo *un, *tu; struct sem_queue *q, *tq; struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm); struct list_head tasks; int i; /* Free the existing undo structures for this semaphore set. */ assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry_safe(un, tu, &sma->list_id, list_id) { list_del(&un->list_id); spin_lock(&un->ulp->lock); un->semid = -1; list_del_rcu(&un->list_proc); spin_unlock(&un->ulp->lock); kfree_rcu(un, rcu); } /* Wake up all pending processes and let them fail with EIDRM. */ INIT_LIST_HEAD(&tasks); list_for_each_entry_safe(q, tq, &sma->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } for (i = 0; i < sma->sem_nsems; i++) { struct sem *sem = sma->sem_base + i; list_for_each_entry_safe(q, tq, &sem->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } } /* Remove the semaphore set from the IDR */ sem_rmid(ns, sma); sem_unlock(sma); wake_up_sem_queue_do(&tasks); ns->used_sems -= sma->sem_nsems; security_sem_free(sma); ipc_rcu_putref(sma); } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
static void freeary(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp) { struct sem_undo *un, *tu; struct sem_queue *q, *tq; struct sem_array *sma = container_of(ipcp, struct sem_array, sem_perm); struct list_head tasks; int i; /* Free the existing undo structures for this semaphore set. */ assert_spin_locked(&sma->sem_perm.lock); list_for_each_entry_safe(un, tu, &sma->list_id, list_id) { list_del(&un->list_id); spin_lock(&un->ulp->lock); un->semid = -1; list_del_rcu(&un->list_proc); spin_unlock(&un->ulp->lock); kfree_rcu(un, rcu); } /* Wake up all pending processes and let them fail with EIDRM. */ INIT_LIST_HEAD(&tasks); list_for_each_entry_safe(q, tq, &sma->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } for (i = 0; i < sma->sem_nsems; i++) { struct sem *sem = sma->sem_base + i; list_for_each_entry_safe(q, tq, &sem->sem_pending, list) { unlink_queue(sma, q); wake_up_sem_queue_prepare(&tasks, q, -EIDRM); } } /* Remove the semaphore set from the IDR */ sem_rmid(ns, sma); sem_unlock(sma, -1); wake_up_sem_queue_do(&tasks); ns->used_sems -= sma->sem_nsems; security_sem_free(sma); ipc_rcu_putref(sma); }
165,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Ins_IUP( INS_ARG ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ FT_UNUSED_ARG; /* ignore empty outlines */ if ( CUR.pts.n_contours == 0 ) return; if ( CUR.opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = CUR.pts.org; V.curs = CUR.pts.cur; V.orus = CUR.pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 ); } V.max_points = CUR.pts.n_points; contour = 0; point = 0; do { end_point = CUR.pts.contours[contour] - CUR.pts.first_point; first_point = point; if ( CUR.pts.n_points <= end_point ) end_point = CUR.pts.n_points; while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( CUR.pts.tags[point] & mask ) != 0 ) { if ( point > 0 ) _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < CUR.pts.n_contours ); } Commit Message: CWE ID: CWE-119
Ins_IUP( INS_ARG ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ FT_UNUSED_ARG; /* ignore empty outlines */ if ( CUR.pts.n_contours == 0 ) return; if ( CUR.opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = CUR.pts.org; V.curs = CUR.pts.cur; V.orus = CUR.pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 ); } V.max_points = CUR.pts.n_points; contour = 0; point = 0; do { end_point = CUR.pts.contours[contour] - CUR.pts.first_point; first_point = point; if ( BOUNDS ( end_point, CUR.pts.n_points ) ) end_point = CUR.pts.n_points - 1; while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( CUR.pts.tags[point] & mask ) != 0 ) { if ( point > 0 ) _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < CUR.pts.n_contours ); }
165,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416
void MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (result != BinaryUploadService::Result::SUCCESS) return; if (!g_browser_process->local_state()->GetBoolean( policy::policy_prefs::kUnsafeEventsReportingEnabled)) return; if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } if (response.dlp_scan_verdict().status() == DlpDeepScanningVerdict::SUCCESS) { if (!response.dlp_scan_verdict().triggered_rules().empty()) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnSensitiveDataEvent(response.dlp_scan_verdict(), url, file_name, download_digest_sha256); } } }
172,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vrrp_print_json(void) { FILE *file; element e; struct json_object *array; if (LIST_ISEMPTY(vrrp_data->vrrp)) return; file = fopen ("/tmp/keepalived.json","w"); if (!file) { log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)", errno, strerror(errno)); return; } array = json_object_new_array(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { struct json_object *instance_json, *json_stats, *json_data, *vips, *evips, *track_ifp, *track_script; #ifdef _HAVE_FIB_ROUTING_ struct json_object *vroutes, *vrules; #endif element f; vrrp_t *vrrp = ELEMENT_DATA(e); instance_json = json_object_new_object(); json_stats = json_object_new_object(); json_data = json_object_new_object(); vips = json_object_new_array(); evips = json_object_new_array(); track_ifp = json_object_new_array(); track_script = json_object_new_array(); #ifdef _HAVE_FIB_ROUTING_ vroutes = json_object_new_array(); vrules = json_object_new_array(); #endif json_object_object_add(json_data, "iname", json_object_new_string(vrrp->iname)); json_object_object_add(json_data, "dont_track_primary", json_object_new_int(vrrp->dont_track_primary)); json_object_object_add(json_data, "skip_check_adv_addr", json_object_new_int(vrrp->skip_check_adv_addr)); json_object_object_add(json_data, "strict_mode", json_object_new_int((int)vrrp->strict_mode)); #ifdef _HAVE_VRRP_VMAC_ json_object_object_add(json_data, "vmac_ifname", json_object_new_string(vrrp->vmac_ifname)); #endif if (!LIST_ISEMPTY(vrrp->track_ifp)) { for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) { interface_t *ifp = ELEMENT_DATA(f); json_object_array_add(track_ifp, json_object_new_string(ifp->ifname)); } } json_object_object_add(json_data, "track_ifp", track_ifp); if (!LIST_ISEMPTY(vrrp->track_script)) { for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) { tracked_sc_t *tsc = ELEMENT_DATA(f); vrrp_script_t *vscript = tsc->scr; json_object_array_add(track_script, json_object_new_string(cmd_str(&vscript->script))); } } json_object_object_add(json_data, "track_script", track_script); json_object_object_add(json_data, "ifp_ifname", json_object_new_string(vrrp->ifp->ifname)); json_object_object_add(json_data, "master_priority", json_object_new_int(vrrp->master_priority)); json_object_object_add(json_data, "last_transition", json_object_new_double(timeval_to_double(&vrrp->last_transition))); json_object_object_add(json_data, "garp_delay", json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "garp_refresh", json_object_new_int((int)vrrp->garp_refresh.tv_sec)); json_object_object_add(json_data, "garp_rep", json_object_new_int((int)vrrp->garp_rep)); json_object_object_add(json_data, "garp_refresh_rep", json_object_new_int((int)vrrp->garp_refresh_rep)); json_object_object_add(json_data, "garp_lower_prio_delay", json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ))); json_object_object_add(json_data, "garp_lower_prio_rep", json_object_new_int((int)vrrp->garp_lower_prio_rep)); json_object_object_add(json_data, "lower_prio_no_advert", json_object_new_int((int)vrrp->lower_prio_no_advert)); json_object_object_add(json_data, "higher_prio_send_advert", json_object_new_int((int)vrrp->higher_prio_send_advert)); json_object_object_add(json_data, "vrid", json_object_new_int(vrrp->vrid)); json_object_object_add(json_data, "base_priority", json_object_new_int(vrrp->base_priority)); json_object_object_add(json_data, "effective_priority", json_object_new_int(vrrp->effective_priority)); json_object_object_add(json_data, "vipset", json_object_new_boolean(vrrp->vipset)); if (!LIST_ISEMPTY(vrrp->vip)) { for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) { ip_address_t *vip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(vips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "vips", vips); if (!LIST_ISEMPTY(vrrp->evip)) { for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) { ip_address_t *evip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(evips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "evips", evips); json_object_object_add(json_data, "promote_secondaries", json_object_new_boolean(vrrp->promote_secondaries)); #ifdef _HAVE_FIB_ROUTING_ if (!LIST_ISEMPTY(vrrp->vroutes)) { for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) { ip_route_t *route = ELEMENT_DATA(f); char *buf = MALLOC(ROUTE_BUF_SIZE); format_iproute(route, buf, ROUTE_BUF_SIZE); json_object_array_add(vroutes, json_object_new_string(buf)); } } json_object_object_add(json_data, "vroutes", vroutes); if (!LIST_ISEMPTY(vrrp->vrules)) { for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) { ip_rule_t *rule = ELEMENT_DATA(f); char *buf = MALLOC(RULE_BUF_SIZE); format_iprule(rule, buf, RULE_BUF_SIZE); json_object_array_add(vrules, json_object_new_string(buf)); } } json_object_object_add(json_data, "vrules", vrules); #endif json_object_object_add(json_data, "adver_int", json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "master_adver_int", json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "accept", json_object_new_int((int)vrrp->accept)); json_object_object_add(json_data, "nopreempt", json_object_new_boolean(vrrp->nopreempt)); json_object_object_add(json_data, "preempt_delay", json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ))); json_object_object_add(json_data, "state", json_object_new_int(vrrp->state)); json_object_object_add(json_data, "wantstate", json_object_new_int(vrrp->wantstate)); json_object_object_add(json_data, "version", json_object_new_int(vrrp->version)); if (vrrp->script_backup) json_object_object_add(json_data, "script_backup", json_object_new_string(cmd_str(vrrp->script_backup))); if (vrrp->script_master) json_object_object_add(json_data, "script_master", json_object_new_string(cmd_str(vrrp->script_master))); if (vrrp->script_fault) json_object_object_add(json_data, "script_fault", json_object_new_string(cmd_str(vrrp->script_fault))); if (vrrp->script_stop) json_object_object_add(json_data, "script_stop", json_object_new_string(cmd_str(vrrp->script_stop))); if (vrrp->script) json_object_object_add(json_data, "script", json_object_new_string(cmd_str(vrrp->script))); if (vrrp->script_master_rx_lower_pri) json_object_object_add(json_data, "script_master_rx_lower_pri", json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri))); json_object_object_add(json_data, "smtp_alert", json_object_new_boolean(vrrp->smtp_alert)); #ifdef _WITH_VRRP_AUTH_ if (vrrp->auth_type) { json_object_object_add(json_data, "auth_type", json_object_new_int(vrrp->auth_type)); if (vrrp->auth_type != VRRP_AUTH_AH) { char auth_data[sizeof(vrrp->auth_data) + 1]; memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data)); auth_data[sizeof(vrrp->auth_data)] = '\0'; json_object_object_add(json_data, "auth_data", json_object_new_string(auth_data)); } } else json_object_object_add(json_data, "auth_type", json_object_new_int(0)); #endif json_object_object_add(json_stats, "advert_rcvd", json_object_new_int64((int64_t)vrrp->stats->advert_rcvd)); json_object_object_add(json_stats, "advert_sent", json_object_new_int64(vrrp->stats->advert_sent)); json_object_object_add(json_stats, "become_master", json_object_new_int64(vrrp->stats->become_master)); json_object_object_add(json_stats, "release_master", json_object_new_int64(vrrp->stats->release_master)); json_object_object_add(json_stats, "packet_len_err", json_object_new_int64((int64_t)vrrp->stats->packet_len_err)); json_object_object_add(json_stats, "advert_interval_err", json_object_new_int64((int64_t)vrrp->stats->advert_interval_err)); json_object_object_add(json_stats, "ip_ttl_err", json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err)); json_object_object_add(json_stats, "invalid_type_rcvd", json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd)); json_object_object_add(json_stats, "addr_list_err", json_object_new_int64((int64_t)vrrp->stats->addr_list_err)); json_object_object_add(json_stats, "invalid_authtype", json_object_new_int64(vrrp->stats->invalid_authtype)); #ifdef _WITH_VRRP_AUTH_ json_object_object_add(json_stats, "authtype_mismatch", json_object_new_int64(vrrp->stats->authtype_mismatch)); json_object_object_add(json_stats, "auth_failure", json_object_new_int64(vrrp->stats->auth_failure)); #endif json_object_object_add(json_stats, "pri_zero_rcvd", json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd)); json_object_object_add(json_stats, "pri_zero_sent", json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent)); json_object_object_add(instance_json, "data", json_data); json_object_object_add(instance_json, "stats", json_stats); json_object_array_add(array, instance_json); } fprintf(file, "%s", json_object_to_json_string(array)); fclose(file); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59
vrrp_print_json(void) { FILE *file; element e; struct json_object *array; if (LIST_ISEMPTY(vrrp_data->vrrp)) return; file = fopen_safe("/tmp/keepalived.json", "w"); if (!file) { log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)", errno, strerror(errno)); return; } array = json_object_new_array(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { struct json_object *instance_json, *json_stats, *json_data, *vips, *evips, *track_ifp, *track_script; #ifdef _HAVE_FIB_ROUTING_ struct json_object *vroutes, *vrules; #endif element f; vrrp_t *vrrp = ELEMENT_DATA(e); instance_json = json_object_new_object(); json_stats = json_object_new_object(); json_data = json_object_new_object(); vips = json_object_new_array(); evips = json_object_new_array(); track_ifp = json_object_new_array(); track_script = json_object_new_array(); #ifdef _HAVE_FIB_ROUTING_ vroutes = json_object_new_array(); vrules = json_object_new_array(); #endif json_object_object_add(json_data, "iname", json_object_new_string(vrrp->iname)); json_object_object_add(json_data, "dont_track_primary", json_object_new_int(vrrp->dont_track_primary)); json_object_object_add(json_data, "skip_check_adv_addr", json_object_new_int(vrrp->skip_check_adv_addr)); json_object_object_add(json_data, "strict_mode", json_object_new_int((int)vrrp->strict_mode)); #ifdef _HAVE_VRRP_VMAC_ json_object_object_add(json_data, "vmac_ifname", json_object_new_string(vrrp->vmac_ifname)); #endif if (!LIST_ISEMPTY(vrrp->track_ifp)) { for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) { interface_t *ifp = ELEMENT_DATA(f); json_object_array_add(track_ifp, json_object_new_string(ifp->ifname)); } } json_object_object_add(json_data, "track_ifp", track_ifp); if (!LIST_ISEMPTY(vrrp->track_script)) { for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) { tracked_sc_t *tsc = ELEMENT_DATA(f); vrrp_script_t *vscript = tsc->scr; json_object_array_add(track_script, json_object_new_string(cmd_str(&vscript->script))); } } json_object_object_add(json_data, "track_script", track_script); json_object_object_add(json_data, "ifp_ifname", json_object_new_string(vrrp->ifp->ifname)); json_object_object_add(json_data, "master_priority", json_object_new_int(vrrp->master_priority)); json_object_object_add(json_data, "last_transition", json_object_new_double(timeval_to_double(&vrrp->last_transition))); json_object_object_add(json_data, "garp_delay", json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "garp_refresh", json_object_new_int((int)vrrp->garp_refresh.tv_sec)); json_object_object_add(json_data, "garp_rep", json_object_new_int((int)vrrp->garp_rep)); json_object_object_add(json_data, "garp_refresh_rep", json_object_new_int((int)vrrp->garp_refresh_rep)); json_object_object_add(json_data, "garp_lower_prio_delay", json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ))); json_object_object_add(json_data, "garp_lower_prio_rep", json_object_new_int((int)vrrp->garp_lower_prio_rep)); json_object_object_add(json_data, "lower_prio_no_advert", json_object_new_int((int)vrrp->lower_prio_no_advert)); json_object_object_add(json_data, "higher_prio_send_advert", json_object_new_int((int)vrrp->higher_prio_send_advert)); json_object_object_add(json_data, "vrid", json_object_new_int(vrrp->vrid)); json_object_object_add(json_data, "base_priority", json_object_new_int(vrrp->base_priority)); json_object_object_add(json_data, "effective_priority", json_object_new_int(vrrp->effective_priority)); json_object_object_add(json_data, "vipset", json_object_new_boolean(vrrp->vipset)); if (!LIST_ISEMPTY(vrrp->vip)) { for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) { ip_address_t *vip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(vips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "vips", vips); if (!LIST_ISEMPTY(vrrp->evip)) { for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) { ip_address_t *evip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(evips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "evips", evips); json_object_object_add(json_data, "promote_secondaries", json_object_new_boolean(vrrp->promote_secondaries)); #ifdef _HAVE_FIB_ROUTING_ if (!LIST_ISEMPTY(vrrp->vroutes)) { for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) { ip_route_t *route = ELEMENT_DATA(f); char *buf = MALLOC(ROUTE_BUF_SIZE); format_iproute(route, buf, ROUTE_BUF_SIZE); json_object_array_add(vroutes, json_object_new_string(buf)); } } json_object_object_add(json_data, "vroutes", vroutes); if (!LIST_ISEMPTY(vrrp->vrules)) { for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) { ip_rule_t *rule = ELEMENT_DATA(f); char *buf = MALLOC(RULE_BUF_SIZE); format_iprule(rule, buf, RULE_BUF_SIZE); json_object_array_add(vrules, json_object_new_string(buf)); } } json_object_object_add(json_data, "vrules", vrules); #endif json_object_object_add(json_data, "adver_int", json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "master_adver_int", json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "accept", json_object_new_int((int)vrrp->accept)); json_object_object_add(json_data, "nopreempt", json_object_new_boolean(vrrp->nopreempt)); json_object_object_add(json_data, "preempt_delay", json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ))); json_object_object_add(json_data, "state", json_object_new_int(vrrp->state)); json_object_object_add(json_data, "wantstate", json_object_new_int(vrrp->wantstate)); json_object_object_add(json_data, "version", json_object_new_int(vrrp->version)); if (vrrp->script_backup) json_object_object_add(json_data, "script_backup", json_object_new_string(cmd_str(vrrp->script_backup))); if (vrrp->script_master) json_object_object_add(json_data, "script_master", json_object_new_string(cmd_str(vrrp->script_master))); if (vrrp->script_fault) json_object_object_add(json_data, "script_fault", json_object_new_string(cmd_str(vrrp->script_fault))); if (vrrp->script_stop) json_object_object_add(json_data, "script_stop", json_object_new_string(cmd_str(vrrp->script_stop))); if (vrrp->script) json_object_object_add(json_data, "script", json_object_new_string(cmd_str(vrrp->script))); if (vrrp->script_master_rx_lower_pri) json_object_object_add(json_data, "script_master_rx_lower_pri", json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri))); json_object_object_add(json_data, "smtp_alert", json_object_new_boolean(vrrp->smtp_alert)); #ifdef _WITH_VRRP_AUTH_ if (vrrp->auth_type) { json_object_object_add(json_data, "auth_type", json_object_new_int(vrrp->auth_type)); if (vrrp->auth_type != VRRP_AUTH_AH) { char auth_data[sizeof(vrrp->auth_data) + 1]; memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data)); auth_data[sizeof(vrrp->auth_data)] = '\0'; json_object_object_add(json_data, "auth_data", json_object_new_string(auth_data)); } } else json_object_object_add(json_data, "auth_type", json_object_new_int(0)); #endif json_object_object_add(json_stats, "advert_rcvd", json_object_new_int64((int64_t)vrrp->stats->advert_rcvd)); json_object_object_add(json_stats, "advert_sent", json_object_new_int64(vrrp->stats->advert_sent)); json_object_object_add(json_stats, "become_master", json_object_new_int64(vrrp->stats->become_master)); json_object_object_add(json_stats, "release_master", json_object_new_int64(vrrp->stats->release_master)); json_object_object_add(json_stats, "packet_len_err", json_object_new_int64((int64_t)vrrp->stats->packet_len_err)); json_object_object_add(json_stats, "advert_interval_err", json_object_new_int64((int64_t)vrrp->stats->advert_interval_err)); json_object_object_add(json_stats, "ip_ttl_err", json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err)); json_object_object_add(json_stats, "invalid_type_rcvd", json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd)); json_object_object_add(json_stats, "addr_list_err", json_object_new_int64((int64_t)vrrp->stats->addr_list_err)); json_object_object_add(json_stats, "invalid_authtype", json_object_new_int64(vrrp->stats->invalid_authtype)); #ifdef _WITH_VRRP_AUTH_ json_object_object_add(json_stats, "authtype_mismatch", json_object_new_int64(vrrp->stats->authtype_mismatch)); json_object_object_add(json_stats, "auth_failure", json_object_new_int64(vrrp->stats->auth_failure)); #endif json_object_object_add(json_stats, "pri_zero_rcvd", json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd)); json_object_object_add(json_stats, "pri_zero_sent", json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent)); json_object_object_add(instance_json, "data", json_data); json_object_object_add(instance_json, "stats", json_stats); json_object_array_add(array, instance_json); } fprintf(file, "%s", json_object_to_json_string(array)); fclose(file); }
168,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; } Commit Message: CWE ID: CWE-119
static int dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; if (stereo && (buf_size & 1)) { buf_size--; buf_end--; } /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; }
165,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_event_task_enable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_enable); mutex_unlock(&current->perf_event_mutex); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int perf_event_task_enable(void) { struct perf_event_context *ctx; struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) { ctx = perf_event_ctx_lock(event); perf_event_for_each_child(event, _perf_event_enable); perf_event_ctx_unlock(event, ctx); } mutex_unlock(&current->perf_event_mutex); return 0; }
166,990
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllClients(); DCHECK(sessions_.empty()); InnerAttachClient(client); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllSessions(); DCHECK(sessions_.empty()); InnerAttachClient(client, false /* restricted */); }
173,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { effect_context_t * context = (effect_context_t *)self; int retsize; int status = 0; pthread_mutex_lock(&lock); if (!effect_exists(context)) { status = -ENOSYS; goto exit; } if (context == NULL || context->state == EFFECT_STATE_UNINITIALIZED) { status = -ENOSYS; goto exit; } switch (cmdCode) { case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->ops.init) *(int *) pReplyData = context->ops.init(context); else *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } *(int *) pReplyData = set_config(context, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { status = -EINVAL; goto exit; } if (!context->offload_enabled) { status = -EINVAL; goto exit; } get_config(context, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: if (context->ops.reset) context->ops.reset(context); break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->state != EFFECT_STATE_INITIALIZED) { status = -ENOSYS; goto exit; } context->state = EFFECT_STATE_ACTIVE; if (context->ops.enable) context->ops.enable(context); ALOGV("%s EFFECT_CMD_ENABLE", __func__); *(int *)pReplyData = 0; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->state != EFFECT_STATE_ACTIVE) { status = -ENOSYS; goto exit; } context->state = EFFECT_STATE_INITIALIZED; if (context->ops.disable) context->ops.disable(context); ALOGV("%s EFFECT_CMD_DISABLE", __func__); *(int *)pReplyData = 0; break; case EFFECT_CMD_GET_PARAM: { if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(uint32_t)) || pReplyData == NULL || *replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint16_t))) { status = -EINVAL; ALOGV("EFFECT_CMD_GET_PARAM invalid command cmdSize %d *replySize %d", cmdSize, *replySize); goto exit; } if (!context->offload_enabled) { status = -EINVAL; goto exit; } effect_param_t *q = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + q->psize); effect_param_t *p = (effect_param_t *)pReplyData; if (context->ops.get_parameter) context->ops.get_parameter(context, p, replySize); } break; case EFFECT_CMD_SET_PARAM: { if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint16_t)) || pReplyData == NULL || *replySize != sizeof(int32_t)) { status = -EINVAL; ALOGV("EFFECT_CMD_SET_PARAM invalid command cmdSize %d *replySize %d", cmdSize, *replySize); goto exit; } *(int32_t *)pReplyData = 0; effect_param_t *p = (effect_param_t *)pCmdData; if (context->ops.set_parameter) *(int32_t *)pReplyData = context->ops.set_parameter(context, p, *replySize); } break; case EFFECT_CMD_SET_DEVICE: { uint32_t device; ALOGV("\t EFFECT_CMD_SET_DEVICE start"); if (pCmdData == NULL || cmdSize < sizeof(uint32_t)) { status = -EINVAL; ALOGV("EFFECT_CMD_SET_DEVICE invalid command cmdSize %d", cmdSize); goto exit; } device = *(uint32_t *)pCmdData; if (context->ops.set_device) context->ops.set_device(context, device); } break; case EFFECT_CMD_SET_VOLUME: case EFFECT_CMD_SET_AUDIO_MODE: break; case EFFECT_CMD_OFFLOAD: { output_context_t *out_ctxt; if (cmdSize != sizeof(effect_offload_param_t) || pCmdData == NULL || pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("%s EFFECT_CMD_OFFLOAD bad format", __func__); status = -EINVAL; break; } effect_offload_param_t* offload_param = (effect_offload_param_t*)pCmdData; ALOGV("%s EFFECT_CMD_OFFLOAD offload %d output %d", __func__, offload_param->isOffload, offload_param->ioHandle); *(int *)pReplyData = 0; context->offload_enabled = offload_param->isOffload; if (context->out_handle == offload_param->ioHandle) break; out_ctxt = get_output(context->out_handle); if (out_ctxt != NULL) remove_effect_from_output(out_ctxt, context); context->out_handle = offload_param->ioHandle; out_ctxt = get_output(context->out_handle); if (out_ctxt != NULL) add_effect_to_output(out_ctxt, context); } break; default: if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY && context->ops.command) status = context->ops.command(context, cmdCode, cmdSize, pCmdData, replySize, pReplyData); else { ALOGW("%s invalid command %d", __func__, cmdCode); status = -EINVAL; } break; } exit: pthread_mutex_unlock(&lock); return status; } Commit Message: DO NOT MERGE Fix AudioEffect reply overflow Bug: 28173666 Change-Id: I055af37a721b20c5da0f1ec4b02f630dcd5aee02 CWE ID: CWE-119
int effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { effect_context_t * context = (effect_context_t *)self; int retsize; int status = 0; pthread_mutex_lock(&lock); if (!effect_exists(context)) { status = -ENOSYS; goto exit; } if (context == NULL || context->state == EFFECT_STATE_UNINITIALIZED) { status = -ENOSYS; goto exit; } switch (cmdCode) { case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->ops.init) *(int *) pReplyData = context->ops.init(context); else *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } *(int *) pReplyData = set_config(context, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { status = -EINVAL; goto exit; } if (!context->offload_enabled) { status = -EINVAL; goto exit; } get_config(context, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: if (context->ops.reset) context->ops.reset(context); break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->state != EFFECT_STATE_INITIALIZED) { status = -ENOSYS; goto exit; } context->state = EFFECT_STATE_ACTIVE; if (context->ops.enable) context->ops.enable(context); ALOGV("%s EFFECT_CMD_ENABLE", __func__); *(int *)pReplyData = 0; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { status = -EINVAL; goto exit; } if (context->state != EFFECT_STATE_ACTIVE) { status = -ENOSYS; goto exit; } context->state = EFFECT_STATE_INITIALIZED; if (context->ops.disable) context->ops.disable(context); ALOGV("%s EFFECT_CMD_DISABLE", __func__); *(int *)pReplyData = 0; break; case EFFECT_CMD_GET_PARAM: { if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(uint32_t)) || pReplyData == NULL || *replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint16_t)) || // constrain memcpy below ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t)) { status = -EINVAL; ALOGV("EFFECT_CMD_GET_PARAM invalid command cmdSize %d *replySize %d", cmdSize, *replySize); goto exit; } if (!context->offload_enabled) { status = -EINVAL; goto exit; } effect_param_t *q = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + q->psize); effect_param_t *p = (effect_param_t *)pReplyData; if (context->ops.get_parameter) context->ops.get_parameter(context, p, replySize); } break; case EFFECT_CMD_SET_PARAM: { if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint16_t)) || pReplyData == NULL || *replySize != sizeof(int32_t)) { status = -EINVAL; ALOGV("EFFECT_CMD_SET_PARAM invalid command cmdSize %d *replySize %d", cmdSize, *replySize); goto exit; } *(int32_t *)pReplyData = 0; effect_param_t *p = (effect_param_t *)pCmdData; if (context->ops.set_parameter) *(int32_t *)pReplyData = context->ops.set_parameter(context, p, *replySize); } break; case EFFECT_CMD_SET_DEVICE: { uint32_t device; ALOGV("\t EFFECT_CMD_SET_DEVICE start"); if (pCmdData == NULL || cmdSize < sizeof(uint32_t)) { status = -EINVAL; ALOGV("EFFECT_CMD_SET_DEVICE invalid command cmdSize %d", cmdSize); goto exit; } device = *(uint32_t *)pCmdData; if (context->ops.set_device) context->ops.set_device(context, device); } break; case EFFECT_CMD_SET_VOLUME: case EFFECT_CMD_SET_AUDIO_MODE: break; case EFFECT_CMD_OFFLOAD: { output_context_t *out_ctxt; if (cmdSize != sizeof(effect_offload_param_t) || pCmdData == NULL || pReplyData == NULL || *replySize != sizeof(int)) { ALOGV("%s EFFECT_CMD_OFFLOAD bad format", __func__); status = -EINVAL; break; } effect_offload_param_t* offload_param = (effect_offload_param_t*)pCmdData; ALOGV("%s EFFECT_CMD_OFFLOAD offload %d output %d", __func__, offload_param->isOffload, offload_param->ioHandle); *(int *)pReplyData = 0; context->offload_enabled = offload_param->isOffload; if (context->out_handle == offload_param->ioHandle) break; out_ctxt = get_output(context->out_handle); if (out_ctxt != NULL) remove_effect_from_output(out_ctxt, context); context->out_handle = offload_param->ioHandle; out_ctxt = get_output(context->out_handle); if (out_ctxt != NULL) add_effect_to_output(out_ctxt, context); } break; default: if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY && context->ops.command) status = context->ops.command(context, cmdCode, cmdSize, pCmdData, replySize, pReplyData); else { ALOGW("%s invalid command %d", __func__, cmdCode); status = -EINVAL; } break; } exit: pthread_mutex_unlock(&lock); return status; }
173,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); args->rmtvaluelen = args->valuelen; } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; }
166,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ovl_remove_upper(struct dentry *dentry, bool is_dir) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *dir = upperdir->d_inode; struct dentry *upper = ovl_dentry_upper(dentry); int err; inode_lock_nested(dir, I_MUTEX_PARENT); err = -ESTALE; if (upper->d_parent == upperdir) { /* Don't let d_delete() think it can reset d_inode */ dget(upper); if (is_dir) err = vfs_rmdir(dir, upper); else err = vfs_unlink(dir, upper, NULL); dput(upper); ovl_dentry_version_inc(dentry->d_parent); } /* * Keeping this dentry hashed would mean having to release * upperpath/lowerpath, which could only be done if we are the * sole user of this dentry. Too tricky... Just unhash for * now. */ if (!err) d_drop(dentry); inode_unlock(dir); return err; } Commit Message: ovl: verify upper dentry before unlink and rename Unlink and rename in overlayfs checked the upper dentry for staleness by verifying upper->d_parent against upperdir. However the dentry can go stale also by being unhashed, for example. Expand the verification to actually look up the name again (under parent lock) and check if it matches the upper dentry. This matches what the VFS does before passing the dentry to filesytem's unlink/rename methods, which excludes any inconsistency caused by overlayfs. Signed-off-by: Miklos Szeredi <[email protected]> CWE ID: CWE-20
static int ovl_remove_upper(struct dentry *dentry, bool is_dir) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *dir = upperdir->d_inode; struct dentry *upper; int err; inode_lock_nested(dir, I_MUTEX_PARENT); upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out_unlock; err = -ESTALE; if (upper == ovl_dentry_upper(dentry)) { if (is_dir) err = vfs_rmdir(dir, upper); else err = vfs_unlink(dir, upper, NULL); ovl_dentry_version_inc(dentry->d_parent); } dput(upper); /* * Keeping this dentry hashed would mean having to release * upperpath/lowerpath, which could only be done if we are the * sole user of this dentry. Too tricky... Just unhash for * now. */ if (!err) d_drop(dentry); out_unlock: inode_unlock(dir); return err; }
167,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian); value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian); return 1; } else if(field_type==4) { // LONG (uint32) *pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian); return 1; } return 0; } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = get_exif_ui16(e, tag_pos+2); value_count = get_exif_ui32(e, tag_pos+4); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = get_exif_ui16(e, tag_pos+8); return 1; } else if(field_type==4) { // LONG (uint32) *pv = get_exif_ui32(e, tag_pos+8); return 1; } return 0; }
168,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Bool GPAC_EventProc(void *ptr, GF_Event *evt) { if (!term) return 0; if (gui_mode==1) { if (evt->type==GF_EVENT_QUIT) { Run = 0; } else if (evt->type==GF_EVENT_KEYDOWN) { switch (evt->key.key_code) { case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (shell_visible) gui_mode=2; } break; default: break; } } return 0; } switch (evt->type) { case GF_EVENT_DURATION: Duration = (u64) ( 1000 * (s64) evt->duration.duration); CanSeek = evt->duration.can_seek; break; case GF_EVENT_MESSAGE: { const char *servName; if (!evt->message.service || !strcmp(evt->message.service, the_url)) { servName = ""; } else if (!strnicmp(evt->message.service, "data:", 5)) { servName = "(embedded data)"; } else { servName = evt->message.service; } if (!evt->message.message) return 0; if (evt->message.error) { if (!is_connected) last_error = evt->message.error; if (evt->message.error==GF_SCRIPT_INFO) { GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message)); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error))); } } else if (!be_quiet) GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message)); } break; case GF_EVENT_PROGRESS: { char *szTitle = ""; if (evt->progress.progress_type==0) { szTitle = "Buffer "; if (bench_mode && (bench_mode!=3) ) { if (evt->progress.done >= evt->progress.total) bench_buffer = 0; else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total; break; } } else if (evt->progress.progress_type==1) { if (bench_mode) break; szTitle = "Download "; } else if (evt->progress.progress_type==2) szTitle = "Import "; gf_set_progress(szTitle, evt->progress.done, evt->progress.total); } break; case GF_EVENT_DBLCLICK: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); return 0; case GF_EVENT_MOUSEDOWN: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 1; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEUP: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 0; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEMOVE: if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) { GF_Event move; move.move.x = evt->mouse.x - last_x; move.move.y = last_y-evt->mouse.y; move.type = GF_EVENT_MOVE; move.move.relative = 1; gf_term_user_event(term, &move); } return 0; case GF_EVENT_KEYUP: switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode); break; } break; case GF_EVENT_KEYDOWN: gf_term_process_shortcut(term, evt); switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) { /*ignore key repeat*/ if (!bench_mode) switch_bench(!bench_mode); } break; case GF_KEY_PAGEDOWN: case GF_KEY_MEDIANEXTTRACK: request_next_playlist_item = 1; break; case GF_KEY_MEDIAPREVIOUSTRACK: break; case GF_KEY_ESCAPE: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); break; case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (!shell_visible) gui_mode=1; } break; case GF_KEY_F: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0)); break; case GF_KEY_T: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0); break; case GF_KEY_D: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER ); break; case GF_KEY_4: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case GF_KEY_5: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case GF_KEY_6: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case GF_KEY_7: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case GF_KEY_O: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) { fprintf(stderr, "Resuming to main content\n"); gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { fprintf(stderr, "Main addon not enabled\n"); } } break; case GF_KEY_P: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ; fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused"); if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED); } } break; case GF_KEY_S: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case GF_KEY_B: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 1); break; case GF_KEY_M: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 0); break; case GF_KEY_H: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 1); } break; case GF_KEY_L: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 0); } break; case GF_KEY_F5: if (is_connected) reload = 1; break; case GF_KEY_A: addon_visible = !addon_visible; gf_term_toggle_addons(term, addon_visible); break; case GF_KEY_UP: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed * 2); } break; case GF_KEY_DOWN: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed / 2); } break; case GF_KEY_LEFT: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(-1 * playback_speed ); } break; } break; case GF_EVENT_CONNECT: if (evt->connect.is_connected) { is_connected = 1; fprintf(stderr, "Service Connected\n"); eos_seen = GF_FALSE; if (playback_speed != FIX_ONE) gf_term_set_speed(term, playback_speed); } else if (is_connected) { fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed"); is_connected = 0; Duration = 0; } if (init_w && init_h) { gf_term_set_size(term, init_w, init_h); } ResetCaption(); break; case GF_EVENT_EOS: eos_seen = GF_TRUE; if (playlist) { if (Duration>1500) request_next_playlist_item = GF_TRUE; } else if (loop_at_end) { restart = 1; } break; case GF_EVENT_SIZE: if (user.init_flags & GF_TERM_WINDOWLESS) { GF_Event move; move.type = GF_EVENT_MOVE; move.move.align_x = align_mode & 0xFF; move.move.align_y = (align_mode>>8) & 0xFF; move.move.relative = 2; gf_term_user_event(term, &move); } break; case GF_EVENT_SCENE_SIZE: if (forced_width && forced_height) { GF_Event size; size.type = GF_EVENT_SIZE; size.size.width = forced_width; size.size.height = forced_height; gf_term_user_event(term, &size); } break; case GF_EVENT_METADATA: ResetCaption(); break; case GF_EVENT_RELOAD: if (is_connected) reload = 1; break; case GF_EVENT_DROPFILE: { u32 i, pos; /*todo - force playlist mode*/ if (readonly_playlist) { gf_fclose(playlist); playlist = NULL; } readonly_playlist = 0; if (!playlist) { readonly_playlist = 0; playlist = gf_temp_file_new(NULL); } pos = ftell(playlist); i=0; while (i<evt->open_file.nb_files) { if (evt->open_file.files[i] != NULL) { fprintf(playlist, "%s\n", evt->open_file.files[i]); } i++; } fseek(playlist, pos, SEEK_SET); request_next_playlist_item = 1; } return 1; case GF_EVENT_QUIT: if (evt->message.error) { fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) ); } Run = 0; break; case GF_EVENT_DISCONNECT: gf_term_disconnect(term); break; case GF_EVENT_MIGRATE: { } break; case GF_EVENT_NAVIGATE_INFO: if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url); break; case GF_EVENT_NAVIGATE: if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) { strcpy(the_url, evt->navigate.to_url); fprintf(stderr, "Navigating to URL %s\n", the_url); gf_term_navigate_to(term, evt->navigate.to_url); return 1; } else { fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url); } break; case GF_EVENT_SET_CAPTION: gf_term_user_event(term, evt); break; case GF_EVENT_AUTHORIZATION: { int maxTries = 1; assert( evt->type == GF_EVENT_AUTHORIZATION); assert( evt->auth.user); assert( evt->auth.password); assert( evt->auth.site_url); while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) { fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url); fprintf(stderr, "login : "); read_line_input(evt->auth.user, 50, 1); fprintf(stderr, "\npassword: "); read_line_input(evt->auth.password, 50, 0); fprintf(stderr, "*********\n"); } if (maxTries < 0) { fprintf(stderr, "**** No User or password has been filled, aborting ***\n"); return 0; } return 1; } case GF_EVENT_ADDON_DETECTED: if (enable_add_ons) { fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url); addon_visible = 1; } return enable_add_ons; } return 0; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
Bool GPAC_EventProc(void *ptr, GF_Event *evt) { if (!term) return 0; if (gui_mode==1) { if (evt->type==GF_EVENT_QUIT) { Run = 0; } else if (evt->type==GF_EVENT_KEYDOWN) { switch (evt->key.key_code) { case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (shell_visible) gui_mode=2; } break; default: break; } } return 0; } switch (evt->type) { case GF_EVENT_DURATION: Duration = (u64) ( 1000 * (s64) evt->duration.duration); CanSeek = evt->duration.can_seek; break; case GF_EVENT_MESSAGE: { const char *servName; if (!evt->message.service || !strcmp(evt->message.service, the_url)) { servName = ""; } else if (!strnicmp(evt->message.service, "data:", 5)) { servName = "(embedded data)"; } else { servName = evt->message.service; } if (!evt->message.message) return 0; if (evt->message.error) { if (!is_connected) last_error = evt->message.error; if (evt->message.error==GF_SCRIPT_INFO) { GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message)); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error))); } } else if (!be_quiet) GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message)); } break; case GF_EVENT_PROGRESS: { char *szTitle = ""; if (evt->progress.progress_type==0) { szTitle = "Buffer "; if (bench_mode && (bench_mode!=3) ) { if (evt->progress.done >= evt->progress.total) bench_buffer = 0; else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total; break; } } else if (evt->progress.progress_type==1) { if (bench_mode) break; szTitle = "Download "; } else if (evt->progress.progress_type==2) szTitle = "Import "; gf_set_progress(szTitle, evt->progress.done, evt->progress.total); } break; case GF_EVENT_DBLCLICK: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); return 0; case GF_EVENT_MOUSEDOWN: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 1; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEUP: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 0; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEMOVE: if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) { GF_Event move; move.move.x = evt->mouse.x - last_x; move.move.y = last_y-evt->mouse.y; move.type = GF_EVENT_MOVE; move.move.relative = 1; gf_term_user_event(term, &move); } return 0; case GF_EVENT_KEYUP: switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode); break; } break; case GF_EVENT_KEYDOWN: gf_term_process_shortcut(term, evt); switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) { /*ignore key repeat*/ if (!bench_mode) switch_bench(!bench_mode); } break; case GF_KEY_PAGEDOWN: case GF_KEY_MEDIANEXTTRACK: request_next_playlist_item = 1; break; case GF_KEY_MEDIAPREVIOUSTRACK: break; case GF_KEY_ESCAPE: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); break; case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (!shell_visible) gui_mode=1; } break; case GF_KEY_F: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0)); break; case GF_KEY_T: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0); break; case GF_KEY_D: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER ); break; case GF_KEY_4: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case GF_KEY_5: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case GF_KEY_6: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case GF_KEY_7: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case GF_KEY_O: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) { fprintf(stderr, "Resuming to main content\n"); gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { fprintf(stderr, "Main addon not enabled\n"); } } break; case GF_KEY_P: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ; fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused"); if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED); } } break; case GF_KEY_S: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case GF_KEY_B: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 1); break; case GF_KEY_M: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 0); break; case GF_KEY_H: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 1); } break; case GF_KEY_L: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 0); } break; case GF_KEY_F5: if (is_connected) reload = 1; break; case GF_KEY_A: addon_visible = !addon_visible; gf_term_toggle_addons(term, addon_visible); break; case GF_KEY_UP: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed * 2); } break; case GF_KEY_DOWN: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed / 2); } break; case GF_KEY_LEFT: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(-1 * playback_speed ); } break; } break; case GF_EVENT_CONNECT: if (evt->connect.is_connected) { is_connected = 1; fprintf(stderr, "Service Connected\n"); eos_seen = GF_FALSE; if (playback_speed != FIX_ONE) gf_term_set_speed(term, playback_speed); } else if (is_connected) { fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed"); is_connected = 0; Duration = 0; } if (init_w && init_h) { gf_term_set_size(term, init_w, init_h); } ResetCaption(); break; case GF_EVENT_EOS: eos_seen = GF_TRUE; if (playlist) { if (Duration>1500) request_next_playlist_item = GF_TRUE; } else if (loop_at_end) { restart = 1; } break; case GF_EVENT_SIZE: if (user.init_flags & GF_TERM_WINDOWLESS) { GF_Event move; move.type = GF_EVENT_MOVE; move.move.align_x = align_mode & 0xFF; move.move.align_y = (align_mode>>8) & 0xFF; move.move.relative = 2; gf_term_user_event(term, &move); } break; case GF_EVENT_SCENE_SIZE: if (forced_width && forced_height) { GF_Event size; size.type = GF_EVENT_SIZE; size.size.width = forced_width; size.size.height = forced_height; gf_term_user_event(term, &size); } break; case GF_EVENT_METADATA: ResetCaption(); break; case GF_EVENT_RELOAD: if (is_connected) reload = 1; break; case GF_EVENT_DROPFILE: { u32 i, pos; /*todo - force playlist mode*/ if (readonly_playlist) { gf_fclose(playlist); playlist = NULL; } readonly_playlist = 0; if (!playlist) { readonly_playlist = 0; playlist = gf_temp_file_new(NULL); } pos = ftell(playlist); i=0; while (i<evt->open_file.nb_files) { if (evt->open_file.files[i] != NULL) { fprintf(playlist, "%s\n", evt->open_file.files[i]); } i++; } fseek(playlist, pos, SEEK_SET); request_next_playlist_item = 1; } return 1; case GF_EVENT_QUIT: if (evt->message.error) { fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) ); } Run = 0; break; case GF_EVENT_DISCONNECT: gf_term_disconnect(term); break; case GF_EVENT_MIGRATE: { } break; case GF_EVENT_NAVIGATE_INFO: if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url); break; case GF_EVENT_NAVIGATE: if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) { strncpy(the_url, evt->navigate.to_url, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; fprintf(stderr, "Navigating to URL %s\n", the_url); gf_term_navigate_to(term, evt->navigate.to_url); return 1; } else { fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url); } break; case GF_EVENT_SET_CAPTION: gf_term_user_event(term, evt); break; case GF_EVENT_AUTHORIZATION: { int maxTries = 1; assert( evt->type == GF_EVENT_AUTHORIZATION); assert( evt->auth.user); assert( evt->auth.password); assert( evt->auth.site_url); while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) { fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url); fprintf(stderr, "login : "); read_line_input(evt->auth.user, 50, 1); fprintf(stderr, "\npassword: "); read_line_input(evt->auth.password, 50, 0); fprintf(stderr, "*********\n"); } if (maxTries < 0) { fprintf(stderr, "**** No User or password has been filled, aborting ***\n"); return 0; } return 1; } case GF_EVENT_ADDON_DETECTED: if (enable_add_ons) { fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url); addon_visible = 1; } return enable_add_ons; } return 0; }
169,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionApiTest::InitializeEmbeddedTestServer() { if (!embedded_test_server()->InitializeAndListen()) return false; test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); return true; } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} CWE ID: CWE-200
bool ExtensionApiTest::InitializeEmbeddedTestServer() { if (!embedded_test_server()->InitializeAndListen()) return false; if (test_config_) { test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); } // else SetUpOnMainThread has not been called yet. Possibly because the // caller needs a valid port in an overridden SetUpCommandLine method. return true; }
172,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Atom::Clear() { delete[] m_string_uid; m_string_uid = NULL; while (m_displays_count > 0) { Display& d = m_displays[--m_displays_count]; d.Clear(); } delete[] m_displays; m_displays = NULL; m_displays_size = 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::Clear()
174,245
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name) { if (name.isEmpty()) return; map.add(name.impl()); if (Frame* f = frame()) f->script()->namedItemAdded(this, name); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name) void HTMLDocument::addItemToMap(HashCountedSet<AtomicString>& map, const AtomicString& name) { if (name.isEmpty()) return; map.add(name); if (Frame* f = frame()) f->script()->namedItemAdded(this, name); }
171,156
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); OnDownloadStarted(download, on_started); } Commit Message: Early return if a download Id is already used when creating a download This is protect against download Id overflow and use-after-free issue. BUG=958533 Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485 Reviewed-by: Xing Liu <[email protected]> Commit-Queue: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#656910} CWE ID: CWE-416
void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); if (download) { // For new downloads, we notify here, rather than earlier, so that // the download_file is bound to download and all the usual // setters (e.g. Cancel) work. for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); } OnDownloadStarted(download, on_started); }
172,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) // error return static_cast<long>(header_status); if (header_status > 0) // underflow return E_BUFFER_NOT_FULL; if (m_pInfo == NULL || m_pTracks == NULL) return E_FILE_FORMAT_INVALID; for (;;) { const int status = LoadCluster(); if (status < 0) // error return status; if (status >= 1) // no more clusters return 0; } }
173,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { PNG_CONST unsigned int scale = (1U<<that->sample_depth)-1; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<<that->red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); that->blue = sample_scale(that->bluef, scale); that->greene += 1./(2*((1U<<that->green_sBIT)-1)); that->bluee += 1./(2*((1U<<that->blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alpha = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that, image_transform_mod_end(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { const unsigned int scale = (1U<<that->sample_depth)-1; const int sig_bits = that->sig_bits; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* This is a bit bogus; really the above calculation should use the red_sBIT * value, not sample_depth, but because libpng does png_set_shift by just * shifting the bits we get errors if we don't do it the same way. */ if (sig_bits && that->red_sBIT < that->sample_depth) that->red >>= that->sample_depth - that->red_sBIT; /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<<that->red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); if (sig_bits && that->green_sBIT < that->sample_depth) that->green >>= that->sample_depth - that->green_sBIT; that->blue = sample_scale(that->bluef, scale); if (sig_bits && that->blue_sBIT < that->sample_depth) that->blue >>= that->sample_depth - that->blue_sBIT; that->greene += 1./(2*((1U<<that->green_sBIT)-1)); that->bluee += 1./(2*((1U<<that->blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alphaf = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } if (sig_bits && that->alpha_sBIT < that->sample_depth) that->alpha >>= that->sample_depth - that->alpha_sBIT; }
173,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PlatformSensorProviderBase::CreateSharedBufferIfNeeded() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (shared_buffer_handle_.is_valid()) return true; shared_buffer_handle_ = mojo::SharedBufferHandle::Create(kSharedBufferSizeInBytes); return shared_buffer_handle_.is_valid(); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
bool PlatformSensorProviderBase::CreateSharedBufferIfNeeded() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (shared_buffer_mapping_.get()) return true; if (!shared_buffer_handle_.is_valid()) { shared_buffer_handle_ = mojo::SharedBufferHandle::Create(kSharedBufferSizeInBytes); if (!shared_buffer_handle_.is_valid()) return false; } // Create a writable mapping for the buffer as soon as possible, that will be // used by all platform sensor implementations that want to update it. Note // that on Android, cloning the shared memory handle readonly (as performed // by CloneSharedBufferHandle()) will seal the region read-only, preventing // future writable mappings to be created (but this one will survive). shared_buffer_mapping_ = shared_buffer_handle_->Map(kSharedBufferSizeInBytes); return shared_buffer_mapping_.get() != nullptr; }
172,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 *opt = (__u8 *)(ra_msg + 1); optlen = (skb_tail_pointer(skb) - skb_transport_header(skb)) - sizeof(struct ra_msg); ND_PRINTK(2, info, "RA: %s, dev: %s\n", __func__, skb->dev->name); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "RA: source address is not link-local\n"); return; } if (optlen < 0) { ND_PRINTK(2, warn, "RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK(2, warn, "RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK(0, err, "RA: can't find inet6 device for %s\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK(2, warn, "RA: invalid ND options\n"); return; } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, did not accept ra for dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT, dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) { ND_PRINTK(2, info, "RA: %s, defrtr is false for dev: %s\n", __func__, skb->dev->name); goto skip_defrtr; } /* Do not accept RA with source-addr found on local machine unless * accept_ra_from_local is set to true. */ if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: default router ignored\n", skb->dev->name); goto skip_defrtr; } lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) { neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (!neigh) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } } if (rt && lifetime == 0) { ip6_del_rt(rt); rt = NULL; } ND_PRINTK(3, info, "RA: rt: %p lifetime: %d, for dev: %s\n", rt, lifetime, skb->dev->name); if (rt == NULL && lifetime) { ND_PRINTK(3, info, "RA: adding default router\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK(0, err, "RA: %s failed to add default route\n", __func__); return; } neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (neigh == NULL) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt6_set_expires(rt, jiffies + (HZ * lifetime)); if (ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; NEIGH_VAR_SET(in6_dev->nd_parms, RETRANS_TIME, rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != NEIGH_VAR(in6_dev->nd_parms, BASE_REACHABLE_TIME)) { NEIGH_VAR_SET(in6_dev->nd_parms, BASE_REACHABLE_TIME, rtime); NEIGH_VAR_SET(in6_dev->nd_parms, GC_STALETIME, 3 * rtime); in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK(2, warn, "RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, accept_ra is false for dev: %s\n", __func__, skb->dev->name); goto out; } #ifdef CONFIG_IPV6_ROUTE_INFO if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: router info ignored.\n", skb->dev->name); goto skip_routeinfo; } if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len == 0 && !in6_dev->cnf.accept_ra_defrtr) continue; if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT (interior routes), dev: %s\n", __func__, skb->dev->name); goto out; } #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, ndopts.nd_opts_src_lladdr != NULL); } } if (ndopts.nd_opts_mtu && in6_dev->cnf.accept_ra_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8 *)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK(2, warn, "RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK(2, warn, "RA: invalid RA options\n"); } out: ip6_rt_put(rt); if (neigh) neigh_release(neigh); } Commit Message: ipv6: Don't reduce hop limit for an interface A local route may have a lower hop_limit set than global routes do. RFC 3756, Section 4.2.7, "Parameter Spoofing" > 1. The attacker includes a Current Hop Limit of one or another small > number which the attacker knows will cause legitimate packets to > be dropped before they reach their destination. > As an example, one possible approach to mitigate this threat is to > ignore very small hop limits. The nodes could implement a > configurable minimum hop limit, and ignore attempts to set it below > said limit. Signed-off-by: D.S. Ljungmark <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-17
static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 *opt = (__u8 *)(ra_msg + 1); optlen = (skb_tail_pointer(skb) - skb_transport_header(skb)) - sizeof(struct ra_msg); ND_PRINTK(2, info, "RA: %s, dev: %s\n", __func__, skb->dev->name); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "RA: source address is not link-local\n"); return; } if (optlen < 0) { ND_PRINTK(2, warn, "RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK(2, warn, "RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK(0, err, "RA: can't find inet6 device for %s\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK(2, warn, "RA: invalid ND options\n"); return; } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, did not accept ra for dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT, dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) { ND_PRINTK(2, info, "RA: %s, defrtr is false for dev: %s\n", __func__, skb->dev->name); goto skip_defrtr; } /* Do not accept RA with source-addr found on local machine unless * accept_ra_from_local is set to true. */ if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: default router ignored\n", skb->dev->name); goto skip_defrtr; } lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) { neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (!neigh) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } } if (rt && lifetime == 0) { ip6_del_rt(rt); rt = NULL; } ND_PRINTK(3, info, "RA: rt: %p lifetime: %d, for dev: %s\n", rt, lifetime, skb->dev->name); if (rt == NULL && lifetime) { ND_PRINTK(3, info, "RA: adding default router\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK(0, err, "RA: %s failed to add default route\n", __func__); return; } neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (neigh == NULL) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt6_set_expires(rt, jiffies + (HZ * lifetime)); if (ra_msg->icmph.icmp6_hop_limit) { /* Only set hop_limit on the interface if it is higher than * the current hop_limit. */ if (in6_dev->cnf.hop_limit < ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; } else { ND_PRINTK(2, warn, "RA: Got route advertisement with lower hop_limit than current\n"); } if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; NEIGH_VAR_SET(in6_dev->nd_parms, RETRANS_TIME, rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != NEIGH_VAR(in6_dev->nd_parms, BASE_REACHABLE_TIME)) { NEIGH_VAR_SET(in6_dev->nd_parms, BASE_REACHABLE_TIME, rtime); NEIGH_VAR_SET(in6_dev->nd_parms, GC_STALETIME, 3 * rtime); in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK(2, warn, "RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, accept_ra is false for dev: %s\n", __func__, skb->dev->name); goto out; } #ifdef CONFIG_IPV6_ROUTE_INFO if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: router info ignored.\n", skb->dev->name); goto skip_routeinfo; } if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len == 0 && !in6_dev->cnf.accept_ra_defrtr) continue; if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT (interior routes), dev: %s\n", __func__, skb->dev->name); goto out; } #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, ndopts.nd_opts_src_lladdr != NULL); } } if (ndopts.nd_opts_mtu && in6_dev->cnf.accept_ra_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8 *)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK(2, warn, "RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK(2, warn, "RA: invalid RA options\n"); } out: ip6_rt_put(rt); if (neigh) neigh_release(neigh); }
166,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettingsPopupView::WebsiteSettingsPopupView( views::View* anchor_view, gfx::NativeView parent_window, Profile* profile, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl) : BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT), web_contents_(web_contents), header_(nullptr), tabbed_pane_(nullptr), permissions_tab_(nullptr), site_data_content_(nullptr), cookie_dialog_link_(nullptr), permissions_content_(nullptr), connection_tab_(nullptr), identity_info_content_(nullptr), certificate_dialog_link_(nullptr), reset_decisions_button_(nullptr), help_center_content_(nullptr), cert_id_(0), help_center_link_(nullptr), connection_info_content_(nullptr), weak_factory_(this) { set_parent_window(parent_window); set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0, kLocationIconVerticalMargin, 0)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int content_column = 0; views::ColumnSet* column_set = layout->AddColumnSet(content_column); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); header_ = new PopupHeaderView(this); layout->StartRow(1, content_column); layout->AddView(header_); layout->AddPaddingRow(1, kHeaderMarginBottom); tabbed_pane_ = new views::TabbedPane(); layout->StartRow(1, content_column); layout->AddView(tabbed_pane_); permissions_tab_ = CreatePermissionsTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_PERMISSIONS, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS), permissions_tab_); connection_tab_ = CreateConnectionTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_CONNECTION, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION), connection_tab_); DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS); tabbed_pane_->set_listener(this); set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft, kPopupMarginBottom, kPopupMarginRight)); views::BubbleDelegateView::CreateBubble(this); presenter_.reset(new WebsiteSettings( this, profile, TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), url, ssl, content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettingsPopupView::WebsiteSettingsPopupView( views::View* anchor_view, gfx::NativeView parent_window, Profile* profile, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl) : content::WebContentsObserver(web_contents), BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT), web_contents_(web_contents), header_(nullptr), tabbed_pane_(nullptr), permissions_tab_(nullptr), site_data_content_(nullptr), cookie_dialog_link_(nullptr), permissions_content_(nullptr), connection_tab_(nullptr), identity_info_content_(nullptr), certificate_dialog_link_(nullptr), reset_decisions_button_(nullptr), help_center_content_(nullptr), cert_id_(0), help_center_link_(nullptr), connection_info_content_(nullptr), weak_factory_(this) { set_parent_window(parent_window); set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0, kLocationIconVerticalMargin, 0)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int content_column = 0; views::ColumnSet* column_set = layout->AddColumnSet(content_column); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); header_ = new PopupHeaderView(this); layout->StartRow(1, content_column); layout->AddView(header_); layout->AddPaddingRow(1, kHeaderMarginBottom); tabbed_pane_ = new views::TabbedPane(); layout->StartRow(1, content_column); layout->AddView(tabbed_pane_); permissions_tab_ = CreatePermissionsTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_PERMISSIONS, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS), permissions_tab_); connection_tab_ = CreateConnectionTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_CONNECTION, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION), connection_tab_); DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS); tabbed_pane_->set_listener(this); set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft, kPopupMarginBottom, kPopupMarginRight)); views::BubbleDelegateView::CreateBubble(this); presenter_.reset(new WebsiteSettings( this, profile, TabSpecificContentSettings::FromWebContents(web_contents), web_contents, url, ssl, content::CertStore::GetInstance())); } void WebsiteSettingsPopupView::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents_->GetMainFrame()) { GetWidget()->Close(); } }
171,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::createGraphicBufferSource( OMX_U32 portIndex, sp<IGraphicBufferConsumer> bufferConsumer, MetadataBufferType *type) { status_t err; const sp<GraphicBufferSource>& surfaceCheck = getGraphicBufferSource(); if (surfaceCheck != NULL) { if (portIndex < NELEM(mMetadataType) && type != NULL) { *type = mMetadataType[portIndex]; } return ALREADY_EXISTS; } if (type != NULL) { *type = kMetadataBufferTypeANWBuffer; } err = storeMetaDataInBuffers_l(portIndex, OMX_TRUE, type); if (err != OK) { return err; } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE oerr = OMX_GetParameter( mHandle, OMX_IndexParamPortDefinition, &def); if (oerr != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, oerr, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } if (def.format.video.eColorFormat != OMX_COLOR_FormatAndroidOpaque) { CLOGW("createInputSurface requires COLOR_FormatSurface " "(AndroidOpaque) color format instead of %s(%#x)", asString(def.format.video.eColorFormat), def.format.video.eColorFormat); return INVALID_OPERATION; } uint32_t usageBits; oerr = OMX_GetParameter( mHandle, (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits, &usageBits); if (oerr != OMX_ErrorNone) { usageBits = 0; } sp<GraphicBufferSource> bufferSource = new GraphicBufferSource(this, def.format.video.nFrameWidth, def.format.video.nFrameHeight, def.nBufferCountActual, usageBits, bufferConsumer); if ((err = bufferSource->initCheck()) != OK) { return err; } setGraphicBufferSource(bufferSource); return OK; } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::createGraphicBufferSource( OMX_U32 portIndex, sp<IGraphicBufferConsumer> bufferConsumer, MetadataBufferType *type) { status_t err; // only allow graphic source on input port, when there are no allocated buffers yet if (portIndex != kPortIndexInput) { android_errorWriteLog(0x534e4554, "29422020"); return BAD_VALUE; } else if (mNumPortBuffers[portIndex] > 0) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } const sp<GraphicBufferSource> surfaceCheck = getGraphicBufferSource(); if (surfaceCheck != NULL) { if (portIndex < NELEM(mMetadataType) && type != NULL) { *type = mMetadataType[portIndex]; } return ALREADY_EXISTS; } if (type != NULL) { *type = kMetadataBufferTypeANWBuffer; } err = storeMetaDataInBuffers_l(portIndex, OMX_TRUE, type); if (err != OK) { return err; } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE oerr = OMX_GetParameter( mHandle, OMX_IndexParamPortDefinition, &def); if (oerr != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, oerr, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } if (def.format.video.eColorFormat != OMX_COLOR_FormatAndroidOpaque) { CLOGW("createInputSurface requires COLOR_FormatSurface " "(AndroidOpaque) color format instead of %s(%#x)", asString(def.format.video.eColorFormat), def.format.video.eColorFormat); return INVALID_OPERATION; } uint32_t usageBits; oerr = OMX_GetParameter( mHandle, (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits, &usageBits); if (oerr != OMX_ErrorNone) { usageBits = 0; } sp<GraphicBufferSource> bufferSource = new GraphicBufferSource(this, def.format.video.nFrameWidth, def.format.video.nFrameHeight, def.nBufferCountActual, usageBits, bufferConsumer); if ((err = bufferSource->initCheck()) != OK) { return err; } setGraphicBufferSource(bufferSource); return OK; }
174,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, String servicesUUID) { if (!connected()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(NetworkError, kGATTServerNotConnected)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); WTF::Optional<String> uuid = WTF::nullopt; if (!servicesUUID.isEmpty()) uuid = servicesUUID; service->RemoteServerGetPrimaryServices( device()->id(), quantity, uuid, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback, wrapPersistent(this), quantity, wrapPersistent(resolver)))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} CWE ID: CWE-119
ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, String servicesUUID) { if (!connected()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(NetworkError, kGATTServerNotConnected)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); service->RemoteServerGetPrimaryServices( device()->id(), quantity, servicesUUID, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback, wrapPersistent(this), quantity, wrapPersistent(resolver)))); return promise; }
172,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { texture_layer_->setTextureId(params.surface_handle); DCHECK(texture_layer_ == layer_); layer_->setBounds(params.size); texture_id_in_layer_ = params.surface_handle; texture_size_in_layer_ = params.size; DCHECK(!CompositorImpl::IsThreadingEnabled()); uint32 sync_point = ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint(); RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, true, sync_point); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAndroid::AcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params, int gpu_host_id) { ImageTransportFactoryAndroid* factory = ImageTransportFactoryAndroid::GetInstance(); // need to delay the ACK until after commit and use more than a single // texture. DCHECK(!CompositorImpl::IsThreadingEnabled()); uint64 previous_buffer = current_buffer_id_; if (previous_buffer && texture_id_in_layer_) { DCHECK(id_to_mailbox_.find(previous_buffer) != id_to_mailbox_.end()); ImageTransportFactoryAndroid::GetInstance()->ReleaseTexture( texture_id_in_layer_, reinterpret_cast<const signed char*>( id_to_mailbox_[previous_buffer].c_str())); } current_buffer_id_ = params.surface_handle; if (!texture_id_in_layer_) { texture_id_in_layer_ = factory->CreateTexture(); texture_layer_->setTextureId(texture_id_in_layer_); } DCHECK(id_to_mailbox_.find(current_buffer_id_) != id_to_mailbox_.end()); ImageTransportFactoryAndroid::GetInstance()->AcquireTexture( texture_id_in_layer_, reinterpret_cast<const signed char*>( id_to_mailbox_[current_buffer_id_].c_str())); texture_layer_->setNeedsDisplay(); texture_layer_->setBounds(params.size); texture_size_in_layer_ = params.size; uint32 sync_point = ImageTransportFactoryAndroid::GetInstance()->InsertSyncPoint(); RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, gpu_host_id, previous_buffer, sync_point); }
171,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( }
170,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); int nonOpt(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->methodWithNonOptionalArgAndOptionalArg(nonOpt); return JSValue::encode(jsUndefined()); } int opt(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithNonOptionalArgAndOptionalArg(nonOpt, opt); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); int nonOpt(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->methodWithNonOptionalArgAndOptionalArg(nonOpt); return JSValue::encode(jsUndefined()); } int opt(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithNonOptionalArgAndOptionalArg(nonOpt, opt); return JSValue::encode(jsUndefined()); }
170,594
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void print_cfs_stats(struct seq_file *m, int cpu) { struct cfs_rq *cfs_rq, *pos; rcu_read_lock(); for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) print_cfs_rq(m, cpu, cfs_rq); rcu_read_unlock(); } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-400
void print_cfs_stats(struct seq_file *m, int cpu) { struct cfs_rq *cfs_rq; rcu_read_lock(); for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq) print_cfs_rq(m, cpu, cfs_rq); rcu_read_unlock(); }
169,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vapic_enter(struct kvm_vcpu *vcpu) { struct kvm_lapic *apic = vcpu->arch.apic; struct page *page; if (!apic || !apic->vapic_addr) return 0; page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT); if (is_error_page(page)) return -EFAULT; vcpu->arch.apic->vapic_page = page; return 0; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
static int vapic_enter(struct kvm_vcpu *vcpu)
165,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); } Commit Message: Issue #656: Fix CVE-2016-1541, VU#862384 When reading OS X metadata entries in Zip archives that were stored without compression, libarchive would use the uncompressed entry size to allocate a buffer but would use the compressed entry size to limit the amount of data copied into that buffer. Since the compressed and uncompressed sizes are provided by data in the archive itself, an attacker could manipulate these values to write data beyond the end of the allocated buffer. This fix provides three new checks to guard against such manipulation and to make libarchive generally more robust when handling this type of entry: 1. If an OS X metadata entry is stored without compression, abort the entire archive if the compressed and uncompressed data sizes do not match. 2. When sanity-checking the size of an OS X metadata entry, abort this entry if either the compressed or uncompressed size is larger than 4MB. 3. When copying data into the allocated buffer, check the copy size against both the compressed entry size and uncompressed entry size. CWE ID: CWE-20
zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ if (rsrc->uncompressed_size != rsrc->compressed_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Malformed OS X metadata entry: inconsistent size"); return (ARCHIVE_FATAL); } #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } if (rsrc->compressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->compressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ if ((size_t)bytes_avail > metadata_bytes) bytes_avail = metadata_bytes; memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); }
167,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int apparmor_setprocattr(struct task_struct *task, char *name, void *value, size_t size) { char *command, *args = value; size_t arg_size; int error; if (size == 0) return -EINVAL; /* args points to a PAGE_SIZE buffer, AppArmor requires that * the buffer must be null terminated or have size <= PAGE_SIZE -1 * so that AppArmor can null terminate them */ if (args[size - 1] != '\0') { if (size == PAGE_SIZE) return -EINVAL; args[size] = '\0'; } /* task can only write its own attributes */ if (current != task) return -EACCES; args = value; args = strim(args); command = strsep(&args, " "); if (!args) return -EINVAL; args = skip_spaces(args); if (!*args) return -EINVAL; arg_size = size - (args - (char *) value); if (strcmp(name, "current") == 0) { if (strcmp(command, "changehat") == 0) { error = aa_setprocattr_changehat(args, arg_size, !AA_DO_TEST); } else if (strcmp(command, "permhat") == 0) { error = aa_setprocattr_changehat(args, arg_size, AA_DO_TEST); } else if (strcmp(command, "changeprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, !AA_DO_TEST); } else if (strcmp(command, "permprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, AA_DO_TEST); } else if (strcmp(command, "permipc") == 0) { error = aa_setprocattr_permipc(args); } else { struct common_audit_data sa; COMMON_AUDIT_DATA_INIT(&sa, NONE); sa.aad.op = OP_SETPROCATTR; sa.aad.info = name; sa.aad.error = -EINVAL; return aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL, &sa, NULL); } } else if (strcmp(name, "exec") == 0) { error = aa_setprocattr_changeprofile(args, AA_ONEXEC, !AA_DO_TEST); } else { /* only support the "current" and "exec" process attributes */ return -EINVAL; } if (!error) error = size; return error; } Commit Message: AppArmor: fix oops in apparmor_setprocattr When invalid parameters are passed to apparmor_setprocattr a NULL deref oops occurs when it tries to record an audit message. This is because it is passing NULL for the profile parameter for aa_audit. But aa_audit now requires that the profile passed is not NULL. Fix this by passing the current profile on the task that is trying to setprocattr. Signed-off-by: Kees Cook <[email protected]> Signed-off-by: John Johansen <[email protected]> Cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID: CWE-20
static int apparmor_setprocattr(struct task_struct *task, char *name, void *value, size_t size) { char *command, *args = value; size_t arg_size; int error; if (size == 0) return -EINVAL; /* args points to a PAGE_SIZE buffer, AppArmor requires that * the buffer must be null terminated or have size <= PAGE_SIZE -1 * so that AppArmor can null terminate them */ if (args[size - 1] != '\0') { if (size == PAGE_SIZE) return -EINVAL; args[size] = '\0'; } /* task can only write its own attributes */ if (current != task) return -EACCES; args = value; args = strim(args); command = strsep(&args, " "); if (!args) return -EINVAL; args = skip_spaces(args); if (!*args) return -EINVAL; arg_size = size - (args - (char *) value); if (strcmp(name, "current") == 0) { if (strcmp(command, "changehat") == 0) { error = aa_setprocattr_changehat(args, arg_size, !AA_DO_TEST); } else if (strcmp(command, "permhat") == 0) { error = aa_setprocattr_changehat(args, arg_size, AA_DO_TEST); } else if (strcmp(command, "changeprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, !AA_DO_TEST); } else if (strcmp(command, "permprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, AA_DO_TEST); } else if (strcmp(command, "permipc") == 0) { error = aa_setprocattr_permipc(args); } else { struct common_audit_data sa; COMMON_AUDIT_DATA_INIT(&sa, NONE); sa.aad.op = OP_SETPROCATTR; sa.aad.info = name; sa.aad.error = -EINVAL; return aa_audit(AUDIT_APPARMOR_DENIED, __aa_current_profile(), GFP_KERNEL, &sa, NULL); } } else if (strcmp(name, "exec") == 0) { error = aa_setprocattr_changeprofile(args, AA_ONEXEC, !AA_DO_TEST); } else { /* only support the "current" and "exec" process attributes */ return -EINVAL; } if (!error) error = size; return error; }
166,219