text
stringlengths
478
227k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void set_fdc(int drive) { if (drive >= 0 && drive < N_DRIVE) { fdc = FDC(drive); current_drive = drive; } if (fdc != 1 && fdc != 0) { pr_info("bad fdc value\n"); return; } set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'floppy: check FDC index for errors before assigning it Jordy Zomer reported a KASAN out-of-bounds read in the floppy driver in wait_til_ready(). Which on the face of it can't happen, since as Willy Tarreau points out, the function does no particular memory access. Except through the FDCS macro, which just indexes a static allocation through teh current fdc, which is always checked against N_FDC. Except the checking happens after we've already assigned the value. The floppy driver is a disgrace (a lot of it going back to my original horrd "design"), and has no real maintainer. Nobody has the hardware, and nobody really cares. But it still gets used in virtual environment because it's one of those things that everybody supports. The whole thing should be re-written, or at least parts of it should be seriously cleaned up. The 'current fdc' index, which is used by the FDCS macro, and which is often shadowed by a local 'fdc' variable, is a prime example of how not to write code. But because nobody has the hardware or the motivation, let's just fix up the immediate problem with a nasty band-aid: test the fdc index before actually assigning it to the static 'fdc' variable. Reported-by: Jordy Zomer <jordy@simplyhacker.com> Cc: Willy Tarreau <w@1wt.eu> Cc: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void AES128GCM_OnWireTxHandler::reset_tx_handler( std::initializer_list<std::uint32_t> update_size_sequence) { if (nonce == initial_nonce) { if (used_initial_nonce) { throw ceph::crypto::onwire::TxHandlerError("out of nonces"); } used_initial_nonce = true; } if(1 != EVP_EncryptInit_ex(ectx.get(), nullptr, nullptr, nullptr, reinterpret_cast<const unsigned char*>(&nonce))) { throw std::runtime_error("EVP_EncryptInit_ex failed"); } buffer.reserve(std::accumulate(std::begin(update_size_sequence), std::end(update_size_sequence), AESGCM_TAG_LEN)); ++nonce.random_seq; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/crypto_onwire: fix endianness of nonce_t As a AES-GCM IV, nonce_t is implicitly shared between server and client. Currently, if their endianness doesn't match, they are unable to communicate in secure mode because each gets its own idea of what the next nonce should be after the counter is incremented. Several RFCs state that the nonce counter should be BE, but since we use LE for everything on-disk and on-wire, make it LE. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject unauthenticated response-header actions Signed-off-by: Matt Benjamin <mbenjamin@redhat.com> Reviewed-by: Casey Bodley <cbodley@redhat.com> (cherry picked from commit d8dd5e513c0c62bbd7d3044d7e2eddcd897bd400)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SES_Wait(struct sess *sp, const struct transport *xp) { struct pool *pp; struct waited *wp; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); CHECK_OBJ_NOTNULL(xp, TRANSPORT_MAGIC); pp = sp->pool; CHECK_OBJ_NOTNULL(pp, POOL_MAGIC); assert(sp->fd > 0); /* * XXX: waiter_epoll prevents us from zeroing the struct because * XXX: it keeps state across calls. */ VTCP_nonblocking(sp->fd); /* * put struct waited on the workspace */ if (WS_ReserveSize(sp->ws, sizeof(struct waited)) < sizeof(struct waited)) { SES_Delete(sp, SC_OVERLOAD, NAN); return; } wp = (void*)sp->ws->f; INIT_OBJ(wp, WAITED_MAGIC); wp->fd = sp->fd; wp->priv1 = sp; wp->priv2 = (uintptr_t)xp; wp->idle = sp->t_idle; wp->func = ses_handle; wp->tmo = SESS_TMO(sp, timeout_idle); if (Wait_Enter(pp->waiter, wp)) SES_Delete(sp, SC_PIPE_OVERFLOW, NAN); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Take sizeof pool_task into account when reserving WS in SES_Wait The assert on WS_ReserveSize() in ses_handle() can not trip because sizeof (struct pool_task) is less than sizeof (struct waited). But to safe guard against future problems if that were to change, this patch makes sure that the session workspace can hold the largest of them before entering the waiter, erroring out if not.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int _free_pwd_session (pwd_session_t *session) { BN_clear_free(session->private_value); BN_clear_free(session->peer_scalar); BN_clear_free(session->my_scalar); BN_clear_free(session->k); EC_POINT_clear_free(session->my_element); EC_POINT_clear_free(session->peer_element); EC_GROUP_free(session->group); EC_POINT_clear_free(session->pwe); BN_clear_free(session->order); BN_clear_free(session->prime); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access The EAP-pwd module created one global OpenSSL BN_CTX instance, and used this instance in all incoming requests. This means that different threads used the same BN_CTX instance, which can result in a crash. An adversary can trigger these crashes by concurrently initiating multiple EAP-pwd handshakes from different clients. Fix this bug by creating a separate BN_CTX instance for each request.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t mon_text_read_t(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct mon_reader_text *rp = file->private_data; struct mon_event_text *ep; struct mon_text_ptr ptr; ep = mon_text_read_wait(rp, file); if (IS_ERR(ep)) return PTR_ERR(ep); mutex_lock(&rp->printf_lock); ptr.cnt = 0; ptr.pbuf = rp->printf_buf; ptr.limit = rp->printf_size; mon_text_read_head_t(rp, &ptr, ep); mon_text_read_statset(rp, &ptr, ep); ptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt, " %d", ep->length); mon_text_read_data(rp, &ptr, ep); if (copy_to_user(buf, rp->printf_buf, ptr.cnt)) ptr.cnt = -EFAULT; mutex_unlock(&rp->printf_lock); kmem_cache_free(rp->e_slab, ep); return ptr.cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'usb: usbmon: Read text within supplied buffer size This change fixes buffer overflows and silent data corruption with the usbmon device driver text file read operations. Signed-off-by: Fredrik Noring <noring@nocrew.org> Signed-off-by: Pete Zaitcev <zaitcev@redhat.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tulip_copy_tx_buffers(TULIPState *s, struct tulip_descriptor *desc) { int len1 = (desc->control >> TDES1_BUF1_SIZE_SHIFT) & TDES1_BUF1_SIZE_MASK; int len2 = (desc->control >> TDES1_BUF2_SIZE_SHIFT) & TDES1_BUF2_SIZE_MASK; if (len1) { pci_dma_read(&s->dev, desc->buf_addr1, s->tx_frame + s->tx_frame_len, len1); s->tx_frame_len += len1; } if (len2) { pci_dma_read(&s->dev, desc->buf_addr2, s->tx_frame + s->tx_frame_len, len2); s->tx_frame_len += len2; } desc->status = (len1 + len2) ? 0 : 0x7fffffff; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length Tulip network driver while copying tx/rx buffers does not check frame size against r/w data length. This may lead to OOB buffer access. Add check to avoid it. Limit iterations over descriptors to avoid potential infinite loop issue in tulip_xmit_list_update. Reported-by: Li Qiang <pangpei.lq@antfin.com> Reported-by: Ziming Zhang <ezrakiez@gmail.com> Reported-by: Jason Wang <jasowang@redhat.com> Tested-by: Li Qiang <liq3ea@gmail.com> Reviewed-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Jason Wang <jasowang@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sd_isoc_init(struct gspca_dev *gspca_dev) { struct usb_host_interface *alt; int max_packet_size; switch (gspca_dev->pixfmt.width) { case 160: max_packet_size = 450; break; case 176: max_packet_size = 600; break; default: max_packet_size = 1022; break; } /* Start isoc bandwidth "negotiation" at max isoc bandwidth */ alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1]; alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(max_packet_size); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: xirlink_cit: add missing descriptor sanity checks Make sure to check that we have two alternate settings and at least one endpoint before accessing the second altsetting structure and dereferencing the endpoint arrays. This specifically avoids dereferencing NULL-pointers or corrupting memory when a device does not have the expected descriptors. Note that the sanity check in cit_get_packet_size() is not redundant as the driver is mixing looking up altsettings by index and by number, which may not coincide. Fixes: 659fefa0eb17 ("V4L/DVB: gspca_xirlink_cit: Add support for camera with a bcd version of 0.01") Fixes: 59f8b0bf3c12 ("V4L/DVB: gspca_xirlink_cit: support bandwidth changing for devices with 1 alt setting") Cc: stable <stable@vger.kernel.org> # 2.6.37 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: transform_cipher_param(struct rte_crypto_sym_xform *xform, VhostUserCryptoSessionParam *param) { int ret; ret = cipher_algo_transform(param->cipher_algo, &xform->cipher.algo); if (unlikely(ret < 0)) return ret; xform->type = RTE_CRYPTO_SYM_XFORM_CIPHER; xform->cipher.key.length = param->cipher_key_len; if (xform->cipher.key.length > 0) xform->cipher.key.data = param->cipher_key_buf; if (param->dir == VIRTIO_CRYPTO_OP_ENCRYPT) xform->cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT; else if (param->dir == VIRTIO_CRYPTO_OP_DECRYPT) xform->cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT; else { VC_LOG_DBG("Bad operation type"); return -VIRTIO_CRYPTO_BADMSG; } ret = get_iv_len(xform->cipher.algo); if (unlikely(ret < 0)) return ret; xform->cipher.iv.length = (uint16_t)ret; xform->cipher.iv.offset = IV_OFFSET; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vhost/crypto: validate keys lengths transform_cipher_param() and transform_chain_param() handle the payload data for the VHOST_USER_CRYPTO_CREATE_SESS message. These payloads have to be validated, since it could come from untrusted sources. Two buffers and their lengths are defined in this payload, one the the auth key and one for the cipher key. But above functions do not validate the key length inputs, which could lead to read out of bounds, as buffers have static sizes of 64 bytes for the cipher key and 512 bytes for the auth key. This patch adds necessary checks on the key length field before being used. CVE-2020-10724 Fixes: e80a98708166 ("vhost/crypto: add session message handler") Cc: stable@dpdk.org Reported-by: Ilja Van Sprundel <ivansprundel@ioactive.com> Signed-off-by: Maxime Coquelin <maxime.coquelin@redhat.com> Reviewed-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Ilja Van Sprundel <ivansprundel@ioactive.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: FastHufDecoder::FastHufDecoder (const char *&table, int numBytes, int minSymbol, int maxSymbol, int rleSymbol) : _rleSymbol (rleSymbol), _numSymbols (0), _minCodeLength (255), _maxCodeLength (0), _idToSymbol (0) { // // List of symbols that we find with non-zero code lengths // (listed in the order we find them). Store these in the // same format as the code book stores codes + lengths - // low 6 bits are the length, everything above that is // the symbol. // std::vector<Int64> symbols; // // The 'base' table is the minimum code at each code length. base[i] // is the smallest code (numerically) of length i. // Int64 base[MAX_CODE_LEN + 1]; // // The 'offset' table is the position (in sorted order) of the first id // of a given code lenght. Array is indexed by code length, like base. // Int64 offset[MAX_CODE_LEN + 1]; // // Count of how many codes at each length there are. Array is // indexed by code length, like base and offset. // size_t codeCount[MAX_CODE_LEN + 1]; for (int i = 0; i <= MAX_CODE_LEN; ++i) { codeCount[i] = 0; base[i] = 0xffffffffffffffffULL; offset[i] = 0; } // // Count the number of codes, the min/max code lengths, the number of // codes with each length, and record symbols with non-zero code // length as we find them. // const char *currByte = table; Int64 currBits = 0; int currBitCount = 0; const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; for (Int64 symbol = static_cast<Int64>(minSymbol); symbol <= static_cast<Int64>(maxSymbol); symbol++) { if (currByte - table > numBytes) { throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " "(Truncated table data)."); } // // Next code length - either: // 0-58 (literal code length) // 59-62 (various lengths runs of 0) // 63 (run of n 0's, with n is the next 8 bits) // Int64 codeLen = readBits (6, currBits, currBitCount, currByte); if (codeLen == (Int64) LONG_ZEROCODE_RUN) { if (currByte - table > numBytes) { throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " "(Truncated table data)."); } int runLen = readBits (8, currBits, currBitCount, currByte) + SHORTEST_LONG_RUN; if (symbol + runLen > static_cast<Int64>(maxSymbol + 1)) { throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " "(Run beyond end of table)."); } symbol += runLen - 1; } else if (codeLen >= static_cast<Int64>(SHORT_ZEROCODE_RUN)) { int runLen = codeLen - SHORT_ZEROCODE_RUN + 2; if (symbol + runLen > static_cast<Int64>(maxSymbol + 1)) { throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " "(Run beyond end of table)."); } symbol += runLen - 1; } else if (codeLen != 0) { symbols.push_back ((symbol << 6) | (codeLen & 63)); if (codeLen < _minCodeLength) _minCodeLength = codeLen; if (codeLen > _maxCodeLength) _maxCodeLength = codeLen; codeCount[codeLen]++; } } for (int i = 0; i < MAX_CODE_LEN; ++i) _numSymbols += codeCount[i]; table = currByte; // // Compute base - once we have the code length counts, there // is a closed form solution for this // { double* countTmp = new double[_maxCodeLength+1]; for (int l = _minCodeLength; l <= _maxCodeLength; ++l) { countTmp[l] = (double)codeCount[l] * (double)(2 << (_maxCodeLength-l)); } for (int l = _minCodeLength; l <= _maxCodeLength; ++l) { double tmp = 0; for (int k =l + 1; k <= _maxCodeLength; ++k) tmp += countTmp[k]; tmp /= (double)(2 << (_maxCodeLength - l)); base[l] = (Int64)ceil (tmp); } delete [] countTmp; } // // Compute offset - these are the positions of the first // id (not symbol) that has length [i] // offset[_maxCodeLength] = 0; for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--) offset[i] = offset[i + 1] + codeCount[i + 1]; // // Allocate and fill the symbol-to-id mapping. Smaller Ids should be // mapped to less-frequent symbols (which have longer codes). Use // the offset table to tell us where the id's for a given code // length start off. // _idToSymbol = new int[_numSymbols]; Int64 mapping[MAX_CODE_LEN + 1]; for (int i = 0; i < MAX_CODE_LEN + 1; ++i) mapping[i] = -1; for (int i = _minCodeLength; i <= _maxCodeLength; ++i) mapping[i] = offset[i]; for (std::vector<Int64>::const_iterator i = symbols.begin(); i != symbols.end(); ++i) { int codeLen = *i & 63; int symbol = *i >> 6; if (mapping[codeLen] >= static_cast<Int64>(_numSymbols)) throw IEX_NAMESPACE::InputExc ("Huffman decode error " "(Invalid symbol in header)."); _idToSymbol[mapping[codeLen]] = symbol; mapping[codeLen]++; } buildTables(base, offset); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ScanLineInputFile::ScanLineInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int numThreads) : _data (new Data (numThreads)), _streamData (new InputStreamMutex()) { _streamData->is = is; _data->memoryMapped = is->isMemoryMapped(); initialize(header); // // (TODO) this is nasty - we need a better way of working out what type of file has been used. // in any case I believe this constructor only gets used with single part files // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us // _data->version=0; readLineOffsets (*_streamData->is, _data->lineOrder, _data->lineOffsets, _data->fileIsComplete); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DeepTiledInputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; if (multiPartBackwardSupport) delete multiPartFile; for (size_t i = 0; i < slices.size(); i++) delete slices[i]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hufUncompress (const char compressed[], int nCompressed, unsigned short raw[], int nRaw) { if (nCompressed == 0) { if (nRaw != 0) notEnoughData(); return; } int im = readUInt (compressed); int iM = readUInt (compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt (compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) invalidTableSize(); const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // if (FastHufDecoder::enabled() && nBits > 128) { FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); } else { AutoArray <Int64, HUF_ENCSIZE> freq; AutoArray <HufDec, HUF_DECSIZE> hdec; hufClearDecTable (hdec); hufUnpackEncTable (&ptr, nCompressed - (ptr - compressed), im, iM, freq); try { if (nBits > 8 * (nCompressed - (ptr - compressed))) invalidNBits(); hufBuildDecTable (freq, im, iM, hdec); hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw); } catch (...) { hufFreeDecTable (hdec); throw; } hufFreeDecTable (hdec); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mt76_add_fragment(struct mt76_dev *dev, struct mt76_queue *q, void *data, int len, bool more) { struct page *page = virt_to_head_page(data); int offset = data - page_address(page); struct sk_buff *skb = q->rx_head; offset += q->buf_offset; skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset, len, q->buf_size); if (more) return; q->rx_head = NULL; dev->drv->rx_skb(dev, q - dev->q_rx, skb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'mt76: fix array overflow on receiving too many fragments for a packet If the hardware receives an oversized packet with too many rx fragments, skb_shinfo(skb)->frags can overflow and corrupt memory of adjacent pages. This becomes especially visible if it corrupts the freelist pointer of a slab page. Cc: stable@vger.kernel.org Signed-off-by: Felix Fietkau <nbd@nbd.name> Signed-off-by: Kalle Valo <kvalo@codeaurora.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_mpt_command (unsigned long arg) { struct mpt_ioctl_command __user *uarg = (void __user *) arg; struct mpt_ioctl_command karg; MPT_ADAPTER *ioc; int iocnum; int rc; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_mpt_command - " "Unable to read in mpt_ioctl_command struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_mpt_command() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } rc = mptctl_do_mpt_command (karg, &uarg->MF); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_replace_fw (unsigned long arg) { struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg; struct mpt_ioctl_replace_fw karg; MPT_ADAPTER *ioc; int iocnum; int newFwSize; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n", ioc->name)); /* If caching FW, Free the old FW image */ if (ioc->cached_fw == NULL) return 0; mpt_free_fw_memory(ioc); /* Allocate memory for the new FW image */ newFwSize = ALIGN(karg.newImageSize, 4); mpt_alloc_fw_memory(ioc, newFwSize); if (ioc->cached_fw == NULL) return -ENOMEM; /* Copy the data from user memory to kernel space */ if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - " "Unable to read in mpt_ioctl_replace_fw image " "@ %p\n", ioc->name, __FILE__, __LINE__, uarg); mpt_free_fw_memory(ioc); return -EFAULT; } /* Update IOCFactsReply */ ioc->facts.FWImageSize = newFwSize; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, "info: WMM: WMM_GET_STATUS cmdresp received: %d\n", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "QSTATUS TLV: %d, %d, %d\n", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "WMM Parameter Set Count: %d\n", wmm_param_ie->qos_info_bitmap & mask); memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'mwifiex: Fix possible buffer overflows in mwifiex_ret_wmm_get_status() mwifiex_ret_wmm_get_status() calls memcpy() without checking the destination size.Since the source is given from remote AP which contains illegal wmm elements , this may trigger a heap buffer overflow. Fix it by putting the length check before calling memcpy(). Signed-off-by: Qing Xu <m1s5p6688@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HiiGetDatabaseInfo( IN CONST EFI_HII_DATABASE_PROTOCOL *This ) { EFI_STATUS Status; EFI_HII_PACKAGE_LIST_HEADER *DatabaseInfo; UINTN DatabaseInfoSize; DatabaseInfo = NULL; DatabaseInfoSize = 0; // // Get HiiDatabase information. // Status = HiiExportPackageLists(This, NULL, &DatabaseInfoSize, DatabaseInfo); ASSERT(Status == EFI_BUFFER_TOO_SMALL); if(DatabaseInfoSize > gDatabaseInfoSize ) { // // Do 25% overallocation to minimize the number of memory allocations after ReadyToBoot. // Since lots of allocation after ReadyToBoot may change memory map and cause S4 resume issue. // gDatabaseInfoSize = DatabaseInfoSize + (DatabaseInfoSize >> 2); if (gRTDatabaseInfoBuffer != NULL){ FreePool(gRTDatabaseInfoBuffer); DEBUG ((DEBUG_WARN, "[HiiDatabase]: Memory allocation is required after ReadyToBoot, which may change memory map and cause S4 resume issue.\n")); } gRTDatabaseInfoBuffer = AllocateRuntimeZeroPool (gDatabaseInfoSize); if (gRTDatabaseInfoBuffer == NULL){ DEBUG ((DEBUG_ERROR, "[HiiDatabase]: No enough memory resource to store the HiiDatabase info.\n")); return EFI_OUT_OF_RESOURCES; } } else { ZeroMem(gRTDatabaseInfoBuffer,gDatabaseInfoSize); } Status = HiiExportPackageLists(This, NULL, &DatabaseInfoSize, gRTDatabaseInfoBuffer); ASSERT_EFI_ERROR (Status); gBS->InstallConfigurationTable (&gEfiHiiDatabaseProtocolGuid, gRTDatabaseInfoBuffer); return EFI_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'MdeModulePkg/HiiDB: Remove configuration table when it's freed (CVE-2019-14586) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1995 Fix the corner case issue that the original configuration runtime memory is freed, but it is still exposed to the OS runtime. So this patch is to remove the configuration table to avoid being used in OS runtime when the configuration runtime memory is freed. Cc: Liming Gao <liming.gao@intel.com> Cc: Eric Dong <eric.dong@intel.com> Cc: Jian J Wang <jian.j.wang@intel.com> Signed-off-by: Dandan Bi <dandan.bi@intel.com> Reviewed-by: Eric Dong <eric.dong@intel.com> Reviewed-by: Jian J Wang <jian.j.wang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int stv06xx_isoc_nego(struct gspca_dev *gspca_dev) { int ret, packet_size, min_packet_size; struct usb_host_interface *alt; struct sd *sd = (struct sd *) gspca_dev; alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1]; packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); min_packet_size = sd->sensor->min_packet_size[gspca_dev->curr_mode]; if (packet_size <= min_packet_size) return -EIO; packet_size -= 100; if (packet_size < min_packet_size) packet_size = min_packet_size; alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(packet_size); ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 1); if (ret < 0) gspca_err(gspca_dev, "set alt 1 err %d\n", ret); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: stv06xx: add missing descriptor sanity checks Make sure to check that we have two alternate settings and at least one endpoint before accessing the second altsetting structure and dereferencing the endpoint arrays. This specifically avoids dereferencing NULL-pointers or corrupting memory when a device does not have the expected descriptors. Note that the sanity checks in stv06xx_start() and pb0100_start() are not redundant as the driver is mixing looking up altsettings by index and by number, which may not coincide. Fixes: 8668d504d72c ("V4L/DVB (12082): gspca_stv06xx: Add support for st6422 bridge and sensor") Fixes: c0b33bdc5b8d ("[media] gspca-stv06xx: support bandwidth changing") Cc: stable <stable@vger.kernel.org> # 2.6.31 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo) { BYTE* newBitMask; if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */ Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */ if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp); return FALSE; } Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */ Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */ /* cbColorTable is only present when bpp is 1, 4 or 8 */ switch (iconInfo->bpp) { case 1: case 4: case 8: if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */ break; default: iconInfo->cbColorTable = 0; break; } if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */ Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */ if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor) return FALSE; /* bitsMask */ newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask); if (!newBitMask) { free(iconInfo->bitsMask); iconInfo->bitsMask = NULL; return FALSE; } iconInfo->bitsMask = newBitMask; Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* colorTable */ if (iconInfo->colorTable == NULL) { if (iconInfo->cbColorTable) { iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable); if (!iconInfo->colorTable) return FALSE; } } else if (iconInfo->cbColorTable) { BYTE* new_tab; new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable); if (!new_tab) { free(iconInfo->colorTable); iconInfo->colorTable = NULL; return FALSE; } iconInfo->colorTable = new_tab; } else { free(iconInfo->colorTable); iconInfo->colorTable = NULL; } if (iconInfo->colorTable) Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable); /* bitsColor */ newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor); if (!newBitMask) { free(iconInfo->bitsColor); iconInfo->bitsColor = NULL; return FALSE; } iconInfo->bitsColor = newBitMask; Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix #6010: Check length in read_icon_info'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { BYTE bitsPerPixelId; CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; if (!update || !s) return NULL; cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!cache_bitmap_v2) goto fail; cache_bitmap_v2->cacheId = flags & 0x0003; cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; bitsPerPixelId = (flags & 0x0078) >> 3; cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ goto fail; cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; } else { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ goto fail; } if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ goto fail; if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } } if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength) goto fail; if (cache_bitmap_v2->bitmapLength == 0) goto fail; cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength); if (!cache_bitmap_v2->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); cache_bitmap_v2->compressed = compressed; return cache_bitmap_v2; fail: free_cache_bitmap_v2_order(update->context, cache_bitmap_v2); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11521: Out of bounds write in planar codec. Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE BOOL ensure_capacity(const BYTE* start, const BYTE* end, size_t size, size_t base) { const size_t available = (uintptr_t)end - (uintptr_t)start; const BOOL rc = available >= size * base; return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix CVE-2020-11524: out of bounds access in interleaved Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: auth_spa_server(auth_instance *ablock, uschar *data) { auth_spa_options_block *ob = (auth_spa_options_block *)(ablock->options_block); uint8x lmRespData[24]; uint8x ntRespData[24]; SPAAuthRequest request; SPAAuthChallenge challenge; SPAAuthResponse response; SPAAuthResponse *responseptr = &response; uschar msgbuf[2048]; uschar *clearpass, *s; /* send a 334, MS Exchange style, and grab the client's request, unless we already have it via an initial response. */ if (!*data && auth_get_no64_data(&data, US"NTLM supported") != OK) return FAIL; if (spa_base64_to_bits(CS &request, sizeof(request), CCS data) < 0) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad base64 data in " "request: %s\n", data); return FAIL; } /* create a challenge and send it back */ spa_build_auth_challenge(&request, &challenge); spa_bits_to_base64(msgbuf, US &challenge, spa_request_length(&challenge)); if (auth_get_no64_data(&data, msgbuf) != OK) return FAIL; /* dump client response */ if (spa_base64_to_bits(CS &response, sizeof(response), CCS data) < 0) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad base64 data in " "response: %s\n", data); return FAIL; } /*************************************************************** PH 07-Aug-2003: The original code here was this: Ustrcpy(msgbuf, unicodeToString(((char*)responseptr) + IVAL(&responseptr->uUser.offset,0), SVAL(&responseptr->uUser.len,0)/2) ); However, if the response data is too long, unicodeToString bombs out on an assertion failure. It uses a 1024 fixed buffer. Bombing out is not a good idea. It's too messy to try to rework that function to return an error because it is called from a number of other places in the auth-spa.c module. Instead, since it is a very small function, I reproduce its code here, with a size check that causes failure if the size of msgbuf is exceeded. ****/ { int i; char * p = (CS responseptr) + IVAL(&responseptr->uUser.offset,0); int len = SVAL(&responseptr->uUser.len,0)/2; if (p + len*2 >= CS (responseptr+1)) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad uUser spec in response\n"); return FAIL; } if (len + 1 >= sizeof(msgbuf)) return FAIL; for (i = 0; i < len; ++i) { msgbuf[i] = *p & 0x7f; p += 2; } msgbuf[i] = 0; } /***************************************************************/ /* Put the username in $auth1 and $1. The former is now the preferred variable; the latter is the original variable. These have to be out of stack memory, and need to be available once known even if not authenticated, for error messages (server_set_id, which only makes it to authenticated_id if we return OK) */ auth_vars[0] = expand_nstring[1] = string_copy(msgbuf); expand_nlength[1] = Ustrlen(msgbuf); expand_nmax = 1; debug_print_string(ablock->server_debug_string); /* customized debug */ /* look up password */ if (!(clearpass = expand_string(ob->spa_serverpassword))) if (f.expand_string_forcedfail) { DEBUG(D_auth) debug_printf("auth_spa_server(): forced failure while " "expanding spa_serverpassword\n"); return FAIL; } else { DEBUG(D_auth) debug_printf("auth_spa_server(): error while expanding " "spa_serverpassword: %s\n", expand_string_message); return DEFER; } /* create local hash copy */ spa_smb_encrypt(clearpass, challenge.challengeData, lmRespData); spa_smb_nt_encrypt(clearpass, challenge.challengeData, ntRespData); /* compare NT hash (LM may not be available) */ s = (US responseptr) + IVAL(&responseptr->ntResponse.offset,0); if (s + 24 >= US (responseptr+1)) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad ntRespData spec in response\n"); return FAIL; } if (memcmp(ntRespData, s, 24) == 0) return auth_check_serv_cond(ablock); /* success. we have a winner. */ /* Expand server_condition as an authorization check (PH) */ return FAIL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Rework SPA fix to avoid overflows. Bug 2571 Amends: 57aa14b216'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int iter_lookup_parent_glue_from_cache(struct module_env* env, struct delegpt* dp, struct regional* region, struct query_info* qinfo) { struct ub_packed_rrset_key* akey; struct delegpt_ns* ns; size_t num = delegpt_count_targets(dp); for(ns = dp->nslist; ns; ns = ns->next) { /* get cached parentside A */ akey = rrset_cache_lookup(env->rrset_cache, ns->name, ns->namelen, LDNS_RR_TYPE_A, qinfo->qclass, PACKED_RRSET_PARENT_SIDE, *env->now, 0); if(akey) { log_rrset_key(VERB_ALGO, "found parent-side", akey); ns->done_pside4 = 1; /* a negative-cache-element has no addresses it adds */ if(!delegpt_add_rrset_A(dp, region, akey, 1)) log_err("malloc failure in lookup_parent_glue"); lock_rw_unlock(&akey->entry.lock); } /* get cached parentside AAAA */ akey = rrset_cache_lookup(env->rrset_cache, ns->name, ns->namelen, LDNS_RR_TYPE_AAAA, qinfo->qclass, PACKED_RRSET_PARENT_SIDE, *env->now, 0); if(akey) { log_rrset_key(VERB_ALGO, "found parent-side", akey); ns->done_pside6 = 1; /* a negative-cache-element has no addresses it adds */ if(!delegpt_add_rrset_AAAA(dp, region, akey, 1)) log_err("malloc failure in lookup_parent_glue"); lock_rw_unlock(&akey->entry.lock); } } /* see if new (but lame) addresses have become available */ return delegpt_count_targets(dp) != num; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_get_cname_target(struct rrset_parse* rrset, uint8_t** sname, size_t* snamelen) { if(rrset->rr_count != 1) { struct rr_parse* sig; verbose(VERB_ALGO, "Found CNAME rrset with " "size > 1: %u", (unsigned)rrset->rr_count); /* use the first CNAME! */ rrset->rr_count = 1; rrset->size = rrset->rr_first->size; for(sig=rrset->rrsig_first; sig; sig=sig->next) rrset->size += sig->size; rrset->rr_last = rrset->rr_first; rrset->rr_first->next = NULL; } if(rrset->rr_first->size < sizeof(uint16_t)+1) return 0; /* CNAME rdata too small */ *sname = rrset->rr_first->ttl_data + sizeof(uint32_t) + sizeof(uint16_t); /* skip ttl, rdatalen */ *snamelen = rrset->rr_first->size - sizeof(uint16_t); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: generate_target_query(struct module_qstate* qstate, struct iter_qstate* iq, int id, uint8_t* name, size_t namelen, uint16_t qtype, uint16_t qclass) { struct module_qstate* subq; if(!generate_sub_request(name, namelen, qtype, qclass, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, 0)) return 0; log_nametypeclass(VERB_QUERY, "new target", name, qtype, qclass); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: processTargetResponse(struct module_qstate* qstate, int id, struct module_qstate* forq) { struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; struct iter_qstate* foriq = (struct iter_qstate*)forq->minfo[id]; struct ub_packed_rrset_key* rrset; struct delegpt_ns* dpns; log_assert(qstate->return_rcode == LDNS_RCODE_NOERROR); foriq->state = QUERYTARGETS_STATE; log_query_info(VERB_ALGO, "processTargetResponse", &qstate->qinfo); log_query_info(VERB_ALGO, "processTargetResponse super", &forq->qinfo); /* Tell the originating event that this target query has finished * (regardless if it succeeded or not). */ foriq->num_target_queries--; /* check to see if parent event is still interested (in orig name). */ if(!foriq->dp) { verbose(VERB_ALGO, "subq: parent not interested, was reset"); return; /* not interested anymore */ } dpns = delegpt_find_ns(foriq->dp, qstate->qinfo.qname, qstate->qinfo.qname_len); if(!dpns) { /* If not interested, just stop processing this event */ verbose(VERB_ALGO, "subq: parent not interested anymore"); /* could be because parent was jostled out of the cache, and a new identical query arrived, that does not want it*/ return; } /* if iq->query_for_pside_glue then add the pside_glue (marked lame) */ if(iq->pside_glue) { /* if the pside_glue is NULL, then it could not be found, * the done_pside is already set when created and a cache * entry created in processFinished so nothing to do here */ log_rrset_key(VERB_ALGO, "add parentside glue to dp", iq->pside_glue); if(!delegpt_add_rrset(foriq->dp, forq->region, iq->pside_glue, 1)) log_err("out of memory adding pside glue"); } /* This response is relevant to the current query, so we * add (attempt to add, anyway) this target(s) and reactivate * the original event. * NOTE: we could only look for the AnswerRRset if the * response type was ANSWER. */ rrset = reply_find_answer_rrset(&iq->qchase, qstate->return_msg->rep); if(rrset) { /* if CNAMEs have been followed - add new NS to delegpt. */ /* BTW. RFC 1918 says NS should not have got CNAMEs. Robust. */ if(!delegpt_find_ns(foriq->dp, rrset->rk.dname, rrset->rk.dname_len)) { /* if dpns->lame then set newcname ns lame too */ if(!delegpt_add_ns(foriq->dp, forq->region, rrset->rk.dname, dpns->lame)) log_err("out of memory adding cnamed-ns"); } /* if dpns->lame then set the address(es) lame too */ if(!delegpt_add_rrset(foriq->dp, forq->region, rrset, dpns->lame)) log_err("out of memory adding targets"); verbose(VERB_ALGO, "added target response"); delegpt_log(VERB_ALGO, foriq->dp); } else { verbose(VERB_ALGO, "iterator TargetResponse failed"); dpns->resolved = 1; /* fail the target */ } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN"); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Assembling pattern from %d elements%s\n", pat_count, orig_rx_flags & RXf_SPLIT ? " for split" : "")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Precompiled pattern%s\n", orig_rx_flags & RXf_SPLIT ? " for split" : "")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL("Regexp out of space"); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ "Eval-group in insecure regular expression"); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Starting parse and generation\n"); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, "foo"); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; /* XXX For backporting, use long jumps if there is any possibility of * overflow */ if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) { RExC_use_BRANCHJ = TRUE; flags |= RESTART_PARSE; } } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Required size %" IVdf " nodes\n", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ "%s %" UVuf " bytes for offset annotations.\n", RExC_offsets ? "Got" : "Couldn't get", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ "\n"); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "Starting post parse optimization\n"); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is "must appear" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP("first:", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""); data.substrs[1].str = newSVpvs(""); data.last_found = newSVpvs(""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name("study_chunk"); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name("study_chunk"); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the "real" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify "special" patterns that might result * in Perl NOT calling the regex engine and instead doing the match "itself", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ "Final program:\n"); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'study_chunk: avoid mutating regexp program within GOSUB gh16947 and gh17743: studying GOSUB may restudy in an inner call (via a mix of recursion and enframing) something that an outer call is in the middle of looking at. Let the outer frame deal with it. (CVE-2020-12723) (cherry picked from commit c4033e740bd18d9fbe3456a9db2ec2053cdc5271)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exif_mnote_data_fuji_load (ExifMnoteData *en, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji*) en; ExifLong c; size_t i, tcount, o, datao; if (!n || !buf || !buf_size) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } datao = 6 + n->offset; if (CHECKOVERFLOW(datao, buf_size, 12)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } n->order = EXIF_BYTE_ORDER_INTEL; datao += exif_get_long (buf + datao + 8, EXIF_BYTE_ORDER_INTEL); if (CHECKOVERFLOW(datao, buf_size, 2)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } /* Read the number of tags */ c = exif_get_short (buf + datao, EXIF_BYTE_ORDER_INTEL); datao += 2; /* Remove any old entries */ exif_mnote_data_fuji_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (en->mem, sizeof (MnoteFujiEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", sizeof (MnoteFujiEntry) * c); return; } /* Parse all c entries, storing ones that are successfully parsed */ tcount = 0; for (i = c, o = datao; i; --i, o += 12) { size_t s; if (CHECKOVERFLOW(o, buf_size, 12)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o, n->order); n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_fuji_tag_get_name (n->entries[tcount].tag)); /* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection, * we will check the buffer sizes closer later. */ if ( exif_format_get_size (n->entries[tcount].format) && buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components ) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components); continue; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (s) { size_t dataofs = o + 8; if (s > 4) /* The data in this case is merely a pointer */ dataofs = exif_get_long (buf + dataofs, n->order) + 6 + n->offset; if (CHECKOVERFLOW(dataofs, buf_size, s)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Tag data past end of " "buffer (%u >= %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (en->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-908'], 'message': 'Ensure the MakerNote data pointers are initialized with NULL. This ensures that an uninitialized pointer isn't dereferenced later in the case where the number of components (and therefore size) is 0. This fixes the second issue reported at https://sourceforge.net/p/libexif/bugs/125/ CVE-2020-13113'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void tw5864_handle_frame(struct tw5864_h264_frame *frame) { #define SKIP_VLCBUF_BYTES 3 struct tw5864_input *input = frame->input; struct tw5864_dev *dev = input->root; struct tw5864_buf *vb; struct vb2_v4l2_buffer *v4l2_buf; int frame_len = frame->vlc_len - SKIP_VLCBUF_BYTES; u8 *dst = input->buf_cur_ptr; u8 tail_mask, vlc_mask = 0; int i; u8 vlc_first_byte = ((u8 *)(frame->vlc.addr + SKIP_VLCBUF_BYTES))[0]; unsigned long flags; int zero_run; u8 *src; u8 *src_end; #ifdef DEBUG if (frame->checksum != tw5864_vlc_checksum((u32 *)frame->vlc.addr, frame_len)) dev_err(&dev->pci->dev, "Checksum of encoded frame doesn't match!\n"); #endif spin_lock_irqsave(&input->slock, flags); vb = input->vb; input->vb = NULL; spin_unlock_irqrestore(&input->slock, flags); v4l2_buf = to_vb2_v4l2_buffer(&vb->vb.vb2_buf); if (!vb) { /* Gone because of disabling */ dev_dbg(&dev->pci->dev, "vb is empty, dropping frame\n"); return; } /* * Check for space. * Mind the overhead of startcode emulation prevention. */ if (input->buf_cur_space_left < frame_len * 5 / 4) { dev_err_once(&dev->pci->dev, "Left space in vb2 buffer, %d bytes, is less than considered safely enough to put frame of length %d. Dropping this frame.\n", input->buf_cur_space_left, frame_len); return; } for (i = 0; i < 8 - input->tail_nb_bits; i++) vlc_mask |= 1 << i; tail_mask = (~vlc_mask) & 0xff; dst[0] = (input->tail & tail_mask) | (vlc_first_byte & vlc_mask); frame_len--; dst++; /* H.264 startcode emulation prevention */ src = frame->vlc.addr + SKIP_VLCBUF_BYTES + 1; src_end = src + frame_len; zero_run = 0; for (; src < src_end; src++) { if (zero_run < 2) { if (*src == 0) ++zero_run; else zero_run = 0; } else { if ((*src & ~0x03) == 0) *dst++ = 0x03; zero_run = *src == 0; } *dst++ = *src; } vb2_set_plane_payload(&vb->vb.vb2_buf, 0, dst - (u8 *)vb2_plane_vaddr(&vb->vb.vb2_buf, 0)); vb->vb.vb2_buf.timestamp = frame->timestamp; v4l2_buf->field = V4L2_FIELD_INTERLACED; v4l2_buf->sequence = frame->seqno; /* Check for motion flags */ if (frame->gop_seqno /* P-frame */ && tw5864_is_motion_triggered(frame)) { struct v4l2_event ev = { .type = V4L2_EVENT_MOTION_DET, .u.motion_det = { .flags = V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ, .frame_sequence = v4l2_buf->sequence, }, }; v4l2_event_queue(&input->vdev, &ev); } vb2_buffer_done(&vb->vb.vb2_buf, VB2_BUF_STATE_DONE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: tw5864: Fix possible NULL pointer dereference in tw5864_handle_frame 'vb' null check should be done before dereferencing it in tw5864_handle_frame, otherwise a NULL pointer dereference may occur. Fixes: 34d1324edd31 ("[media] pci: Add tw5864 driver") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: f_pyeval(typval_T *argvars, typval_T *rettv) { char_u *str; char_u buf[NUMBUFLEN]; if (p_pyx == 0) p_pyx = 2; str = tv_get_string_buf(&argvars[0], buf); do_pyeval(str, rettv); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'patch 8.1.0881: can execute shell commands in rvim through interfaces Problem: Can execute shell commands in rvim through interfaces. Solution: Disable using interfaces in restricted mode. Allow for writing file with writefile(), histadd() and a few others.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in ntlm_read_NegotiateMessage'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s) { UINT16 eventId; UINT32 pduLength; UINT error; Stream_Read_UINT16(s, eventId); /* eventId (2 bytes) */ Stream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */ #ifdef WITH_DEBUG_RDPEI WLog_DBG(TAG, "rdpei_recv_pdu: eventId: %" PRIu16 " (%s) length: %" PRIu32 "", eventId, rdpei_eventid_string(eventId), pduLength); #endif switch (eventId) { case EVENTID_SC_READY: if ((error = rdpei_recv_sc_ready_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_sc_ready_pdu failed with error %" PRIu32 "!", error); return error; } if ((error = rdpei_send_cs_ready_pdu(callback))) { WLog_ERR(TAG, "rdpei_send_cs_ready_pdu failed with error %" PRIu32 "!", error); return error; } break; case EVENTID_SUSPEND_TOUCH: if ((error = rdpei_recv_suspend_touch_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_suspend_touch_pdu failed with error %" PRIu32 "!", error); return error; } break; case EVENTID_RESUME_TOUCH: if ((error = rdpei_recv_resume_touch_pdu(callback, s))) { WLog_ERR(TAG, "rdpei_recv_resume_touch_pdu failed with error %" PRIu32 "!", error); return error; } break; default: break; } return CHANNEL_RC_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed oob read in irp_write and similar'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionImpl::StreamImpl::encodeData(Buffer::Instance& data, bool end_stream) { ASSERT(!local_end_stream_); local_end_stream_ = end_stream; pending_send_data_.move(data); if (data_deferred_) { int rc = nghttp2_session_resume_data(parent_.session_, stream_id_); ASSERT(rc == 0); data_deferred_ = false; } parent_.sendPendingFrames(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ConnectionImpl::onStreamClose(int32_t stream_id, uint32_t error_code) { StreamImpl* stream = getStream(stream_id); if (stream) { ENVOY_CONN_LOG(debug, "stream closed: {}", connection_, error_code); if (!stream->remote_end_stream_ || !stream->local_end_stream_) { StreamResetReason reason; if (stream->reset_due_to_messaging_error_) { // Unfortunately, the nghttp2 API makes it incredibly difficult to clearly understand // the flow of resets. I.e., did the reset originate locally? Was it remote? Here, // we attempt to track cases in which we sent a reset locally due to an invalid frame // received from the remote. We only do that in two cases currently (HTTP messaging layer // errors from https://tools.ietf.org/html/rfc7540#section-8 which nghttp2 is very strict // about). In other cases we treat invalid frames as a protocol error and just kill // the connection. reason = StreamResetReason::LocalReset; } else { reason = error_code == NGHTTP2_REFUSED_STREAM ? StreamResetReason::RemoteRefusedStreamReset : StreamResetReason::RemoteReset; } stream->runResetCallbacks(reason); } connection_.dispatcher().deferredDelete(stream->removeFromList(active_streams_)); // Any unconsumed data must be consumed before the stream is deleted. // nghttp2 does not appear to track this internally, and any stream deleted // with outstanding window will contribute to a slow connection-window leak. nghttp2_session_consume(session_, stream_id, stream->unconsumed_bytes_); stream->unconsumed_bytes_ = 0; nghttp2_session_set_stream_user_data(session_, stream->stream_id_, nullptr); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_P(SslCertficateIntegrationTest, ServerEcdsaClientRsaOnly) { server_rsa_cert_ = false; server_ecdsa_cert_ = true; initialize(); auto codec_client = makeRawHttpConnection(makeSslClientConnection(rsaOnlyClientOptions())); EXPECT_FALSE(codec_client->connected()); const std::string counter_name = listenerStatPrefix("ssl.connection_error"); Stats::CounterSharedPtr counter = test_server_->counter(counter_name); test_server_->waitForCounterGe(counter_name, 1); EXPECT_EQ(1U, counter->value()); counter->reset(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_P(Http2CodecImplDeferredResetTest, DeferredResetServer) { initialize(); InSequence s; TestRequestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); EXPECT_CALL(request_decoder_, decodeHeaders_(_, false)); request_encoder_->encodeHeaders(request_headers, false); // In this case we do the same thing as DeferredResetClient but on the server side. ON_CALL(server_connection_, write(_, _)) .WillByDefault( Invoke([&](Buffer::Instance& data, bool) -> void { client_wrapper_.buffer_.add(data); })); TestResponseHeaderMapImpl response_headers{{":status", "200"}}; response_encoder_->encodeHeaders(response_headers, false); Buffer::OwnedImpl body(std::string(1024 * 1024, 'a')); EXPECT_CALL(server_stream_callbacks_, onAboveWriteBufferHighWatermark()).Times(AnyNumber()); response_encoder_->encodeData(body, true); EXPECT_CALL(server_stream_callbacks_, onResetStream(StreamResetReason::LocalReset, _)); response_encoder_->getStream().resetStream(StreamResetReason::LocalReset); MockStreamCallbacks client_stream_callbacks; request_encoder_->getStream().addCallbacks(client_stream_callbacks); EXPECT_CALL(response_decoder_, decodeHeaders_(_, false)); EXPECT_CALL(response_decoder_, decodeData(_, false)).Times(AtLeast(1)); EXPECT_CALL(client_stream_callbacks, onResetStream(StreamResetReason::RemoteReset, _)); setupDefaultConnectionMocks(); auto status = client_wrapper_.dispatch(Buffer::OwnedImpl(), *client_); EXPECT_TRUE(status.ok()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'http/2: add stats and stream flush timeout (#139) This commit adds a new stream flush timeout to guard against a remote server that does not open window once an entire stream has been buffered for flushing. Additional stats have also been added to better understand the codecs view of active streams as well as amount of data buffered. Signed-off-by: Matt Klein <mklein@lyft.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(Http1ServerConnectionImplTest, LargeTrailersRejectedIgnored) { // Default limit of 60 KiB std::string long_string = "big: " + std::string(60 * 1024, 'q') + "\r\n"; testTrailersExceedLimit(long_string, false); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': '[http1] Include request URL in request header size computation, and reject partial headers that exceed configured limits (#145) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_P(ClusterMemoryTestRunner, MemoryLargeClusterSizeWithRealSymbolTable) { symbol_table_creator_test_peer_.setUseFakeSymbolTables(false); // A unique instance of ClusterMemoryTest allows for multiple runs of Envoy with // differing configuration. This is necessary for measuring the memory consumption // between the different instances within the same test. const size_t m100 = ClusterMemoryTestHelper::computeMemoryDelta(1, 0, 101, 0, true); const size_t m_per_cluster = (m100) / 100; // Note: if you are increasing this golden value because you are adding a // stat, please confirm that this will be generally useful to most Envoy // users. Otherwise you are adding to the per-cluster memory overhead, which // will be significant for Envoy installations that are massively // multi-tenant. // // History of golden values: // // Date PR Bytes Per Cluster Notes // exact upper-bound // ---------- ----- ----------------- ----- // 2019/08/09 7882 35489 36000 Initial version // 2019/09/02 8118 34585 34500 Share symbol-tables in cluster/host stats. // 2019/09/16 8100 34585 34500 Add transport socket matcher in cluster. // 2019/09/25 8226 34777 35000 dns: enable dns failure refresh rate configuration // 2019/09/30 8354 34969 35000 Implement transport socket match. // 2019/10/17 8537 34966 35000 add new enum value HTTP3 // 2019/10/17 8484 34998 35000 stats: add unit support to histogram // 2019/11/01 8859 35221 36000 build: switch to libc++ by default // 2019/11/15 9040 35029 35500 build: update protobuf to 3.10.1 // 2019/11/15 9031 35061 35500 upstream: track whether cluster is local // 2019/12/10 8779 35053 35000 use var-length coding for name lengths // 2020/01/07 9069 35548 35700 upstream: Implement retry concurrency budgets // 2020/01/07 9564 35580 36000 RefcountPtr for CentralCache. // 2020/01/09 8889 35644 36000 api: add UpstreamHttpProtocolOptions message // 2019/01/09 9227 35772 36500 router: per-cluster histograms w/ timeout budget // 2020/01/12 9633 35932 36500 config: support recovery of original message when // upgrading. // 2020/03/16 9964 36220 36800 http2: support custom SETTINGS parameters. // 2020/03/24 10501 36300 36800 upstream: upstream_rq_retry_limit_exceeded. // 2020/04/02 10624 35564 36000 Use 100 clusters rather than 1000 to avoid timeouts // 2020/04/07 10661 35557 36000 fix clang tidy on master // 2020/04/23 10531 36281 36800 http: max stream duration upstream support. // 2020/05/05 10908 36345 36800 router: add InternalRedirectPolicy and predicate // 2020/05/13 10531 36537 36800 Refactor resource manager // 2020/05/20 11223 36603 36800 Add primary clusters tracking to cluster manager. // 2020/06/10 11561 36603 36923 Make upstreams pluggable // Note: when adjusting this value: EXPECT_MEMORY_EQ is active only in CI // 'release' builds, where we control the platform and tool-chain. So you // will need to find the correct value only after failing CI and looking // at the logs. // // On a local clang8/libstdc++/linux flow, the memory usage was observed in // June 2019 to be 64 bytes higher than it is in CI/release. Your mileage may // vary. // // If you encounter a failure here, please see // https://github.com/envoyproxy/envoy/blob/master/source/docs/stats.md#stats-memory-tests // for details on how to fix. EXPECT_MEMORY_EQ(m_per_cluster, 36603); EXPECT_MEMORY_LE(m_per_cluster, 38000); // Round up to allow platform variations. } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'listener: Add configurable accepted connection limits (#153) Add support for per-listener limits on accepted connections. Signed-off-by: Tony Allen <tony@allen.gg>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void InstanceImpl::onRuntimeReady() { // Begin initializing secondary clusters after RTDS configuration has been applied. clusterManager().initializeSecondaryClusters(bootstrap_); if (bootstrap_.has_hds_config()) { const auto& hds_config = bootstrap_.hds_config(); async_client_manager_ = std::make_unique<Grpc::AsyncClientManagerImpl>( *config_.clusterManager(), thread_local_, time_source_, *api_, grpc_context_.statNames()); hds_delegate_ = std::make_unique<Upstream::HdsDelegate>( stats_store_, Config::Utility::factoryForGrpcApiConfigSource(*async_client_manager_, hds_config, stats_store_, false) ->create(), hds_config.transport_api_version(), *dispatcher_, Runtime::LoaderSingleton::get(), stats_store_, *ssl_context_manager_, *random_generator_, info_factory_, access_log_manager_, *config_.clusterManager(), *local_info_, *admin_, *singleton_manager_, thread_local_, messageValidationContext().dynamicValidationVisitor(), *api_); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'overload: Runtime configurable global connection limits (#147) Signed-off-by: Tony Allen <tony@allen.gg>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(OwnedImplTest, ReserveReuse) { Buffer::OwnedImpl buffer; static constexpr uint64_t NumIovecs = 2; Buffer::RawSlice iovecs[NumIovecs]; // Reserve some space and leave it uncommitted. uint64_t num_reserved = buffer.reserve(8192, iovecs, NumIovecs); EXPECT_EQ(1, num_reserved); const void* first_slice = iovecs[0].mem_; // Reserve more space and verify that it begins with the same slice from the last reservation. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); EXPECT_EQ(first_slice, iovecs[0].mem_); const void* second_slice = iovecs[1].mem_; // Repeat the last reservation and verify that it yields the same slices. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); EXPECT_EQ(first_slice, iovecs[0].mem_); EXPECT_EQ(second_slice, iovecs[1].mem_); expectSlices({{0, 12248, 12248}, {0, 8152, 8152}}, buffer); // Request a larger reservation, verify that the second entry is replaced with a block with a // larger size. num_reserved = buffer.reserve(30000, iovecs, NumIovecs); const void* third_slice = iovecs[1].mem_; EXPECT_EQ(2, num_reserved); EXPECT_EQ(first_slice, iovecs[0].mem_); EXPECT_EQ(12248, iovecs[0].len_); EXPECT_NE(second_slice, iovecs[1].mem_); EXPECT_EQ(30000 - iovecs[0].len_, iovecs[1].len_); expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}}, buffer); // Repeating a the reservation request for a smaller block returns the previous entry. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); EXPECT_EQ(first_slice, iovecs[0].mem_); EXPECT_EQ(second_slice, iovecs[1].mem_); expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}}, buffer); // Repeat the larger reservation notice that it doesn't match the prior reservation for 30000 // bytes. num_reserved = buffer.reserve(30000, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); EXPECT_EQ(first_slice, iovecs[0].mem_); EXPECT_EQ(12248, iovecs[0].len_); EXPECT_NE(second_slice, iovecs[1].mem_); EXPECT_NE(third_slice, iovecs[1].mem_); EXPECT_EQ(30000 - iovecs[0].len_, iovecs[1].len_); expectSlices({{0, 12248, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {0, 20440, 20440}}, buffer); // Commit the most recent reservation and verify the representation. buffer.commit(iovecs, num_reserved); expectSlices({{12248, 0, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {17752, 2688, 20440}}, buffer); // Do another reservation. num_reserved = buffer.reserve(16384, iovecs, NumIovecs); EXPECT_EQ(2, num_reserved); expectSlices({{12248, 0, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {17752, 2688, 20440}, {0, 16344, 16344}}, buffer); // And commit. buffer.commit(iovecs, num_reserved); expectSlices({{12248, 0, 12248}, {0, 8152, 8152}, {0, 20440, 20440}, {20440, 0, 20440}, {13696, 2648, 16344}}, buffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool ConnectionImpl::addOutboundFrameFragment(Buffer::OwnedImpl& output, const uint8_t* data, size_t length) { // Reset the outbound frame type (set in the onBeforeFrameSend callback) since the // onBeforeFrameSend callback is not called for DATA frames. bool is_outbound_flood_monitored_control_frame = false; std::swap(is_outbound_flood_monitored_control_frame, is_outbound_flood_monitored_control_frame_); try { incrementOutboundFrameCount(is_outbound_flood_monitored_control_frame); } catch (const FrameFloodException&) { return false; } auto fragment = Buffer::OwnedBufferFragmentImpl::create( absl::string_view(reinterpret_cast<const char*>(data), length), is_outbound_flood_monitored_control_frame ? control_frame_buffer_releasor_ : frame_buffer_releasor_); // The Buffer::OwnedBufferFragmentImpl object will be deleted in the *frame_buffer_releasor_ // callback. output.addBufferFragment(*fragment.release()); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': '[buffer] Add on-drain hook to buffer API and use it to avoid fragmentation due to tracking of H2 data and control frames in the output buffer (#144) Signed-off-by: antonio <avd@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, UINT32 x, UINT32 y, UINT32 width, UINT32 height) { VideoClientContextPriv* priv = video->priv; PresentationContext* ret = calloc(1, sizeof(*ret)); if (!ret) return NULL; ret->video = video; ret->PresentationId = PresentationId; ret->h264 = h264_context_new(FALSE); if (!ret->h264) { WLog_ERR(TAG, "unable to create a h264 context"); goto error_h264; } h264_context_reset(ret->h264, width, height); ret->currentSample = Stream_New(NULL, 4096); if (!ret->currentSample) { WLog_ERR(TAG, "unable to create current packet stream"); goto error_currentSample; } ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4); if (!ret->surfaceData) { WLog_ERR(TAG, "unable to allocate surfaceData"); goto error_surfaceData; } ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height); if (!ret->surface) { WLog_ERR(TAG, "unable to create surface"); goto error_surface; } ret->yuv = yuv_context_new(FALSE); if (!ret->yuv) { WLog_ERR(TAG, "unable to create YUV decoder"); goto error_yuv; } yuv_context_reset(ret->yuv, width, height); ret->refCounter = 1; return ret; error_yuv: video->deleteSurface(video, ret->surface); error_surface: BufferPool_Return(priv->surfacePool, ret->surfaceData); error_surfaceData: Stream_Free(ret->currentSample, TRUE); error_currentSample: h264_context_free(ret->h264); error_h264: free(ret); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed int overflow in PresentationContext_new Thanks to hac425 CVE-2020-11038'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status RoleGraph::getBSONForRole(RoleGraph* graph, const RoleName& roleName, mutablebson::Element result) try { if (!graph->roleExists(roleName)) { return Status(ErrorCodes::RoleNotFound, str::stream() << roleName.getFullName() << "does not name an existing role"); } std::string id = str::stream() << roleName.getDB() << "." << roleName.getRole(); uassertStatusOK(result.appendString("_id", id)); uassertStatusOK( result.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, roleName.getRole())); uassertStatusOK( result.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, roleName.getDB())); // Build privileges array mutablebson::Element privilegesArrayElement = result.getDocument().makeElementArray("privileges"); uassertStatusOK(result.pushBack(privilegesArrayElement)); const PrivilegeVector& privileges = graph->getDirectPrivileges(roleName); uassertStatusOK(Privilege::getBSONForPrivileges(privileges, privilegesArrayElement)); // Build roles array mutablebson::Element rolesArrayElement = result.getDocument().makeElementArray("roles"); uassertStatusOK(result.pushBack(rolesArrayElement)); for (RoleNameIterator roles = graph->getDirectSubordinates(roleName); roles.more(); roles.next()) { const RoleName& subRole = roles.get(); mutablebson::Element roleObj = result.getDocument().makeElementObject(""); uassertStatusOK( roleObj.appendString(AuthorizationManager::ROLE_NAME_FIELD_NAME, subRole.getRole())); uassertStatusOK( roleObj.appendString(AuthorizationManager::ROLE_DB_FIELD_NAME, subRole.getDB())); uassertStatusOK(rolesArrayElement.pushBack(roleObj)); } return Status::OK(); } catch (...) { ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-863'], 'message': 'SERVER-45472 Ensure RoleGraph can serialize authentication restrictions to BSON'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool PackLinuxElf64::calls_crt1(Elf64_Rela const *rela, int sz) { if (!dynsym || !dynstr) { return false; } for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf64_Rela)), ++rela, ++relnum) { unsigned const symnum = get_te64(&rela->r_info) >> 32; char const *const symnam = get_dynsym_name(symnum, relnum); if (0==strcmp(symnam, "__libc_start_main") // glibc || 0==strcmp(symnam, "__libc_init") // Android || 0==strcmp(symnam, "__uClibc_main") || 0==strcmp(symnam, "__uClibc_start_main")) return true; } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-190'], 'message': 'Avoid bogus values in PT_DYNAMIC segment. Detect duplicate DT_*. Detect out-of-bounds hashtab and gashtab. Detect missing DT_REL, DT_RELA. Detect out-of-bounds d_val. https://github.com/upx/upx/issues/317 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _PUBLIC_ enum ndr_err_code ndr_push_nbt_string(struct ndr_push *ndr, int ndr_flags, const char *s) { if (!(ndr_flags & NDR_SCALARS)) { return NDR_ERR_SUCCESS; } while (s && *s) { enum ndr_err_code ndr_err; char *compname; size_t complen; uint32_t offset; /* see if we have pushed the remaining string already, * if so we use a label pointer to this string */ ndr_err = ndr_token_retrieve_cmp_fn(&ndr->nbt_string_list, s, &offset, (comparison_fn_t)strcmp, false); if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { uint8_t b[2]; if (offset > 0x3FFF) { return ndr_push_error(ndr, NDR_ERR_STRING, "offset for nbt string label pointer %u[%08X] > 0x00003FFF", offset, offset); } b[0] = 0xC0 | (offset>>8); b[1] = (offset & 0xFF); return ndr_push_bytes(ndr, b, 2); } complen = strcspn(s, "."); /* we need to make sure the length fits into 6 bytes */ if (complen > 0x3F) { return ndr_push_error(ndr, NDR_ERR_STRING, "component length %u[%08X] > 0x0000003F", (unsigned)complen, (unsigned)complen); } if (s[complen] == '.' && s[complen+1] == '\0') { complen++; } compname = talloc_asprintf(ndr, "%c%*.*s", (unsigned char)complen, (unsigned char)complen, (unsigned char)complen, s); NDR_ERR_HAVE_NO_MEMORY(compname); /* remember the current componemt + the rest of the string * so it can be reused later */ NDR_CHECK(ndr_token_store(ndr, &ndr->nbt_string_list, s, ndr->offset)); /* push just this component into the blob */ NDR_CHECK(ndr_push_bytes(ndr, (const uint8_t *)compname, complen+1)); talloc_free(compname); s += complen; if (*s == '.') s++; } /* if we reach the end of the string and have pushed the last component * without using a label pointer, we need to terminate the string */ return ndr_push_bytes(ndr, (const uint8_t *)"", 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'CVE-2020-10745: ndr/dns-utils: prepare for NBT compatibility NBT has a funny thing where it sometimes needs to send a trailing dot as part of the last component, because the string representation is a user name. In DNS, "example.com", and "example.com." are the same, both having three components ("example", "com", ""); in NBT, we want to treat them differently, with the second form having the three components ("example", "com.", ""). This retains the logic of e6e2ec0001fe3c010445e26cc0efddbc1f73416b. Also DNS compression cannot be turned off for NBT. BUG: https://bugzilla.samba.org/show_bug.cgi?id=14378 Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int imap_exec(struct ImapAccountData *adata, const char *cmdstr, ImapCmdFlags flags) { int rc; rc = cmd_start(adata, cmdstr, flags); if (rc < 0) { cmd_handle_fatal(adata); return IMAP_EXEC_FATAL; } if (flags & IMAP_CMD_QUEUE) return IMAP_EXEC_SUCCESS; if ((flags & IMAP_CMD_POLL) && (C_ImapPollTimeout > 0) && ((mutt_socket_poll(adata->conn, C_ImapPollTimeout)) == 0)) { mutt_error(_("Connection to %s timed out"), adata->conn->account.host); cmd_handle_fatal(adata); return IMAP_EXEC_FATAL; } /* Allow interruptions, particularly useful if there are network problems. */ mutt_sig_allow_interrupt(true); do { rc = imap_cmd_step(adata); } while (rc == IMAP_RES_CONTINUE); mutt_sig_allow_interrupt(false); if (rc == IMAP_RES_NO) return IMAP_EXEC_ERROR; if (rc != IMAP_RES_OK) { if (adata->status != IMAP_FATAL) return IMAP_EXEC_ERROR; mutt_debug(LL_DEBUG1, "command failed: %s\n", adata->buf); return IMAP_EXEC_FATAL; } return IMAP_EXEC_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94', 'CWE-74'], 'message': 'tls: clear data after a starttls acknowledgement After a starttls acknowledgement message, clear the buffers of any incoming data / commands. This will ensure that all future data is handled securely. Co-authored-by: Pietro Cerutti <gahr@gahr.ch>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: usm_free_usmStateReference(void *old) { struct usmStateReference *old_ref = (struct usmStateReference *) old; if (old_ref) { if (old_ref->usr_name_length) SNMP_FREE(old_ref->usr_name); if (old_ref->usr_engine_id_length) SNMP_FREE(old_ref->usr_engine_id); if (old_ref->usr_auth_protocol_length) SNMP_FREE(old_ref->usr_auth_protocol); if (old_ref->usr_priv_protocol_length) SNMP_FREE(old_ref->usr_priv_protocol); if (old_ref->usr_auth_key_length && old_ref->usr_auth_key) { SNMP_ZERO(old_ref->usr_auth_key, old_ref->usr_auth_key_length); SNMP_FREE(old_ref->usr_auth_key); } if (old_ref->usr_priv_key_length && old_ref->usr_priv_key) { SNMP_ZERO(old_ref->usr_priv_key, old_ref->usr_priv_key_length); SNMP_FREE(old_ref->usr_priv_key); } SNMP_ZERO(old_ref, sizeof(*old_ref)); SNMP_FREE(old_ref); } } /* end usm_free_usmStateReference() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'libsnmp, USM: Introduce a reference count in struct usmStateReference This patch fixes https://sourceforge.net/p/net-snmp/bugs/2956/.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: webSocketsHasDataInBuffer(rfbClientPtr cl) { ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx; if (wsctx && wsctx->readbuflen) return TRUE; return (cl->sslctx && rfbssl_pending(cl) > 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'fix overflow and refactor websockets decode (Hybi) fix critical heap-based buffer overflow which allowed easy modification of a return address via an overwritten function pointer fix bug causing connections to fail due a "one websocket frame = one ws_read" assumption, which failed with LibVNCServer-0.9.11 refactor websocket Hybi decode to use a simple state machine for decoding of websocket frames'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { #ifdef USE_X3FTOOLS if (write_thumb == &LibRaw::x3f_thumb_loader) { INT64 tsize = x3f_thumb_size(); if (tsize < 2048 || INT64(ID.toffset) + tsize < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } #else if (0) {} #endif else { if (INT64(ID.toffset) + INT64(T.tlength) < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + INT64(T.tlength) > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } ID.input->seek(ID.toffset, SEEK_SET); if (write_thumb == &LibRaw::jpeg_thumb) { if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "jpeg_thumb()"); ID.input->read(T.thumb, 1, T.tlength); unsigned char *tthumb = (unsigned char *)T.thumb; tthumb[0] = 0xff; tthumb[1] = 0xd8; #ifdef NO_JPEG T.tcolors = 3; #else { jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmp_buffer)) { err2: // Error in original JPEG thumb, read it again because // original bytes 0-1 was damaged above jpeg_destroy_decompress(&cinfo); T.tcolors = 3; T.tformat = LIBRAW_THUMBNAIL_UNKNOWN; ID.input->seek(ID.toffset, SEEK_SET); ID.input->read(T.thumb, 1, T.tlength); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) goto err2; T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3) ? cinfo.num_components : 3; jpeg_destroy_decompress(&cinfo); } #endif T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::layer_thumb) { int colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; if (colors != 1 && colors != 3) return LIBRAW_UNSUPPORTED_THUMBNAIL; int tlength = T.twidth * T.theight; if (T.thumb) free(T.thumb); T.thumb = (char *)calloc(colors, tlength); merror(T.thumb, "layer_thumb()"); unsigned char *tbuf = (unsigned char *)calloc(colors, tlength); merror(tbuf, "layer_thumb()"); ID.input->read(tbuf, colors, T.tlength); if (libraw_internal_data.unpacker_data.thumb_misc >> 8 && colors == 3) // GRB order for (int i = 0; i < tlength; i++) { T.thumb[i * 3] = tbuf[i + tlength]; T.thumb[i * 3 + 1] = tbuf[i]; T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength]; } else if (colors == 3) // RGB or 1-channel for (int i = 0; i < tlength; i++) { T.thumb[i * 3] = tbuf[i]; T.thumb[i * 3 + 1] = tbuf[i + tlength]; T.thumb[i * 3 + 2] = tbuf[i + 2 * tlength]; } else if (colors == 1) { free(T.thumb); T.thumb = (char *)tbuf; tbuf = 0; } if (tbuf) free(tbuf); T.tcolors = colors; T.tlength = colors * tlength; T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::rollei_thumb) { int i; int tlength = T.twidth * T.theight; if (T.thumb) free(T.thumb); T.tcolors = 3; T.thumb = (char *)calloc(T.tcolors, tlength); merror(T.thumb, "layer_thumb()"); unsigned short *tbuf = (unsigned short *)calloc(2, tlength); merror(tbuf, "layer_thumb()"); read_shorts(tbuf, tlength); for (i = 0; i < tlength; i++) { T.thumb[i * 3] = (tbuf[i] << 3) & 0xff; T.thumb[i * 3 + 1] = (tbuf[i] >> 5 << 2) & 0xff; T.thumb[i * 3 + 2] = (tbuf[i] >> 11 << 3) & 0xff; } free(tbuf); T.tlength = T.tcolors * tlength; T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { if (t_bytesps > 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more // bits int t_length = T.twidth * T.theight * t_colors; if (T.tlength && (int)T.tlength < t_length) // try to find tiff ifd with needed offset { int pifd = find_ifd_by_offset(libraw_internal_data.internal_data.toffset); if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count && tiff_ifd[pifd].strip_byte_counts_count) { // We found it, calculate final size unsigned total_size = 0; for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++) total_size += tiff_ifd[pifd].strip_byte_counts[i]; if (total_size != (unsigned)t_length) // recalculate colors { if (total_size == T.twidth * T.tlength * 3) T.tcolors = 3; else if (total_size == T.twidth * T.tlength) T.tcolors = 1; } T.tlength = total_size; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "ppm_thumb()"); char *dest = T.thumb; INT64 pos = ID.input->tell(); for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count && i < tiff_ifd[pifd].strip_offsets_count; i++) { int remain = T.tlength; int sz = tiff_ifd[pifd].strip_byte_counts[i]; int off = tiff_ifd[pifd].strip_offsets[i]; if (off >= 0 && off + sz <= ID.input->size() && sz <= remain) { ID.input->seek(off, SEEK_SET); ID.input->read(dest, sz, 1); remain -= sz; dest += sz; } } ID.input->seek(pos, SEEK_SET); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } } if (!T.tlength) T.tlength = t_length; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); if (!T.tcolors) T.tcolors = t_colors; merror(T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { if (t_bytesps > 2) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for // more bits int o_bps = (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1; int o_length = T.twidth * T.theight * t_colors * o_bps; int i_length = T.twidth * T.theight * t_colors * 2; if (!T.tlength) T.tlength = o_length; ushort *t_thumb = (ushort *)calloc(i_length, 1); ID.input->read(t_thumb, 1, i_length); if ((libraw_internal_data.unpacker_data.order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)t_thumb, (char *)t_thumb, i_length); if (T.thumb) free(T.thumb); if ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS)) { T.thumb = (char *)t_thumb; T.tformat = LIBRAW_THUMBNAIL_BITMAP16; } else { T.thumb = (char *)malloc(o_length); merror(T.thumb, "ppm_thumb()"); for (int i = 0; i < o_length; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; } SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } #ifdef USE_X3FTOOLS else if (write_thumb == &LibRaw::x3f_thumb_loader) { x3f_thumb_loader(); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } #endif else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-125'], 'message': 'Thumbnail size range check'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { BYTE bitsPerPixelId; CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; if (!update || !s) return NULL; cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!cache_bitmap_v2) goto fail; cache_bitmap_v2->cacheId = flags & 0x0003; cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; bitsPerPixelId = (flags & 0x0078) >> 3; cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ goto fail; cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; } else { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ goto fail; } if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ goto fail; if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } } if (cache_bitmap_v2->bitmapLength == 0) goto fail; if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength) goto fail; if (cache_bitmap_v2->bitmapLength == 0) goto fail; cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength); if (!cache_bitmap_v2->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); cache_bitmap_v2->compressed = compressed; return cache_bitmap_v2; fail: free_cache_bitmap_v2_order(update->context, cache_bitmap_v2); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed OOB read in update_read_cache_bitmap_v3_order CVE-2020-11096 thanks @antonio-morales for finding this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision), trio_class_t* self, TRIO_CONST char* string, trio_flags_t flags, int width, int precision) { int length; int ch; assert(VALID(self)); assert(VALID(self->OutStream)); if (string == NULL) { string = internalNullString; length = sizeof(internalNullString) - 1; #if TRIO_FEATURE_QUOTE /* Disable quoting for the null pointer */ flags &= (~FLAGS_QUOTE); #endif width = 0; } else { if (precision == 0) { length = trio_length(string); } else { length = trio_length_max(string, precision); } } if ((NO_PRECISION != precision) && (precision < length)) { length = precision; } width -= length; #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif if (!(flags & FLAGS_LEFTADJUST)) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } while (length-- > 0) { /* The ctype parameters must be an unsigned char (or EOF) */ ch = (int)((unsigned char)(*string++)); TrioWriteStringCharacter(self, ch, flags); } if (flags & FLAGS_LEFTADJUST) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed TrioParse and trio_length limts. CVE-2020-4030 thanks to @antonio-morales for finding this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static BOOL ntlm_av_pair_add_copy(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_PAIR* pAvPair, size_t cbAvPair) { if (!ntlm_av_pair_check(pAvPair, cbAvPair)) return FALSE; return ntlm_av_pair_add(pAvPairList, cbAvPairList, ntlm_av_pair_get_id(pAvPair), ntlm_av_pair_get_value_pointer(pAvPair), ntlm_av_pair_get_len(pAvPair)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Fixed OOB read in ntlm_av_pair_get CVE-2020-11097 thanks to @antonio-morales for finding this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int blobAddData(blob *b, const unsigned char *data, size_t len) { #if HAVE_CLI_GETPAGESIZE static int pagesize; int growth; #endif assert(b != NULL); #ifdef CL_DEBUG assert(b->magic == BLOBCLASS); #endif assert(data != NULL); if (len == 0) return 0; if (b->isClosed) { /* * Should be cli_dbgmsg, but I want to see them for now, * and cli_dbgmsg doesn't support debug levels */ cli_warnmsg("Reopening closed blob\n"); b->isClosed = 0; } /* * The payoff here is between reducing the number of calls to * malloc/realloc and not overallocating memory. A lot of machines * are more tight with memory than one may imagine which is why * we don't just allocate a *huge* amount and be done with it. Closing * the blob helps because that reclaims memory. If you know the maximum * size of a blob before you start adding data, use blobGrow() that's * the most optimum */ #if HAVE_CLI_GETPAGESIZE if (pagesize == 0) { pagesize = cli_getpagesize(); if (pagesize == 0) pagesize = 4096; } growth = pagesize; if (len >= (size_t)pagesize) growth = ((len / pagesize) + 1) * pagesize; /*cli_dbgmsg("blobGrow: b->size %lu, b->len %lu, len %lu, growth = %u\n", b->size, b->len, len, growth);*/ if (b->data == NULL) { assert(b->len == 0); assert(b->size == 0); b->size = growth; b->data = cli_malloc(growth); } else if (b->size < b->len + (off_t)len) { unsigned char *p = cli_realloc(b->data, b->size + growth); if (p == NULL) return -1; b->size += growth; b->data = p; } #else if (b->data == NULL) { assert(b->len == 0); assert(b->size == 0); b->size = (off_t)len * 4; b->data = cli_malloc(b->size); } else if (b->size < b->len + (off_t)len) { unsigned char *p = cli_realloc(b->data, b->size + (len * 4)); if (p == NULL) return -1; b->size += (off_t)len * 4; b->data = p; } #endif if (b->data) { memcpy(&b->data[b->len], data, len); b->len += (off_t)len; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fuzz-22348 null deref in egg utf8 conversion Corrected memory leaks and a null dereference in the egg utf8 conversion.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void luaD_call (lua_State *L, StkId func, int nresults) { lua_CFunction f; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ f = clCvalue(s2v(func))->f; goto Cfunc; case LUA_VLCF: /* light C function */ f = fvalue(s2v(func)); Cfunc: { int n; /* number of returns */ CallInfo *ci = next_ci(L); checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ci->nresults = nresults; ci->callstatus = CIST_C; ci->top = L->top + LUA_MINSTACK; ci->func = func; L->ci = ci; lua_assert(ci->top <= L->stack_last); if (L->hookmask & LUA_MASKCALL) { int narg = cast_int(L->top - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); break; } case LUA_VLCL: { /* Lua function */ CallInfo *ci = next_ci(L); Proto *p = clLvalue(s2v(func))->p; int narg = cast_int(L->top - func) - 1; /* number of real arguments */ int nfixparams = p->numparams; int fsize = p->maxstacksize; /* frame size */ checkstackp(L, fsize, func); ci->nresults = nresults; ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus = 0; ci->top = func + 1 + fsize; ci->func = func; L->ci = ci; for (; narg < nfixparams; narg++) setnilvalue(s2v(L->top++)); /* complete missing arguments */ lua_assert(ci->top <= L->stack_last); luaV_execute(L, ci); /* run the function */ break; } default: { /* not a function */ checkstackp(L, 1, func); /* space for metamethod */ luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ goto retry; /* try again with metamethod */ } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-125', 'CWE-787'], 'message': 'Fixed bugs of stack reallocation x GC Macro 'checkstackGC' was doing a GC step after resizing the stack; the GC could shrink the stack and undo the resize. Moreover, macro 'checkstackp' also does a GC step, which could remove the preallocated CallInfo when calling a function. (Its name has been changed to 'checkstackGCp' to emphasize that it calls the GC.)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { if(iterator->next) rfbDecrClientRef(iterator->next); free(iterator); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'libvncserver: add missing NULL pointer checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void luaV_execute (lua_State *L, CallInfo *ci) { LClosure *cl; TValue *k; StkId base; const Instruction *pc; int trap; #if LUA_USE_JUMPTABLE #include "ljumptab.h" #endif tailcall: trap = L->hookmask; cl = clLvalue(s2v(ci->func)); k = cl->p->k; pc = ci->u.l.savedpc; if (trap) { if (cl->p->is_vararg) trap = 0; /* hooks will start after VARARGPREP instruction */ else if (pc == cl->p->code) /* first instruction (not resuming)? */ luaD_hookcall(L, ci); ci->u.l.trap = 1; /* there may be other hooks */ } base = ci->func + 1; /* main loop of interpreter */ for (;;) { Instruction i; /* instruction being executed */ StkId ra; /* instruction's A register */ vmfetch(); lua_assert(base == ci->func + 1); lua_assert(base <= L->top && L->top < L->stack + L->stacksize); /* invalidate top for instructions not expecting it */ lua_assert(isIT(i) || (cast_void(L->top = base), 1)); vmdispatch (GET_OPCODE(i)) { vmcase(OP_MOVE) { setobjs2s(L, ra, RB(i)); vmbreak; } vmcase(OP_LOADI) { lua_Integer b = GETARG_sBx(i); setivalue(s2v(ra), b); vmbreak; } vmcase(OP_LOADF) { int b = GETARG_sBx(i); setfltvalue(s2v(ra), cast_num(b)); vmbreak; } vmcase(OP_LOADK) { TValue *rb = k + GETARG_Bx(i); setobj2s(L, ra, rb); vmbreak; } vmcase(OP_LOADKX) { TValue *rb; rb = k + GETARG_Ax(*pc); pc++; setobj2s(L, ra, rb); vmbreak; } vmcase(OP_LOADFALSE) { setbfvalue(s2v(ra)); vmbreak; } vmcase(OP_LFALSESKIP) { setbfvalue(s2v(ra)); pc++; /* skip next instruction */ vmbreak; } vmcase(OP_LOADTRUE) { setbtvalue(s2v(ra)); vmbreak; } vmcase(OP_LOADNIL) { int b = GETARG_B(i); do { setnilvalue(s2v(ra++)); } while (b--); vmbreak; } vmcase(OP_GETUPVAL) { int b = GETARG_B(i); setobj2s(L, ra, cl->upvals[b]->v); vmbreak; } vmcase(OP_SETUPVAL) { UpVal *uv = cl->upvals[GETARG_B(i)]; setobj(L, uv->v, s2v(ra)); luaC_barrier(L, uv, s2v(ra)); vmbreak; } vmcase(OP_GETTABUP) { const TValue *slot; TValue *upval = cl->upvals[GETARG_B(i)]->v; TValue *rc = KC(i); TString *key = tsvalue(rc); /* key must be a string */ if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { setobj2s(L, ra, slot); } else Protect(luaV_finishget(L, upval, rc, ra, slot)); vmbreak; } vmcase(OP_GETTABLE) { const TValue *slot; TValue *rb = vRB(i); TValue *rc = vRC(i); lua_Unsigned n; if (ttisinteger(rc) /* fast track for integers? */ ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot)) : luaV_fastget(L, rb, rc, slot, luaH_get)) { setobj2s(L, ra, slot); } else Protect(luaV_finishget(L, rb, rc, ra, slot)); vmbreak; } vmcase(OP_GETI) { const TValue *slot; TValue *rb = vRB(i); int c = GETARG_C(i); if (luaV_fastgeti(L, rb, c, slot)) { setobj2s(L, ra, slot); } else { TValue key; setivalue(&key, c); Protect(luaV_finishget(L, rb, &key, ra, slot)); } vmbreak; } vmcase(OP_GETFIELD) { const TValue *slot; TValue *rb = vRB(i); TValue *rc = KC(i); TString *key = tsvalue(rc); /* key must be a string */ if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) { setobj2s(L, ra, slot); } else Protect(luaV_finishget(L, rb, rc, ra, slot)); vmbreak; } vmcase(OP_SETTABUP) { const TValue *slot; TValue *upval = cl->upvals[GETARG_A(i)]->v; TValue *rb = KB(i); TValue *rc = RKC(i); TString *key = tsvalue(rb); /* key must be a string */ if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) { luaV_finishfastset(L, upval, slot, rc); } else Protect(luaV_finishset(L, upval, rb, rc, slot)); vmbreak; } vmcase(OP_SETTABLE) { const TValue *slot; TValue *rb = vRB(i); /* key (table is in 'ra') */ TValue *rc = RKC(i); /* value */ lua_Unsigned n; if (ttisinteger(rb) /* fast track for integers? */ ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot)) : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) { luaV_finishfastset(L, s2v(ra), slot, rc); } else Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); vmbreak; } vmcase(OP_SETI) { const TValue *slot; int c = GETARG_B(i); TValue *rc = RKC(i); if (luaV_fastgeti(L, s2v(ra), c, slot)) { luaV_finishfastset(L, s2v(ra), slot, rc); } else { TValue key; setivalue(&key, c); Protect(luaV_finishset(L, s2v(ra), &key, rc, slot)); } vmbreak; } vmcase(OP_SETFIELD) { const TValue *slot; TValue *rb = KB(i); TValue *rc = RKC(i); TString *key = tsvalue(rb); /* key must be a string */ if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) { luaV_finishfastset(L, s2v(ra), slot, rc); } else Protect(luaV_finishset(L, s2v(ra), rb, rc, slot)); vmbreak; } vmcase(OP_NEWTABLE) { int b = GETARG_B(i); /* log2(hash size) + 1 */ int c = GETARG_C(i); /* array size */ Table *t; if (b > 0) b = 1 << (b - 1); /* size is 2^(b - 1) */ lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0)); if (TESTARG_k(i)) /* non-zero extra argument? */ c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */ pc++; /* skip extra argument */ L->top = ra + 1; /* correct top in case of emergency GC */ t = luaH_new(L); /* memory allocation */ sethvalue2s(L, ra, t); if (b != 0 || c != 0) luaH_resize(L, t, c, b); /* idem */ checkGC(L, ra + 1); vmbreak; } vmcase(OP_SELF) { const TValue *slot; TValue *rb = vRB(i); TValue *rc = RKC(i); TString *key = tsvalue(rc); /* key must be a string */ setobj2s(L, ra + 1, rb); if (luaV_fastget(L, rb, key, slot, luaH_getstr)) { setobj2s(L, ra, slot); } else Protect(luaV_finishget(L, rb, rc, ra, slot)); vmbreak; } vmcase(OP_ADDI) { op_arithI(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_ADDK) { op_arithK(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_SUBK) { op_arithK(L, l_subi, luai_numsub); vmbreak; } vmcase(OP_MULK) { op_arithK(L, l_muli, luai_nummul); vmbreak; } vmcase(OP_MODK) { op_arithK(L, luaV_mod, luaV_modf); vmbreak; } vmcase(OP_POWK) { op_arithfK(L, luai_numpow); vmbreak; } vmcase(OP_DIVK) { op_arithfK(L, luai_numdiv); vmbreak; } vmcase(OP_IDIVK) { op_arithK(L, luaV_idiv, luai_numidiv); vmbreak; } vmcase(OP_BANDK) { op_bitwiseK(L, l_band); vmbreak; } vmcase(OP_BORK) { op_bitwiseK(L, l_bor); vmbreak; } vmcase(OP_BXORK) { op_bitwiseK(L, l_bxor); vmbreak; } vmcase(OP_SHRI) { TValue *rb = vRB(i); int ic = GETARG_sC(i); lua_Integer ib; if (tointegerns(rb, &ib)) { pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic)); } vmbreak; } vmcase(OP_SHLI) { TValue *rb = vRB(i); int ic = GETARG_sC(i); lua_Integer ib; if (tointegerns(rb, &ib)) { pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib)); } vmbreak; } vmcase(OP_ADD) { op_arith(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_SUB) { op_arith(L, l_subi, luai_numsub); vmbreak; } vmcase(OP_MUL) { op_arith(L, l_muli, luai_nummul); vmbreak; } vmcase(OP_MOD) { op_arith(L, luaV_mod, luaV_modf); vmbreak; } vmcase(OP_POW) { op_arithf(L, luai_numpow); vmbreak; } vmcase(OP_DIV) { /* float division (always with floats) */ op_arithf(L, luai_numdiv); vmbreak; } vmcase(OP_IDIV) { /* floor division */ op_arith(L, luaV_idiv, luai_numidiv); vmbreak; } vmcase(OP_BAND) { op_bitwise(L, l_band); vmbreak; } vmcase(OP_BOR) { op_bitwise(L, l_bor); vmbreak; } vmcase(OP_BXOR) { op_bitwise(L, l_bxor); vmbreak; } vmcase(OP_SHR) { op_bitwise(L, luaV_shiftr); vmbreak; } vmcase(OP_SHL) { op_bitwise(L, luaV_shiftl); vmbreak; } vmcase(OP_MMBIN) { Instruction pi = *(pc - 2); /* original arith. expression */ TValue *rb = vRB(i); TMS tm = (TMS)GETARG_C(i); StkId result = RA(pi); lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR); Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm)); vmbreak; } vmcase(OP_MMBINI) { Instruction pi = *(pc - 2); /* original arith. expression */ int imm = GETARG_sB(i); TMS tm = (TMS)GETARG_C(i); int flip = GETARG_k(i); StkId result = RA(pi); Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm)); vmbreak; } vmcase(OP_MMBINK) { Instruction pi = *(pc - 2); /* original arith. expression */ TValue *imm = KB(i); TMS tm = (TMS)GETARG_C(i); int flip = GETARG_k(i); StkId result = RA(pi); Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm)); vmbreak; } vmcase(OP_UNM) { TValue *rb = vRB(i); lua_Number nb; if (ttisinteger(rb)) { lua_Integer ib = ivalue(rb); setivalue(s2v(ra), intop(-, 0, ib)); } else if (tonumberns(rb, nb)) { setfltvalue(s2v(ra), luai_numunm(L, nb)); } else Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM)); vmbreak; } vmcase(OP_BNOT) { TValue *rb = vRB(i); lua_Integer ib; if (tointegerns(rb, &ib)) { setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib)); } else Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT)); vmbreak; } vmcase(OP_NOT) { TValue *rb = vRB(i); if (l_isfalse(rb)) setbtvalue(s2v(ra)); else setbfvalue(s2v(ra)); vmbreak; } vmcase(OP_LEN) { Protect(luaV_objlen(L, ra, vRB(i))); vmbreak; } vmcase(OP_CONCAT) { int n = GETARG_B(i); /* number of elements to concatenate */ L->top = ra + n; /* mark the end of concat operands */ ProtectNT(luaV_concat(L, n)); checkGC(L, L->top); /* 'luaV_concat' ensures correct top */ vmbreak; } vmcase(OP_CLOSE) { Protect(luaF_close(L, ra, LUA_OK)); vmbreak; } vmcase(OP_TBC) { /* create new to-be-closed upvalue */ halfProtect(luaF_newtbcupval(L, ra)); vmbreak; } vmcase(OP_JMP) { dojump(ci, i, 0); vmbreak; } vmcase(OP_EQ) { int cond; TValue *rb = vRB(i); Protect(cond = luaV_equalobj(L, s2v(ra), rb)); docondjump(); vmbreak; } vmcase(OP_LT) { op_order(L, l_lti, LTnum, lessthanothers); vmbreak; } vmcase(OP_LE) { op_order(L, l_lei, LEnum, lessequalothers); vmbreak; } vmcase(OP_EQK) { TValue *rb = KB(i); /* basic types do not use '__eq'; we can use raw equality */ int cond = luaV_rawequalobj(s2v(ra), rb); docondjump(); vmbreak; } vmcase(OP_EQI) { int cond; int im = GETARG_sB(i); if (ttisinteger(s2v(ra))) cond = (ivalue(s2v(ra)) == im); else if (ttisfloat(s2v(ra))) cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im)); else cond = 0; /* other types cannot be equal to a number */ docondjump(); vmbreak; } vmcase(OP_LTI) { op_orderI(L, l_lti, luai_numlt, 0, TM_LT); vmbreak; } vmcase(OP_LEI) { op_orderI(L, l_lei, luai_numle, 0, TM_LE); vmbreak; } vmcase(OP_GTI) { op_orderI(L, l_gti, luai_numgt, 1, TM_LT); vmbreak; } vmcase(OP_GEI) { op_orderI(L, l_gei, luai_numge, 1, TM_LE); vmbreak; } vmcase(OP_TEST) { int cond = !l_isfalse(s2v(ra)); docondjump(); vmbreak; } vmcase(OP_TESTSET) { TValue *rb = vRB(i); if (l_isfalse(rb) == GETARG_k(i)) pc++; else { setobj2s(L, ra, rb); donextjump(ci); } vmbreak; } vmcase(OP_CALL) { int b = GETARG_B(i); int nresults = GETARG_C(i) - 1; if (b != 0) /* fixed number of arguments? */ L->top = ra + b; /* top signals number of arguments */ /* else previous instruction set top */ ProtectNT(luaD_call(L, ra, nresults)); vmbreak; } vmcase(OP_TAILCALL) { int b = GETARG_B(i); /* number of arguments + 1 (function) */ int nparams1 = GETARG_C(i); /* delat is virtual 'func' - real 'func' (vararg functions) */ int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0; if (b != 0) L->top = ra + b; else /* previous instruction set top */ b = cast_int(L->top - ra); savepc(ci); /* some calls here can raise errors */ if (TESTARG_k(i)) { /* close upvalues from current call; the compiler ensures that there are no to-be-closed variables here, so this call cannot change the stack */ luaF_close(L, base, NOCLOSINGMETH); lua_assert(base == ci->func + 1); } while (!ttisfunction(s2v(ra))) { /* not a function? */ luaD_tryfuncTM(L, ra); /* try '__call' metamethod */ b++; /* there is now one extra argument */ checkstackGCp(L, 1, ra); } if (!ttisLclosure(s2v(ra))) { /* C function? */ luaD_call(L, ra, LUA_MULTRET); /* call it */ updatetrap(ci); updatestack(ci); /* stack may have been relocated */ ci->func -= delta; luaD_poscall(L, ci, cast_int(L->top - ra)); return; } ci->func -= delta; luaD_pretailcall(L, ci, ra, b); /* prepare call frame */ goto tailcall; } vmcase(OP_RETURN) { int n = GETARG_B(i) - 1; /* number of results */ int nparams1 = GETARG_C(i); if (n < 0) /* not fixed? */ n = cast_int(L->top - ra); /* get what is available */ savepc(ci); if (TESTARG_k(i)) { /* may there be open upvalues? */ if (L->top < ci->top) L->top = ci->top; luaF_close(L, base, LUA_OK); updatetrap(ci); updatestack(ci); } if (nparams1) /* vararg function? */ ci->func -= ci->u.l.nextraargs + nparams1; L->top = ra + n; /* set call for 'luaD_poscall' */ luaD_poscall(L, ci, n); return; } vmcase(OP_RETURN0) { if (L->hookmask) { L->top = ra; halfProtectNT(luaD_poscall(L, ci, 0)); /* no hurry... */ } else { /* do the 'poscall' here */ int nres = ci->nresults; L->ci = ci->previous; /* back to caller */ L->top = base - 1; while (nres-- > 0) setnilvalue(s2v(L->top++)); /* all results are nil */ } return; } vmcase(OP_RETURN1) { if (L->hookmask) { L->top = ra + 1; halfProtectNT(luaD_poscall(L, ci, 1)); /* no hurry... */ } else { /* do the 'poscall' here */ int nres = ci->nresults; L->ci = ci->previous; /* back to caller */ if (nres == 0) L->top = base - 1; /* asked for no results */ else { setobjs2s(L, base - 1, ra); /* at least this result */ L->top = base; while (--nres > 0) /* complete missing results */ setnilvalue(s2v(L->top++)); } } return; } vmcase(OP_FORLOOP) { if (ttisinteger(s2v(ra + 2))) { /* integer loop? */ lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1))); if (count > 0) { /* still more iterations? */ lua_Integer step = ivalue(s2v(ra + 2)); lua_Integer idx = ivalue(s2v(ra)); /* internal index */ chgivalue(s2v(ra + 1), count - 1); /* update counter */ idx = intop(+, idx, step); /* add step to index */ chgivalue(s2v(ra), idx); /* update internal index */ setivalue(s2v(ra + 3), idx); /* and control variable */ pc -= GETARG_Bx(i); /* jump back */ } } else if (floatforloop(ra)) /* float loop */ pc -= GETARG_Bx(i); /* jump back */ updatetrap(ci); /* allows a signal to break the loop */ vmbreak; } vmcase(OP_FORPREP) { savestate(L, ci); /* in case of errors */ if (forprep(L, ra)) pc += GETARG_Bx(i) + 1; /* skip the loop */ vmbreak; } vmcase(OP_TFORPREP) { /* create to-be-closed upvalue (if needed) */ halfProtect(luaF_newtbcupval(L, ra + 3)); pc += GETARG_Bx(i); i = *(pc++); /* go to next instruction */ lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i)); goto l_tforcall; } vmcase(OP_TFORCALL) { l_tforcall: /* 'ra' has the iterator function, 'ra + 1' has the state, 'ra + 2' has the control variable, and 'ra + 3' has the to-be-closed variable. The call will use the stack after these values (starting at 'ra + 4') */ /* push function, state, and control variable */ memcpy(ra + 4, ra, 3 * sizeof(*ra)); L->top = ra + 4 + 3; ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */ updatestack(ci); /* stack may have changed */ i = *(pc++); /* go to next instruction */ lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i)); goto l_tforloop; } vmcase(OP_TFORLOOP) { l_tforloop: if (!ttisnil(s2v(ra + 4))) { /* continue loop? */ setobjs2s(L, ra + 2, ra + 4); /* save control variable */ pc -= GETARG_Bx(i); /* jump back */ } vmbreak; } vmcase(OP_SETLIST) { int n = GETARG_B(i); unsigned int last = GETARG_C(i); Table *h = hvalue(s2v(ra)); if (n == 0) n = cast_int(L->top - ra) - 1; /* get up to the top */ else L->top = ci->top; /* correct top in case of emergency GC */ last += n; if (TESTARG_k(i)) { last += GETARG_Ax(*pc) * (MAXARG_C + 1); pc++; } if (last > luaH_realasize(h)) /* needs more space? */ luaH_resizearray(L, h, last); /* preallocate it at once */ for (; n > 0; n--) { TValue *val = s2v(ra + n); setobj2t(L, &h->array[last - 1], val); last--; luaC_barrierback(L, obj2gco(h), val); } vmbreak; } vmcase(OP_CLOSURE) { Proto *p = cl->p->p[GETARG_Bx(i)]; halfProtect(pushclosure(L, p, cl->upvals, base, ra)); checkGC(L, ra + 1); vmbreak; } vmcase(OP_VARARG) { int n = GETARG_C(i) - 1; /* required results */ Protect(luaT_getvarargs(L, ci, ra, n)); vmbreak; } vmcase(OP_VARARGPREP) { ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p)); if (trap) { luaD_hookcall(L, ci); L->oldpc = pc + 1; /* next opcode will be seen as a "new" line */ } updatebase(ci); /* function has new base after adjustment */ vmbreak; } vmcase(OP_EXTRAARG) { lua_assert(0); vmbreak; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fixed bug: invalid 'oldpc' when returning to a function The field 'L->oldpc' is not always updated when control returns to a function; an invalid value can seg. fault when computing 'changedline'. (One example is an error in a finalizer; control can return to 'luaV_execute' without executing 'luaD_poscall'.) Instead of trying to fix all possible corner cases, it seems safer to be resilient to invalid values for 'oldpc'. Valid but wrong values at most cause an extra call to a line hook.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ProcXIChangeHierarchy(ClientPtr client) { xXIAnyHierarchyChangeInfo *any; size_t len; /* length of data remaining in request */ int rc = Success; int flags[MAXDEVICES] = { 0 }; REQUEST(xXIChangeHierarchyReq); REQUEST_AT_LEAST_SIZE(xXIChangeHierarchyReq); if (!stuff->num_changes) return rc; len = ((size_t)stuff->length << 2) - sizeof(xXIChangeHierarchyReq); any = (xXIAnyHierarchyChangeInfo *) &stuff[1]; while (stuff->num_changes--) { if (len < sizeof(xXIAnyHierarchyChangeInfo)) { rc = BadLength; goto unwind; } SWAPIF(swaps(&any->type)); SWAPIF(swaps(&any->length)); if (len < ((size_t)any->length << 2)) return BadLength; #define CHANGE_SIZE_MATCH(type) \ do { \ if ((len < sizeof(type)) || (any->length != (sizeof(type) >> 2))) { \ rc = BadLength; \ goto unwind; \ } \ } while(0) switch (any->type) { case XIAddMaster: { xXIAddMasterInfo *c = (xXIAddMasterInfo *) any; /* Variable length, due to appended name string */ if (len < sizeof(xXIAddMasterInfo)) { rc = BadLength; goto unwind; } SWAPIF(swaps(&c->name_len)); if (c->name_len > (len - sizeof(xXIAddMasterInfo))) { rc = BadLength; goto unwind; } rc = add_master(client, c, flags); if (rc != Success) goto unwind; } break; case XIRemoveMaster: { xXIRemoveMasterInfo *r = (xXIRemoveMasterInfo *) any; CHANGE_SIZE_MATCH(xXIRemoveMasterInfo); rc = remove_master(client, r, flags); if (rc != Success) goto unwind; } break; case XIDetachSlave: { xXIDetachSlaveInfo *c = (xXIDetachSlaveInfo *) any; CHANGE_SIZE_MATCH(xXIDetachSlaveInfo); rc = detach_slave(client, c, flags); if (rc != Success) goto unwind; } break; case XIAttachSlave: { xXIAttachSlaveInfo *c = (xXIAttachSlaveInfo *) any; CHANGE_SIZE_MATCH(xXIAttachSlaveInfo); rc = attach_slave(client, c, flags); if (rc != Success) goto unwind; } break; } len -= any->length * 4; any = (xXIAnyHierarchyChangeInfo *) ((char *) any + any->length * 4); } unwind: XISendDeviceHierarchyEvent(flags); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-191'], 'message': 'Fix XIChangeHierarchy() integer underflow CVE-2020-14346 / ZDI-CAN-11429 This vulnerability was discovered by: Jan-Niklas Sohn working with Trend Micro Zero Day Initiative Signed-off-by: Matthieu Herrb <matthieu@herrb.eu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _XimAttributeToValue( Xic ic, XIMResourceList res, CARD16 *data, INT16 data_len, XPointer value, BITMASK32 mode) { switch (res->resource_size) { case XimType_SeparatorOfNestedList: case XimType_NEST: break; case XimType_CARD8: case XimType_CARD16: case XimType_CARD32: case XimType_Window: case XimType_XIMHotKeyState: _XCopyToArg((XPointer)data, (XPointer *)&value, data_len); break; case XimType_STRING8: { char *str; if (!(value)) return False; if (!(str = Xmalloc(data_len + 1))) return False; (void)memcpy(str, (char *)data, data_len); str[data_len] = '\0'; *((char **)value) = str; break; } case XimType_XIMStyles: { INT16 num = data[0]; register CARD32 *style_list = (CARD32 *)&data[2]; XIMStyle *style; XIMStyles *rep; register int i; char *p; int alloc_len; if (!(value)) return False; alloc_len = sizeof(XIMStyles) + sizeof(XIMStyle) * num; if (!(p = Xmalloc(alloc_len))) return False; rep = (XIMStyles *)p; style = (XIMStyle *)(p + sizeof(XIMStyles)); for (i = 0; i < num; i++) style[i] = (XIMStyle)style_list[i]; rep->count_styles = (unsigned short)num; rep->supported_styles = style; *((XIMStyles **)value) = rep; break; } case XimType_XRectangle: { XRectangle *rep; if (!(value)) return False; if (!(rep = Xmalloc(sizeof(XRectangle)))) return False; rep->x = data[0]; rep->y = data[1]; rep->width = data[2]; rep->height = data[3]; *((XRectangle **)value) = rep; break; } case XimType_XPoint: { XPoint *rep; if (!(value)) return False; if (!(rep = Xmalloc(sizeof(XPoint)))) return False; rep->x = data[0]; rep->y = data[1]; *((XPoint **)value) = rep; break; } case XimType_XFontSet: { INT16 len = data[0]; char *base_name; XFontSet rep = (XFontSet)NULL; char **missing_list = NULL; int missing_count; char *def_string; if (!(value)) return False; if (!ic) return False; if (!(base_name = Xmalloc(len + 1))) return False; (void)strncpy(base_name, (char *)&data[1], (int)len); base_name[len] = '\0'; if (mode & XIM_PREEDIT_ATTR) { if (!strcmp(base_name, ic->private.proto.preedit_font)) { rep = ic->core.preedit_attr.fontset; } else if (!ic->private.proto.preedit_font_length) { rep = XCreateFontSet(ic->core.im->core.display, base_name, &missing_list, &missing_count, &def_string); } } else if (mode & XIM_STATUS_ATTR) { if (!strcmp(base_name, ic->private.proto.status_font)) { rep = ic->core.status_attr.fontset; } else if (!ic->private.proto.status_font_length) { rep = XCreateFontSet(ic->core.im->core.display, base_name, &missing_list, &missing_count, &def_string); } } Xfree(base_name); Xfree(missing_list); *((XFontSet *)value) = rep; break; } case XimType_XIMHotKeyTriggers: { INT32 num = *((CARD32 *)data); register CARD32 *key_list = (CARD32 *)&data[2]; XIMHotKeyTrigger *key; XIMHotKeyTriggers *rep; register int i; char *p; int alloc_len; if (!(value)) return False; alloc_len = sizeof(XIMHotKeyTriggers) + sizeof(XIMHotKeyTrigger) * num; if (!(p = Xmalloc(alloc_len))) return False; rep = (XIMHotKeyTriggers *)p; key = (XIMHotKeyTrigger *)(p + sizeof(XIMHotKeyTriggers)); for (i = 0; i < num; i++, key_list += 3) { key[i].keysym = (KeySym)key_list[0]; /* keysym */ key[i].modifier = (int)key_list[1]; /* modifier */ key[i].modifier_mask = (int)key_list[2]; /* modifier_mask */ } rep->num_hot_key = (int)num; rep->key = key; *((XIMHotKeyTriggers **)value) = rep; break; } case XimType_XIMStringConversion: { break; } default: return False; } return True; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'fix integer overflows in _XimAttributeToValue() Signed-off-by: Matthieu Herrb <matthieu@herrb.eu> Reviewed-by: Matthieu Herrb <matthieu@herrb.eu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _mibindex_add( const char *dirname, int i ) { const int old_mibindex_max = _mibindex_max; DEBUGMSGTL(("mibindex", "add: %s (%d)\n", dirname, i )); if ( i == -1 ) i = _mibindex++; if ( i >= _mibindex_max ) { /* * If the index array is full (or non-existent) * then expand (or create) it */ _mibindex_max = i + 10; _mibindexes = realloc(_mibindexes, _mibindex_max * sizeof(_mibindexes[0])); netsnmp_assert(_mibindexes); memset(_mibindexes + old_mibindex_max, 0, (_mibindex_max - old_mibindex_max) * sizeof(_mibindexes[0])); } _mibindexes[ i ] = strdup( dirname ); if ( i >= _mibindex ) _mibindex = i+1; DEBUGMSGTL(("mibindex", "add: %d/%d/%d\n", i, _mibindex, _mibindex_max )); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'CHANGES: snmpd: Stop reading and writing the mib_indexes/* files Caching directory contents is something the operating system should do and is not something Net-SNMP should do. Instead of storing a copy of the directory contents in ${tmp_dir}/mib_indexes/${n}, always scan a MIB directory.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: apr_status_t h2_push_diary_digest64_set(h2_push_diary *diary, const char *authority, const char *data64url, apr_pool_t *pool) { const char *data; apr_size_t len = h2_util_base64url_decode(&data, data64url, pool); /* Intentional no APLOGNO */ ap_log_perror(APLOG_MARK, GCSLOG_LEVEL, 0, pool, "h2_push_diary_digest64_set: digest=%s, dlen=%d", data64url, (int)len); return h2_push_diary_digest_set(diary, authority, data, len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444'], 'message': '* Removing support for abandoned draft of http-wg regarding cache-digests.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int get_netnsid_from_name(const char *name) { struct { struct nlmsghdr n; struct rtgenmsg g; char buf[1024]; } req = { .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)), .n.nlmsg_flags = NLM_F_REQUEST, .n.nlmsg_type = RTM_GETNSID, .g.rtgen_family = AF_UNSPEC, }; struct nlmsghdr *answer; struct rtattr *tb[NETNSA_MAX + 1]; struct rtgenmsg *rthdr; int len, fd; netns_nsid_socket_init(); fd = netns_get_fd(name); if (fd < 0) return fd; addattr32(&req.n, 1024, NETNSA_FD, fd); if (rtnl_talk(&rtnsh, &req.n, &answer) < 0) { close(fd); return -2; } close(fd); /* Validate message and parse attributes */ if (answer->nlmsg_type == NLMSG_ERROR) goto err_out; rthdr = NLMSG_DATA(answer); len = answer->nlmsg_len - NLMSG_SPACE(sizeof(*rthdr)); if (len < 0) goto err_out; parse_rtattr(tb, NETNSA_MAX, NETNS_RTA(rthdr), len); if (tb[NETNSA_NSID]) { free(answer); return rta_getattr_u32(tb[NETNSA_NSID]); } err_out: free(answer); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ipnetns: use-after-free problem in get_netnsid_from_name func Follow the following steps: # ip netns add net1 # export MALLOC_MMAP_THRESHOLD_=0 # ip netns list then Segmentation fault (core dumped) will occur. In get_netnsid_from_name func, answer is freed before rta_getattr_u32(tb[NETNSA_NSID]), where tb[] refers to answer`s content. If we set MALLOC_MMAP_THRESHOLD_=0, mmap will be adoped to malloc memory, which will be freed immediately after calling free func. So reading tb[NETNSA_NSID] will access the released memory after free(answer). Here, we will call get_netnsid_from_name(tb[NETNSA_NSID]) before free(answer). Fixes: 86bf43c7c2f ("lib/libnetlink: update rtnl_talk to support malloc buff at run time") Reported-by: Huiying Kou <kouhuiying@huawei.com> Signed-off-by: Zhiqiang Liu <liuzhiqiang26@huawei.com> Acked-by: Phil Sutter <phil@nwl.cc> Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SProcRecordCreateContext(ClientPtr client) { REQUEST(xRecordCreateContextReq); int status; swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xRecordCreateContextReq); if ((status = SwapCreateRegister((void *) stuff)) != Success) return status; return ProcRecordCreateContext(client); } /* SProcRecordCreateContext */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-191'], 'message': 'Fix XRecordRegisterClients() Integer underflow CVE-2020-14362 ZDI-CAN-11574 This vulnerability was discovered by: Jan-Niklas Sohn working with Trend Micro Zero Day Initiative Signed-off-by: Matthieu Herrb <matthieu@herrb.eu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pkcs11rsa_verify(dst_context_t *dctx, const isc_region_t *sig) { CK_RV rv; CK_MECHANISM mech = { CKM_RSA_PKCS, NULL, 0 }; CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE keyType = CKK_RSA; CK_ATTRIBUTE keyTemplate[] = { { CKA_CLASS, &keyClass, (CK_ULONG) sizeof(keyClass) }, { CKA_KEY_TYPE, &keyType, (CK_ULONG) sizeof(keyType) }, { CKA_TOKEN, &falsevalue, (CK_ULONG) sizeof(falsevalue) }, { CKA_PRIVATE, &falsevalue, (CK_ULONG) sizeof(falsevalue) }, { CKA_VERIFY, &truevalue, (CK_ULONG) sizeof(truevalue) }, { CKA_MODULUS, NULL, 0 }, { CKA_PUBLIC_EXPONENT, NULL, 0 }, }; CK_ATTRIBUTE *attr; CK_BYTE digest[MAX_DER_SIZE + ISC_SHA512_DIGESTLENGTH]; CK_BYTE *der; CK_ULONG derlen; CK_ULONG hashlen; CK_ULONG dgstlen; pk11_context_t *pk11_ctx = dctx->ctxdata.pk11_ctx; dst_key_t *key = dctx->key; pk11_object_t *rsa = key->keydata.pkey; isc_result_t ret = ISC_R_SUCCESS; unsigned int i; #ifndef PK11_MD5_DISABLE REQUIRE(key->key_alg == DST_ALG_RSAMD5 || key->key_alg == DST_ALG_RSASHA1 || key->key_alg == DST_ALG_NSEC3RSASHA1 || key->key_alg == DST_ALG_RSASHA256 || key->key_alg == DST_ALG_RSASHA512); #else REQUIRE(key->key_alg == DST_ALG_RSASHA1 || key->key_alg == DST_ALG_NSEC3RSASHA1 || key->key_alg == DST_ALG_RSASHA256 || key->key_alg == DST_ALG_RSASHA512); #endif REQUIRE(rsa != NULL); switch (key->key_alg) { #ifndef PK11_MD5_DISABLE case DST_ALG_RSAMD5: der = md5_der; derlen = sizeof(md5_der); hashlen = ISC_MD5_DIGESTLENGTH; break; #endif case DST_ALG_RSASHA1: case DST_ALG_NSEC3RSASHA1: der = sha1_der; derlen = sizeof(sha1_der); hashlen = ISC_SHA1_DIGESTLENGTH; break; case DST_ALG_RSASHA256: der = sha256_der; derlen = sizeof(sha256_der); hashlen = ISC_SHA256_DIGESTLENGTH; break; case DST_ALG_RSASHA512: der = sha512_der; derlen = sizeof(sha512_der); hashlen = ISC_SHA512_DIGESTLENGTH; break; default: INSIST(0); ISC_UNREACHABLE(); } dgstlen = derlen + hashlen; INSIST(dgstlen <= sizeof(digest)); memmove(digest, der, derlen); PK11_RET(pkcs_C_DigestFinal, (pk11_ctx->session, digest + derlen, &hashlen), DST_R_SIGNFAILURE); for (attr = pk11_attribute_first(rsa); attr != NULL; attr = pk11_attribute_next(rsa, attr)) switch (attr->type) { case CKA_MODULUS: INSIST(keyTemplate[5].type == attr->type); keyTemplate[5].pValue = isc_mem_get(dctx->mctx, attr->ulValueLen); if (keyTemplate[5].pValue == NULL) DST_RET(ISC_R_NOMEMORY); memmove(keyTemplate[5].pValue, attr->pValue, attr->ulValueLen); keyTemplate[5].ulValueLen = attr->ulValueLen; break; case CKA_PUBLIC_EXPONENT: INSIST(keyTemplate[6].type == attr->type); keyTemplate[6].pValue = isc_mem_get(dctx->mctx, attr->ulValueLen); if (keyTemplate[6].pValue == NULL) DST_RET(ISC_R_NOMEMORY); memmove(keyTemplate[6].pValue, attr->pValue, attr->ulValueLen); keyTemplate[6].ulValueLen = attr->ulValueLen; if (pk11_numbits(attr->pValue, attr->ulValueLen) > RSA_MAX_PUBEXP_BITS) DST_RET(DST_R_VERIFYFAILURE); break; } pk11_ctx->object = CK_INVALID_HANDLE; pk11_ctx->ontoken = false; PK11_RET(pkcs_C_CreateObject, (pk11_ctx->session, keyTemplate, (CK_ULONG) 7, &hKey), ISC_R_FAILURE); PK11_RET(pkcs_C_VerifyInit, (pk11_ctx->session, &mech, hKey), ISC_R_FAILURE); PK11_RET(pkcs_C_Verify, (pk11_ctx->session, digest, dgstlen, (CK_BYTE_PTR) sig->base, (CK_ULONG) sig->length), DST_R_VERIFYFAILURE); err: if (hKey != CK_INVALID_HANDLE) (void) pkcs_C_DestroyObject(pk11_ctx->session, hKey); for (i = 5; i <= 6; i++) if (keyTemplate[i].pValue != NULL) { isc_safe_memwipe(keyTemplate[i].pValue, keyTemplate[i].ulValueLen); isc_mem_put(dctx->mctx, keyTemplate[i].pValue, keyTemplate[i].ulValueLen); } pk11_return_session(pk11_ctx); isc_safe_memwipe(pk11_ctx, sizeof(*pk11_ctx)); isc_mem_put(dctx->mctx, pk11_ctx, sizeof(*pk11_ctx)); dctx->ctxdata.pk11_ctx = NULL; return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Fix crash in pk11_numbits() when native-pkcs11 is used When pk11_numbits() is passed a user provided input that contains all zeroes (via crafted DNS message), it would crash with assertion failure. Fix that by properly handling such input.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tiffsep_print_page(gx_device_printer * pdev, gp_file * file) { tiffsep_device * const tfdev = (tiffsep_device *)pdev; int num_std_colorants = tfdev->devn_params.num_std_colorant_names; int num_order = tfdev->devn_params.num_separation_order_names; int num_spot = tfdev->devn_params.separations.num_separations; int num_comp, comp_num, sep_num, code = 0, code1 = 0; cmyk_composite_map cmyk_map[GX_DEVICE_COLOR_MAX_COMPONENTS]; char *name = NULL; bool double_f = false; int base_filename_length = length_base_file_name(tfdev, &double_f); int save_depth = pdev->color_info.depth; int save_numcomps = pdev->color_info.num_components; const char *fmt; gs_parsed_file_name_t parsed; int plane_count = 0; /* quiet compiler */ int factor = tfdev->downscale.downscale_factor; int mfs = tfdev->downscale.min_feature_size; int dst_bpc = tfdev->BitsPerComponent; gx_downscaler_t ds; int width = gx_downscaler_scale(tfdev->width, factor); int height = gx_downscaler_scale(tfdev->height, factor); name = (char *)gs_alloc_bytes(pdev->memory, gp_file_name_sizeof, "tiffsep_print_page(name)"); if (!name) return_error(gs_error_VMerror); /* Print the names of the spot colors */ if (num_order == 0) { for (sep_num = 0; sep_num < num_spot; sep_num++) { copy_separation_name(tfdev, name, gp_file_name_sizeof - base_filename_length - SUFFIX_SIZE, sep_num, 0); dmlprintf1(pdev->memory, "%%%%SeparationName: %s\n", name); } } /* * Since different pages may have different spot colors, if this is for a * page after Page 1, we require that each output file is unique with a "fmt" * (i.e. %d) as part of the filename. We create individual separation files * for each page of the input. * Since the TIFF lib requires seeakable files, /dev/null or nul: are * not allowed (as they are with the psdcmyk devices). */ code = gx_parse_output_file_name(&parsed, &fmt, tfdev->fname, strlen(tfdev->fname), pdev->memory); if (code < 0 || (fmt == NULL && tfdev->PageCount > 0)) { emprintf(tfdev->memory, "\nUse of the %%d format is required to output more than one page to tiffsep.\n" "See doc/Devices.htm#TIFF for details.\n\n"); code = gs_note_error(gs_error_ioerror); } /* Write the page directory for the CMYK equivalent file. */ if (!tfdev->comp_file) { pdev->color_info.depth = dst_bpc*4; /* Create directory for 32 bit cmyk */ if (!tfdev->UseBigTIFF && tfdev->Compression==COMPRESSION_NONE && height > ((unsigned long) 0xFFFFFFFF - (file ? gp_ftell(file) : 0))/(width*4)) { /* note width is never 0 in print_page */ dmprintf(pdev->memory, "CMYK composite file would be too large! Reduce resolution or enable compression.\n"); return_error(gs_error_rangecheck); /* this will overflow 32 bits */ } code = gx_device_open_output_file((gx_device *)pdev, pdev->fname, true, true, &(tfdev->comp_file)); if (code < 0) { goto done; } tfdev->tiff_comp = tiff_from_filep(pdev, pdev->dname, tfdev->comp_file, tfdev->BigEndian, tfdev->UseBigTIFF); if (!tfdev->tiff_comp) { code = gs_note_error(gs_error_invalidfileaccess); goto done; } } code = tiff_set_fields_for_printer(pdev, tfdev->tiff_comp, factor, 0, tfdev->write_datetime); if (dst_bpc == 1 || dst_bpc == 8) { tiff_set_cmyk_fields(pdev, tfdev->tiff_comp, dst_bpc, tfdev->Compression, tfdev->MaxStripSize); } else { /* Catch-all just for safety's sake */ tiff_set_cmyk_fields(pdev, tfdev->tiff_comp, dst_bpc, COMPRESSION_NONE, tfdev->MaxStripSize); } pdev->color_info.depth = save_depth; if (code < 0) { goto done; } /* Set up the separation output files */ num_comp = number_output_separations( tfdev->color_info.num_components, num_std_colorants, num_order, num_spot); if (!tfdev->NoSeparationFiles && !num_order && num_comp < num_std_colorants + num_spot) { dmlprintf(pdev->memory, "Warning: skipping one or more colour separations, see: Devices.htm#TIFF\n"); } if (!tfdev->NoSeparationFiles) { for (comp_num = 0; comp_num < num_comp; comp_num++) { int sep_num = tfdev->devn_params.separation_order_map[comp_num]; code = create_separation_file_name(tfdev, name, gp_file_name_sizeof, sep_num, true); if (code < 0) { goto done; } /* * Close the old separation file if we are creating individual files * for each page. */ if (tfdev->sep_file[comp_num] != NULL && fmt != NULL) { code = tiffsep_close_sep_file(tfdev, name, comp_num); if (code >= 0) code = gs_remove_outputfile_control_path(tfdev->memory, name); if (code < 0) return code; } /* Open the separation file, if not already open */ if (tfdev->sep_file[comp_num] == NULL) { code = gs_add_outputfile_control_path(tfdev->memory, name); if (code < 0) { goto done; } code = gx_device_open_output_file((gx_device *)pdev, name, true, true, &(tfdev->sep_file[comp_num])); if (code < 0) { goto done; } tfdev->tiff[comp_num] = tiff_from_filep(pdev, name, tfdev->sep_file[comp_num], tfdev->BigEndian, tfdev->UseBigTIFF); if (!tfdev->tiff[comp_num]) { code = gs_note_error(gs_error_ioerror); goto done; } } pdev->color_info.depth = dst_bpc; /* Create files for 8 bit gray */ pdev->color_info.num_components = 1; if (!tfdev->UseBigTIFF && tfdev->Compression == COMPRESSION_NONE && height * 8 / dst_bpc > ((unsigned long)0xFFFFFFFF - (file ? gp_ftell(file) : 0)) / width) /* note width is never 0 in print_page */ { code = gs_note_error(gs_error_rangecheck); /* this will overflow 32 bits */ goto done; } code = tiff_set_fields_for_printer(pdev, tfdev->tiff[comp_num], factor, 0, tfdev->write_datetime); tiff_set_gray_fields(pdev, tfdev->tiff[comp_num], dst_bpc, tfdev->Compression, tfdev->MaxStripSize); pdev->color_info.depth = save_depth; pdev->color_info.num_components = save_numcomps; if (code < 0) { goto done; } } } build_cmyk_map((gx_device*) tfdev, num_comp, &tfdev->equiv_cmyk_colors, cmyk_map); if (tfdev->PrintSpotCMYK) { code = print_cmyk_equivalent_colors(tfdev, num_comp, cmyk_map); if (code < 0) { goto done; } } { int raster_plane = bitmap_raster(width * 8); byte *planes[GS_CLIENT_COLOR_MAX_COMPONENTS] = { 0 }; int cmyk_raster = width * NUM_CMYK_COMPONENTS; int pixel, y; byte * sep_line; int plane_index; int offset_plane = 0; sep_line = gs_alloc_bytes(pdev->memory, cmyk_raster, "tiffsep_print_page"); if (!sep_line) { code = gs_note_error(gs_error_VMerror); goto done; } if (!tfdev->NoSeparationFiles) for (comp_num = 0; comp_num < num_comp; comp_num++ ) TIFFCheckpointDirectory(tfdev->tiff[comp_num]); TIFFCheckpointDirectory(tfdev->tiff_comp); /* Write the page data. */ { gs_get_bits_params_t params; int byte_width; /* Return planar data */ params.options = (GB_RETURN_POINTER | GB_RETURN_COPY | GB_ALIGN_STANDARD | GB_OFFSET_0 | GB_RASTER_STANDARD | GB_PACKING_PLANAR | GB_COLORS_NATIVE | GB_ALPHA_NONE); params.x_offset = 0; params.raster = bitmap_raster(width * pdev->color_info.depth); if (num_order > 0) { /* In this case, there was a specification for a separation color order, which indicates what colorants we will actually creat individual separation files for. We need to allocate for the standard colorants. This is due to the fact that even when we specify a single spot colorant, we still create the composite CMYK output file. */ for (comp_num = 0; comp_num < num_std_colorants; comp_num++) { planes[comp_num] = gs_alloc_bytes(pdev->memory, raster_plane, "tiffsep_print_page"); params.data[comp_num] = planes[comp_num]; if (params.data[comp_num] == NULL) { code = gs_note_error(gs_error_VMerror); goto cleanup; } } offset_plane = num_std_colorants; /* Now we need to make sure that we do not allocate extra planes if any of the colorants in the order list are one of the standard colorant names */ plane_index = plane_count = num_std_colorants; for (comp_num = 0; comp_num < num_comp; comp_num++) { int temp_pos; temp_pos = tfdev->devn_params.separation_order_map[comp_num]; if (temp_pos >= num_std_colorants) { /* We have one that is not a standard colorant name so allocate a new plane */ planes[plane_count] = gs_alloc_bytes(pdev->memory, raster_plane, "tiffsep_print_page"); /* Assign the new plane to the appropriate position */ params.data[plane_index] = planes[plane_count]; if (params.data[plane_index] == NULL) { code = gs_note_error(gs_error_VMerror); goto cleanup; } plane_count += 1; } else { /* Assign params.data with the appropriate std. colorant plane position */ params.data[plane_index] = planes[temp_pos]; } plane_index += 1; } } else { /* Sep color order number was not specified so just render all the planes that we can */ for (comp_num = 0; comp_num < num_comp; comp_num++) { planes[comp_num] = gs_alloc_bytes(pdev->memory, raster_plane, "tiffsep_print_page"); params.data[comp_num] = planes[comp_num]; if (params.data[comp_num] == NULL) { code = gs_note_error(gs_error_VMerror); goto cleanup; } } } code = gx_downscaler_init_planar_trapped(&ds, (gx_device *)pdev, &params, num_comp, factor, mfs, 8, dst_bpc, tfdev->downscale.trap_w, tfdev->downscale.trap_h, tfdev->downscale.trap_order); if (code < 0) goto cleanup; byte_width = (width * dst_bpc + 7)>>3; for (y = 0; y < height; ++y) { code = gx_downscaler_get_bits_rectangle(&ds, &params, y); if (code < 0) goto cleanup; /* Write separation data (tiffgray format) */ if (!tfdev->NoSeparationFiles) { for (comp_num = 0; comp_num < num_comp; comp_num++) { byte *src; byte *dest = sep_line; if (num_order > 0) { src = params.data[tfdev->devn_params.separation_order_map[comp_num]]; } else src = params.data[comp_num]; for (pixel = 0; pixel < byte_width; pixel++, dest++, src++) *dest = MAX_COLOR_VALUE - *src; /* Gray is additive */ TIFFWriteScanline(tfdev->tiff[comp_num], (tdata_t)sep_line, y, 0); } } /* Write CMYK equivalent data */ switch(dst_bpc) { default: case 8: build_cmyk_raster_line_fromplanar(&params, sep_line, width, num_comp, cmyk_map, num_order, tfdev); break; case 4: build_cmyk_raster_line_fromplanar_4bpc(&params, sep_line, width, num_comp, cmyk_map, num_order, tfdev); break; case 2: build_cmyk_raster_line_fromplanar_2bpc(&params, sep_line, width, num_comp, cmyk_map, num_order, tfdev); break; case 1: build_cmyk_raster_line_fromplanar_1bpc(&params, sep_line, width, num_comp, cmyk_map, num_order, tfdev); break; } TIFFWriteScanline(tfdev->tiff_comp, (tdata_t)sep_line, y, 0); } cleanup: if (num_order > 0) { /* Free up the standard colorants if num_order was set. In this process, we need to make sure that none of them were the standard colorants. plane_count should have the sum of the std. colorants plus any non-standard ones listed in separation color order */ for (comp_num = 0; comp_num < plane_count; comp_num++) { gs_free_object(pdev->memory, planes[comp_num], "tiffsep_print_page"); } } else { for (comp_num = 0; comp_num < num_comp; comp_num++) { gs_free_object(pdev->memory, planes[comp_num + offset_plane], "tiffsep_print_page"); } } gx_downscaler_fin(&ds); gs_free_object(pdev->memory, sep_line, "tiffsep_print_page"); } code1 = code; if (!tfdev->NoSeparationFiles) { for (comp_num = 0; comp_num < num_comp; comp_num++) { TIFFWriteDirectory(tfdev->tiff[comp_num]); if (fmt) { int sep_num = tfdev->devn_params.separation_order_map[comp_num]; code = create_separation_file_name(tfdev, name, gp_file_name_sizeof, sep_num, false); if (code < 0) { code1 = code; continue; } code = tiffsep_close_sep_file(tfdev, name, comp_num); if (code >= 0) code = gs_remove_outputfile_control_path(tfdev->memory, name); if (code < 0) { code1 = code; } } } } TIFFWriteDirectory(tfdev->tiff_comp); if (fmt) { code = tiffsep_close_comp_file(tfdev, pdev->fname); } if (code1 < 0) { code = code1; } } done: if (name) gs_free_object(pdev->memory, name, "tiffsep_print_page(name)"); return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Tiffsep and Tiffsep1 - abort on multi-page input wtithout %d OutputFile Bug #701821 "Segmentation fault at tiff//libtiff/tif_dirinfo.c:513 in TIFFFindField" The tiffsep and tiffsep1 only set 'code' to an error when an attempt is made to write a second output file without using %d in the OutputFile specification. This causes problems later when attempting to process the files. The devices should exit without trying to further process the pages under these conditions and this commit returns immediately on error. The other devices like this already return immediately on error, it looks like the code here was copied between devices without realising that the tiffsep and tiffsep1 devices didn't exit when the error condition was set.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: epsc_print_page(gx_device_printer * pdev, gp_file * prn_stream) { static int graphics_modes_9[5] = { -1, 0 /*60 */ , 1 /*120 */ , -1, DD + 3 /*240 */ }; static int graphics_modes_24[7] = { -1, 32 /*60 */ , 33 /*120 */ , 39 /*180 */ , -1, -1, DD + 40 /*360 */ }; int y_24pin = pdev->y_pixels_per_inch > 72; int y_mult = (y_24pin ? 3 : 1); int line_size = (pdev->width + 7) >> 3; /* always mono */ int in_size = line_size * (8 * y_mult); byte *in = (byte *) gs_malloc(pdev->memory, in_size + 1, 1, "epsc_print_page(in)"); int out_size = ((pdev->width + 7) & -8) * y_mult; byte *out = (byte *) gs_malloc(pdev->memory, out_size + 1, 1, "epsc_print_page(out)"); int x_dpi = (int)pdev->x_pixels_per_inch; char start_graphics = (char) ((y_24pin ? graphics_modes_24 : graphics_modes_9)[x_dpi / 60]); int first_pass = (start_graphics & DD ? 1 : 0); int last_pass = first_pass * 2; int dots_per_space = x_dpi / 10; /* pica space = 1/10" */ int bytes_per_space = dots_per_space * y_mult; int skip = 0, lnum = 0, pass; /* declare color buffer and related vars */ byte *color_in; int color_line_size, color_in_size; int spare_bits = (pdev->width % 8); /* left over bits to go to margin */ int whole_bits = pdev->width - spare_bits; /* Check allocations */ if (in == 0 || out == 0) { if (in) gs_free(pdev->memory, (char *)in, in_size + 1, 1, "epsc_print_page(in)"); if (out) gs_free(pdev->memory, (char *)out, out_size + 1, 1, "epsc_print_page(out)"); return -1; } /* Initialize the printer and reset the margins. */ gp_fwrite("\033@\033P\033l\000\033Q\377\033U\001\r", 1, 14, prn_stream); /* Create color buffer */ if (gx_device_has_color(pdev)) { color_line_size = gdev_mem_bytes_per_scan_line((gx_device *) pdev); color_in_size = color_line_size * (8 * y_mult); if ((color_in = (byte *) gs_malloc(pdev->memory, color_in_size + 1, 1, "epsc_print_page(color)")) == 0) { gs_free(pdev->memory, (char *)in, in_size + 1, 1, "epsc_print_page(in)"); gs_free(pdev->memory, (char *)out, out_size + 1, 1, "epsc_print_page(out)"); return (-1); } } else { color_in = in; color_in_size = in_size; color_line_size = line_size; } /* Print lines of graphics */ while (lnum < pdev->height) { int lcnt; byte *nextcolor = NULL; /* position where next color appears */ byte *nextmono = NULL; /* position to map next color */ /* Copy 1 scan line and test for all zero. */ gdev_prn_copy_scan_lines(pdev, lnum, color_in, color_line_size); if (color_in[0] == 0 && !memcmp((char *)color_in, (char *)color_in + 1, color_line_size - 1) ) { lnum++; skip += 3 / y_mult; continue; } /* Vertical tab to the appropriate position. */ while (skip > 255) { gp_fputs("\033J\377", prn_stream); skip -= 255; } if (skip) gp_fprintf(prn_stream, "\033J%c", skip); /* Copy the rest of the scan lines. */ lcnt = 1 + gdev_prn_copy_scan_lines(pdev, lnum + 1, color_in + color_line_size, color_in_size - color_line_size); if (lcnt < 8 * y_mult) { memset((char *)(color_in + lcnt * color_line_size), 0, color_in_size - lcnt * color_line_size); if (gx_device_has_color(pdev)) /* clear the work buffer */ memset((char *)(in + lcnt * line_size), 0, in_size - lcnt * line_size); } /* ** We need to create a normal epson scan line from our color scan line ** We do this by setting a bit in the "in" buffer if the pixel byte is set ** to any color. We then search for any more pixels of that color, setting ** "in" accordingly. If any other color is found, we save it for the next ** pass. There may be up to 7 passes. ** In the future, we should make the passes so as to maximize the ** life of the color ribbon (i.e. go lightest to darkest). */ do { byte *inp = in; byte *in_end = in + line_size; byte *out_end = out; byte *out_blk; register byte *outp; if (gx_device_has_color(pdev)) { register int i, j; register byte *outbuf, *realbuf; byte current_color; int end_next_bits = whole_bits; int lastbits; /* Move to the point in the scanline that has a new color */ if (nextcolor) { realbuf = nextcolor; outbuf = nextmono; memset((char *)in, 0, (nextmono - in)); i = nextcolor - color_in; nextcolor = NULL; end_next_bits = (i / color_line_size) * color_line_size + whole_bits; } else { i = 0; realbuf = color_in; outbuf = in; nextcolor = NULL; } /* move thru the color buffer, turning on the appropriate ** bit in the "mono" buffer", setting pointers to the next ** color and changing the color output of the epson */ for (current_color = 0; i <= color_in_size && outbuf < in + in_size; outbuf++) { /* Remember, line_size is rounded up to next whole byte ** whereas color_line_size is the proper length ** We only want to set the proper bits in the last line_size byte. */ if (spare_bits && i == end_next_bits) { end_next_bits = whole_bits + i + spare_bits; lastbits = 8 - spare_bits; } else lastbits = 0; for (*outbuf = 0, j = 8; --j >= lastbits && i <= color_in_size; realbuf++, i++) { if (*realbuf) { if (current_color > 0) { if (*realbuf == current_color) { *outbuf |= 1 << j; *realbuf = 0; /* throw this byte away */ } /* save this location for next pass */ else if (nextcolor == NULL) { nextcolor = realbuf - (7 - j); nextmono = outbuf; } } else { *outbuf |= 1 << j; current_color = *realbuf; /* set color */ *realbuf = 0; } } } } *outbuf = 0; /* zero the end, for safe keeping */ /* Change color on the EPSON, current_color must be set ** but lets check anyway */ if (current_color) gp_fprintf(prn_stream, "\033r%c", current_color ^ 7); } /* We have to 'transpose' blocks of 8 pixels x 8 lines, */ /* because that's how the printer wants the data. */ /* If we are in a 24-pin mode, we have to transpose */ /* groups of 3 lines at a time. */ if (y_24pin) { for (; inp < in_end; inp++, out_end += 24) { gdev_prn_transpose_8x8(inp, line_size, out_end, 3); gdev_prn_transpose_8x8(inp + line_size * 8, line_size, out_end + 1, 3); gdev_prn_transpose_8x8(inp + line_size * 16, line_size, out_end + 2, 3); } /* Remove trailing 0s. */ while (out_end > out && out_end[-1] == 0 && out_end[-2] == 0 && out_end[-3] == 0) out_end -= 3; } else { for (; inp < in_end; inp++, out_end += 8) { gdev_prn_transpose_8x8(inp, line_size, out_end, 1); } /* Remove trailing 0s. */ while (out_end > out && out_end[-1] == 0) out_end--; } for (pass = first_pass; pass <= last_pass; pass++) { for (out_blk = outp = out; outp < out_end;) { /* Skip a run of leading 0s. */ /* At least 10 are needed to make tabbing worth it. */ /* We do everything by 3's to avoid having to make */ /* different cases for 9- and 24-pin. */ if (*outp == 0 && outp + 12 <= out_end && outp[1] == 0 && outp[2] == 0 && (outp[3] | outp[4] | outp[5]) == 0 && (outp[6] | outp[7] | outp[8]) == 0 && (outp[9] | outp[10] | outp[11]) == 0) { byte *zp = outp; int tpos; byte *newp; outp += 12; while (outp + 3 <= out_end && *outp == 0 && outp[1] == 0 && outp[2] == 0) outp += 3; tpos = (outp - out) / bytes_per_space; newp = out + tpos * bytes_per_space; if (newp > zp + 10) { /* Output preceding bit data. */ if (zp > out_blk) /* only false at */ /* beginning of line */ epsc_output_run(out_blk, (int)(zp - out_blk), y_mult, start_graphics, prn_stream, pass); /* Tab over to the appropriate position. */ gp_fprintf(prn_stream, "\033D%c%c\t", tpos, 0); out_blk = outp = newp; } } else outp += y_mult; } if (outp > out_blk) epsc_output_run(out_blk, (int)(outp - out_blk), y_mult, start_graphics, prn_stream, pass); gp_fputc('\r', prn_stream); } } while (nextcolor); skip = 24; lnum += 8 * y_mult; } /* Eject the page and reinitialize the printer */ gp_fputs("\f\033@", prn_stream); gs_free(pdev->memory, (char *)out, out_size + 1, 1, "epsc_print_page(out)"); gs_free(pdev->memory, (char *)in, in_size + 1, 1, "epsc_print_page(in)"); if (gx_device_has_color(pdev)) gs_free(pdev->memory, (char *)color_in, color_in_size + 1, 1, "epsc_print_page(rin)"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Bug 701794: check for x_dpi out of range in epsc_print_page(). Avoids out-of-bounds of local arrays graphics_modes_9 and graphics_modes_24. Larger diff than would like, because can't return error from within declarations in old-style C. Fixes: ./sanbin/gs -r680 -sOutputFile=tmp -sDEVICE=epsonc ../bug-701794.pdf'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SRC_DumpSources(void) { FILE *out; int i; for (i = 0; i < n_sources; i++) { out = open_dumpfile(sources[i], "w"); if (!out) continue; SST_SaveToFile(sources[i]->stats, out); fclose(out); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions Replace all fopen(), rename(), and unlink() calls with the new util functions.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_hwclock_file(const char *hwclock_file) { FILE *in; char line[256]; int i; if (!hwclock_file || !hwclock_file[0]) return; in = fopen(hwclock_file, "r"); if (!in) { LOG(LOGS_WARN, "Could not open %s : %s", hwclock_file, strerror(errno)); return; } /* Read third line from the file. */ for (i = 0; i < 3; i++) { if (!fgets(line, sizeof(line), in)) break; } fclose(in); if (i == 3 && !strncmp(line, "LOCAL", 5)) { rtc_on_utc = 0; } else if (i == 3 && !strncmp(line, "UTC", 3)) { rtc_on_utc = 1; } else { LOG(LOGS_WARN, "Could not read RTC LOCAL/UTC setting from %s", hwclock_file); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions Replace all fopen(), rename(), and unlink() calls with the new util functions.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bind_unix_address(int sock_fd, const char *addr, int flags) { union sockaddr_all saddr; if (snprintf(saddr.un.sun_path, sizeof (saddr.un.sun_path), "%s", addr) >= sizeof (saddr.un.sun_path)) { DEBUG_LOG("Unix socket path %s too long", addr); return 0; } saddr.un.sun_family = AF_UNIX; unlink(addr); /* PRV_BindSocket() doesn't support Unix sockets yet */ if (bind(sock_fd, &saddr.sa, sizeof (saddr.un)) < 0) { DEBUG_LOG("Could not bind Unix socket to %s : %s", addr, strerror(errno)); return 0; } /* Allow access to everyone with access to the directory if requested */ if (flags & SCK_FLAG_ALL_PERMISSIONS && chmod(addr, 0666) < 0) { DEBUG_LOG("Could not change permissions of %s : %s", addr, strerror(errno)); return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'switch to new util file functions Replace all fopen(), rename(), and unlink() calls with the new util functions.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_attr_shortform_verify( struct xfs_inode *ip) { struct xfs_attr_shortform *sfp; struct xfs_attr_sf_entry *sfep; struct xfs_attr_sf_entry *next_sfep; char *endp; struct xfs_ifork *ifp; int i; int64_t size; ASSERT(ip->i_afp->if_format == XFS_DINODE_FMT_LOCAL); ifp = XFS_IFORK_PTR(ip, XFS_ATTR_FORK); sfp = (struct xfs_attr_shortform *)ifp->if_u1.if_data; size = ifp->if_bytes; /* * Give up if the attribute is way too short. */ if (size < sizeof(struct xfs_attr_sf_hdr)) return __this_address; endp = (char *)sfp + size; /* Check all reported entries */ sfep = &sfp->list[0]; for (i = 0; i < sfp->hdr.count; i++) { /* * struct xfs_attr_sf_entry has a variable length. * Check the fixed-offset parts of the structure are * within the data buffer. */ if (((char *)sfep + sizeof(*sfep)) >= endp) return __this_address; /* Don't allow names with known bad length. */ if (sfep->namelen == 0) return __this_address; /* * Check that the variable-length part of the structure is * within the data buffer. The next entry starts after the * name component, so nextentry is an acceptable test. */ next_sfep = XFS_ATTR_SF_NEXTENTRY(sfep); if ((char *)next_sfep > endp) return __this_address; /* * Check for unknown flags. Short form doesn't support * the incomplete or local bits, so we can use the namespace * mask here. */ if (sfep->flags & ~XFS_ATTR_NSP_ONDISK_MASK) return __this_address; /* * Check for invalid namespace combinations. We only allow * one namespace flag per xattr, so we can just count the * bits (i.e. hweight) here. */ if (hweight8(sfep->flags & XFS_ATTR_NSP_ONDISK_MASK) > 1) return __this_address; sfep = next_sfep; } if ((void *)sfep != (void *)endp) return __this_address; return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-131'], 'message': 'xfs: fix boundary test in xfs_attr_shortform_verify The boundary test for the fixed-offset parts of xfs_attr_sf_entry in xfs_attr_shortform_verify is off by one, because the variable array at the end is defined as nameval[1] not nameval[]. Hence we need to subtract 1 from the calculation. This can be shown by: # touch file # setfattr -n root.a file and verifications will fail when it's written to disk. This only matters for a last attribute which has a single-byte name and no value, otherwise the combination of namelen & valuelen will push endp further out and this test won't fail. Fixes: 1e1bbd8e7ee06 ("xfs: create structure verifier function for shortform xattrs") Signed-off-by: Eric Sandeen <sandeen@redhat.com> Reviewed-by: Darrick J. Wong <darrick.wong@oracle.com> Signed-off-by: Darrick J. Wong <darrick.wong@oracle.com> Reviewed-by: Christoph Hellwig <hch@lst.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static BROTLI_INLINE uint32_t GetCopyBase(uint16_t copycode) { return kCopyBase[copycode]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826) * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB * simplify max Huffman table size calculation * eliminate symbol duplicates (static arrays in .h files) * minor combing in research/ code'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static BROTLI_INLINE uint32_t BitMask(uint32_t n) { if (BROTLI_IS_CONSTANT(n) || BROTLI_HAS_UBFX) { /* Masking with this expression turns to a single "Unsigned Bit Field Extract" UBFX instruction on ARM. */ return ~((0xFFFFFFFFu) << n); } else { return kBitMask[n]; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Update (#826) * IMPORTANT: decoder: fix potential overflow when input chunk is >2GiB * simplify max Huffman table size calculation * eliminate symbol duplicates (static arrays in .h files) * minor combing in research/ code'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vgacon_scrollback_init(int vc_num) { int pitch = vga_video_num_columns * 2; size_t size = CONFIG_VGACON_SOFT_SCROLLBACK_SIZE * 1024; int rows = size / pitch; void *data; data = kmalloc_array(CONFIG_VGACON_SOFT_SCROLLBACK_SIZE, 1024, GFP_NOWAIT); vgacon_scrollbacks[vc_num].data = data; vgacon_scrollback_cur = &vgacon_scrollbacks[vc_num]; vgacon_scrollback_cur->rows = rows - 1; vgacon_scrollback_cur->size = rows * pitch; vgacon_scrollback_reset(vc_num, size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vgacon: remove software scrollback support Yunhai Zhang recently fixed a VGA software scrollback bug in commit ebfdfeeae8c0 ("vgacon: Fix for missing check in scrollback handling"), but that then made people look more closely at some of this code, and there were more problems on the vgacon side, but also the fbcon software scrollback. We don't really have anybody who maintains this code - probably because nobody actually _uses_ it any more. Sure, people still use both VGA and the framebuffer consoles, but they are no longer the main user interfaces to the kernel, and haven't been for decades, so these kinds of extra features end up bitrotting and not really being used. So rather than try to maintain a likely unused set of code, I'll just aggressively remove it, and see if anybody even notices. Maybe there are people who haven't jumped on the whole GUI badnwagon yet, and think it's just a fad. And maybe those people use the scrollback code. If that turns out to be the case, we can resurrect this again, once we've found the sucker^Wmaintainer for it who actually uses it. Reported-by: NopNop Nop <nopitydays@gmail.com> Tested-by: Willy Tarreau <w@1wt.eu> Cc: 张云海 <zhangyunhai@nsfocus.com> Acked-by: Andy Lutomirski <luto@amacapital.net> Acked-by: Willy Tarreau <w@1wt.eu> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hugetlb_sysctl_handler_common(bool obey_mempolicy, struct ctl_table *table, int write, void *buffer, size_t *length, loff_t *ppos) { struct hstate *h = &default_hstate; unsigned long tmp = h->max_huge_pages; int ret; if (!hugepages_supported()) return -EOPNOTSUPP; table->data = &tmp; table->maxlen = sizeof(unsigned long); ret = proc_doulongvec_minmax(table, write, buffer, length, ppos); if (ret) goto out; if (write) ret = __nr_hugepages_store_common(obey_mempolicy, h, NUMA_NO_NODE, tmp, *length); out: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'mm/hugetlb: fix a race between hugetlb sysctl handlers There is a race between the assignment of `table->data` and write value to the pointer of `table->data` in the __do_proc_doulongvec_minmax() on the other thread. CPU0: CPU1: proc_sys_write hugetlb_sysctl_handler proc_sys_call_handler hugetlb_sysctl_handler_common hugetlb_sysctl_handler table->data = &tmp; hugetlb_sysctl_handler_common table->data = &tmp; proc_doulongvec_minmax do_proc_doulongvec_minmax sysctl_head_finish __do_proc_doulongvec_minmax unuse_table i = table->data; *i = val; // corrupt CPU1's stack Fix this by duplicating the `table`, and only update the duplicate of it. And introduce a helper of proc_hugetlb_doulongvec_minmax() to simplify the code. The following oops was seen: BUG: kernel NULL pointer dereference, address: 0000000000000000 #PF: supervisor instruction fetch in kernel mode #PF: error_code(0x0010) - not-present page Code: Bad RIP value. ... Call Trace: ? set_max_huge_pages+0x3da/0x4f0 ? alloc_pool_huge_page+0x150/0x150 ? proc_doulongvec_minmax+0x46/0x60 ? hugetlb_sysctl_handler_common+0x1c7/0x200 ? nr_hugepages_store+0x20/0x20 ? copy_fd_bitmaps+0x170/0x170 ? hugetlb_sysctl_handler+0x1e/0x20 ? proc_sys_call_handler+0x2f1/0x300 ? unregister_sysctl_table+0xb0/0xb0 ? __fd_install+0x78/0x100 ? proc_sys_write+0x14/0x20 ? __vfs_write+0x4d/0x90 ? vfs_write+0xef/0x240 ? ksys_write+0xc0/0x160 ? __ia32_sys_read+0x50/0x50 ? __close_fd+0x129/0x150 ? __x64_sys_write+0x43/0x50 ? do_syscall_64+0x6c/0x200 ? entry_SYSCALL_64_after_hwframe+0x44/0xa9 Fixes: e5ff215941d5 ("hugetlb: multiple hstates for multiple page sizes") Signed-off-by: Muchun Song <songmuchun@bytedance.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Reviewed-by: Mike Kravetz <mike.kravetz@oracle.com> Cc: Andi Kleen <ak@linux.intel.com> Link: http://lkml.kernel.org/r/20200828031146.43035-1-songmuchun@bytedance.com Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc) { int i, j, len; UChar *p; for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) { len = enclen(enc, p); if (i + len > OPT_EXACT_MAXLEN) break; for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; if (p >= end) to->reach_end = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '#207: Out-of-bounds write'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void do_client_file_xfer(VirtioPort *vport, VDAgentMessage *message_header, uint8_t *data) { uint32_t msg_type, id; UdscsConnection *conn; switch (message_header->type) { case VD_AGENT_FILE_XFER_START: { VDAgentFileXferStartMessage *s = (VDAgentFileXferStartMessage *)data; if (!active_session_conn) { send_file_xfer_status(vport, "Could not find an agent connection belonging to the " "active session, cancelling client file-xfer request %u", s->id, VD_AGENT_FILE_XFER_STATUS_VDAGENT_NOT_CONNECTED, NULL, 0); return; } else if (session_info_session_is_locked(session_info)) { syslog(LOG_DEBUG, "Session is locked, skipping file-xfer-start"); send_file_xfer_status(vport, "User's session is locked and cannot start file transfer. " "Cancelling client file-xfer request %u", s->id, VD_AGENT_FILE_XFER_STATUS_SESSION_LOCKED, NULL, 0); return; } else if (g_hash_table_size(active_xfers) >= MAX_ACTIVE_TRANSFERS) { VDAgentFileXferStatusError error = { GUINT32_TO_LE(VD_AGENT_FILE_XFER_STATUS_ERROR_GLIB_IO), GUINT32_TO_LE(G_IO_ERROR_TOO_MANY_OPEN_FILES), }; size_t detail_size = sizeof(error); if (!VD_AGENT_HAS_CAPABILITY(capabilities, capabilities_size, VD_AGENT_CAP_FILE_XFER_DETAILED_ERRORS)) { detail_size = 0; } send_file_xfer_status(vport, "Too many transfers ongoing. " "Cancelling client file-xfer request %u", s->id, VD_AGENT_FILE_XFER_STATUS_ERROR, (void*) &error, detail_size); return; } msg_type = VDAGENTD_FILE_XFER_START; id = s->id; // associate the id with the active connection g_hash_table_insert(active_xfers, GUINT_TO_POINTER(id), active_session_conn); break; } case VD_AGENT_FILE_XFER_STATUS: { VDAgentFileXferStatusMessage *s = (VDAgentFileXferStatusMessage *)data; msg_type = VDAGENTD_FILE_XFER_STATUS; id = s->id; break; } case VD_AGENT_FILE_XFER_DATA: { VDAgentFileXferDataMessage *d = (VDAgentFileXferDataMessage *)data; msg_type = VDAGENTD_FILE_XFER_DATA; id = d->id; break; } default: g_return_if_reached(); /* quiet uninitialized variable warning */ } conn = g_hash_table_lookup(active_xfers, GUINT_TO_POINTER(id)); if (!conn) { if (debug) syslog(LOG_DEBUG, "Could not find file-xfer %u (cancelled?)", id); return; } udscs_write(conn, msg_type, 0, 0, data, message_header->size); // client told that transfer is ended, agents too stop the transfer // and release resources if (message_header->type == VD_AGENT_FILE_XFER_STATUS) { g_hash_table_remove(active_xfers, GUINT_TO_POINTER(id)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'vdagentd: do not allow to use an already used file-xfer id Signed-off-by: Uri Lublin <uril@redhat.com> Acked-by: Frediano Ziglio <fziglio@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg) { bool src_known = tnum_subreg_is_const(src_reg->var_off); bool dst_known = tnum_subreg_is_const(dst_reg->var_off); struct tnum var32_off = tnum_subreg(dst_reg->var_off); s32 smin_val = src_reg->smin_value; u32 umin_val = src_reg->umin_value; /* Assuming scalar64_min_max_or will be called so it is safe * to skip updating register for known case. */ if (src_known && dst_known) return; /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); dst_reg->u32_max_value = var32_off.value | var32_off.mask; if (dst_reg->s32_min_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->s32_min_value = S32_MIN; dst_reg->s32_max_value = S32_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->s32_min_value = dst_reg->umin_value; dst_reg->s32_max_value = dst_reg->umax_value; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-681', 'CWE-787'], 'message': 'bpf: Fix scalar32_min_max_or bounds tracking Simon reported an issue with the current scalar32_min_max_or() implementation. That is, compared to the other 32 bit subreg tracking functions, the code in scalar32_min_max_or() stands out that it's using the 64 bit registers instead of 32 bit ones. This leads to bounds tracking issues, for example: [...] 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm 8: (79) r1 = *(u64 *)(r0 +0) R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm 9: (b7) r0 = 1 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm 10: (18) r2 = 0x600000002 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 12: (ad) if r1 < r2 goto pc+1 R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 13: (95) exit 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 14: (25) if r1 > 0x0 goto pc+1 R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 15: (95) exit 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 16: (47) r1 |= 0 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x1; 0x700000000),s32_max_value=1,u32_max_value=1) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm [...] The bound tests on the map value force the upper unsigned bound to be 25769803777 in 64 bit (0b11000000000000000000000000000000001) and then lower one to be 1. By using OR they are truncated and thus result in the range [1,1] for the 32 bit reg tracker. This is incorrect given the only thing we know is that the value must be positive and thus 2147483647 (0b1111111111111111111111111111111) at max for the subregs. Fix it by using the {u,s}32_{min,max}_value vars instead. This also makes sense, for example, for the case where we update dst_reg->s32_{min,max}_value in the else branch we need to use the newly computed dst_reg->u32_{min,max}_value as we know that these are positive. Previously, in the else branch the 64 bit values of umin_value=1 and umax_value=32212254719 were used and latter got truncated to be 1 as upper bound there. After the fix the subreg range is now correct: [...] 8: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm 8: (79) r1 = *(u64 *)(r0 +0) R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R10=fp0 fp-8=mmmmmmmm 9: R0=map_value(id=0,off=0,ks=4,vs=48,imm=0) R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm 9: (b7) r0 = 1 10: R0_w=inv1 R1_w=inv(id=0) R10=fp0 fp-8=mmmmmmmm 10: (18) r2 = 0x600000002 12: R0_w=inv1 R1_w=inv(id=0) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 12: (ad) if r1 < r2 goto pc+1 R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 13: R0_w=inv1 R1_w=inv(id=0,umin_value=25769803778) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 13: (95) exit 14: R0_w=inv1 R1_w=inv(id=0,umax_value=25769803777,var_off=(0x0; 0x7ffffffff)) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 14: (25) if r1 > 0x0 goto pc+1 R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 15: R0_w=inv1 R1_w=inv(id=0,umax_value=0,var_off=(0x0; 0x7fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 15: (95) exit 16: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=25769803777,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm 16: (47) r1 |= 0 17: R0_w=inv1 R1_w=inv(id=0,umin_value=1,umax_value=32212254719,var_off=(0x0; 0x77fffffff),u32_max_value=2147483647) R2_w=inv25769803778 R10=fp0 fp-8=mmmmmmmm [...] Fixes: 3f50f132d840 ("bpf: Verifier, do explicit ALU32 bounds tracking") Reported-by: Simon Scannell <scannell.smn@gmail.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Reviewed-by: John Fastabend <john.fastabend@gmail.com> Acked-by: Alexei Starovoitov <ast@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_image->background_color.alpha_trait=BlendPixelTrait; dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_image->background_color.alpha_trait=BlendPixelTrait; bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; prev_image->background_color.alpha_trait=BlendPixelTrait; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-369'], 'message': 'There is a Division by Zero in function OptimizeLayerFrames (#2743) in file MagickCore/layer.c. cur->ticks_per_seconds can be zero with a crafted input argument *image. This is similar to CVE-2019-13454.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void handle_irq_for_port(evtchn_port_t port) { int irq; irq = get_evtchn_to_irq(port); if (irq != -1) generic_handle_irq(irq); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'xen/events: defer eoi in case of excessive number of events In case rogue guests are sending events at high frequency it might happen that xen_evtchn_do_upcall() won't stop processing events in dom0. As this is done in irq handling a crash might be the result. In order to avoid that, delay further inter-domain events after some time in xen_evtchn_do_upcall() by forcing eoi processing into a worker on the same cpu, thus inhibiting new events coming in. The time after which eoi processing is to be delayed is configurable via a new module parameter "event_loop_timeout" which specifies the maximum event loop time in jiffies (default: 2, the value was chosen after some tests showing that a value of 2 was the lowest with an only slight drop of dom0 network throughput while multiple guests performed an event storm). How long eoi processing will be delayed can be specified via another parameter "event_eoi_delay" (again in jiffies, default 10, again the value was chosen after testing with different delay values). This is part of XSA-332. Cc: stable@vger.kernel.org Reported-by: Julien Grall <julien@xen.org> Signed-off-by: Juergen Gross <jgross@suse.com> Reviewed-by: Stefano Stabellini <sstabellini@kernel.org> Reviewed-by: Wei Liu <wl@xen.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int get_evtchn_to_irq(evtchn_port_t evtchn) { if (evtchn >= xen_evtchn_max_channels()) return -1; if (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL) return -1; return evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-476'], 'message': 'xen/events: avoid removing an event channel while handling it Today it can happen that an event channel is being removed from the system while the event handling loop is active. This can lead to a race resulting in crashes or WARN() splats when trying to access the irq_info structure related to the event channel. Fix this problem by using a rwlock taken as reader in the event handling loop and as writer when deallocating the irq_info structure. As the observed problem was a NULL dereference in evtchn_from_irq() make this function more robust against races by testing the irq_info pointer to be not NULL before dereferencing it. And finally make all accesses to evtchn_to_irq[row][col] atomic ones in order to avoid seeing partial updates of an array element in irq handling. Note that irq handling can be entered only for event channels which have been valid before, so any not populated row isn't a problem in this regard, as rows are only ever added and never removed. This is XSA-331. Cc: stable@vger.kernel.org Reported-by: Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com> Reported-by: Jinoh Kang <luke1337@theori.io> Signed-off-by: Juergen Gross <jgross@suse.com> Reviewed-by: Stefano Stabellini <sstabellini@kernel.org> Reviewed-by: Wei Liu <wl@xen.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception) { char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; Image *image; ImageInfo *image_info; char *name, s[2]; const char *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; PNGErrorInfo error_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); image = CloneImage(IMimage,0,0,MagickFalse,exception); if (image == (Image *) NULL) return(MagickFalse); image_info=(ImageInfo *) CloneImageInfo(IMimage_info); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MagickPathExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MagickPathExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%g", image->gamma); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image,exception); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if ((image->storage_class != PseudoClass) && (image->colormap != (PixelInfo *) NULL)) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image,exception); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register Quantum *r; if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBA(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBA(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBA(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (r == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBA(r); r+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBA(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; number_opaque = (int) image->colors; number_transparent = 0; number_semitransparent = 0; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->alpha_trait == UndefinedPixelTrait))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; if (image->alpha_trait != UndefinedPixelTrait) { number_transparent = 2; number_semitransparent = 1; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; if (image->depth != GetImageDepth(image,exception)) (void) SetImageDepth(image,image->depth,exception); for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->alpha_trait is MagickFalse, we ignore the alpha channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ int n; PixelInfo opaque[260], semitransparent[260], transparent[260]; register const Quantum *r; register Quantum *q; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->alpha_trait=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { r=GetVirtualPixels(image,0,y,image->columns,1,exception); if (r == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait == UndefinedPixelTrait || GetPixelAlpha(image,r) == OpaqueAlpha) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelInfoPixel(image,r,opaque); opaque[0].alpha=OpaqueAlpha; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(image,r,opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelInfoPixel(image,r,opaque+i); opaque[i].alpha=OpaqueAlpha; } } } else if (GetPixelAlpha(image,r) == TransparentAlpha) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelInfoPixel(image,r,transparent); ping_trans_color.red=(unsigned short) GetPixelRed(image,r); ping_trans_color.green=(unsigned short) GetPixelGreen(image,r); ping_trans_color.blue=(unsigned short) GetPixelBlue(image,r); ping_trans_color.gray=(unsigned short) GetPixelGray(image,r); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(image,r,transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelInfoPixel(image,r,transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelInfoPixel(image,r,semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(image,r,semitransparent+i) && GetPixelAlpha(image,r) == semitransparent[i].alpha) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelInfoPixel(image,r,semitransparent+i); } } } r+=GetPixelChannels(image); } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } if (number_opaque < 259) { for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != GetPixelGreen(image,r) || GetPixelRed(image,r) != GetPixelBlue(image,r)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { r=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(image,r) != 0 && GetPixelRed(image,r) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } r+=GetPixelChannels(image); } } } } } if (image_colors < 257) { PixelInfo colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors,exception) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->alpha_trait == UndefinedPixelTrait || image->colormap[i].alpha == GetPixelAlpha(image,q)) && image->colormap[i].red == GetPixelRed(image,q) && image->colormap[i].green == GetPixelGreen(image,q) && image->colormap[i].blue == GetPixelBlue(image,q)) { SetPixelIndex(image,i,q); break; } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,alpha)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].alpha); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) < OpaqueAlpha/2) { SetPixelViaPixelInfo(image,&image->background_color,q); SetPixelAlpha(image,TransparentAlpha,q); } else SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].alpha = (image->colormap[i].alpha > TransparentAlpha/2 ? TransparentAlpha : OpaqueAlpha); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR04PixelRGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR03RGB(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) == OpaqueAlpha) LBR02PixelBlue(q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 && GetPixelAlpha(image,q) == OpaqueAlpha) { SetPixelRed(image,ScaleCharToQuantum(0x24),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { register const Quantum *q; for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelAlpha(image,q) != TransparentAlpha && (unsigned short) GetPixelRed(image,q) == ping_trans_color.red && (unsigned short) GetPixelGreen(image,q) == ping_trans_color.green && (unsigned short) GetPixelBlue(image,q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q+=GetPixelChannels(image); } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { image_info=DestroyImageInfo(image_info); image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",IMimage->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED error_info.image=image; error_info.exception=exception; ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->alpha_trait); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->resolution.x != 0) && (image->resolution.y != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->resolution.x+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->resolution.y+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->resolution.x; ping_pHYs_y_resolution=(png_uint_32) image->resolution.y; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else if (image_info->type == TrueColorAlphaType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } else if (image_info->type == PaletteType || image_info->type == PaletteAlphaType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; else { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->alpha_trait == UndefinedPixelTrait && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } (void) old_bit_depth; image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(GetPixelInfoIntensity(image, image->colormap)) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green= ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) ScaleQuantumToChar(image->colormap[i].alpha); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)* (ScaleQuantumToShort(((GetPixelInfoIntensity(image, &image->background_color))) +.5))); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This will be addressed soon in a release that accomodates "-define png:compression-strategy", etc. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait) { /* Add an opaque matte channel */ image->alpha_trait = BlendPixelTrait; (void) SetImageAlpha(image,OpaqueAlpha,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { ping_have_iCCP = MagickTrue; if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); } else { /* Do not write hex-encoded ICC chunk */ name=GetNextImageProfile(image); continue; } } #endif /* WRITE_iCCP */ if (LocaleCompare(name,"exif") == 0) { /* Do not write hex-encoded ICC chunk; we will write it later as an eXIf chunk */ name=GetNextImageProfile(image); continue; } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXt chunk with uuencoded %s profile", name); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); } name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME",exception); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify",exception); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp,exception); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } png_write_info(ping,ping_info); /* write orNT if image->orientation is defined */ if (image->orientation != UndefinedOrientation) { unsigned char chunk[6]; (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_orNT); LogPNGChunk(logging,mng_orNT,1L); /* PNG uses Exif orientation values */ chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels)); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) || ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse)) { /* Palette, Bilevel, or Opaque Monochrome */ QuantumType quantum_type; register const Quantum *p; quantum_type=RedQuantum; if (mng_info->IsPalette) { quantum_type=GrayQuantum; if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) quantum_type=IndexQuantum; } SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,ping_pixels,exception); if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const Quantum *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,exception); else (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA", pass); p=GetVirtualPixels(image,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, exception); } else { (void) ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property,exception); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write eXIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); PNGType(chunk,mng_eXIf); if (length < 7) { ping_profile=DestroyStringInfo(ping_profile); break; /* otherwise crashes */ } if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' && *(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0') { /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; data += 6; } LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data, (uInt) length)); ping_profile=DestroyStringInfo(ping_profile); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (ping_have_blob != MagickFalse) (void) CloseBlob(image); image_info=DestroyImageInfo(image_info); image=DestroyImage(image); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1715'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static irqreturn_t sunkbd_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct sunkbd *sunkbd = serio_get_drvdata(serio); if (sunkbd->reset <= -1) { /* * If cp[i] is 0xff, sunkbd->reset will stay -1. * The keyboard sends 0xff 0xff 0xID on powerup. */ sunkbd->reset = data; wake_up_interruptible(&sunkbd->wait); goto out; } if (sunkbd->layout == -1) { sunkbd->layout = data; wake_up_interruptible(&sunkbd->wait); goto out; } switch (data) { case SUNKBD_RET_RESET: schedule_work(&sunkbd->tq); sunkbd->reset = -1; break; case SUNKBD_RET_LAYOUT: sunkbd->layout = -1; break; case SUNKBD_RET_ALLUP: /* All keys released */ break; default: if (!sunkbd->enabled) break; if (sunkbd->keycode[data & SUNKBD_KEY]) { input_report_key(sunkbd->dev, sunkbd->keycode[data & SUNKBD_KEY], !(data & SUNKBD_RELEASE)); input_sync(sunkbd->dev); } else { printk(KERN_WARNING "sunkbd.c: Unknown key (scancode %#x) %s.\n", data & SUNKBD_KEY, data & SUNKBD_RELEASE ? "released" : "pressed"); } } out: return IRQ_HANDLED; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Input: sunkbd - avoid use-after-free in teardown paths We need to make sure we cancel the reinit work before we tear down the driver structures. Reported-by: Bodong Zhao <nopitydays@gmail.com> Tested-by: Bodong Zhao <nopitydays@gmail.com> Cc: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int vt_io_fontreset(struct console_font_op *op) { int ret; if (__is_defined(BROKEN_GRAPHICS_PROGRAMS)) { /* * With BROKEN_GRAPHICS_PROGRAMS defined, the default font is * not saved. */ return -ENOSYS; } op->op = KD_FONT_OP_SET_DEFAULT; op->data = NULL; ret = con_font_op(vc_cons[fg_console].d, op); if (ret) return ret; console_lock(); con_set_default_unimap(vc_cons[fg_console].d); console_unlock(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'tty: make FONTX ioctl use the tty pointer they were actually passed Some of the font tty ioctl's always used the current foreground VC for their operations. Don't do that then. This fixes a data race on fg_console. Side note: both Michael Ellerman and Jiri Slaby point out that all these ioctls are deprecated, and should probably have been removed long ago, and everything seems to be using the KDFONTOP ioctl instead. In fact, Michael points out that it looks like busybox's loadfont program seems to have switched over to using KDFONTOP exactly _because_ of this bug (ahem.. 12 years ago ;-). Reported-by: Minh Yuan <yuanmingbuaa@gmail.com> Acked-by: Michael Ellerman <mpe@ellerman.id.au> Acked-by: Jiri Slaby <jirislaby@kernel.org> Cc: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport MagickStatusType ParseMetaGeometry(const char *geometry,ssize_t *x, ssize_t *y,size_t *width,size_t *height) { GeometryInfo geometry_info; MagickStatusType flags; size_t former_height, former_width; /* Ensure the image geometry is valid. */ assert(x != (ssize_t *) NULL); assert(y != (ssize_t *) NULL); assert(width != (size_t *) NULL); assert(height != (size_t *) NULL); if ((geometry == (char *) NULL) || (*geometry == '\0')) return(NoValue); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",geometry); /* Parse geometry using GetGeometry. */ SetGeometryInfo(&geometry_info); former_width=(*width); former_height=(*height); flags=GetGeometry(geometry,x,y,width,height); if ((flags & PercentValue) != 0) { MagickStatusType percent_flags; PointInfo scale; /* Geometry is a percentage of the image size. */ percent_flags=ParseGeometry(geometry,&geometry_info); scale.x=geometry_info.rho; if ((percent_flags & RhoValue) == 0) scale.x=100.0; scale.y=geometry_info.sigma; if ((percent_flags & SigmaValue) == 0) scale.y=scale.x; *width=(size_t) MagickMax(floor(scale.x*former_width/100.0+0.5),1.0); *height=(size_t) MagickMax(floor(scale.y*former_height/100.0+0.5),1.0); former_width=(*width); former_height=(*height); } if ((flags & AspectRatioValue) != 0) { double geometry_ratio, image_ratio; /* Geometry is a relative to image size and aspect ratio. */ (void) ParseGeometry(geometry,&geometry_info); geometry_ratio=geometry_info.rho; image_ratio=(double) former_width* PerceptibleReciprocal((double) former_height); if (geometry_ratio >= image_ratio) { *width=former_width; *height=(size_t) floor((double) (former_height*image_ratio/ geometry_ratio)+0.5); } else { *width=(size_t) floor((double) (former_width*geometry_ratio/ image_ratio)+0.5); *height=former_height; } former_width=(*width); former_height=(*height); } if (((flags & AspectValue) != 0) || ((*width == former_width) && (*height == former_height))) { if ((flags & RhoValue) == 0) *width=former_width; if ((flags & SigmaValue) == 0) *height=former_height; } else { double scale_factor; /* Respect aspect ratio of the image. */ if ((former_width == 0) || (former_height == 0)) scale_factor=1.0; else if (((flags & RhoValue) != 0) && (flags & SigmaValue) != 0) { scale_factor=(double) *width/(double) former_width; if ((flags & MinimumValue) == 0) { if (scale_factor > ((double) *height/(double) former_height)) scale_factor=(double) *height/(double) former_height; } else if (scale_factor < ((double) *height/(double) former_height)) scale_factor=(double) *height/(double) former_height; } else if ((flags & RhoValue) != 0) { scale_factor=(double) *width/(double) former_width; if (((flags & MinimumValue) != 0) && (scale_factor < ((double) *width/(double) former_height))) scale_factor=(double) *width/(double) former_height; } else { scale_factor=(double) *height/(double) former_height; if (((flags & MinimumValue) != 0) && (scale_factor < ((double) *height/(double) former_width))) scale_factor=(double) *height/(double) former_width; } *width=MagickMax((size_t) floor(scale_factor*former_width+0.5),1UL); *height=MagickMax((size_t) floor(scale_factor*former_height+0.5),1UL); } if ((flags & GreaterValue) != 0) { if (former_width < *width) *width=former_width; if (former_height < *height) *height=former_height; } if ((flags & LessValue) != 0) { if (former_width > *width) *width=former_width; if (former_height > *height) *height=former_height; } if ((flags & AreaValue) != 0) { double area, distance; PointInfo scale; /* Geometry is a maximum area in pixels. */ (void) ParseGeometry(geometry,&geometry_info); area=geometry_info.rho+sqrt(MagickEpsilon); distance=sqrt((double) former_width*former_height); scale.x=(double) former_width*PerceptibleReciprocal(distance/sqrt(area)); scale.y=(double) former_height*PerceptibleReciprocal(distance/sqrt(area)); if ((scale.x < (double) *width) || (scale.y < (double) *height)) { *width=(unsigned long) (former_width*PerceptibleReciprocal( distance/sqrt(area))); *height=(unsigned long) (former_height*PerceptibleReciprocal( distance/sqrt(area))); } former_width=(*width); former_height=(*height); } return(flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1725'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char header[MagickPathExtent]; const char *property; MagickBooleanType status; register const Quantum *p; register ssize_t i, x; size_t length; ssize_t count, y; unsigned char pixel[4], *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Write header. */ (void) memset(header,' ',MagickPathExtent); length=CopyMagickString(header,"#?RADIANCE\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); property=GetImageProperty(image,"comment",exception); if ((property != (const char *) NULL) && (strchr(property,'\n') == (char *) NULL)) { count=FormatLocaleString(header,MagickPathExtent,"#%.*s\n", MagickPathExtent-3,property); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } property=GetImageProperty(image,"hdr:exposure",exception); if (property != (const char *) NULL) { count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n", strtod(property,(char **) NULL)); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } if (image->gamma != 0.0) { count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n", image->gamma); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } count=FormatLocaleString(header,MagickPathExtent, "PRIMARIES=%g %g %g %g %g %g %g %g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x,image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y, image->chromaticity.white_point.x,image->chromaticity.white_point.y); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n", (double) image->rows,(double) image->columns); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); /* Write HDR pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,4*(image->columns+128)*sizeof(*pixels)); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixel[0]=2; pixel[1]=2; pixel[2]=(unsigned char) (image->columns >> 8); pixel[3]=(unsigned char) (image->columns & 0xff); count=WriteBlob(image,4*sizeof(*pixel),pixel); if (count != (ssize_t) (4*sizeof(*pixel))) break; } i=0; for (x=0; x < (ssize_t) image->columns; x++) { double gamma; pixel[0]=0; pixel[1]=0; pixel[2]=0; pixel[3]=0; gamma=QuantumScale*GetPixelRed(image,p); if ((QuantumScale*GetPixelGreen(image,p)) > gamma) gamma=QuantumScale*GetPixelGreen(image,p); if ((QuantumScale*GetPixelBlue(image,p)) > gamma) gamma=QuantumScale*GetPixelBlue(image,p); if (gamma > MagickEpsilon) { int exponent; gamma=frexp(gamma,&exponent)*256.0/gamma; pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p)); pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p)); pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p)); pixel[3]=(unsigned char) (exponent+128); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixels[x]=pixel[0]; pixels[x+image->columns]=pixel[1]; pixels[x+2*image->columns]=pixel[2]; pixels[x+3*image->columns]=pixel[3]; } else { pixels[i++]=pixel[0]; pixels[i++]=pixel[1]; pixels[i++]=pixel[2]; pixels[i++]=pixel[3]; } p+=GetPixelChannels(image); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { for (i=0; i < 4; i++) length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]); } else { count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1713'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline unsigned int ScaleQuantumToLong(const Quantum quantum) { #if !defined(MAGICKCORE_HDRI_SUPPORT) return((unsigned int) quantum); #else if (quantum <= 0.0) return(0); if ((quantum) >= 4294967295.0) return(4294967295); return((unsigned int) (quantum+0.5)); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline unsigned int ScaleQuantumToLong(const Quantum quantum) { #if !defined(MAGICKCORE_HDRI_SUPPORT) return((unsigned int) (16843009UL*quantum)); #else if (quantum <= 0.0) return(0UL); if ((16843009.0*quantum) >= 4294967295.0) return(4294967295UL); return((unsigned int) (16843009.0*quantum+0.5)); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1751'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool is_sst_request_valid(const std::string &msg) { size_t method_len = strlen(msg.c_str()); if (method_len == 0) { return false; } std::string method = msg.substr(0, method_len); // Is this method allowed? auto res = std::find(std::begin(allowed_sst_methods), std::end(allowed_sst_methods), method); if (res == std::end(allowed_sst_methods)) { return false; } const char *data_ptr = msg.c_str() + method_len + 1; size_t data_len = strlen(data_ptr); // method + null + data + null if (method_len + 1 + data_len + 1 != msg.length()) { // Someone tries to piggyback after 2nd null return false; } if (data_len > 0) { /* We allow custom sst scripts, so data can be anything. We could create and maintain the list of forbidden characters and the ways they could be used to inject the command to the OS. However this approach seems to be too error prone. Instead of this we will just allow alpha-num + a few special characters (colon, slash, dot, underscore, square brackets). */ std::string data = msg.substr(method_len + 1, data_len); static const std::regex allowed_chars_regex("[\\w:\\/\\.\\[\\]]+"); if (!std::regex_match(data, allowed_chars_regex)) { return false; } } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-77'], 'message': 'PXC-3392: Donor uses invalid SST methods Dot allowed in SST method name. Hyphen allowed in SST data.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lldp_decode(struct lldpd *cfg, char *frame, int s, struct lldpd_hardware *hardware, struct lldpd_chassis **newchassis, struct lldpd_port **newport) { struct lldpd_chassis *chassis; struct lldpd_port *port; const char lldpaddr[] = LLDP_MULTICAST_ADDR; const char dot1[] = LLDP_TLV_ORG_DOT1; const char dot3[] = LLDP_TLV_ORG_DOT3; const char med[] = LLDP_TLV_ORG_MED; const char dcbx[] = LLDP_TLV_ORG_DCBX; unsigned char orgid[3]; int length, gotend = 0, ttl_received = 0; int tlv_size, tlv_type, tlv_subtype; u_int8_t *pos, *tlv; char *b; #ifdef ENABLE_DOT1 struct lldpd_vlan *vlan = NULL; int vlan_len; struct lldpd_ppvid *ppvid; struct lldpd_pi *pi = NULL; #endif struct lldpd_mgmt *mgmt; int af; u_int8_t addr_str_length, addr_str_buffer[32]; u_int8_t addr_family, addr_length, *addr_ptr, iface_subtype; u_int32_t iface_number, iface; #ifdef ENABLE_CUSTOM struct lldpd_custom *custom = NULL; #endif log_debug("lldp", "receive LLDP PDU on %s", hardware->h_ifname); if ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) { log_warn("lldp", "failed to allocate remote chassis"); return -1; } TAILQ_INIT(&chassis->c_mgmt); if ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) { log_warn("lldp", "failed to allocate remote port"); free(chassis); return -1; } #ifdef ENABLE_DOT1 TAILQ_INIT(&port->p_vlans); TAILQ_INIT(&port->p_ppvids); TAILQ_INIT(&port->p_pids); #endif #ifdef ENABLE_CUSTOM TAILQ_INIT(&port->p_custom_list); #endif length = s; pos = (u_int8_t*)frame; if (length < 2*ETHER_ADDR_LEN + sizeof(u_int16_t)) { log_warnx("lldp", "too short frame received on %s", hardware->h_ifname); goto malformed; } if (PEEK_CMP(lldpaddr, ETHER_ADDR_LEN) != 0) { log_info("lldp", "frame not targeted at LLDP multicast address received on %s", hardware->h_ifname); goto malformed; } PEEK_DISCARD(ETHER_ADDR_LEN); /* Skip source address */ if (PEEK_UINT16 != ETHERTYPE_LLDP) { log_info("lldp", "non LLDP frame received on %s", hardware->h_ifname); goto malformed; } while (length && (!gotend)) { if (length < 2) { log_warnx("lldp", "tlv header too short received on %s", hardware->h_ifname); goto malformed; } tlv_size = PEEK_UINT16; tlv_type = tlv_size >> 9; tlv_size = tlv_size & 0x1ff; (void)PEEK_SAVE(tlv); if (length < tlv_size) { log_warnx("lldp", "frame too short for tlv received on %s", hardware->h_ifname); goto malformed; } switch (tlv_type) { case LLDP_TLV_END: if (tlv_size != 0) { log_warnx("lldp", "lldp end received with size not null on %s", hardware->h_ifname); goto malformed; } if (length) log_debug("lldp", "extra data after lldp end on %s", hardware->h_ifname); gotend = 1; break; case LLDP_TLV_CHASSIS_ID: case LLDP_TLV_PORT_ID: CHECK_TLV_SIZE(2, "Port Id"); tlv_subtype = PEEK_UINT8; if ((tlv_subtype == 0) || (tlv_subtype > 7)) { log_warnx("lldp", "unknown subtype for tlv id received on %s", hardware->h_ifname); goto malformed; } if ((b = (char *)calloc(1, tlv_size - 1)) == NULL) { log_warn("lldp", "unable to allocate memory for id tlv " "received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(b, tlv_size - 1); if (tlv_type == LLDP_TLV_PORT_ID) { port->p_id_subtype = tlv_subtype; port->p_id = b; port->p_id_len = tlv_size - 1; } else { chassis->c_id_subtype = tlv_subtype; chassis->c_id = b; chassis->c_id_len = tlv_size - 1; } break; case LLDP_TLV_TTL: CHECK_TLV_SIZE(2, "TTL"); chassis->c_ttl = PEEK_UINT16; ttl_received = 1; break; case LLDP_TLV_PORT_DESCR: case LLDP_TLV_SYSTEM_NAME: case LLDP_TLV_SYSTEM_DESCR: if (tlv_size < 1) { log_debug("lldp", "empty tlv received on %s", hardware->h_ifname); break; } if ((b = (char *)calloc(1, tlv_size + 1)) == NULL) { log_warn("lldp", "unable to allocate memory for string tlv " "received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(b, tlv_size); if (tlv_type == LLDP_TLV_PORT_DESCR) port->p_descr = b; else if (tlv_type == LLDP_TLV_SYSTEM_NAME) chassis->c_name = b; else chassis->c_descr = b; break; case LLDP_TLV_SYSTEM_CAP: CHECK_TLV_SIZE(4, "System capabilities"); chassis->c_cap_available = PEEK_UINT16; chassis->c_cap_enabled = PEEK_UINT16; break; case LLDP_TLV_MGMT_ADDR: CHECK_TLV_SIZE(1, "Management address"); addr_str_length = PEEK_UINT8; if (addr_str_length > sizeof(addr_str_buffer)) { log_warnx("lldp", "too large management address on %s", hardware->h_ifname); goto malformed; } CHECK_TLV_SIZE(1 + addr_str_length, "Management address"); PEEK_BYTES(addr_str_buffer, addr_str_length); addr_length = addr_str_length - 1; addr_family = addr_str_buffer[0]; addr_ptr = &addr_str_buffer[1]; CHECK_TLV_SIZE(1 + addr_str_length + 5, "Management address"); iface_subtype = PEEK_UINT8; iface_number = PEEK_UINT32; af = lldpd_af_from_lldp_proto(addr_family); if (af == LLDPD_AF_UNSPEC) break; if (iface_subtype == LLDP_MGMT_IFACE_IFINDEX) iface = iface_number; else iface = 0; mgmt = lldpd_alloc_mgmt(af, addr_ptr, addr_length, iface); if (mgmt == NULL) { assert(errno == ENOMEM); log_warn("lldp", "unable to allocate memory " "for management address"); goto malformed; } TAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries); break; case LLDP_TLV_ORG: CHECK_TLV_SIZE(1 + (int)sizeof(orgid), "Organisational"); PEEK_BYTES(orgid, sizeof(orgid)); tlv_subtype = PEEK_UINT8; if (memcmp(dot1, orgid, sizeof(orgid)) == 0) { #ifndef ENABLE_DOT1 hardware->h_rx_unrecognized_cnt++; #else /* Dot1 */ switch (tlv_subtype) { case LLDP_TLV_DOT1_VLANNAME: CHECK_TLV_SIZE(7, "VLAN"); if ((vlan = (struct lldpd_vlan *)calloc(1, sizeof(struct lldpd_vlan))) == NULL) { log_warn("lldp", "unable to alloc vlan " "structure for " "tlv received on %s", hardware->h_ifname); goto malformed; } vlan->v_vid = PEEK_UINT16; vlan_len = PEEK_UINT8; CHECK_TLV_SIZE(7 + vlan_len, "VLAN"); if ((vlan->v_name = (char *)calloc(1, vlan_len + 1)) == NULL) { log_warn("lldp", "unable to alloc vlan name for " "tlv received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(vlan->v_name, vlan_len); TAILQ_INSERT_TAIL(&port->p_vlans, vlan, v_entries); vlan = NULL; break; case LLDP_TLV_DOT1_PVID: CHECK_TLV_SIZE(6, "PVID"); port->p_pvid = PEEK_UINT16; break; case LLDP_TLV_DOT1_PPVID: CHECK_TLV_SIZE(7, "PPVID"); /* validation needed */ /* PPVID has to be unique if more than one PPVID TLVs are received - discard if duplicate */ /* if support bit is not set and enabled bit is set - PPVID TLV is considered error and discarded */ /* if PPVID > 4096 - bad and discard */ if ((ppvid = (struct lldpd_ppvid *)calloc(1, sizeof(struct lldpd_ppvid))) == NULL) { log_warn("lldp", "unable to alloc ppvid " "structure for " "tlv received on %s", hardware->h_ifname); goto malformed; } ppvid->p_cap_status = PEEK_UINT8; ppvid->p_ppvid = PEEK_UINT16; TAILQ_INSERT_TAIL(&port->p_ppvids, ppvid, p_entries); break; case LLDP_TLV_DOT1_PI: /* validation needed */ /* PI has to be unique if more than one PI TLVs are received - discard if duplicate ?? */ CHECK_TLV_SIZE(5, "PI"); if ((pi = (struct lldpd_pi *)calloc(1, sizeof(struct lldpd_pi))) == NULL) { log_warn("lldp", "unable to alloc PI " "structure for " "tlv received on %s", hardware->h_ifname); goto malformed; } pi->p_pi_len = PEEK_UINT8; CHECK_TLV_SIZE(5 + pi->p_pi_len, "PI"); if ((pi->p_pi = (char *)calloc(1, pi->p_pi_len)) == NULL) { log_warn("lldp", "unable to alloc pid name for " "tlv received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(pi->p_pi, pi->p_pi_len); TAILQ_INSERT_TAIL(&port->p_pids, pi, p_entries); pi = NULL; break; default: /* Unknown Dot1 TLV, ignore it */ hardware->h_rx_unrecognized_cnt++; } #endif } else if (memcmp(dot3, orgid, sizeof(orgid)) == 0) { #ifndef ENABLE_DOT3 hardware->h_rx_unrecognized_cnt++; #else /* Dot3 */ switch (tlv_subtype) { case LLDP_TLV_DOT3_MAC: CHECK_TLV_SIZE(9, "MAC/PHY"); port->p_macphy.autoneg_support = PEEK_UINT8; port->p_macphy.autoneg_enabled = (port->p_macphy.autoneg_support & 0x2) >> 1; port->p_macphy.autoneg_support = port->p_macphy.autoneg_support & 0x1; port->p_macphy.autoneg_advertised = PEEK_UINT16; port->p_macphy.mau_type = PEEK_UINT16; break; case LLDP_TLV_DOT3_LA: CHECK_TLV_SIZE(9, "Link aggregation"); PEEK_DISCARD_UINT8; port->p_aggregid = PEEK_UINT32; break; case LLDP_TLV_DOT3_MFS: CHECK_TLV_SIZE(6, "MFS"); port->p_mfs = PEEK_UINT16; break; case LLDP_TLV_DOT3_POWER: CHECK_TLV_SIZE(7, "Power"); port->p_power.devicetype = PEEK_UINT8; port->p_power.supported = (port->p_power.devicetype & 0x2) >> 1; port->p_power.enabled = (port->p_power.devicetype & 0x4) >> 2; port->p_power.paircontrol = (port->p_power.devicetype & 0x8) >> 3; port->p_power.devicetype = (port->p_power.devicetype & 0x1)? LLDP_DOT3_POWER_PSE:LLDP_DOT3_POWER_PD; port->p_power.pairs = PEEK_UINT8; port->p_power.class = PEEK_UINT8; /* 802.3at? */ if (tlv_size >= 12) { port->p_power.powertype = PEEK_UINT8; port->p_power.source = (port->p_power.powertype & (1<<5 | 1<<4)) >> 4; port->p_power.priority = (port->p_power.powertype & (1<<1 | 1<<0)); port->p_power.powertype = (port->p_power.powertype & (1<<7))? LLDP_DOT3_POWER_8023AT_TYPE1: LLDP_DOT3_POWER_8023AT_TYPE2; port->p_power.requested = PEEK_UINT16; port->p_power.allocated = PEEK_UINT16; } else port->p_power.powertype = LLDP_DOT3_POWER_8023AT_OFF; break; default: /* Unknown Dot3 TLV, ignore it */ hardware->h_rx_unrecognized_cnt++; } #endif } else if (memcmp(med, orgid, sizeof(orgid)) == 0) { /* LLDP-MED */ #ifndef ENABLE_LLDPMED hardware->h_rx_unrecognized_cnt++; #else u_int32_t policy; unsigned loctype; unsigned power; switch (tlv_subtype) { case LLDP_TLV_MED_CAP: CHECK_TLV_SIZE(7, "LLDP-MED capabilities"); chassis->c_med_cap_available = PEEK_UINT16; chassis->c_med_type = PEEK_UINT8; port->p_med_cap_enabled |= LLDP_MED_CAP_CAP; break; case LLDP_TLV_MED_POLICY: CHECK_TLV_SIZE(8, "LLDP-MED policy"); policy = PEEK_UINT32; if (((policy >> 24) < 1) || ((policy >> 24) > LLDP_MED_APPTYPE_LAST)) { log_info("lldp", "unknown policy field %d " "received on %s", policy, hardware->h_ifname); break; } port->p_med_policy[(policy >> 24) - 1].type = (policy >> 24); port->p_med_policy[(policy >> 24) - 1].unknown = ((policy & 0x800000) != 0); port->p_med_policy[(policy >> 24) - 1].tagged = ((policy & 0x400000) != 0); port->p_med_policy[(policy >> 24) - 1].vid = (policy & 0x001FFE00) >> 9; port->p_med_policy[(policy >> 24) - 1].priority = (policy & 0x1C0) >> 6; port->p_med_policy[(policy >> 24) - 1].dscp = policy & 0x3F; port->p_med_cap_enabled |= LLDP_MED_CAP_POLICY; break; case LLDP_TLV_MED_LOCATION: CHECK_TLV_SIZE(5, "LLDP-MED Location"); loctype = PEEK_UINT8; if ((loctype < 1) || (loctype > LLDP_MED_LOCFORMAT_LAST)) { log_info("lldp", "unknown location type " "received on %s", hardware->h_ifname); break; } if ((port->p_med_location[loctype - 1].data = (char*)malloc(tlv_size - 5)) == NULL) { log_warn("lldp", "unable to allocate memory " "for LLDP-MED location for " "frame received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(port->p_med_location[loctype - 1].data, tlv_size - 5); port->p_med_location[loctype - 1].data_len = tlv_size - 5; port->p_med_location[loctype - 1].format = loctype; port->p_med_cap_enabled |= LLDP_MED_CAP_LOCATION; break; case LLDP_TLV_MED_MDI: CHECK_TLV_SIZE(7, "LLDP-MED PoE-MDI"); power = PEEK_UINT8; switch (power & 0xC0) { case 0x0: port->p_med_power.devicetype = LLDP_MED_POW_TYPE_PSE; port->p_med_cap_enabled |= LLDP_MED_CAP_MDI_PSE; switch (power & 0x30) { case 0x0: port->p_med_power.source = LLDP_MED_POW_SOURCE_UNKNOWN; break; case 0x10: port->p_med_power.source = LLDP_MED_POW_SOURCE_PRIMARY; break; case 0x20: port->p_med_power.source = LLDP_MED_POW_SOURCE_BACKUP; break; default: port->p_med_power.source = LLDP_MED_POW_SOURCE_RESERVED; } break; case 0x40: port->p_med_power.devicetype = LLDP_MED_POW_TYPE_PD; port->p_med_cap_enabled |= LLDP_MED_CAP_MDI_PD; switch (power & 0x30) { case 0x0: port->p_med_power.source = LLDP_MED_POW_SOURCE_UNKNOWN; break; case 0x10: port->p_med_power.source = LLDP_MED_POW_SOURCE_PSE; break; case 0x20: port->p_med_power.source = LLDP_MED_POW_SOURCE_LOCAL; break; default: port->p_med_power.source = LLDP_MED_POW_SOURCE_BOTH; } break; default: port->p_med_power.devicetype = LLDP_MED_POW_TYPE_RESERVED; } if ((power & 0x0F) > LLDP_MED_POW_PRIO_LOW) port->p_med_power.priority = LLDP_MED_POW_PRIO_UNKNOWN; else port->p_med_power.priority = power & 0x0F; port->p_med_power.val = PEEK_UINT16; break; case LLDP_TLV_MED_IV_HW: case LLDP_TLV_MED_IV_SW: case LLDP_TLV_MED_IV_FW: case LLDP_TLV_MED_IV_SN: case LLDP_TLV_MED_IV_MANUF: case LLDP_TLV_MED_IV_MODEL: case LLDP_TLV_MED_IV_ASSET: if (tlv_size <= 4) b = NULL; else { if ((b = (char*)malloc(tlv_size - 3)) == NULL) { log_warn("lldp", "unable to allocate " "memory for LLDP-MED " "inventory for frame " "received on %s", hardware->h_ifname); goto malformed; } PEEK_BYTES(b, tlv_size - 4); b[tlv_size - 4] = '\0'; } switch (tlv_subtype) { case LLDP_TLV_MED_IV_HW: chassis->c_med_hw = b; break; case LLDP_TLV_MED_IV_FW: chassis->c_med_fw = b; break; case LLDP_TLV_MED_IV_SW: chassis->c_med_sw = b; break; case LLDP_TLV_MED_IV_SN: chassis->c_med_sn = b; break; case LLDP_TLV_MED_IV_MANUF: chassis->c_med_manuf = b; break; case LLDP_TLV_MED_IV_MODEL: chassis->c_med_model = b; break; case LLDP_TLV_MED_IV_ASSET: chassis->c_med_asset = b; break; } port->p_med_cap_enabled |= LLDP_MED_CAP_IV; break; default: /* Unknown LLDP MED, ignore it */ hardware->h_rx_unrecognized_cnt++; } #endif /* ENABLE_LLDPMED */ } else if (memcmp(dcbx, orgid, sizeof(orgid)) == 0) { log_debug("lldp", "unsupported DCBX tlv received on %s - ignore", hardware->h_ifname); hardware->h_rx_unrecognized_cnt++; } else { log_debug("lldp", "unknown org tlv [%02x:%02x:%02x] received on %s", orgid[0], orgid[1], orgid[2], hardware->h_ifname); hardware->h_rx_unrecognized_cnt++; #ifdef ENABLE_CUSTOM custom = (struct lldpd_custom*)calloc(1, sizeof(struct lldpd_custom)); if (!custom) { log_warn("lldp", "unable to allocate memory for custom TLV"); goto malformed; } custom->oui_info_len = tlv_size > 4 ? tlv_size - 4 : 0; memcpy(custom->oui, orgid, sizeof(custom->oui)); custom->subtype = tlv_subtype; if (custom->oui_info_len > 0) { custom->oui_info = malloc(custom->oui_info_len); if (!custom->oui_info) { log_warn("lldp", "unable to allocate memory for custom TLV data"); goto malformed; } PEEK_BYTES(custom->oui_info, custom->oui_info_len); } TAILQ_INSERT_TAIL(&port->p_custom_list, custom, next); custom = NULL; #endif } break; default: log_warnx("lldp", "unknown tlv (%d) received on %s", tlv_type, hardware->h_ifname); goto malformed; } if (pos > tlv + tlv_size) { log_warnx("lldp", "BUG: already past TLV!"); goto malformed; } PEEK_DISCARD(tlv + tlv_size - pos); } /* Some random check */ if ((chassis->c_id == NULL) || (port->p_id == NULL) || (!ttl_received) || (gotend == 0)) { log_warnx("lldp", "some mandatory tlv are missing for frame received on %s", hardware->h_ifname); goto malformed; } *newchassis = chassis; *newport = port; return 1; malformed: #ifdef ENABLE_CUSTOM free(custom); #endif #ifdef ENABLE_DOT1 free(vlan); free(pi); #endif lldpd_chassis_cleanup(chassis, 1); lldpd_port_cleanup(port, 1); free(port); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'protocols: don't use assert on paths that can be reached Malformed packets should not make lldpd crash. Ensure we can handle them by not using assert() in this part.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; BMPSubtype bmp_subtype; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, imageListLength, type; ssize_t y; unsigned char *bmp_data, *pixels; MagickOffsetType profile_data, profile_size, profile_size_pad; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (((image->columns << 3) != (int) (image->columns << 3)) || ((image->rows << 3) != (int) (image->rows << 3))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); type=4; if (LocaleCompare(image_info->magick,"BMP2") == 0) type=2; else if (LocaleCompare(image_info->magick,"BMP3") == 0) type=3; option=GetImageOption(image_info,"bmp:format"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",option); if (LocaleCompare(option,"bmp2") == 0) type=2; if (LocaleCompare(option,"bmp3") == 0) type=3; if (LocaleCompare(option,"bmp4") == 0) type=4; } scene=0; imageListLength=GetImageListLength(image); do { /* Initialize BMP raster file header. */ if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; bmp_info.alpha_mask=0xff000000U; bmp_subtype=UndefinedSubtype; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; option=GetImageOption(image_info,"bmp:subtype"); if (option != (const char *) NULL) { if (image->alpha_trait != UndefinedPixelTrait) { if (LocaleNCompare(option,"ARGB4444",8) == 0) { bmp_subtype=ARGB4444; bmp_info.red_mask=0x00000f00U; bmp_info.green_mask=0x000000f0U; bmp_info.blue_mask=0x0000000fU; bmp_info.alpha_mask=0x0000f000U; } else if (LocaleNCompare(option,"ARGB1555",8) == 0) { bmp_subtype=ARGB1555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0x00008000U; } } else { if (LocaleNCompare(option,"RGB555",6) == 0) { bmp_subtype=RGB555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } else if (LocaleNCompare(option,"RGB565",6) == 0) { bmp_subtype=RGB565; bmp_info.red_mask=0x0000f800U; bmp_info.green_mask=0x000007e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } } } if (bmp_subtype != UndefinedSubtype) { bmp_info.bits_per_pixel=16; bmp_info.compression=BI_BITFIELDS; } else { bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,"bmp3:alpha"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,"icc"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) || ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { unsigned int byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((unsigned int) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { unsigned short pixel; pixel=0; if (bmp_subtype == ARGB4444) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(image,p),15) << 12); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),15) << 8); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),15) << 4); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),15)); } else if (bmp_subtype == RGB565) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),31) << 11); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),63) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),31)); } else { if (bmp_subtype == ARGB1555) pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(image,p),1) << 15); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),31) << 10); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),31) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),31)); } *((unsigned short *) q)=pixel; q+=2; p+=GetPixelChannels(image); } for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing BMP version %.20g datastream",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=DirectClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image depth=%.20g",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RGB"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_BITFIELDS"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=UNKNOWN (%u)",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=unspecified"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=%u",bmp_info.number_colors); } profile_data=0; profile_size=0; profile_size_pad=0; if (profile != (StringInfo *) NULL) { profile_data=(MagickOffsetType) bmp_info.file_size-14; /* from head of BMP info header */ profile_size=(MagickOffsetType) GetStringInfoLength(profile); if ((profile_size % 4) > 0) profile_size_pad=4-(profile_size%4); bmp_info.file_size+=profile_size+profile_size_pad; } (void) WriteBlob(image,2,(unsigned char *) "BM"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,bmp_info.red_mask); (void) WriteBlobLSBLong(image,bmp_info.green_mask); (void) WriteBlobLSBLong(image,bmp_info.blue_mask); (void) WriteBlobLSBLong(image,bmp_info.alpha_mask); if (profile != (StringInfo *) NULL) (void) WriteBlobLSBLong(image,0x4D424544U); /* PROFILE_EMBEDDED */ else (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,(unsigned int) profile_data); (void) WriteBlobLSBLong(image,(unsigned int) (profile_size+profile_size_pad)); (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Colormap: %.20g entries",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Pixels: %u bytes",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); if (profile != (StringInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Profile: %g bytes",(double) profile_size+profile_size_pad); (void) WriteBlob(image,(size_t) profile_size,GetStringInfoDatum(profile)); if (profile_size_pad > 0) /* padding for 4 bytes multiple */ (void) WriteBlob(image,(size_t) profile_size_pad,"\0\0\0"); } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1749'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _inplace_spans (void *abstract_renderer, int y, int h, const cairo_half_open_span_t *spans, unsigned num_spans) { cairo_image_span_renderer_t *r = abstract_renderer; uint8_t *mask; int x0, x1; if (num_spans == 0) return CAIRO_STATUS_SUCCESS; if (num_spans == 2 && spans[0].coverage == 0xff) { pixman_image_composite32 (r->op, r->src, NULL, r->u.composite.dst, spans[0].x + r->u.composite.src_x, y + r->u.composite.src_y, 0, 0, spans[0].x, y, spans[1].x - spans[0].x, h); return CAIRO_STATUS_SUCCESS; } mask = (uint8_t *)pixman_image_get_data (r->mask); x1 = x0 = spans[0].x; do { int len = spans[1].x - spans[0].x; *mask++ = spans[0].coverage; if (len > 1) { if (len >= r->u.composite.run_length && spans[0].coverage == 0xff) { if (x1 != x0) { pixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst, x0 + r->u.composite.src_x, y + r->u.composite.src_y, 0, 0, x0, y, x1 - x0, h); } pixman_image_composite32 (r->op, r->src, NULL, r->u.composite.dst, spans[0].x + r->u.composite.src_x, y + r->u.composite.src_y, 0, 0, spans[0].x, y, len, h); mask = (uint8_t *)pixman_image_get_data (r->mask); x0 = spans[1].x; } else if (spans[0].coverage == 0x0) { if (x1 != x0) { pixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst, x0 + r->u.composite.src_x, y + r->u.composite.src_y, 0, 0, x0, y, x1 - x0, h); } mask = (uint8_t *)pixman_image_get_data (r->mask); x0 = spans[1].x; }else { memset (mask, spans[0].coverage, --len); mask += len; } } x1 = spans[1].x; spans++; } while (--num_spans > 1); if (x1 != x0) { pixman_image_composite32 (r->op, r->src, r->mask, r->u.composite.dst, x0 + r->u.composite.src_x, y + r->u.composite.src_y, 0, 0, x0, y, x1 - x0, h); } return CAIRO_STATUS_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'image: Enable inplace compositing with opacities for general routines On a SNB i5-2500: Speedups ======== firefox-chalkboard 34284.16 -> 19637.40: 1.74x speedup swfdec-giant-steps 778.35 -> 665.37: 1.17x speedup ocitysmap 485.64 -> 431.94: 1.12x speedup Slowdowns ========= firefox-fishbowl 46878.98 -> 54407.14: 1.16x slowdown That slow down is due to overhead of the increased number of calls to pixman_image_composite32() (pixman_transform_point for analyzing the source extents in particular) outweighing any advantage gained by performing the rasterisation in a single pass and eliding gaps. The solution that has been floated in the past is for an interface into pixman to only perform the analysis once and then to return a kernel to use for all spans. Signed-off-by: Chris Wilson <chris@chris-wilson.co.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: im_vips2dz( IMAGE *in, const char *filename ) { char *p, *q; char name[FILENAME_MAX]; char mode[FILENAME_MAX]; char buf[FILENAME_MAX]; int i; VipsForeignDzLayout layout = VIPS_FOREIGN_DZ_LAYOUT_DZ; char *suffix = ".jpeg"; int overlap = 0; int tile_size = 256; VipsForeignDzDepth depth = VIPS_FOREIGN_DZ_DEPTH_ONEPIXEL; gboolean centre = FALSE; VipsAngle angle = VIPS_ANGLE_D0; /* We can't use im_filename_split() --- it assumes that we have a * filename with an extension before the ':', and filename here is * actually a dirname. * * Just split on the first ':'. */ im_strncpy( name, filename, FILENAME_MAX ); if( (p = strchr( name, ':' )) ) { *p = '\0'; im_strncpy( mode, p + 1, FILENAME_MAX ); } strcpy( buf, mode ); p = &buf[0]; if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_LAYOUT, q )) < 0 ) return( -1 ); layout = i; } if( (q = im_getnextoption( &p )) ) suffix = g_strdup( q ); if( (q = im_getnextoption( &p )) ) overlap = atoi( q ); if( (q = im_getnextoption( &p )) ) tile_size = atoi( q ); if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_FOREIGN_DZ_DEPTH, q )) < 0 ) return( -1 ); depth = i; } if( (q = im_getnextoption( &p )) ) { if( im_isprefix( "cen", q ) ) centre = TRUE; } if( (q = im_getnextoption( &p )) ) { if( (i = vips_enum_from_nick( "im_vips2dz", VIPS_TYPE_ANGLE, q )) < 0 ) return( -1 ); angle = i; } if( vips_dzsave( in, name, "layout", layout, "suffix", suffix, "overlap", overlap, "tile_size", tile_size, "depth", depth, "centre", centre, "angle", angle, NULL ) ) return( -1 ); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369', 'CWE-908'], 'message': 'fix a used-before-set error in im_vips2dz we were reading an uninited string in a vips7 compatibility wrapper, thanks yifengchen-cc see https://github.com/libvips/libvips/issues/1419'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildInexactBoundsIfIndexIsMultiKey) { BSONObj indexPattern = BSON("a" << 1); auto testIndex = buildSimpleIndexEntry(indexPattern); testIndex.multikey = true; BSONObj matchObj = BSON("a" << BSON("$ne" << BSONNULL)); auto expr = parseMatchExpression(matchObj); OrderedIntervalList oil; IndexBoundsBuilder::BoundsTightness tightness; IndexBoundsBuilder::translate( expr.get(), indexPattern.firstElement(), testIndex, &oil, &tightness); ASSERT_EQUALS(oil.name, "a"); ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH); assertBoundsRepresentNotEqualsNull(oil); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'SERVER-44377 generate correct plan for indexed inequalities to null'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: JsonServerSelectionTestCase(fs::path testFilePath) { parseTest(testFilePath); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_F(ServerSelectorTestFixture, ShouldFilterCorrectlyByLatencyWindow) { const auto delta = Milliseconds(10); const auto windowWidth = Milliseconds(100); const auto lowerBound = Milliseconds(100); auto window = LatencyWindow(lowerBound, windowWidth); std::vector<ServerDescriptionPtr> servers = { make_with_latency(window.lower - delta, HostAndPort("less")), make_with_latency(window.lower, HostAndPort("boundary-lower")), make_with_latency(window.lower + delta, HostAndPort("within")), make_with_latency(window.upper, HostAndPort("boundary-upper")), make_with_latency(window.upper + delta, HostAndPort("greater"))}; window.filterServers(&servers); ASSERT_EQ(3, servers.size()); ASSERT_EQ(HostAndPort("boundary-lower"), servers[0]->getAddress()); ASSERT_EQ(HostAndPort("within"), servers[1]->getAddress()); ASSERT_EQ(HostAndPort("boundary-upper"), servers[2]->getAddress()); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'SERVER-50170 fix max staleness read preference parameter for server selection'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int resize_runtime_buffer(struct snd_rawmidi_runtime *runtime, struct snd_rawmidi_params *params, bool is_input) { char *newbuf, *oldbuf; if (params->buffer_size < 32 || params->buffer_size > 1024L * 1024L) return -EINVAL; if (params->avail_min < 1 || params->avail_min > params->buffer_size) return -EINVAL; if (params->buffer_size != runtime->buffer_size) { newbuf = kvzalloc(params->buffer_size, GFP_KERNEL); if (!newbuf) return -ENOMEM; spin_lock_irq(&runtime->lock); oldbuf = runtime->buffer; runtime->buffer = newbuf; runtime->buffer_size = params->buffer_size; __reset_runtime_ptrs(runtime, is_input); spin_unlock_irq(&runtime->lock); kvfree(oldbuf); } runtime->avail_min = params->avail_min; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'ALSA: rawmidi: Fix racy buffer resize under concurrent accesses The rawmidi core allows user to resize the runtime buffer via ioctl, and this may lead to UAF when performed during concurrent reads or writes: the read/write functions unlock the runtime lock temporarily during copying form/to user-space, and that's the race window. This patch fixes the hole by introducing a reference counter for the runtime buffer read/write access and returns -EBUSY error when the resize is performed concurrently against read/write. Note that the ref count field is a simple integer instead of refcount_t here, since the all contexts accessing the buffer is basically protected with a spinlock, hence we need no expensive atomic ops. Also, note that this busy check is needed only against read / write functions, and not in receive/transmit callbacks; the race can happen only at the spinlock hole mentioned in the above, while the whole function is protected for receive / transmit callbacks. Reported-by: butt3rflyh4ck <butterflyhuangxx@gmail.com> Cc: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/CAFcO6XMWpUVK_yzzCpp8_XP7+=oUpQvuBeCbMffEDkpe8jWrfg@mail.gmail.com Link: https://lore.kernel.org/r/s5heerw3r5z.wl-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hfi1_file_open(struct inode *inode, struct file *fp) { struct hfi1_filedata *fd; struct hfi1_devdata *dd = container_of(inode->i_cdev, struct hfi1_devdata, user_cdev); if (!((dd->flags & HFI1_PRESENT) && dd->kregbase1)) return -EINVAL; if (!atomic_inc_not_zero(&dd->user_refcount)) return -ENXIO; /* The real work is performed later in assign_ctxt() */ fd = kzalloc(sizeof(*fd), GFP_KERNEL); if (!fd || init_srcu_struct(&fd->pq_srcu)) goto nomem; spin_lock_init(&fd->pq_rcu_lock); spin_lock_init(&fd->tid_lock); spin_lock_init(&fd->invalid_lock); fd->rec_cpu_num = -1; /* no cpu affinity by default */ fd->mm = current->mm; mmgrab(fd->mm); fd->dd = dd; fp->private_data = fd; return 0; nomem: kfree(fd); fp->private_data = NULL; if (atomic_dec_and_test(&dd->user_refcount)) complete(&dd->user_comp); return -ENOMEM; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times Two earlier bug fixes have created a security problem in the hfi1 driver. One fix aimed to solve an issue where current->mm was not valid when closing the hfi1 cdev. It attempted to do this by saving a cached value of the current->mm pointer at file open time. This is a problem if another process with access to the FD calls in via write() or ioctl() to pin pages via the hfi driver. The other fix tried to solve a use after free by taking a reference on the mm. To fix this correctly we use the existing cached value of the mm in the mmu notifier. Now we can check in the insert, evict, etc. routines that current->mm matched what the notifier was registered for. If not, then don't allow access. The register of the mmu notifier will save the mm pointer. Since in do_exit() the exit_mm() is called before exit_files(), which would call our close routine a reference is needed on the mm. We rely on the mmgrab done by the registration of the notifier, whereas before it was explicit. The mmu notifier deregistration happens when the user context is torn down, the creation of which triggered the registration. Also of note is we do not do any explicit work to protect the interval tree notifier. It doesn't seem that this is going to be needed since we aren't actually doing anything with current->mm. The interval tree notifier stuff still has a FIXME noted from a previous commit that will be addressed in a follow on patch. Cc: <stable@vger.kernel.org> Fixes: e0cf75deab81 ("IB/hfi1: Fix mm_struct use after free") Fixes: 3faa3d9a308e ("IB/hfi1: Make use of mm consistent") Link: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com Suggested-by: Jann Horn <jannh@google.com> Reported-by: Jason Gunthorpe <jgg@nvidia.com> Reviewed-by: Ira Weiny <ira.weiny@intel.com> Reviewed-by: Mike Marciniszyn <mike.marciniszyn@cornelisnetworks.com> Signed-off-by: Dennis Dalessandro <dennis.dalessandro@cornelisnetworks.com> Signed-off-by: Jason Gunthorpe <jgg@nvidia.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void hfi1_mmu_rb_evict(struct mmu_rb_handler *handler, void *evict_arg) { struct mmu_rb_node *rbnode, *ptr; struct list_head del_list; unsigned long flags; bool stop = false; INIT_LIST_HEAD(&del_list); spin_lock_irqsave(&handler->lock, flags); list_for_each_entry_safe_reverse(rbnode, ptr, &handler->lru_list, list) { if (handler->ops->evict(handler->ops_arg, rbnode, evict_arg, &stop)) { __mmu_int_rb_remove(rbnode, &handler->root); /* move from LRU list to delete list */ list_move(&rbnode->list, &del_list); } if (stop) break; } spin_unlock_irqrestore(&handler->lock, flags); while (!list_empty(&del_list)) { rbnode = list_first_entry(&del_list, struct mmu_rb_node, list); list_del(&rbnode->list); handler->ops->remove(handler->ops_arg, rbnode); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'IB/hfi1: Ensure correct mm is used at all times Two earlier bug fixes have created a security problem in the hfi1 driver. One fix aimed to solve an issue where current->mm was not valid when closing the hfi1 cdev. It attempted to do this by saving a cached value of the current->mm pointer at file open time. This is a problem if another process with access to the FD calls in via write() or ioctl() to pin pages via the hfi driver. The other fix tried to solve a use after free by taking a reference on the mm. To fix this correctly we use the existing cached value of the mm in the mmu notifier. Now we can check in the insert, evict, etc. routines that current->mm matched what the notifier was registered for. If not, then don't allow access. The register of the mmu notifier will save the mm pointer. Since in do_exit() the exit_mm() is called before exit_files(), which would call our close routine a reference is needed on the mm. We rely on the mmgrab done by the registration of the notifier, whereas before it was explicit. The mmu notifier deregistration happens when the user context is torn down, the creation of which triggered the registration. Also of note is we do not do any explicit work to protect the interval tree notifier. It doesn't seem that this is going to be needed since we aren't actually doing anything with current->mm. The interval tree notifier stuff still has a FIXME noted from a previous commit that will be addressed in a follow on patch. Cc: <stable@vger.kernel.org> Fixes: e0cf75deab81 ("IB/hfi1: Fix mm_struct use after free") Fixes: 3faa3d9a308e ("IB/hfi1: Make use of mm consistent") Link: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com Suggested-by: Jann Horn <jannh@google.com> Reported-by: Jason Gunthorpe <jgg@nvidia.com> Reviewed-by: Ira Weiny <ira.weiny@intel.com> Reviewed-by: Mike Marciniszyn <mike.marciniszyn@cornelisnetworks.com> Signed-off-by: Dennis Dalessandro <dennis.dalessandro@cornelisnetworks.com> Signed-off-by: Jason Gunthorpe <jgg@nvidia.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: look_for_existing_users_sync (GdmDisplay *self) { GdmDisplayPrivate *priv; GError *error = NULL; GVariant *call_result; GVariant *user_list; priv = gdm_display_get_instance_private (self); priv->accountsservice_proxy = g_dbus_proxy_new_sync (priv->connection, 0, NULL, "org.freedesktop.Accounts", "/org/freedesktop/Accounts", "org.freedesktop.Accounts", NULL, &error); if (!priv->accountsservice_proxy) { g_critical ("Failed to contact accountsservice: %s", error->message); goto out; } call_result = g_dbus_proxy_call_sync (priv->accountsservice_proxy, "ListCachedUsers", NULL, 0, -1, NULL, &error); if (!call_result) { g_critical ("Failed to list cached users: %s", error->message); goto out; } g_variant_get (call_result, "(@ao)", &user_list); priv->have_existing_user_accounts = g_variant_n_children (user_list) > 0; g_variant_unref (user_list); g_variant_unref (call_result); out: g_clear_error (&error); return priv->accountsservice_proxy != NULL && call_result != NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'display: Use autoptr to handle errors in look for existing users It will make things just cleaner'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __do_execve_file(int fd, struct filename *filename, struct user_arg_ptr argv, struct user_arg_ptr envp, int flags, struct file *file) { char *pathbuf = NULL; struct linux_binprm *bprm; struct files_struct *displaced; int retval; if (IS_ERR(filename)) return PTR_ERR(filename); /* * We move the actual failure in case of RLIMIT_NPROC excess from * set*uid() to execve() because too many poorly written programs * don't check setuid() return code. Here we additionally recheck * whether NPROC limit is still exceeded. */ if ((current->flags & PF_NPROC_EXCEEDED) && atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) { retval = -EAGAIN; goto out_ret; } /* We're below the limit (still or again), so we don't want to make * further execve() calls fail. */ current->flags &= ~PF_NPROC_EXCEEDED; retval = unshare_files(&displaced); if (retval) goto out_ret; retval = -ENOMEM; bprm = kzalloc(sizeof(*bprm), GFP_KERNEL); if (!bprm) goto out_files; retval = prepare_bprm_creds(bprm); if (retval) goto out_free; check_unsafe_exec(bprm); current->in_execve = 1; if (!file) file = do_open_execat(fd, filename, flags); retval = PTR_ERR(file); if (IS_ERR(file)) goto out_unmark; sched_exec(); bprm->file = file; if (!filename) { bprm->filename = "none"; } else if (fd == AT_FDCWD || filename->name[0] == '/') { bprm->filename = filename->name; } else { if (filename->name[0] == '\0') pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd); else pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s", fd, filename->name); if (!pathbuf) { retval = -ENOMEM; goto out_unmark; } /* * Record that a name derived from an O_CLOEXEC fd will be * inaccessible after exec. Relies on having exclusive access to * current->files (due to unshare_files above). */ if (close_on_exec(fd, rcu_dereference_raw(current->files->fdt))) bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE; bprm->filename = pathbuf; } bprm->interp = bprm->filename; retval = bprm_mm_init(bprm); if (retval) goto out_unmark; retval = prepare_arg_pages(bprm, argv, envp); if (retval < 0) goto out; retval = prepare_binprm(bprm); if (retval < 0) goto out; retval = copy_strings_kernel(1, &bprm->filename, bprm); if (retval < 0) goto out; bprm->exec = bprm->p; retval = copy_strings(bprm->envc, envp, bprm); if (retval < 0) goto out; retval = copy_strings(bprm->argc, argv, bprm); if (retval < 0) goto out; would_dump(bprm, bprm->file); retval = exec_binprm(bprm); if (retval < 0) goto out; /* execve succeeded */ current->fs->in_exec = 0; current->in_execve = 0; membarrier_execve(current); rseq_execve(current); acct_update_integrals(current); task_numa_free(current); free_bprm(bprm); kfree(pathbuf); if (filename) putname(filename); if (displaced) put_files_struct(displaced); return retval; out: if (bprm->mm) { acct_arg_size(bprm, 0); mmput(bprm->mm); } out_unmark: current->fs->in_exec = 0; current->in_execve = 0; out_free: free_bprm(bprm); kfree(pathbuf); out_files: if (displaced) reset_files_struct(displaced); out_ret: if (filename) putname(filename); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'sched/fair: Don't free p->numa_faults with concurrent readers When going through execve(), zero out the NUMA fault statistics instead of freeing them. During execve, the task is reachable through procfs and the scheduler. A concurrent /proc/*/sched reader can read data from a freed ->numa_faults allocation (confirmed by KASAN) and write it back to userspace. I believe that it would also be possible for a use-after-free read to occur through a race between a NUMA fault and execve(): task_numa_fault() can lead to task_numa_compare(), which invokes task_weight() on the currently running task of a different CPU. Another way to fix this would be to make ->numa_faults RCU-managed or add extra locking, but it seems easier to wipe the NUMA fault statistics on execve. Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Petr Mladek <pmladek@suse.com> Cc: Sergey Senozhatsky <sergey.senozhatsky@gmail.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Will Deacon <will@kernel.org> Fixes: 82727018b0d3 ("sched/numa: Call task_numa_free() from do_execve()") Link: https://lkml.kernel.org/r/20190716152047.14424-1-jannh@google.com Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>