project
string
commit_id
string
target
int64
func
string
cwe
string
big_vul_idx
string
idx
int64
hash
string
size
float64
message
string
dataset
string
vim
35a319b77f897744eec1155b736e9372c9c5575f
1
get_address( exarg_T *eap UNUSED, char_u **ptr, cmd_addr_T addr_type, int skip, // only skip the address, don't use it int silent, // no errors or side effects int to_other_file, // flag: may jump to other file int address_count UNUSED) // 1 for first address, >1 after comma { int c; int i; long n; char_u *cmd; pos_T pos; pos_T *fp; linenr_T lnum; buf_T *buf; cmd = skipwhite(*ptr); lnum = MAXLNUM; do { switch (*cmd) { case '.': // '.' - Cursor position ++cmd; switch (addr_type) { case ADDR_LINES: case ADDR_OTHER: lnum = curwin->w_cursor.lnum; break; case ADDR_WINDOWS: lnum = CURRENT_WIN_NR; break; case ADDR_ARGUMENTS: lnum = curwin->w_arg_idx + 1; break; case ADDR_LOADED_BUFFERS: case ADDR_BUFFERS: lnum = curbuf->b_fnum; break; case ADDR_TABS: lnum = CURRENT_TAB_NR; break; case ADDR_NONE: case ADDR_TABS_RELATIVE: case ADDR_UNSIGNED: addr_error(addr_type); cmd = NULL; goto error; break; case ADDR_QUICKFIX: #ifdef FEAT_QUICKFIX lnum = qf_get_cur_idx(eap); #endif break; case ADDR_QUICKFIX_VALID: #ifdef FEAT_QUICKFIX lnum = qf_get_cur_valid_idx(eap); #endif break; } break; case '$': // '$' - last line ++cmd; switch (addr_type) { case ADDR_LINES: case ADDR_OTHER: lnum = curbuf->b_ml.ml_line_count; break; case ADDR_WINDOWS: lnum = LAST_WIN_NR; break; case ADDR_ARGUMENTS: lnum = ARGCOUNT; break; case ADDR_LOADED_BUFFERS: buf = lastbuf; while (buf->b_ml.ml_mfp == NULL) { if (buf->b_prev == NULL) break; buf = buf->b_prev; } lnum = buf->b_fnum; break; case ADDR_BUFFERS: lnum = lastbuf->b_fnum; break; case ADDR_TABS: lnum = LAST_TAB_NR; break; case ADDR_NONE: case ADDR_TABS_RELATIVE: case ADDR_UNSIGNED: addr_error(addr_type); cmd = NULL; goto error; break; case ADDR_QUICKFIX: #ifdef FEAT_QUICKFIX lnum = qf_get_size(eap); if (lnum == 0) lnum = 1; #endif break; case ADDR_QUICKFIX_VALID: #ifdef FEAT_QUICKFIX lnum = qf_get_valid_size(eap); if (lnum == 0) lnum = 1; #endif break; } break; case '\'': // ''' - mark if (*++cmd == NUL) { cmd = NULL; goto error; } if (addr_type != ADDR_LINES) { addr_error(addr_type); cmd = NULL; goto error; } if (skip) ++cmd; else { // Only accept a mark in another file when it is // used by itself: ":'M". fp = getmark(*cmd, to_other_file && cmd[1] == NUL); ++cmd; if (fp == (pos_T *)-1) // Jumped to another file. lnum = curwin->w_cursor.lnum; else { if (check_mark(fp) == FAIL) { cmd = NULL; goto error; } lnum = fp->lnum; } } break; case '/': case '?': // '/' or '?' - search c = *cmd++; if (addr_type != ADDR_LINES) { addr_error(addr_type); cmd = NULL; goto error; } if (skip) // skip "/pat/" { cmd = skip_regexp(cmd, c, magic_isset()); if (*cmd == c) ++cmd; } else { int flags; pos = curwin->w_cursor; // save curwin->w_cursor // When '/' or '?' follows another address, start from // there. if (lnum != MAXLNUM) curwin->w_cursor.lnum = lnum; // Start a forward search at the end of the line (unless // before the first line). // Start a backward search at the start of the line. // This makes sure we never match in the current // line, and can match anywhere in the // next/previous line. if (c == '/' && curwin->w_cursor.lnum > 0) curwin->w_cursor.col = MAXCOL; else curwin->w_cursor.col = 0; searchcmdlen = 0; flags = silent ? 0 : SEARCH_HIS | SEARCH_MSG; if (!do_search(NULL, c, c, cmd, 1L, flags, NULL)) { curwin->w_cursor = pos; cmd = NULL; goto error; } lnum = curwin->w_cursor.lnum; curwin->w_cursor = pos; // adjust command string pointer cmd += searchcmdlen; } break; case '\\': // "\?", "\/" or "\&", repeat search ++cmd; if (addr_type != ADDR_LINES) { addr_error(addr_type); cmd = NULL; goto error; } if (*cmd == '&') i = RE_SUBST; else if (*cmd == '?' || *cmd == '/') i = RE_SEARCH; else { emsg(_(e_backslash_should_be_followed_by)); cmd = NULL; goto error; } if (!skip) { /* * When search follows another address, start from * there. */ if (lnum != MAXLNUM) pos.lnum = lnum; else pos.lnum = curwin->w_cursor.lnum; /* * Start the search just like for the above * do_search(). */ if (*cmd != '?') pos.col = MAXCOL; else pos.col = 0; pos.coladd = 0; if (searchit(curwin, curbuf, &pos, NULL, *cmd == '?' ? BACKWARD : FORWARD, (char_u *)"", 1L, SEARCH_MSG, i, NULL) != FAIL) lnum = pos.lnum; else { cmd = NULL; goto error; } } ++cmd; break; default: if (VIM_ISDIGIT(*cmd)) // absolute line number lnum = getdigits(&cmd); } for (;;) { cmd = skipwhite(cmd); if (*cmd != '-' && *cmd != '+' && !VIM_ISDIGIT(*cmd)) break; if (lnum == MAXLNUM) { switch (addr_type) { case ADDR_LINES: case ADDR_OTHER: // "+1" is same as ".+1" lnum = curwin->w_cursor.lnum; break; case ADDR_WINDOWS: lnum = CURRENT_WIN_NR; break; case ADDR_ARGUMENTS: lnum = curwin->w_arg_idx + 1; break; case ADDR_LOADED_BUFFERS: case ADDR_BUFFERS: lnum = curbuf->b_fnum; break; case ADDR_TABS: lnum = CURRENT_TAB_NR; break; case ADDR_TABS_RELATIVE: lnum = 1; break; case ADDR_QUICKFIX: #ifdef FEAT_QUICKFIX lnum = qf_get_cur_idx(eap); #endif break; case ADDR_QUICKFIX_VALID: #ifdef FEAT_QUICKFIX lnum = qf_get_cur_valid_idx(eap); #endif break; case ADDR_NONE: case ADDR_UNSIGNED: lnum = 0; break; } } if (VIM_ISDIGIT(*cmd)) i = '+'; // "number" is same as "+number" else i = *cmd++; if (!VIM_ISDIGIT(*cmd)) // '+' is '+1', but '+0' is not '+1' n = 1; else n = getdigits(&cmd); if (addr_type == ADDR_TABS_RELATIVE) { emsg(_(e_invalid_range)); cmd = NULL; goto error; } else if (addr_type == ADDR_LOADED_BUFFERS || addr_type == ADDR_BUFFERS) lnum = compute_buffer_local_count( addr_type, lnum, (i == '-') ? -1 * n : n); else { #ifdef FEAT_FOLDING // Relative line addressing, need to adjust for folded lines // now, but only do it after the first address. if (addr_type == ADDR_LINES && (i == '-' || i == '+') && address_count >= 2) (void)hasFolding(lnum, NULL, &lnum); #endif if (i == '-') lnum -= n; else lnum += n; } } } while (*cmd == '/' || *cmd == '?'); error: *ptr = cmd; return lnum; }
null
null
209,802
255515585455667424007181368478490735353
350
patch 8.2.3489: ml_get error after search with range Problem: ml_get error after search with range. Solution: Limit the line number to the buffer line count.
other
spice-vd_agent
812ca777469a377c84b9861d7d326bfc72563304
1
static void agent_connect(UdscsConnection *conn) { struct agent_data *agent_data; agent_data = g_new0(struct agent_data, 1); GError *err = NULL; if (session_info) { PidUid pid_uid = vdagent_connection_get_peer_pid_uid(VDAGENT_CONNECTION(conn), &err); if (err || pid_uid.pid <= 0) { static const char msg[] = "Could not get peer PID, disconnecting new client"; if (err) { syslog(LOG_ERR, "%s: %s", msg, err->message); g_error_free(err); } else { syslog(LOG_ERR, "%s", msg); } agent_data_destroy(agent_data); udscs_server_destroy_connection(server, conn); return; } agent_data->session = session_info_session_for_pid(session_info, pid_uid.pid); uid_t session_uid = session_info_uid_for_session(session_info, agent_data->session); /* Check that the UID of the PID did not change, this should be done after * computing the session to avoid race conditions. * This can happen as vdagent_connection_get_peer_pid_uid get information * from the time of creating the socket, but the process in the meantime * have been replaced */ if (!check_uid_of_pid(pid_uid.pid, pid_uid.uid) || /* Check that the user launching the Agent is the same as session one * or root user. * This prevents session hijacks from other users. */ (pid_uid.uid != 0 && pid_uid.uid != session_uid)) { syslog(LOG_ERR, "UID mismatch: UID=%u PID=%u suid=%u", pid_uid.uid, pid_uid.pid, session_uid); agent_data_destroy(agent_data); udscs_server_destroy_connection(server, conn); return; } } g_object_set_data_full(G_OBJECT(conn), "agent_data", agent_data, (GDestroyNotify) agent_data_destroy); udscs_write(conn, VDAGENTD_VERSION, 0, 0, (uint8_t *)VERSION, strlen(VERSION) + 1); update_active_session_connection(conn); if (device_info) { forward_data_to_session_agent(VDAGENTD_GRAPHICS_DEVICE_INFO, (uint8_t *) device_info, device_info_size); } }
null
null
209,927
222631144345982891983039723210387088765
54
vdagentd: Limit number of agents per session to 1 Signed-off-by: Frediano Ziglio <[email protected]> Acked-by: Uri Lublin <[email protected]>
other
FreeRDP
06c32f170093a6ecde93e3bc07fed6a706bfbeb3
1
static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, UINT32 x, UINT32 y, UINT32 width, UINT32 height) { VideoClientContextPriv* priv = video->priv; PresentationContext* ret = calloc(1, sizeof(*ret)); if (!ret) return NULL; ret->video = video; ret->PresentationId = PresentationId; ret->h264 = h264_context_new(FALSE); if (!ret->h264) { WLog_ERR(TAG, "unable to create a h264 context"); goto error_h264; } h264_context_reset(ret->h264, width, height); ret->currentSample = Stream_New(NULL, 4096); if (!ret->currentSample) { WLog_ERR(TAG, "unable to create current packet stream"); goto error_currentSample; } ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4); if (!ret->surfaceData) { WLog_ERR(TAG, "unable to allocate surfaceData"); goto error_surfaceData; } ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height); if (!ret->surface) { WLog_ERR(TAG, "unable to create surface"); goto error_surface; } ret->yuv = yuv_context_new(FALSE); if (!ret->yuv) { WLog_ERR(TAG, "unable to create YUV decoder"); goto error_yuv; } yuv_context_reset(ret->yuv, width, height); ret->refCounter = 1; return ret; error_yuv: video->deleteSurface(video, ret->surface); error_surface: BufferPool_Return(priv->surfacePool, ret->surfaceData); error_surfaceData: Stream_Free(ret->currentSample, TRUE); error_currentSample: h264_context_free(ret->h264); error_h264: free(ret); return NULL; }
null
null
209,931
64323647283435453826655663150287402829
63
Fixed int overflow in PresentationContext_new Thanks to hac425 CVE-2020-11038
other
linux
8188a18ee2e48c9a7461139838048363bfce3fef
1
struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev, const struct pci_device_id *ent, const struct iwl_cfg_trans_params *cfg_trans) { struct iwl_trans_pcie *trans_pcie; struct iwl_trans *trans; int ret, addr_size; ret = pcim_enable_device(pdev); if (ret) return ERR_PTR(ret); if (cfg_trans->gen2) trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, &trans_ops_pcie_gen2); else trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, &trans_ops_pcie); if (!trans) return ERR_PTR(-ENOMEM); trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans); trans_pcie->trans = trans; trans_pcie->opmode_down = true; spin_lock_init(&trans_pcie->irq_lock); spin_lock_init(&trans_pcie->reg_lock); mutex_init(&trans_pcie->mutex); init_waitqueue_head(&trans_pcie->ucode_write_waitq); trans_pcie->tso_hdr_page = alloc_percpu(struct iwl_tso_hdr_page); if (!trans_pcie->tso_hdr_page) { ret = -ENOMEM; goto out_no_pci; } trans_pcie->debug_rfkill = -1; if (!cfg_trans->base_params->pcie_l1_allowed) { /* * W/A - seems to solve weird behavior. We need to remove this * if we don't want to stay in L1 all the time. This wastes a * lot of power. */ pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM); } trans_pcie->def_rx_queue = 0; if (cfg_trans->use_tfh) { addr_size = 64; trans_pcie->max_tbs = IWL_TFH_NUM_TBS; trans_pcie->tfd_size = sizeof(struct iwl_tfh_tfd); } else { addr_size = 36; trans_pcie->max_tbs = IWL_NUM_OF_TBS; trans_pcie->tfd_size = sizeof(struct iwl_tfd); } trans->max_skb_frags = IWL_PCIE_MAX_FRAGS(trans_pcie); pci_set_master(pdev); ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(addr_size)); if (!ret) ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(addr_size)); if (ret) { ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (!ret) ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)); /* both attempts failed: */ if (ret) { dev_err(&pdev->dev, "No suitable DMA available\n"); goto out_no_pci; } } ret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME); if (ret) { dev_err(&pdev->dev, "pcim_iomap_regions_request_all failed\n"); goto out_no_pci; } trans_pcie->hw_base = pcim_iomap_table(pdev)[0]; if (!trans_pcie->hw_base) { dev_err(&pdev->dev, "pcim_iomap_table failed\n"); ret = -ENODEV; goto out_no_pci; } /* We disable the RETRY_TIMEOUT register (0x41) to keep * PCI Tx retries from interfering with C3 CPU state */ pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00); trans_pcie->pci_dev = pdev; iwl_disable_interrupts(trans); trans->hw_rev = iwl_read32(trans, CSR_HW_REV); if (trans->hw_rev == 0xffffffff) { dev_err(&pdev->dev, "HW_REV=0xFFFFFFFF, PCI issues?\n"); ret = -EIO; goto out_no_pci; } /* * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have * changed, and now the revision step also includes bit 0-1 (no more * "dash" value). To keep hw_rev backwards compatible - we'll store it * in the old format. */ if (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000) { trans->hw_rev = (trans->hw_rev & 0xfff0) | (CSR_HW_REV_STEP(trans->hw_rev << 2) << 2); ret = iwl_pcie_prepare_card_hw(trans); if (ret) { IWL_WARN(trans, "Exit HW not ready\n"); goto out_no_pci; } /* * in-order to recognize C step driver should read chip version * id located at the AUX bus MISC address space. */ ret = iwl_finish_nic_init(trans, cfg_trans); if (ret) goto out_no_pci; } IWL_DEBUG_INFO(trans, "HW REV: 0x%0x\n", trans->hw_rev); iwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans); trans->hw_id = (pdev->device << 16) + pdev->subsystem_device; snprintf(trans->hw_id_str, sizeof(trans->hw_id_str), "PCI ID: 0x%04X:0x%04X", pdev->device, pdev->subsystem_device); /* Initialize the wait queue for commands */ init_waitqueue_head(&trans_pcie->wait_command_queue); init_waitqueue_head(&trans_pcie->sx_waitq); if (trans_pcie->msix_enabled) { ret = iwl_pcie_init_msix_handler(pdev, trans_pcie); if (ret) goto out_no_pci; } else { ret = iwl_pcie_alloc_ict(trans); if (ret) goto out_no_pci; ret = devm_request_threaded_irq(&pdev->dev, pdev->irq, iwl_pcie_isr, iwl_pcie_irq_handler, IRQF_SHARED, DRV_NAME, trans); if (ret) { IWL_ERR(trans, "Error allocating IRQ %d\n", pdev->irq); goto out_free_ict; } trans_pcie->inta_mask = CSR_INI_SET_MASK; } trans_pcie->rba.alloc_wq = alloc_workqueue("rb_allocator", WQ_HIGHPRI | WQ_UNBOUND, 1); INIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work); #ifdef CONFIG_IWLWIFI_DEBUGFS trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED; mutex_init(&trans_pcie->fw_mon_data.mutex); #endif return trans; out_free_ict: iwl_pcie_free_ict(trans); out_no_pci: free_percpu(trans_pcie->tso_hdr_page); iwl_trans_free(trans); return ERR_PTR(ret); }
null
null
209,955
289089530533588866739258153063562155262
182
iwlwifi: pcie: fix rb_allocator workqueue allocation We don't handle failures in the rb_allocator workqueue allocation correctly. To fix that, move the code earlier so the cleanup is easier and we don't have to undo all the interrupt allocations in this case. Signed-off-by: Johannes Berg <[email protected]> Signed-off-by: Luca Coelho <[email protected]>
other
ImageMagick6
359331c61193138ce2b85331df25235b81499cfc
1
static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MaxTextExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent), sizeof(*str)); if (str == (unsigned char *) NULL) return 0; for (tagindx=0; tagindx<taglen; tagindx++) { c = *s++; len--; if (len < 0) return(-1); str[tagindx]=(unsigned char) c; } str[taglen]=0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); }
null
null
209,968
31937307999454282543374419514958142498
108
https://github.com/ImageMagick/ImageMagick/issues/1118
other
lua
1f3c6f4534c6411313361697d98d1145a1f030fa
1
static void singlevar (LexState *ls, expdesc *var) { TString *varname = str_checkname(ls); FuncState *fs = ls->fs; singlevaraux(fs, varname, var, 1); if (var->k == VVOID) { /* global name? */ expdesc key; singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ lua_assert(var->k != VVOID); /* this one must exist */ codestring(&key, varname); /* key is variable name */ luaK_indexed(fs, var, &key); /* env[varname] */ } }
null
null
210,050
77598380782050292005225014667111133353
12
Bug: Lua can generate wrong code when _ENV is <const>
other
file
46a8443f76cec4b41ec736eca396984c74664f84
1
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; }
null
null
210,090
158437719526821639214821236611683344689
155
Limit the number of elements in a vector (found by oss-fuzz)
other
cifs-utils
48a654e2e763fce24c22e1b9c695b42804bbdd4a
1
get_password(const char *prompt, char *input, int capacity) { #ifdef ENABLE_SYSTEMD int is_systemd_running; struct stat a, b; /* We simply test whether the systemd cgroup hierarchy is * mounted */ is_systemd_running = (lstat("/sys/fs/cgroup", &a) == 0) && (lstat("/sys/fs/cgroup/systemd", &b) == 0) && (a.st_dev != b.st_dev); if (is_systemd_running) { char *cmd, *ret; FILE *ask_pass_fp = NULL; cmd = ret = NULL; if (asprintf(&cmd, "systemd-ask-password \"%s\"", prompt) >= 0) { ask_pass_fp = popen (cmd, "re"); free (cmd); } if (ask_pass_fp) { ret = fgets(input, capacity, ask_pass_fp); pclose(ask_pass_fp); } if (ret) { int len = strlen(input); if (input[len - 1] == '\n') input[len - 1] = '\0'; return input; } } #endif /* * Falling back to getpass(..) * getpass is obsolete, but there's apparently nothing that replaces it */ char *tmp_pass = getpass(prompt); if (!tmp_pass) return NULL; strncpy(input, tmp_pass, capacity - 1); input[capacity - 1] = '\0'; /* zero-out the static buffer */ memset(tmp_pass, 0, strlen(tmp_pass)); return input; }
null
null
210,091
146515580432364483729475109533187749032
52
CVE-2020-14342: mount.cifs: fix shell command injection A bug has been reported recently for the mount.cifs utility which is part of the cifs-utils package. The tool has a shell injection issue where one can embed shell commands via the username mount option. Those commands will be run via popen() in the context of the user calling mount. The bug requires cifs-utils to be built with --with-systemd (enabled by default if supported). A quick test to check if the mount.cifs binary is vulnerable is to look for popen() calls like so: $ nm mount.cifs | grep popen U popen@@GLIBC_2.2.5 If the user is allowed to run mount.cifs via sudo, he can obtain a root shell. sudo mount.cifs -o username='`sh`' //1 /mnt If mount.cifs has the setuid bit, the command will still be run as the calling user (no privilege escalation). The bug was introduced in June 2012 with commit 4e264031d0da7d3f2 ("mount.cifs: Use systemd's mechanism for getting password, if present."). Affected versions: cifs-utils-5.6 cifs-utils-5.7 cifs-utils-5.8 cifs-utils-5.9 cifs-utils-6.0 cifs-utils-6.1 cifs-utils-6.2 cifs-utils-6.3 cifs-utils-6.4 cifs-utils-6.5 cifs-utils-6.6 cifs-utils-6.7 cifs-utils-6.8 cifs-utils-6.9 cifs-utils-6.10 Bug: https://bugzilla.samba.org/show_bug.cgi?id=14442 Reported-by: Vadim Lebedev <[email protected]> Signed-off-by: Paulo Alcantara (SUSE) <[email protected]> Signed-off-by: Aurelien Aptel <[email protected]>
other
linux
9b0971ca7fc75daca80c0bb6c02e96059daea90a
1
int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in) { if (!setup_vmgexit_scratch(svm, in, svm->vmcb->control.exit_info_2)) return -EINVAL; return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->ghcb_sa, svm->ghcb_sa_len / size, in); }
null
null
210,094
108558706420318584874169195743763305829
8
KVM: SEV-ES: fix another issue with string I/O VMGEXITs If the guest requests string I/O from the hypervisor via VMGEXIT, SW_EXITINFO2 will contain the REP count. However, sev_es_string_io was incorrectly treating it as the size of the GHCB buffer in bytes. This fixes the "outsw" test in the experimental SEV tests of kvm-unit-tests. Cc: [email protected] Fixes: 7ed9abfe8e9f ("KVM: SVM: Support string IO operations for an SEV-ES guest") Reported-by: Marc Orr <[email protected]> Tested-by: Marc Orr <[email protected]> Reviewed-by: Marc Orr <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
other
curl
178bd7db34f77e020fb8562890c5625ccbd67093
1
static CURLcode parseurlandfillconn(struct SessionHandle *data, struct connectdata *conn, bool *prot_missing, char **userp, char **passwdp, char **optionsp) { char *at; char *fragment; char *path = data->state.path; char *query; int rc; char protobuf[16] = ""; const char *protop = ""; CURLcode result; bool rebuild_url = FALSE; *prot_missing = FALSE; /************************************************************* * Parse the URL. * * We need to parse the url even when using the proxy, because we will need * the hostname and port in case we are trying to SSL connect through the * proxy -- and we don't know if we will need to use SSL until we parse the * url ... ************************************************************/ if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]", protobuf, path)) && Curl_raw_equal(protobuf, "file")) { if(path[0] == '/' && path[1] == '/') { /* Allow omitted hostname (e.g. file:/<path>). This is not strictly * speaking a valid file: URL by RFC 1738, but treating file:/<path> as * file://localhost/<path> is similar to how other schemes treat missing * hostnames. See RFC 1808. */ /* This cannot be done with strcpy() in a portable manner, since the memory areas overlap! */ memmove(path, path + 2, strlen(path + 2)+1); } /* * we deal with file://<host>/<path> differently since it supports no * hostname other than "localhost" and "127.0.0.1", which is unique among * the URL protocols specified in RFC 1738 */ if(path[0] != '/') { /* the URL included a host name, we ignore host names in file:// URLs as the standards don't define what to do with them */ char *ptr=strchr(path, '/'); if(ptr) { /* there was a slash present RFC1738 (section 3.1, page 5) says: The rest of the locator consists of data specific to the scheme, and is known as the "url-path". It supplies the details of how the specified resource can be accessed. Note that the "/" between the host (or port) and the url-path is NOT part of the url-path. As most agents use file://localhost/foo to get '/foo' although the slash preceding foo is a separator and not a slash for the path, a URL as file://localhost//foo must be valid as well, to refer to the same file with an absolute path. */ if(ptr[1] && ('/' == ptr[1])) /* if there was two slashes, we skip the first one as that is then used truly as a separator */ ptr++; /* This cannot be made with strcpy, as the memory chunks overlap! */ memmove(path, ptr, strlen(ptr)+1); } } protop = "file"; /* protocol string */ } else { /* clear path */ path[0]=0; if(2 > sscanf(data->change.url, "%15[^\n:]://%[^\n/?]%[^\n]", protobuf, conn->host.name, path)) { /* * The URL was badly formatted, let's try the browser-style _without_ * protocol specified like 'http://'. */ rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path); if(1 > rc) { /* * We couldn't even get this format. * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is * assigned, but the return value is EOF! */ #if defined(__DJGPP__) && (DJGPP_MINOR == 4) if(!(rc == -1 && *conn->host.name)) #endif { failf(data, "<url> malformed"); return CURLE_URL_MALFORMAT; } } /* * Since there was no protocol part specified, we guess what protocol it * is based on the first letters of the server name. */ /* Note: if you add a new protocol, please update the list in * lib/version.c too! */ if(checkprefix("FTP.", conn->host.name)) protop = "ftp"; else if(checkprefix("DICT.", conn->host.name)) protop = "DICT"; else if(checkprefix("LDAP.", conn->host.name)) protop = "LDAP"; else if(checkprefix("IMAP.", conn->host.name)) protop = "IMAP"; else if(checkprefix("SMTP.", conn->host.name)) protop = "smtp"; else if(checkprefix("POP3.", conn->host.name)) protop = "pop3"; else { protop = "http"; } *prot_missing = TRUE; /* not given in URL */ } else protop = protobuf; } /* We search for '?' in the host name (but only on the right side of a * @-letter to allow ?-letters in username and password) to handle things * like http://example.com?param= (notice the missing '/'). */ at = strchr(conn->host.name, '@'); if(at) query = strchr(at+1, '?'); else query = strchr(conn->host.name, '?'); if(query) { /* We must insert a slash before the '?'-letter in the URL. If the URL had a slash after the '?', that is where the path currently begins and the '?string' is still part of the host name. We must move the trailing part from the host name and put it first in the path. And have it all prefixed with a slash. */ size_t hostlen = strlen(query); size_t pathlen = strlen(path); /* move the existing path plus the zero byte forward, to make room for the host-name part */ memmove(path+hostlen+1, path, pathlen+1); /* now copy the trailing host part in front of the existing path */ memcpy(path+1, query, hostlen); path[0]='/'; /* prepend the missing slash */ rebuild_url = TRUE; *query=0; /* now cut off the hostname at the ? */ } else if(!path[0]) { /* if there's no path set, use a single slash */ strcpy(path, "/"); rebuild_url = TRUE; } /* If the URL is malformatted (missing a '/' after hostname before path) we * insert a slash here. The only letter except '/' we accept to start a path * is '?'. */ if(path[0] == '?') { /* We need this function to deal with overlapping memory areas. We know that the memory area 'path' points to is 'urllen' bytes big and that is bigger than the path. Use +1 to move the zero byte too. */ memmove(&path[1], path, strlen(path)+1); path[0] = '/'; rebuild_url = TRUE; } else { /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */ char *newp = Curl_dedotdotify(path); if(!newp) return CURLE_OUT_OF_MEMORY; if(strcmp(newp, path)) { rebuild_url = TRUE; free(data->state.pathbuffer); data->state.pathbuffer = newp; data->state.path = newp; path = newp; } else free(newp); } /* * "rebuild_url" means that one or more URL components have been modified so * we need to generate an updated full version. We need the corrected URL * when communicating over HTTP proxy and we don't know at this point if * we're using a proxy or not. */ if(rebuild_url) { char *reurl; size_t plen = strlen(path); /* new path, should be 1 byte longer than the original */ size_t urllen = strlen(data->change.url); /* original URL length */ size_t prefixlen = strlen(conn->host.name); if(!*prot_missing) prefixlen += strlen(protop) + strlen("://"); reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */ if(!reurl) return CURLE_OUT_OF_MEMORY; /* copy the prefix */ memcpy(reurl, data->change.url, prefixlen); /* append the trailing piece + zerobyte */ memcpy(&reurl[prefixlen], path, plen + 1); /* possible free the old one */ if(data->change.url_alloc) { Curl_safefree(data->change.url); data->change.url_alloc = FALSE; } infof(data, "Rebuilt URL to: %s\n", reurl); data->change.url = reurl; data->change.url_alloc = TRUE; /* free this later */ } /* * Parse the login details from the URL and strip them out of * the host name */ result = parse_url_login(data, conn, userp, passwdp, optionsp); if(result) return result; if(conn->host.name[0] == '[') { /* This looks like an IPv6 address literal. See if there is an address scope if there is no location header */ char *percent = strchr(conn->host.name, '%'); if(percent) { unsigned int identifier_offset = 3; char *endp; unsigned long scope; if(strncmp("%25", percent, 3) != 0) { infof(data, "Please URL encode %% as %%25, see RFC 6874.\n"); identifier_offset = 1; } scope = strtoul(percent + identifier_offset, &endp, 10); if(*endp == ']') { /* The address scope was well formed. Knock it out of the hostname. */ memmove(percent, endp, strlen(endp)+1); conn->scope_id = (unsigned int)scope; } else { /* Zone identifier is not numeric */ #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX) char ifname[IFNAMSIZ + 2]; char *square_bracket; unsigned int scopeidx = 0; strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2); /* Ensure nullbyte termination */ ifname[IFNAMSIZ + 1] = '\0'; square_bracket = strchr(ifname, ']'); if(square_bracket) { /* Remove ']' */ *square_bracket = '\0'; scopeidx = if_nametoindex(ifname); if(scopeidx == 0) { infof(data, "Invalid network interface: %s; %s\n", ifname, strerror(errno)); } } if(scopeidx > 0) { char *p = percent + identifier_offset + strlen(ifname); /* Remove zone identifier from hostname */ memmove(percent, p, strlen(p) + 1); conn->scope_id = scopeidx; } else #endif /* HAVE_NET_IF_H && IFNAMSIZ */ infof(data, "Invalid IPv6 address format\n"); } } } if(data->set.scope_id) /* Override any scope that was set above. */ conn->scope_id = data->set.scope_id; /* Remove the fragment part of the path. Per RFC 2396, this is always the last part of the URI. We are looking for the first '#' so that we deal gracefully with non conformant URI such as http://example.com#foo#bar. */ fragment = strchr(path, '#'); if(fragment) { *fragment = 0; /* we know the path part ended with a fragment, so we know the full URL string does too and we need to cut it off from there so it isn't used over proxy */ fragment = strchr(data->change.url, '#'); if(fragment) *fragment = 0; } /* * So if the URL was A://B/C#D, * protop is A * conn->host.name is B * data->state.path is /C */ return findprotocol(data, conn, protop); }
null
null
210,111
234649323869183170019648024125067573246
333
url-parsing: reject CRLFs within URLs Bug: http://curl.haxx.se/docs/adv_20150108B.html Reported-by: Andrey Labunets
other
php-src
2baeb167a08b0186a885208bdc8b5871f1681dc8
1
gdImagePtr gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor) { const int angle_rounded = (int)floor(angle * 100); if (bgcolor < 0 || bgcolor >= gdMaxColors) { return NULL; } /* impact perf a bit, but not that much. Implementation for palette images can be done at a later point. */ if (src->trueColor == 0) { if (bgcolor >= 0) { bgcolor = gdTrueColorAlpha(src->red[bgcolor], src->green[bgcolor], src->blue[bgcolor], src->alpha[bgcolor]); } gdImagePaletteToTrueColor(src); } /* no interpolation needed here */ switch (angle_rounded) { case 9000: return gdImageRotate90(src, 0); case 18000: return gdImageRotate180(src, 0); case 27000: return gdImageRotate270(src, 0); } if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) { return NULL; } switch (src->interpolation_id) { case GD_NEAREST_NEIGHBOUR: return gdImageRotateNearestNeighbour(src, angle, bgcolor); break; case GD_BILINEAR_FIXED: return gdImageRotateBilinear(src, angle, bgcolor); break; case GD_BICUBIC_FIXED: return gdImageRotateBicubicFixed(src, angle, bgcolor); break; default: return gdImageRotateGeneric(src, angle, bgcolor); } return NULL; }
null
null
210,161
53394462158955746827830335739471974855
50
Improve fix for bug #70976
other
linux
8cae8cd89f05f6de223d63e6d15e31c8ba9cf53b
1
static void *seq_buf_alloc(unsigned long size) { return kvmalloc(size, GFP_KERNEL_ACCOUNT); }
null
null
210,203
97148506821253610384021441624150243008
4
seq_file: disallow extremely large seq buffer allocations There is no reasonable need for a buffer larger than this, and it avoids int overflow pitfalls. Fixes: 058504edd026 ("fs/seq_file: fallback to vmalloc allocation") Suggested-by: Al Viro <[email protected]> Reported-by: Qualys Security Advisory <[email protected]> Signed-off-by: Eric Sandeen <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>
other
linux
cefa91b2332d7009bc0be5d951d6cbbf349f90f8
1
static struct nlattr *reserve_sfa_size(struct sw_flow_actions **sfa, int attr_len, bool log) { struct sw_flow_actions *acts; int new_acts_size; size_t req_size = NLA_ALIGN(attr_len); int next_offset = offsetof(struct sw_flow_actions, actions) + (*sfa)->actions_len; if (req_size <= (ksize(*sfa) - next_offset)) goto out; new_acts_size = max(next_offset + req_size, ksize(*sfa) * 2); if (new_acts_size > MAX_ACTIONS_BUFSIZE) { if ((MAX_ACTIONS_BUFSIZE - next_offset) < req_size) { OVS_NLERR(log, "Flow action size exceeds max %u", MAX_ACTIONS_BUFSIZE); return ERR_PTR(-EMSGSIZE); } new_acts_size = MAX_ACTIONS_BUFSIZE; } acts = nla_alloc_flow_actions(new_acts_size); if (IS_ERR(acts)) return (void *)acts; memcpy(acts->actions, (*sfa)->actions, (*sfa)->actions_len); acts->actions_len = (*sfa)->actions_len; acts->orig_len = (*sfa)->orig_len; kfree(*sfa); *sfa = acts; out: (*sfa)->actions_len += req_size; return (struct nlattr *) ((unsigned char *)(*sfa) + next_offset); }
null
null
210,204
164800371311040127858876310286623599655
38
openvswitch: fix OOB access in reserve_sfa_size() Given a sufficiently large number of actions, while copying and reserving memory for a new action of a new flow, if next_offset is greater than MAX_ACTIONS_BUFSIZE, the function reserve_sfa_size() does not return -EMSGSIZE as expected, but it allocates MAX_ACTIONS_BUFSIZE bytes increasing actions_len by req_size. This can then lead to an OOB write access, especially when further actions need to be copied. Fix it by rearranging the flow action size check. KASAN splat below: ================================================================== BUG: KASAN: slab-out-of-bounds in reserve_sfa_size+0x1ba/0x380 [openvswitch] Write of size 65360 at addr ffff888147e4001c by task handler15/836 CPU: 1 PID: 836 Comm: handler15 Not tainted 5.18.0-rc1+ #27 ... Call Trace: <TASK> dump_stack_lvl+0x45/0x5a print_report.cold+0x5e/0x5db ? __lock_text_start+0x8/0x8 ? reserve_sfa_size+0x1ba/0x380 [openvswitch] kasan_report+0xb5/0x130 ? reserve_sfa_size+0x1ba/0x380 [openvswitch] kasan_check_range+0xf5/0x1d0 memcpy+0x39/0x60 reserve_sfa_size+0x1ba/0x380 [openvswitch] __add_action+0x24/0x120 [openvswitch] ovs_nla_add_action+0xe/0x20 [openvswitch] ovs_ct_copy_action+0x29d/0x1130 [openvswitch] ? __kernel_text_address+0xe/0x30 ? unwind_get_return_address+0x56/0xa0 ? create_prof_cpu_mask+0x20/0x20 ? ovs_ct_verify+0xf0/0xf0 [openvswitch] ? prep_compound_page+0x198/0x2a0 ? __kasan_check_byte+0x10/0x40 ? kasan_unpoison+0x40/0x70 ? ksize+0x44/0x60 ? reserve_sfa_size+0x75/0x380 [openvswitch] __ovs_nla_copy_actions+0xc26/0x2070 [openvswitch] ? __zone_watermark_ok+0x420/0x420 ? validate_set.constprop.0+0xc90/0xc90 [openvswitch] ? __alloc_pages+0x1a9/0x3e0 ? __alloc_pages_slowpath.constprop.0+0x1da0/0x1da0 ? unwind_next_frame+0x991/0x1e40 ? __mod_node_page_state+0x99/0x120 ? __mod_lruvec_page_state+0x2e3/0x470 ? __kasan_kmalloc_large+0x90/0xe0 ovs_nla_copy_actions+0x1b4/0x2c0 [openvswitch] ovs_flow_cmd_new+0x3cd/0xb10 [openvswitch] ... Cc: [email protected] Fixes: f28cd2af22a0 ("openvswitch: fix flow actions reallocation") Signed-off-by: Paolo Valerio <[email protected]> Acked-by: Eelco Chaudron <[email protected]> Signed-off-by: David S. Miller <[email protected]>
other
squid
780c4ea1b4c9d2fb41f6962aa6ed73ae57f74b2b
1
gopherToHTML(GopherStateData * gopherState, char *inbuf, int len) { char *pos = inbuf; char *lpos = NULL; char *tline = NULL; LOCAL_ARRAY(char, line, TEMP_BUF_SIZE); LOCAL_ARRAY(char, tmpbuf, TEMP_BUF_SIZE); char *name = NULL; char *selector = NULL; char *host = NULL; char *port = NULL; char *escaped_selector = NULL; const char *icon_url = NULL; char gtype; StoreEntry *entry = NULL; memset(tmpbuf, '\0', TEMP_BUF_SIZE); memset(line, '\0', TEMP_BUF_SIZE); entry = gopherState->entry; if (gopherState->conversion == GopherStateData::HTML_INDEX_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, "Gopher Index %s", html_url); storeAppendPrintf(entry, "<p>This is a searchable Gopher index. Use the search\n" "function of your browser to enter search terms.\n" "<ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } if (gopherState->conversion == GopherStateData::HTML_CSO_PAGE) { char *html_url = html_quote(entry->url()); gopherHTMLHeader(entry, "CSO Search of %s", html_url); storeAppendPrintf(entry, "<P>A CSO database usually contains a phonebook or\n" "directory. Use the search function of your browser to enter\n" "search terms.</P><ISINDEX>\n"); gopherHTMLFooter(entry); /* now let start sending stuff to client */ entry->flush(); gopherState->HTML_header_added = 1; return; } String outbuf; if (!gopherState->HTML_header_added) { if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT) gopherHTMLHeader(entry, "CSO Search Result", NULL); else gopherHTMLHeader(entry, "Gopher Menu", NULL); outbuf.append ("<PRE>"); gopherState->HTML_header_added = 1; gopherState->HTML_pre = 1; } while (pos < inbuf + len) { int llen; int left = len - (pos - inbuf); lpos = (char *)memchr(pos, '\n', left); if (lpos) { ++lpos; /* Next line is after \n */ llen = lpos - pos; } else { llen = left; } if (gopherState->len + llen >= TEMP_BUF_SIZE) { debugs(10, DBG_IMPORTANT, "GopherHTML: Buffer overflow. Lost some data on URL: " << entry->url() ); llen = TEMP_BUF_SIZE - gopherState->len - 1; } if (!lpos) { /* there is no complete line in inbuf */ /* copy it to temp buffer */ /* note: llen is adjusted above */ memcpy(gopherState->buf + gopherState->len, pos, llen); gopherState->len += llen; break; } if (gopherState->len != 0) { /* there is something left from last tx. */ memcpy(line, gopherState->buf, gopherState->len); memcpy(line + gopherState->len, pos, llen); llen += gopherState->len; gopherState->len = 0; } else { memcpy(line, pos, llen); } line[llen + 1] = '\0'; /* move input to next line */ pos = lpos; /* at this point. We should have one line in buffer to process */ if (*line == '.') { /* skip it */ memset(line, '\0', TEMP_BUF_SIZE); continue; } switch (gopherState->conversion) { case GopherStateData::HTML_INDEX_RESULT: case GopherStateData::HTML_DIR: { tline = line; gtype = *tline; ++tline; name = tline; selector = strchr(tline, TAB); if (selector) { *selector = '\0'; ++selector; host = strchr(selector, TAB); if (host) { *host = '\0'; ++host; port = strchr(host, TAB); if (port) { char *junk; port[0] = ':'; junk = strchr(host, TAB); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\r'); if (junk) *junk++ = 0; /* Chop port */ else { junk = strchr(host, '\n'); if (junk) *junk++ = 0; /* Chop port */ } } if ((port[1] == '0') && (!port[2])) port[0] = 0; /* 0 means none */ } /* escape a selector here */ escaped_selector = xstrdup(rfc1738_escape_part(selector)); switch (gtype) { case GOPHER_DIRECTORY: icon_url = mimeGetIconURL("internal-menu"); break; case GOPHER_HTML: case GOPHER_FILE: icon_url = mimeGetIconURL("internal-text"); break; case GOPHER_INDEX: case GOPHER_CSO: icon_url = mimeGetIconURL("internal-index"); break; case GOPHER_IMAGE: case GOPHER_GIF: case GOPHER_PLUS_IMAGE: icon_url = mimeGetIconURL("internal-image"); break; case GOPHER_SOUND: case GOPHER_PLUS_SOUND: icon_url = mimeGetIconURL("internal-sound"); break; case GOPHER_PLUS_MOVIE: icon_url = mimeGetIconURL("internal-movie"); break; case GOPHER_TELNET: case GOPHER_3270: icon_url = mimeGetIconURL("internal-telnet"); break; case GOPHER_BIN: case GOPHER_MACBINHEX: case GOPHER_DOSBIN: case GOPHER_UUENCODED: icon_url = mimeGetIconURL("internal-binary"); break; case GOPHER_INFO: icon_url = NULL; break; default: icon_url = mimeGetIconURL("internal-unknown"); break; } memset(tmpbuf, '\0', TEMP_BUF_SIZE); if ((gtype == GOPHER_TELNET) || (gtype == GOPHER_3270)) { if (strlen(escaped_selector) != 0) snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s@%s%s%s/\">%s</A>\n", icon_url, escaped_selector, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); else snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"telnet://%s%s%s/\">%s</A>\n", icon_url, rfc1738_escape_part(host), *port ? ":" : "", port, html_quote(name)); } else if (gtype == GOPHER_INFO) { snprintf(tmpbuf, TEMP_BUF_SIZE, "\t%s\n", html_quote(name)); } else { if (strncmp(selector, "GET /", 5) == 0) { /* WWW link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"http://%s/%s\">%s</A>\n", icon_url, host, rfc1738_escape_unescaped(selector + 5), html_quote(name)); } else { /* Standard link */ snprintf(tmpbuf, TEMP_BUF_SIZE, "<IMG border=\"0\" SRC=\"%s\"> <A HREF=\"gopher://%s/%c%s\">%s</A>\n", icon_url, host, gtype, escaped_selector, html_quote(name)); } } safe_free(escaped_selector); outbuf.append(tmpbuf); } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } } else { memset(line, '\0', TEMP_BUF_SIZE); continue; } break; } /* HTML_DIR, HTML_INDEX_RESULT */ case GopherStateData::HTML_CSO_RESULT: { if (line[0] == '-') { int code, recno; char *s_code, *s_recno, *result; s_code = strtok(line + 1, ":\n"); s_recno = strtok(NULL, ":\n"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); recno = atoi(s_recno); if (code != 200) break; if (gopherState->cso_recno != recno) { snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>Record# %d<br><i>%s</i></H2>\n<PRE>", recno, html_quote(result)); gopherState->cso_recno = recno; } else { snprintf(tmpbuf, TEMP_BUF_SIZE, "%s\n", html_quote(result)); } outbuf.append(tmpbuf); break; } else { int code; char *s_code, *result; s_code = strtok(line, ":"); result = strtok(NULL, "\n"); if (!result) break; code = atoi(s_code); switch (code) { case 200: { /* OK */ /* Do nothing here */ break; } case 102: /* Number of matches */ case 501: /* No Match */ case 502: { /* Too Many Matches */ /* Print the message the server returns */ snprintf(tmpbuf, TEMP_BUF_SIZE, "</PRE><HR noshade size=\"1px\"><H2>%s</H2>\n<PRE>", html_quote(result)); outbuf.append(tmpbuf); break; } } } } /* HTML_CSO_RESULT */ default: break; /* do nothing */ } /* switch */ } /* while loop */ if (outbuf.size() > 0) { entry->append(outbuf.rawBuf(), outbuf.size()); /* now let start sending stuff to client */ entry->flush(); } outbuf.clean(); return; }
null
null
210,206
45378845076609950836102901037731379763
338
Improve handling of Gopher responses (#1022)
other
virglrenderer
24f67de7a9088a873844a39be03cee6882260ac9
1
void vrend_renderer_blit(struct vrend_context *ctx, uint32_t dst_handle, uint32_t src_handle, const struct pipe_blit_info *info) { struct vrend_resource *src_res, *dst_res; src_res = vrend_renderer_ctx_res_lookup(ctx, src_handle); dst_res = vrend_renderer_ctx_res_lookup(ctx, dst_handle); if (!src_res) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, src_handle); return; } if (!dst_res) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, dst_handle); return; } if (ctx->in_error) return; if (info->render_condition_enable == false) vrend_pause_render_condition(ctx, true); VREND_DEBUG(dbg_blit, ctx, "BLIT: rc:%d scissor:%d filter:%d alpha:%d mask:0x%x\n" " From %s(%s) ms:%d [%d, %d, %d]+[%d, %d, %d] lvl:%d\n" " To %s(%s) ms:%d [%d, %d, %d]+[%d, %d, %d] lvl:%d\n", info->render_condition_enable, info->scissor_enable, info->filter, info->alpha_blend, info->mask, util_format_name(src_res->base.format), util_format_name(info->src.format), src_res->base.nr_samples, info->src.box.x, info->src.box.y, info->src.box.z, info->src.box.width, info->src.box.height, info->src.box.depth, info->src.level, util_format_name(dst_res->base.format), util_format_name(info->dst.format), dst_res->base.nr_samples, info->dst.box.x, info->dst.box.y, info->dst.box.z, info->dst.box.width, info->dst.box.height, info->dst.box.depth, info->dst.level); /* The Gallium blit function can be called for a general blit that may * scale, convert the data, and apply some rander states, or it is called via * glCopyImageSubData. If the src or the dst image are equal, or the two * images formats are the same, then Galliums such calles are redirected * to resource_copy_region, in this case and if no render states etx need * to be applied, forward the call to glCopyImageSubData, otherwise do a * normal blit. */ if (has_feature(feat_copy_image) && (!info->render_condition_enable || !ctx->sub->cond_render_gl_mode) && format_is_copy_compatible(info->src.format,info->dst.format, false) && !info->scissor_enable && (info->filter == PIPE_TEX_FILTER_NEAREST) && !info->alpha_blend && (info->mask == PIPE_MASK_RGBA) && src_res->base.nr_samples == dst_res->base.nr_samples && info->src.box.width == info->dst.box.width && info->src.box.height == info->dst.box.height && info->src.box.depth == info->dst.box.depth) { VREND_DEBUG(dbg_blit, ctx, " Use glCopyImageSubData\n"); vrend_copy_sub_image(src_res, dst_res, info->src.level, &info->src.box, info->dst.level, info->dst.box.x, info->dst.box.y, info->dst.box.z); } else { VREND_DEBUG(dbg_blit, ctx, " Use blit_int\n"); vrend_renderer_blit_int(ctx, src_res, dst_res, info); } if (info->render_condition_enable == false) vrend_pause_render_condition(ctx, false); }
null
null
210,223
169593091364991276328916287779477119456
69
vrend: check info formats in blits Closes #141 Closes #142 v2 : drop colon in error description (Emil) Signed-off-by: Gert Wollny <[email protected]> Reviewed-by: Emil Velikov <[email protected]>
other
ImageMagick
ca3654ebf7a439dc736f56f083c9aa98e4464b7f
1
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MagickPathExtent]; CINInfo cin; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; ssize_t i; Quantum *q; size_t length; ssize_t count, y; unsigned char magick[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,"dpx:file.version",property,exception); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,"dpx:file.filename",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,"dpx:file.create_date",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,"dpx:file.create_time",property,exception); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,"dpx:image.orientation","%d", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,"dpx:image.label",property,exception); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,"dpx:origination.filename",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,"dpx:origination.create_date",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,"dpx:origination.create_time",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,"dpx:origination.device",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,"dpx:origination.model",property,exception); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,"dpx:origination.serial",property,exception); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,"dpx:film.offset","%d", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format)); (void) SetImageProperty(image,"dpx:film.format",property,exception); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,"dpx:film.frame_position","%.20g", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,"dpx:film.frame_id",property,exception); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,"dpx:film.slate_info",property,exception); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const unsigned char *) NULL, cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,"dpx:user.data",profile,exception); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,MagickFalse); quantum_type=RGBQuantum; length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } status=SetQuantumPad(image,quantum_info,0); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { const void *stream; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; stream=ReadBlobStream(image,length,pixels,&count); if ((size_t) count != length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,(unsigned char *) stream,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); SetImageColorspace(image,LogColorspace,exception); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
null
null
210,252
5095021731992187930150897366063988213
415
https://github.com/ImageMagick/ImageMagick/issues/4988
other
vim
6669de1b235843968e88844ca6d3c8dec4b01a9e
1
sug_filltree(spellinfo_T *spin, slang_T *slang) { char_u *byts; idx_T *idxs; int depth; idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u tword[MAXWLEN]; char_u tsalword[MAXWLEN]; int c; idx_T n; unsigned words_done = 0; int wordcount[MAXWLEN]; // We use si_foldroot for the soundfolded trie. spin->si_foldroot = wordtree_alloc(spin); if (spin->si_foldroot == NULL) return FAIL; // let tree_add_word() know we're adding to the soundfolded tree spin->si_sugtree = TRUE; /* * Go through the whole case-folded tree, soundfold each word and put it * in the trie. */ byts = slang->sl_fbyts; idxs = slang->sl_fidxs; arridx[0] = 0; curi[0] = 1; wordcount[0] = 0; depth = 0; while (depth >= 0 && !got_int) { if (curi[depth] > byts[arridx[depth]]) { // Done all bytes at this node, go up one level. idxs[arridx[depth]] = wordcount[depth]; if (depth > 0) wordcount[depth - 1] += wordcount[depth]; --depth; line_breakcheck(); } else { // Do one more byte at this node. n = arridx[depth] + curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { // Sound-fold the word. tword[depth] = NUL; spell_soundfold(slang, tword, TRUE, tsalword); // We use the "flags" field for the MSB of the wordnr, // "region" for the LSB of the wordnr. if (tree_add_word(spin, tsalword, spin->si_foldroot, words_done >> 16, words_done & 0xffff, 0) == FAIL) return FAIL; ++words_done; ++wordcount[depth]; // Reset the block count each time to avoid compression // kicking in. spin->si_blocks_cnt = 0; // Skip over any other NUL bytes (same word with different // flags). But don't go over the end. while (n + 1 < slang->sl_fbyts_len && byts[n + 1] == 0) { ++n; ++curi[depth]; } } else { // Normal char, go one level deeper. tword[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; wordcount[depth] = 0; } } } smsg(_("Total number of words: %d"), words_done); return OK; }
null
null
210,271
251994504140226133444029248568129507567
97
patch 9.0.0240: crash when using ":mkspell" with an empty .dic file Problem: Crash when using ":mkspell" with an empty .dic file. Solution: Check for an empty word tree.
other
mongo
f3604b901d688c194de5e430c7fbab060c9dc8e0
1
createRandomCursorExecutor(const CollectionPtr& coll, const boost::intrusive_ptr<ExpressionContext>& expCtx, long long sampleSize, long long numRecords, boost::optional<BucketUnpacker> bucketUnpacker) { OperationContext* opCtx = expCtx->opCtx; // Verify that we are already under a collection lock. We avoid taking locks ourselves in this // function because double-locking forces any PlanExecutor we create to adopt a NO_YIELD policy. invariant(opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS)); static const double kMaxSampleRatioForRandCursor = 0.05; if (!expCtx->ns.isTimeseriesBucketsCollection()) { if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) { return std::pair{nullptr, false}; } } else { // Suppose that a time-series bucket collection is observed to contain 200 buckets, and the // 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the // maximum possible measurment count would be 200 * 1000 = 200,000. While the // 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small // relative to the total number of measurements in the time-series collection, for larger // sample sizes the top-k sort based sample is faster. Experiments have approximated that // the tipping point is roughly when the requested sample size is greater than 1% of the // maximum possible number of measurements in the collection (i.e. numBuckets * // maxMeasurementsPerBucket). static const double kCoefficient = 0.01; if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) { return std::pair{nullptr, false}; } } // Attempt to get a random cursor from the RecordStore. auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx); if (!rsRandCursor) { // The storage engine has no random cursor support. return std::pair{nullptr, false}; } // Build a MultiIteratorStage and pass it the random-sampling RecordCursor. auto ws = std::make_unique<WorkingSet>(); std::unique_ptr<PlanStage> root = std::make_unique<MultiIteratorStage>(expCtx.get(), ws.get(), coll); static_cast<MultiIteratorStage*>(root.get())->addIterator(std::move(rsRandCursor)); // If the incoming operation is sharded, use the CSS to infer the filtering metadata for the // collection, otherwise treat it as unsharded auto collectionFilter = CollectionShardingState::get(opCtx, coll->ns()) ->getOwnershipFilter( opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup); TrialStage* trialStage = nullptr; // Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample // cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch // to a collection scan if the ratio of orphaned to owned documents encountered over the first // 100 works() is such that we would have chosen not to optimize. static const size_t kMaxPresampleSize = 100; if (collectionFilter.isSharded() && !expCtx->ns.isTimeseriesBucketsCollection()) { // The ratio of owned to orphaned documents must be at least equal to the ratio between the // requested sampleSize and the maximum permitted sampleSize for the original constraints to // be satisfied. For instance, if there are 200 documents and the sampleSize is 5, then at // least (5 / (200*0.05)) = (5/10) = 50% of those documents must be owned. If less than 5% // of the documents in the collection are owned, we default to the backup plan. const auto minAdvancedToWorkRatio = std::max( sampleSize / (numRecords * kMaxSampleRatioForRandCursor), kMaxSampleRatioForRandCursor); // The trial plan is SHARDING_FILTER-MULTI_ITERATOR. auto randomCursorPlan = std::make_unique<ShardFilterStage>( expCtx.get(), collectionFilter, ws.get(), std::move(root)); // The backup plan is SHARDING_FILTER-COLLSCAN. std::unique_ptr<PlanStage> collScanPlan = std::make_unique<CollectionScan>( expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr); collScanPlan = std::make_unique<ShardFilterStage>( expCtx.get(), collectionFilter, ws.get(), std::move(collScanPlan)); // Place a TRIAL stage at the root of the plan tree, and pass it the trial and backup plans. root = std::make_unique<TrialStage>(expCtx.get(), ws.get(), std::move(randomCursorPlan), std::move(collScanPlan), kMaxPresampleSize, minAdvancedToWorkRatio); trialStage = static_cast<TrialStage*>(root.get()); } else if (expCtx->ns.isTimeseriesBucketsCollection()) { // We can't take ARHASH optimization path for a direct $sample on the system.buckets // collection because data is in compressed form. If we did have a direct $sample on the // system.buckets collection, then the 'bucketUnpacker' would not be set up properly. We // also should bail out early if a $sample is made against a time series collection that is // empty. If we don't the 'minAdvancedToWorkRatio' can be nan/-nan depending on the // architecture. if (!(bucketUnpacker && numRecords)) { return std::pair{nullptr, false}; } // Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and // 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are // not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many // duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses // the top-k sort sampling approach. // // Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500 // documents on average. The observed trial advanced/work ratio approximates the average // bucket fullness, noted here as "abf". In this example, abf = 500 / 1000 = 0.5. // Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs // better than backup plan when // // sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount // // This inequality can be rewritten as // // abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount) // // Therefore, if the advanced/work ratio exceeds this threshold, we will use the // 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user // becomes larger with respect to the number of buckets, we require a higher advanced/work // ratio in order to justify using 'SampleFromTimeseriesBucket'. // // Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When // buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a // lot of sampling "misses". static const auto kCoefficient = 0.02; static const auto kMinBucketFullness = 0.25; const auto minAdvancedToWorkRatio = std::max( std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0), kMinBucketFullness); auto arhashPlan = std::make_unique<SampleFromTimeseriesBucket>( expCtx.get(), ws.get(), std::move(root), *bucketUnpacker, // By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the // 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling // attempts during the 'TrialStage's trial period. kMaxPresampleSize + 5, sampleSize, gTimeseriesBucketMaxCount); std::unique_ptr<PlanStage> collScanPlan = std::make_unique<CollectionScan>( expCtx.get(), coll, CollectionScanParams{}, ws.get(), nullptr); auto topkSortPlan = std::make_unique<UnpackTimeseriesBucket>( expCtx.get(), ws.get(), std::move(collScanPlan), *bucketUnpacker); root = std::make_unique<TrialStage>(expCtx.get(), ws.get(), std::move(arhashPlan), std::move(topkSortPlan), kMaxPresampleSize, minAdvancedToWorkRatio); trialStage = static_cast<TrialStage*>(root.get()); } auto execStatus = plan_executor_factory::make(expCtx, std::move(ws), std::move(root), &coll, opCtx->inMultiDocumentTransaction() ? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY : PlanYieldPolicy::YieldPolicy::YIELD_AUTO, QueryPlannerParams::RETURN_OWNED_DATA); if (!execStatus.isOK()) { return execStatus.getStatus(); } // For sharded collections, the root of the plan tree is a TrialStage that may have chosen // either a random-sampling cursor trial plan or a COLLSCAN backup plan. We can only optimize // the $sample aggregation stage if the trial plan was chosen. return std::pair{std::move(execStatus.getValue()), !trialStage || !trialStage->pickedBackupPlan()}; }
null
null
210,273
215078869678300356623594887635131238477
171
SERVER-59071 Treat '$sample' as unsharded when connecting directly to shards
other
unicorn
3d3deac5e6d38602b689c4fef5dac004f07a2e63
1
void qemu_ram_free(struct uc_struct *uc, RAMBlock *block) { if (!block) { return; } //if (block->host) { // ram_block_notify_remove(block->host, block->max_length); //} QLIST_REMOVE(block, next); uc->ram_list.mru_block = NULL; /* Write list before version */ //smp_wmb(); // call_rcu(block, reclaim_ramblock, rcu); reclaim_ramblock(uc, block); }
null
null
210,278
286566417295332213708845549763308309187
17
Fix crash when mapping a big memory and calling uc_close
other
qemu
b05b267840515730dbf6753495d5b7bd8b04ad1c
1
static int i2c_ddc_rx(I2CSlave *i2c) { I2CDDCState *s = I2CDDC(i2c); int value; value = s->edid_blob[s->reg]; s->reg++; return value; }
null
null
210,282
37416930783842934030853774949027461552
9
i2c-ddc: fix oob read Suggested-by: Michael Hanselmann <[email protected]> Signed-off-by: Gerd Hoffmann <[email protected]> Reviewed-by: Michael Hanselmann <[email protected]> Reviewed-by: Philippe Mathieu-Daudé <[email protected]> Message-id: [email protected]
other
dpdk
af74f7db384ed149fe42b21dbd7975f8a54ef227
1
vhost_user_set_inflight_fd(struct virtio_net **pdev, struct vhu_msg_context *ctx, int main_fd __rte_unused) { uint64_t mmap_size, mmap_offset; uint16_t num_queues, queue_size; struct virtio_net *dev = *pdev; uint32_t pervq_inflight_size; struct vhost_virtqueue *vq; void *addr; int fd, i; int numa_node = SOCKET_ID_ANY; fd = ctx->fds[0]; if (ctx->msg.size != sizeof(ctx->msg.payload.inflight) || fd < 0) { VHOST_LOG_CONFIG(ERR, "(%s) invalid set_inflight_fd message size is %d,fd is %d\n", dev->ifname, ctx->msg.size, fd); return RTE_VHOST_MSG_RESULT_ERR; } mmap_size = ctx->msg.payload.inflight.mmap_size; mmap_offset = ctx->msg.payload.inflight.mmap_offset; num_queues = ctx->msg.payload.inflight.num_queues; queue_size = ctx->msg.payload.inflight.queue_size; if (vq_is_packed(dev)) pervq_inflight_size = get_pervq_shm_size_packed(queue_size); else pervq_inflight_size = get_pervq_shm_size_split(queue_size); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd mmap_size: %"PRIu64"\n", dev->ifname, mmap_size); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd mmap_offset: %"PRIu64"\n", dev->ifname, mmap_offset); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd num_queues: %u\n", dev->ifname, num_queues); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd queue_size: %u\n", dev->ifname, queue_size); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd fd: %d\n", dev->ifname, fd); VHOST_LOG_CONFIG(INFO, "(%s) set_inflight_fd pervq_inflight_size: %d\n", dev->ifname, pervq_inflight_size); /* * If VQ 0 has already been allocated, try to allocate on the same * NUMA node. It can be reallocated later in numa_realloc(). */ if (dev->nr_vring > 0) numa_node = dev->virtqueue[0]->numa_node; if (!dev->inflight_info) { dev->inflight_info = rte_zmalloc_socket("inflight_info", sizeof(struct inflight_mem_info), 0, numa_node); if (dev->inflight_info == NULL) { VHOST_LOG_CONFIG(ERR, "(%s) failed to alloc dev inflight area\n", dev->ifname); return RTE_VHOST_MSG_RESULT_ERR; } dev->inflight_info->fd = -1; } if (dev->inflight_info->addr) { munmap(dev->inflight_info->addr, dev->inflight_info->size); dev->inflight_info->addr = NULL; } addr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, mmap_offset); if (addr == MAP_FAILED) { VHOST_LOG_CONFIG(ERR, "(%s) failed to mmap share memory.\n", dev->ifname); return RTE_VHOST_MSG_RESULT_ERR; } if (dev->inflight_info->fd >= 0) { close(dev->inflight_info->fd); dev->inflight_info->fd = -1; } dev->inflight_info->fd = fd; dev->inflight_info->addr = addr; dev->inflight_info->size = mmap_size; for (i = 0; i < num_queues; i++) { vq = dev->virtqueue[i]; if (!vq) continue; if (vq_is_packed(dev)) { vq->inflight_packed = addr; vq->inflight_packed->desc_num = queue_size; } else { vq->inflight_split = addr; vq->inflight_split->desc_num = queue_size; } addr = (void *)((char *)addr + pervq_inflight_size); } return RTE_VHOST_MSG_RESULT_OK; }
null
null
210,283
198843124641558155906607607135738096976
96
vhost: fix FD leak with inflight messages Even if unlikely, a buggy vhost-user master might attach fds to inflight messages. Add checks like for other types of vhost-user messages. Fixes: d87f1a1cb7b6 ("vhost: support inflight info sharing") Cc: [email protected] Signed-off-by: David Marchand <[email protected]> Reviewed-by: Maxime Coquelin <[email protected]>
other
dpdk
af74f7db384ed149fe42b21dbd7975f8a54ef227
1
vhost_user_get_inflight_fd(struct virtio_net **pdev, struct vhu_msg_context *ctx, int main_fd __rte_unused) { struct rte_vhost_inflight_info_packed *inflight_packed; uint64_t pervq_inflight_size, mmap_size; uint16_t num_queues, queue_size; struct virtio_net *dev = *pdev; int fd, i, j; int numa_node = SOCKET_ID_ANY; void *addr; if (ctx->msg.size != sizeof(ctx->msg.payload.inflight)) { VHOST_LOG_CONFIG(ERR, "(%s) invalid get_inflight_fd message size is %d\n", dev->ifname, ctx->msg.size); return RTE_VHOST_MSG_RESULT_ERR; } /* * If VQ 0 has already been allocated, try to allocate on the same * NUMA node. It can be reallocated later in numa_realloc(). */ if (dev->nr_vring > 0) numa_node = dev->virtqueue[0]->numa_node; if (dev->inflight_info == NULL) { dev->inflight_info = rte_zmalloc_socket("inflight_info", sizeof(struct inflight_mem_info), 0, numa_node); if (!dev->inflight_info) { VHOST_LOG_CONFIG(ERR, "(%s) failed to alloc dev inflight area\n", dev->ifname); return RTE_VHOST_MSG_RESULT_ERR; } dev->inflight_info->fd = -1; } num_queues = ctx->msg.payload.inflight.num_queues; queue_size = ctx->msg.payload.inflight.queue_size; VHOST_LOG_CONFIG(INFO, "(%s) get_inflight_fd num_queues: %u\n", dev->ifname, ctx->msg.payload.inflight.num_queues); VHOST_LOG_CONFIG(INFO, "(%s) get_inflight_fd queue_size: %u\n", dev->ifname, ctx->msg.payload.inflight.queue_size); if (vq_is_packed(dev)) pervq_inflight_size = get_pervq_shm_size_packed(queue_size); else pervq_inflight_size = get_pervq_shm_size_split(queue_size); mmap_size = num_queues * pervq_inflight_size; addr = inflight_mem_alloc(dev, "vhost-inflight", mmap_size, &fd); if (!addr) { VHOST_LOG_CONFIG(ERR, "(%s) failed to alloc vhost inflight area\n", dev->ifname); ctx->msg.payload.inflight.mmap_size = 0; return RTE_VHOST_MSG_RESULT_ERR; } memset(addr, 0, mmap_size); if (dev->inflight_info->addr) { munmap(dev->inflight_info->addr, dev->inflight_info->size); dev->inflight_info->addr = NULL; } if (dev->inflight_info->fd >= 0) { close(dev->inflight_info->fd); dev->inflight_info->fd = -1; } dev->inflight_info->addr = addr; dev->inflight_info->size = ctx->msg.payload.inflight.mmap_size = mmap_size; dev->inflight_info->fd = ctx->fds[0] = fd; ctx->msg.payload.inflight.mmap_offset = 0; ctx->fd_num = 1; if (vq_is_packed(dev)) { for (i = 0; i < num_queues; i++) { inflight_packed = (struct rte_vhost_inflight_info_packed *)addr; inflight_packed->used_wrap_counter = 1; inflight_packed->old_used_wrap_counter = 1; for (j = 0; j < queue_size; j++) inflight_packed->desc[j].next = j + 1; addr = (void *)((char *)addr + pervq_inflight_size); } } VHOST_LOG_CONFIG(INFO, "(%s) send inflight mmap_size: %"PRIu64"\n", dev->ifname, ctx->msg.payload.inflight.mmap_size); VHOST_LOG_CONFIG(INFO, "(%s) send inflight mmap_offset: %"PRIu64"\n", dev->ifname, ctx->msg.payload.inflight.mmap_offset); VHOST_LOG_CONFIG(INFO, "(%s) send inflight fd: %d\n", dev->ifname, ctx->fds[0]); return RTE_VHOST_MSG_RESULT_REPLY; }
null
null
210,284
33623247974536318315256615866397928606
94
vhost: fix FD leak with inflight messages Even if unlikely, a buggy vhost-user master might attach fds to inflight messages. Add checks like for other types of vhost-user messages. Fixes: d87f1a1cb7b6 ("vhost: support inflight info sharing") Cc: [email protected] Signed-off-by: David Marchand <[email protected]> Reviewed-by: Maxime Coquelin <[email protected]>
other
ImageMagick
b2b48d50300a9fbcd0aa0d9230fd6d7a08f7671e
1
static Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception) { double bounding_height, bounding_width, image_height, image_height_inch, image_width, image_width_inch, resolution_y, resolution_x, units_per_inch; float wmf_width, wmf_height; Image *image; MagickBooleanType status; unsigned long wmf_options_flags = 0; wmf_error_t wmf_error; wmf_magick_t *ddata = 0; wmfAPI *API = 0; wmfAPI_Options wmf_api_options; wmfD_Rect bbox; image=AcquireImage(image_info,exception); if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse) { if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OpenBlob failed"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } image=DestroyImageList(image); return((Image *) NULL); } /* * Create WMF API * */ /* Register callbacks */ wmf_options_flags |= WMF_OPT_FUNCTION; (void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options)); wmf_api_options.function = ipa_functions; /* Ignore non-fatal errors */ wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL; wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options); if (wmf_error != wmf_E_None) { if (API) wmf_api_destroy(API); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " wmf_api_create failed"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary"); } /* Register progress monitor */ wmf_status_function(API,image,magick_progress_callback); ddata=WMF_MAGICK_GetData(API); ddata->image=image; ddata->image_info=image_info; ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL); ddata->exception=exception; ddata->draw_info->font=(char *) RelinquishMagickMemory(ddata->draw_info->font); ddata->draw_info->text=(char *) RelinquishMagickMemory(ddata->draw_info->text); #if defined(MAGICKCORE_WMF_DELEGATE) /* Must initialize font subystem for WMFlite interface */ lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */ /* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */ #endif /* * Open BLOB input via libwmf API * */ wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek, ipa_blob_tell,(void*)image); if (wmf_error != wmf_E_None) { wmf_api_destroy(API); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " wmf_bbuf_input failed"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* * Scan WMF file * */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scanning WMF to obtain bounding box"); wmf_error=wmf_scan(API, 0, &bbox); if (wmf_error != wmf_E_None) { wmf_api_destroy(API); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " wmf_scan failed with wmf_error %d", wmf_error); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } ThrowReaderException(DelegateError,"FailedToScanFile"); } /* * Compute dimensions and scale factors * */ ddata->bbox=bbox; /* User specified resolution */ resolution_y=DefaultResolution; if (image->resolution.y != 0.0) { resolution_y = image->resolution.y; if (image->units == PixelsPerCentimeterResolution) resolution_y *= CENTIMETERS_PER_INCH; } resolution_x=DefaultResolution; if (image->resolution.x != 0.0) { resolution_x = image->resolution.x; if (image->units == PixelsPerCentimeterResolution) resolution_x *= CENTIMETERS_PER_INCH; } /* Obtain output size expressed in metafile units */ wmf_error=wmf_size(API,&wmf_width,&wmf_height); if (wmf_error != wmf_E_None) { wmf_api_destroy(API); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " wmf_size failed with wmf_error %d", wmf_error); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } ThrowReaderException(DelegateError,"FailedToComputeOutputSize"); } /* Obtain (or guess) metafile units */ if ((API)->File->placeable) units_per_inch=(API)->File->pmh->Inch; else if ( (wmf_width*wmf_height) < 1024*1024) units_per_inch=POINTS_PER_INCH; /* MM_TEXT */ else units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */ /* Calculate image width and height based on specified DPI resolution */ image_width_inch = (double) wmf_width / units_per_inch; image_height_inch = (double) wmf_height / units_per_inch; image_width = image_width_inch * resolution_x; image_height = image_height_inch * resolution_y; /* Compute bounding box scale factors and origin translations * * This all just a hack since libwmf does not currently seem to * provide the mapping between LOGICAL coordinates and DEVICE * coordinates. This mapping is necessary in order to know * where to place the logical bounding box within the image. * */ bounding_width = bbox.BR.x - bbox.TL.x; bounding_height = bbox.BR.y - bbox.TL.y; ddata->scale_x = image_width/bounding_width; ddata->translate_x = 0-bbox.TL.x; ddata->rotate = 0; /* Heuristic: guess that if the vertical coordinates mostly span negative values, then the image must be inverted. */ if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) ) { /* Normal (Origin at top left of image) */ ddata->scale_y = (image_height/bounding_height); ddata->translate_y = 0-bbox.TL.y; } else { /* Inverted (Origin at bottom left of image) */ ddata->scale_y = (-image_height/bounding_height); ddata->translate_y = 0-bbox.BR.y; } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Placeable metafile: %s", (API)->File->placeable ? "Yes" : "No"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Size in metafile units: %gx%g",wmf_width,wmf_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Metafile units/inch: %g",units_per_inch); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Size in inches: %gx%g", image_width_inch,image_height_inch); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bounding Box: %g,%g %g,%g", bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bounding width x height: %gx%g",bounding_width, bounding_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Output resolution: %gx%g",resolution_x,resolution_y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image size: %gx%g",image_width,image_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bounding box scale factor: %g,%g",ddata->scale_x, ddata->scale_y); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Translation: %g,%g", ddata->translate_x, ddata->translate_y); } #if 0 #if 0 { typedef struct _wmfPlayer_t wmfPlayer_t; struct _wmfPlayer_t { wmfPen default_pen; wmfBrush default_brush; wmfFont default_font; wmfDC* dc; /* current dc */ }; wmfDC *dc; #define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc) dc = WMF_ELICIT_DC(API); printf("dc->Window.Ox = %d\n", dc->Window.Ox); printf("dc->Window.Oy = %d\n", dc->Window.Oy); printf("dc->Window.width = %d\n", dc->Window.width); printf("dc->Window.height = %d\n", dc->Window.height); printf("dc->pixel_width = %g\n", dc->pixel_width); printf("dc->pixel_height = %g\n", dc->pixel_height); #if defined(MAGICKCORE_WMF_DELEGATE) /* Only in libwmf 0.3 */ printf("dc->Ox = %.d\n", dc->Ox); printf("dc->Oy = %.d\n", dc->Oy); printf("dc->width = %.d\n", dc->width); printf("dc->height = %.d\n", dc->height); #endif } #endif #endif /* * Create canvas image * */ image->rows=(unsigned long) ceil(image_height); image->columns=(unsigned long) ceil(image_width); if (image_info->ping != MagickFalse) { wmf_api_destroy(API); (void) CloseBlob(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating canvas image with size %lux%lu",(unsigned long) image->rows, (unsigned long) image->columns); /* * Set solid background color */ { image->background_color = image_info->background_color; if (image->background_color.alpha != OpaqueAlpha) image->alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); } /* * Play file to generate Vector drawing commands * */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Playing WMF to prepare vectors"); wmf_error = wmf_play(API, 0, &bbox); if (wmf_error != wmf_E_None) { wmf_api_destroy(API); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Playing WMF failed with wmf_error %d", wmf_error); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "leave ReadWMFImage()"); } ThrowReaderException(DelegateError,"FailedToRenderFile"); } /* * Scribble on canvas image * */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Rendering WMF vectors"); DrawRender(ddata->draw_wand); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()"); /* Cleanup allocated data */ wmf_api_destroy(API); (void) CloseBlob(image); /* Return image */ return image; }
null
null
210,303
300633970874720310555933364696625627697
375
https://github.com/ImageMagick/ImageMagick/issues/544
other
libxml2
38eae571111db3b43ffdeb05487c9f60551906fb
1
xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, const xmlChar **URI, int *tlen) { const xmlChar *localname; const xmlChar *prefix; const xmlChar *attname; const xmlChar *aprefix; const xmlChar *nsname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int maxatts = ctxt->maxatts; int nratts, nbatts, nbdef; int i, j, nbNs, attval, oldline, oldcol, inputNr; const xmlChar *base; unsigned long cur; int nsNr = ctxt->nsNr; if (RAW != '<') return(NULL); NEXT1; /* * NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that * point since the attribute values may be stored as pointers to * the buffer and calling SHRINK would destroy them ! * The Shrinking is only possible once the full set of attribute * callbacks have been done. */ reparse: SHRINK; base = ctxt->input->base; cur = ctxt->input->cur - ctxt->input->base; inputNr = ctxt->inputNr; oldline = ctxt->input->line; oldcol = ctxt->input->col; nbatts = 0; nratts = 0; nbdef = 0; nbNs = 0; attval = 0; /* Forget any namespaces added during an earlier parse of this element. */ ctxt->nsNr = nsNr; localname = xmlParseQName(ctxt, &prefix); if (localname == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "StartTag: invalid element name\n"); return(NULL); } *tlen = ctxt->input->cur - ctxt->input->base - cur; /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; int len = -1, alloc = 0; attname = xmlParseAttribute2(ctxt, prefix, localname, &aprefix, &attvalue, &len, &alloc); if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) { if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); attvalue = NULL; goto base_changed; } if ((attname != NULL) && (attvalue != NULL)) { if (len < 0) len = xmlStrlen(attvalue); if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (URL == NULL) { xmlErrMemory(ctxt, "dictionary allocation failure"); if ((attvalue != NULL) && (alloc != 0)) xmlFree(attvalue); return(NULL); } if (*URL != 0) { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns: '%s' is not a valid URI\n", URL, NULL, NULL); } else { if (uri->scheme == NULL) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns: URI %s is not absolute\n", URL, NULL, NULL); } xmlFreeURI(uri); } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI cannot be the default namespace\n", NULL, NULL, NULL); } goto skip_default_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_default_ns; } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, NULL, attname); else if (nsPush(ctxt, NULL, URL) > 0) nbNs++; skip_default_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; continue; } if (aprefix == ctxt->str_xmlns) { const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len); xmlURIPtr uri; if (attname == ctxt->str_xml) { if (URL != ctxt->str_xml_ns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace prefix mapped to wrong URI\n", NULL, NULL, NULL); } /* * Do not keep a namespace definition node */ goto skip_ns; } if (URL == ctxt->str_xml_ns) { if (attname != ctxt->str_xml) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xml namespace URI mapped to wrong prefix\n", NULL, NULL, NULL); } goto skip_ns; } if (attname == ctxt->str_xmlns) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "redefinition of the xmlns prefix is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((len == 29) && (xmlStrEqual(URL, BAD_CAST "http://www.w3.org/2000/xmlns/"))) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "reuse of the xmlns namespace name is forbidden\n", NULL, NULL, NULL); goto skip_ns; } if ((URL == NULL) || (URL[0] == 0)) { xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE, "xmlns:%s: Empty XML namespace is not allowed\n", attname, NULL, NULL); goto skip_ns; } else { uri = xmlParseURI((const char *) URL); if (uri == NULL) { xmlNsErr(ctxt, XML_WAR_NS_URI, "xmlns:%s: '%s' is not a valid URI\n", attname, URL, NULL); } else { if ((ctxt->pedantic) && (uri->scheme == NULL)) { xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE, "xmlns:%s: URI %s is not absolute\n", attname, URL, NULL); } xmlFreeURI(uri); } } /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) xmlErrAttributeDup(ctxt, aprefix, attname); else if (nsPush(ctxt, attname, URL) > 0) nbNs++; skip_ns: if (alloc != 0) xmlFree(attvalue); if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; continue; } /* * Add the pair to atts */ if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { if (attvalue[len] == 0) xmlFree(attvalue); goto failed; } maxatts = ctxt->maxatts; atts = ctxt->atts; } ctxt->attallocs[nratts++] = alloc; atts[nbatts++] = attname; atts[nbatts++] = aprefix; atts[nbatts++] = NULL; /* the URI will be fetched later */ atts[nbatts++] = attvalue; attvalue += len; atts[nbatts++] = attvalue; /* * tag if some deallocation is needed */ if (alloc != 0) attval = 1; } else { if ((attvalue != NULL) && (attvalue[len] == 0)) xmlFree(attvalue); } failed: GROW if (ctxt->instate == XML_PARSER_EOF) break; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); break; } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } GROW; if ((ctxt->input->base != base) || (inputNr != ctxt->inputNr)) goto base_changed; } /* * The attributes defaulting */ if (ctxt->attsDefault != NULL) { xmlDefAttrsPtr defaults; defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix); if (defaults != NULL) { for (i = 0;i < defaults->nbAttrs;i++) { attname = defaults->values[5 * i]; aprefix = defaults->values[5 * i + 1]; /* * special work for namespaces defaulted defs */ if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, NULL); if (nsname != defaults->values[5 * i + 2]) { if (nsPush(ctxt, NULL, defaults->values[5 * i + 2]) > 0) nbNs++; } } else if (aprefix == ctxt->str_xmlns) { /* * check that it's not a defined namespace */ for (j = 1;j <= nbNs;j++) if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname) break; if (j <= nbNs) continue; nsname = xmlGetNamespace(ctxt, attname); if (nsname != defaults->values[2]) { if (nsPush(ctxt, attname, defaults->values[5 * i + 2]) > 0) nbNs++; } } else { /* * check that it's not a defined attribute */ for (j = 0;j < nbatts;j+=5) { if ((attname == atts[j]) && (aprefix == atts[j+1])) break; } if (j < nbatts) continue; if ((atts == NULL) || (nbatts + 5 > maxatts)) { if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) { return(NULL); } maxatts = ctxt->maxatts; atts = ctxt->atts; } atts[nbatts++] = attname; atts[nbatts++] = aprefix; if (aprefix == NULL) atts[nbatts++] = NULL; else atts[nbatts++] = xmlGetNamespace(ctxt, aprefix); atts[nbatts++] = defaults->values[5 * i + 2]; atts[nbatts++] = defaults->values[5 * i + 3]; if ((ctxt->standalone == 1) && (defaults->values[5 * i + 4] != NULL)) { xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED, "standalone: attribute %s on %s defaulted from external subset\n", attname, localname); } nbdef++; } } } } /* * The attributes checkings */ for (i = 0; i < nbatts;i += 5) { /* * The default namespace does not apply to attribute names. */ if (atts[i + 1] != NULL) { nsname = xmlGetNamespace(ctxt, atts[i + 1]); if (nsname == NULL) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s for %s on %s is not defined\n", atts[i + 1], atts[i], localname); } atts[i + 2] = nsname; } else nsname = NULL; /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. * As extended by the Namespace in XML REC. */ for (j = 0; j < i;j += 5) { if (atts[i] == atts[j]) { if (atts[i+1] == atts[j+1]) { xmlErrAttributeDup(ctxt, atts[i+1], atts[i]); break; } if ((nsname != NULL) && (atts[j + 2] == nsname)) { xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED, "Namespaced Attribute %s in '%s' redefined\n", atts[i], nsname, NULL); break; } } } } nsname = xmlGetNamespace(ctxt, prefix); if ((prefix != NULL) && (nsname == NULL)) { xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE, "Namespace prefix %s on %s is not defined\n", prefix, localname, NULL); } *pref = prefix; *URI = nsname; /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) && (!ctxt->disableSAX)) { if (nbNs > 0) ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs], nbatts / 5, nbdef, atts); else ctxt->sax->startElementNs(ctxt->userData, localname, prefix, nsname, 0, NULL, nbatts / 5, nbdef, atts); } /* * Free up attribute allocated strings if needed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } return(localname); base_changed: /* * the attribute strings are valid iif the base didn't changed */ if (attval != 0) { for (i = 3,j = 0; j < nratts;i += 5,j++) if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL)) xmlFree((xmlChar *) atts[i]); } /* * We can't switch from one entity to another in the middle * of a start tag */ if (inputNr != ctxt->inputNr) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Start tag doesn't start and stop in the same entity\n"); return(NULL); } ctxt->input->cur = ctxt->input->base + cur; ctxt->input->line = oldline; ctxt->input->col = oldcol; if (ctxt->wellFormed == 1) { goto reparse; } return(NULL); }
null
null
210,378
222205143045940612724836722883651844635
459
Heap use-after-free in xmlSAX2AttributeNs For https://bugzilla.gnome.org/show_bug.cgi?id=759020 * parser.c: (xmlParseStartTag2): Attribute strings are only valid if the base does not change, so add another check where the base may change. Make sure to set 'attvalue' to NULL after freeing it. * result/errors/759020.xml: Added. * result/errors/759020.xml.err: Added. * result/errors/759020.xml.str: Added. * test/errors/759020.xml: Added test case.
other
vim
6f98371532fcff911b462d51bc64f2ce8a6ae682
1
do_arg_all( int count, int forceit, // hide buffers in current windows int keep_tabs) // keep current tabs, for ":tab drop file" { int i; win_T *wp, *wpnext; char_u *opened; // Array of weight for which args are open: // 0: not opened // 1: opened in other tab // 2: opened in curtab // 3: opened in curtab and curwin // int opened_len; // length of opened[] int use_firstwin = FALSE; // use first window for arglist int tab_drop_empty_window = FALSE; int split_ret = OK; int p_ea_save; alist_T *alist; // argument list to be used buf_T *buf; tabpage_T *tpnext; int had_tab = cmdmod.cmod_tab; win_T *old_curwin, *last_curwin; tabpage_T *old_curtab, *last_curtab; win_T *new_curwin = NULL; tabpage_T *new_curtab = NULL; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { emsg(_(e_invalid_in_cmdline_window)); return; } #endif if (ARGCOUNT <= 0) { // Don't give an error message. We don't want it when the ":all" // command is in the .vimrc. return; } setpcmark(); opened_len = ARGCOUNT; opened = alloc_clear(opened_len); if (opened == NULL) return; // Autocommands may do anything to the argument list. Make sure it's not // freed while we are working here by "locking" it. We still have to // watch out for its size to be changed. alist = curwin->w_alist; ++alist->al_refcount; old_curwin = curwin; old_curtab = curtab; # ifdef FEAT_GUI need_mouse_correct = TRUE; # endif // Try closing all windows that are not in the argument list. // Also close windows that are not full width; // When 'hidden' or "forceit" set the buffer becomes hidden. // Windows that have a changed buffer and can't be hidden won't be closed. // When the ":tab" modifier was used do this for all tab pages. if (had_tab > 0) goto_tabpage_tp(first_tabpage, TRUE, TRUE); for (;;) { tpnext = curtab->tp_next; for (wp = firstwin; wp != NULL; wp = wpnext) { wpnext = wp->w_next; buf = wp->w_buffer; if (buf->b_ffname == NULL || (!keep_tabs && (buf->b_nwindows > 1 || wp->w_width != Columns))) i = opened_len; else { // check if the buffer in this window is in the arglist for (i = 0; i < opened_len; ++i) { if (i < alist->al_ga.ga_len && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum || fullpathcmp(alist_name(&AARGLIST(alist)[i]), buf->b_ffname, TRUE, TRUE) & FPC_SAME)) { int weight = 1; if (old_curtab == curtab) { ++weight; if (old_curwin == wp) ++weight; } if (weight > (int)opened[i]) { opened[i] = (char_u)weight; if (i == 0) { if (new_curwin != NULL) new_curwin->w_arg_idx = opened_len; new_curwin = wp; new_curtab = curtab; } } else if (keep_tabs) i = opened_len; if (wp->w_alist != alist) { // Use the current argument list for all windows // containing a file from it. alist_unlink(wp->w_alist); wp->w_alist = alist; ++wp->w_alist->al_refcount; } break; } } } wp->w_arg_idx = i; if (i == opened_len && !keep_tabs)// close this window { if (buf_hide(buf) || forceit || buf->b_nwindows > 1 || !bufIsChanged(buf)) { // If the buffer was changed, and we would like to hide it, // try autowriting. if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) { bufref_T bufref; set_bufref(&bufref, buf); (void)autowrite(buf, FALSE); // check if autocommands removed the window if (!win_valid(wp) || !bufref_valid(&bufref)) { wpnext = firstwin; // start all over... continue; } } // don't close last window if (ONE_WINDOW && (first_tabpage->tp_next == NULL || !had_tab)) use_firstwin = TRUE; else { win_close(wp, !buf_hide(buf) && !bufIsChanged(buf)); // check if autocommands removed the next window if (!win_valid(wpnext)) wpnext = firstwin; // start all over... } } } } // Without the ":tab" modifier only do the current tab page. if (had_tab == 0 || tpnext == NULL) break; // check if autocommands removed the next tab page if (!valid_tabpage(tpnext)) tpnext = first_tabpage; // start all over... goto_tabpage_tp(tpnext, TRUE, TRUE); } // Open a window for files in the argument list that don't have one. // ARGCOUNT may change while doing this, because of autocommands. if (count > opened_len || count <= 0) count = opened_len; // Don't execute Win/Buf Enter/Leave autocommands here. ++autocmd_no_enter; ++autocmd_no_leave; last_curwin = curwin; last_curtab = curtab; win_enter(lastwin, FALSE); // ":tab drop file" should re-use an empty window to avoid "--remote-tab" // leaving an empty tab page when executed locally. if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1 && curbuf->b_ffname == NULL && !curbuf->b_changed) { use_firstwin = TRUE; tab_drop_empty_window = TRUE; } for (i = 0; i < count && !got_int; ++i) { if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1) arg_had_last = TRUE; if (opened[i] > 0) { // Move the already present window to below the current window if (curwin->w_arg_idx != i) { FOR_ALL_WINDOWS(wpnext) { if (wpnext->w_arg_idx == i) { if (keep_tabs) { new_curwin = wpnext; new_curtab = curtab; } else if (wpnext->w_frame->fr_parent != curwin->w_frame->fr_parent) { emsg(_("E249: window layout changed unexpectedly")); i = count; break; } else win_move_after(wpnext, curwin); break; } } } } else if (split_ret == OK) { // trigger events for tab drop if (tab_drop_empty_window && i == count - 1) --autocmd_no_enter; if (!use_firstwin) // split current window { p_ea_save = p_ea; p_ea = TRUE; // use space from all windows split_ret = win_split(0, WSP_ROOM | WSP_BELOW); p_ea = p_ea_save; if (split_ret == FAIL) continue; } else // first window: do autocmd for leaving this buffer --autocmd_no_leave; // edit file "i" curwin->w_arg_idx = i; if (i == 0) { new_curwin = curwin; new_curtab = curtab; } (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL, ECMD_ONE, ((buf_hide(curwin->w_buffer) || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0) + ECMD_OLDBUF, curwin); if (tab_drop_empty_window && i == count - 1) ++autocmd_no_enter; if (use_firstwin) ++autocmd_no_leave; use_firstwin = FALSE; } ui_breakcheck(); // When ":tab" was used open a new tab for a new window repeatedly. if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) cmdmod.cmod_tab = 9999; } // Remove the "lock" on the argument list. alist_unlink(alist); --autocmd_no_enter; // restore last referenced tabpage's curwin if (last_curtab != new_curtab) { if (valid_tabpage(last_curtab)) goto_tabpage_tp(last_curtab, TRUE, TRUE); if (win_valid(last_curwin)) win_enter(last_curwin, FALSE); } // to window with first arg if (valid_tabpage(new_curtab)) goto_tabpage_tp(new_curtab, TRUE, TRUE); if (win_valid(new_curwin)) win_enter(new_curwin, FALSE); --autocmd_no_leave; vim_free(opened); }
null
null
210,393
330220089447816493732267062578517135263
291
patch 8.2.3884: crash when clearing the argument list while using it Problem: Crash when clearing the argument list while using it. Solution: Lock the argument list for ":all".
other
ghostpdl
362ec9daadb9992b0def3520cd1dc6fa52edd1c4
1
fill_threshhold_buffer(byte *dest_strip, byte *src_strip, int src_width, int left_offset, int left_width, int num_tiles, int right_width) { byte *ptr_out_temp = dest_strip; int ii; /* Left part */ memcpy(dest_strip, src_strip + left_offset, left_width); ptr_out_temp += left_width; /* Now the full parts */ for (ii = 0; ii < num_tiles; ii++){ memcpy(ptr_out_temp, src_strip, src_width); ptr_out_temp += src_width; } /* Now the remainder */ memcpy(ptr_out_temp, src_strip, right_width); #ifdef PACIFY_VALGRIND ptr_out_temp += right_width; ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1); if (ii > 0) memset(ptr_out_temp, 0, ii); #endif }
null
null
210,420
126101196157599127576699537006064922278
24
Fix bug 697459 Buffer overflow in fill_threshold_buffer There was an overflow check for ht_buffer size, but none for the larger threshold_buffer. Note that this file didn't fail on Windows because the combination of the ht_buffer and the size of the (miscalculated due to overflow) threshold_buffer would have exceeded the 2Gb limit.
other
ghostpdl
366ad48d076c1aa4c8f83c65011258a04e348207
1
jetp3852_print_page(gx_device_printer *pdev, gp_file *prn_stream) { #define DATA_SIZE (LINE_SIZE * 8) unsigned int cnt_2prn; unsigned int count,tempcnt; unsigned char vtp,cntc1,cntc2; int line_size_color_plane; byte data[DATA_SIZE]; byte plane_data[LINE_SIZE * 3]; /* Set initial condition for printer */ gp_fputs("\033@",prn_stream); /* Send each scan line in turn */ { int lnum; int line_size = gdev_mem_bytes_per_scan_line((gx_device *)pdev); int num_blank_lines = 0; if (line_size > DATA_SIZE) { emprintf2(pdev->memory, "invalid resolution and/or width gives line_size = %d, max. is %d\n", line_size, DATA_SIZE); return_error(gs_error_rangecheck); } for ( lnum = 0; lnum < pdev->height; lnum++ ) { byte *end_data = data + line_size; gdev_prn_copy_scan_lines(pdev, lnum, (byte *)data, line_size); /* Remove trailing 0s. */ while ( end_data > data && end_data[-1] == 0 ) end_data--; if ( end_data == data ) { /* Blank line */ num_blank_lines++; } else { int i; byte *odp; byte *row; /* Pad with 0s to fill out the last */ /* block of 8 bytes. */ memset(end_data, 0, 7); /* Transpose the data to get pixel planes. */ for ( i = 0, odp = plane_data; i < DATA_SIZE; i += 8, odp++ ) { /* The following is for 16-bit machines */ #define spread3(c)\ { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L } static ulong spr40[8] = spread3(0x40); static ulong spr8[8] = spread3(8); static ulong spr2[8] = spread3(2); register byte *dp = data + i; register ulong pword = (spr40[dp[0]] << 1) + (spr40[dp[1]]) + (spr40[dp[2]] >> 1) + (spr8[dp[3]] << 1) + (spr8[dp[4]]) + (spr8[dp[5]] >> 1) + (spr2[dp[6]]) + (spr2[dp[7]] >> 1); odp[0] = (byte)(pword >> 16); odp[LINE_SIZE] = (byte)(pword >> 8); odp[LINE_SIZE*2] = (byte)(pword); } /* Skip blank lines if any */ if ( num_blank_lines > 0 ) { /* Do "dot skips" */ while(num_blank_lines > 255) { gp_fputs("\033e\377",prn_stream); num_blank_lines -= 255; } vtp = num_blank_lines; gp_fprintf(prn_stream,"\033e%c",vtp); num_blank_lines = 0; } /* Transfer raster graphics in the order R, G, B. */ /* Apparently it is stored in B, G, R */ /* Calculate the amount of data to send by what */ /* Ghostscript tells us the scan line_size in (bytes) */ count = line_size / 3; line_size_color_plane = count / 3; cnt_2prn = line_size_color_plane * 3 + 5; tempcnt = cnt_2prn; cntc1 = (tempcnt & 0xFF00) >> 8; cntc2 = (tempcnt & 0x00FF); gp_fprintf(prn_stream, "\033[O%c%c\200\037",cntc2,cntc1); gp_fputc('\000',prn_stream); gp_fputs("\124\124",prn_stream); for ( row = plane_data + LINE_SIZE * 2, i = 0; i < 3; row -= LINE_SIZE, i++ ) { int jj; byte ctemp; odp = row; /* Complement bytes */ for (jj=0; jj< line_size_color_plane; jj++) { ctemp = *odp; *odp++ = ~ctemp; } gp_fwrite(row, sizeof(byte), line_size_color_plane, prn_stream); } } } } /* eject page */ gp_fputs("\014", prn_stream); return 0; }
null
null
210,453
302183289353260954524490328979171476250
118
Bug 701815: avoid uninitialised bytes being >7, which broke indexing. Fixes: ./sanbin/gs -dBATCH -dNOPAUSE -sOutputFile=tmp -sDEVICE=jetp3852 ../bug-701815.pdf
other
linux
89c2b3b74918200e46699338d7bcc19b1ea12110
1
static int io_read(struct io_kiocb *req, unsigned int issue_flags) { struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs; struct kiocb *kiocb = &req->rw.kiocb; struct iov_iter __iter, *iter = &__iter; struct io_async_rw *rw = req->async_data; ssize_t io_size, ret, ret2; bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK; if (rw) { iter = &rw->iter; iovec = NULL; } else { ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock); if (ret < 0) return ret; } io_size = iov_iter_count(iter); req->result = io_size; /* Ensure we clear previously set non-block flag */ if (!force_nonblock) kiocb->ki_flags &= ~IOCB_NOWAIT; else kiocb->ki_flags |= IOCB_NOWAIT; /* If the file doesn't support async, just async punt */ if (force_nonblock && !io_file_supports_async(req, READ)) { ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true); return ret ?: -EAGAIN; } ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size); if (unlikely(ret)) { kfree(iovec); return ret; } ret = io_iter_do_read(req, iter); if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) { req->flags &= ~REQ_F_REISSUE; /* IOPOLL retry should happen for io-wq threads */ if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL)) goto done; /* no retry on NONBLOCK nor RWF_NOWAIT */ if (req->flags & REQ_F_NOWAIT) goto done; /* some cases will consume bytes even on error returns */ iov_iter_revert(iter, io_size - iov_iter_count(iter)); ret = 0; } else if (ret == -EIOCBQUEUED) { goto out_free; } else if (ret <= 0 || ret == io_size || !force_nonblock || (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) { /* read all, failed, already did sync or don't want to retry */ goto done; } ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true); if (ret2) return ret2; iovec = NULL; rw = req->async_data; /* now use our persistent iterator, if we aren't already */ iter = &rw->iter; do { io_size -= ret; rw->bytes_done += ret; /* if we can retry, do so with the callbacks armed */ if (!io_rw_should_retry(req)) { kiocb->ki_flags &= ~IOCB_WAITQ; return -EAGAIN; } /* * Now retry read with the IOCB_WAITQ parts set in the iocb. If * we get -EIOCBQUEUED, then we'll get a notification when the * desired page gets unlocked. We can also get a partial read * here, and if we do, then just retry at the new offset. */ ret = io_iter_do_read(req, iter); if (ret == -EIOCBQUEUED) return 0; /* we got some bytes, but not all. retry. */ kiocb->ki_flags &= ~IOCB_WAITQ; } while (ret > 0 && ret < io_size); done: kiocb_done(kiocb, ret, issue_flags); out_free: /* it's faster to check here then delegate to kfree */ if (iovec) kfree(iovec); return 0; }
null
null
210,484
9767670992332379490534176378394297980
97
io_uring: reexpand under-reexpanded iters [ 74.211232] BUG: KASAN: stack-out-of-bounds in iov_iter_revert+0x809/0x900 [ 74.212778] Read of size 8 at addr ffff888025dc78b8 by task syz-executor.0/828 [ 74.214756] CPU: 0 PID: 828 Comm: syz-executor.0 Not tainted 5.14.0-rc3-next-20210730 #1 [ 74.216525] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.14.0-0-g155821a1990b-prebuilt.qemu.org 04/01/2014 [ 74.219033] Call Trace: [ 74.219683] dump_stack_lvl+0x8b/0xb3 [ 74.220706] print_address_description.constprop.0+0x1f/0x140 [ 74.224226] kasan_report.cold+0x7f/0x11b [ 74.226085] iov_iter_revert+0x809/0x900 [ 74.227960] io_write+0x57d/0xe40 [ 74.232647] io_issue_sqe+0x4da/0x6a80 [ 74.242578] __io_queue_sqe+0x1ac/0xe60 [ 74.245358] io_submit_sqes+0x3f6e/0x76a0 [ 74.248207] __do_sys_io_uring_enter+0x90c/0x1a20 [ 74.257167] do_syscall_64+0x3b/0x90 [ 74.257984] entry_SYSCALL_64_after_hwframe+0x44/0xae old_size = iov_iter_count(); ... iov_iter_revert(old_size - iov_iter_count()); If iov_iter_revert() is done base on the initial size as above, and the iter is truncated and not reexpanded in the middle, it miscalculates borders causing problems. This trace is due to no one reexpanding after generic_write_checks(). Now iters store how many bytes has been truncated, so reexpand them to the initial state right before reverting. Cc: [email protected] Reported-by: Palash Oswal <[email protected]> Reported-by: Sudip Mukherjee <[email protected]> Reported-and-tested-by: [email protected] Signed-off-by: Pavel Begunkov <[email protected]> Signed-off-by: Al Viro <[email protected]>
other
vim
3d51ce18ab1be4f9f6061568a4e7fabf00b21794
1
win_close(win_T *win, int free_buf) { win_T *wp; int other_buffer = FALSE; int close_curwin = FALSE; int dir; int help_window = FALSE; tabpage_T *prev_curtab = curtab; frame_T *win_frame = win->w_frame->fr_parent; #ifdef FEAT_DIFF int had_diffmode = win->w_p_diff; #endif #ifdef MESSAGE_QUEUE int did_decrement = FALSE; #endif #if defined(FEAT_TERMINAL) && defined(FEAT_PROP_POPUP) // Can close a popup window with a terminal if the job has finished. if (may_close_term_popup() == OK) return OK; #endif if (ERROR_IF_ANY_POPUP_WINDOW) return FAIL; if (last_window()) { emsg(_(e_cannot_close_last_window)); return FAIL; } if (win->w_closing || (win->w_buffer != NULL && win->w_buffer->b_locked > 0)) return FAIL; // window is already being closed if (win_unlisted(win)) { emsg(_(e_cannot_close_autocmd_or_popup_window)); return FAIL; } if ((firstwin == aucmd_win || lastwin == aucmd_win) && one_window()) { emsg(_(e_cannot_close_window_only_autocmd_window_would_remain)); return FAIL; } // When closing the last window in a tab page first go to another tab page // and then close the window and the tab page to avoid that curwin and // curtab are invalid while we are freeing memory. if (close_last_window_tabpage(win, free_buf, prev_curtab)) return FAIL; // When closing the help window, try restoring a snapshot after closing // the window. Otherwise clear the snapshot, it's now invalid. if (bt_help(win->w_buffer)) help_window = TRUE; else clear_snapshot(curtab, SNAP_HELP_IDX); if (win == curwin) { #ifdef FEAT_JOB_CHANNEL leaving_window(curwin); #endif /* * Guess which window is going to be the new current window. * This may change because of the autocommands (sigh). */ wp = frame2win(win_altframe(win, NULL)); /* * Be careful: If autocommands delete the window or cause this window * to be the last one left, return now. */ if (wp->w_buffer != curbuf) { other_buffer = TRUE; win->w_closing = TRUE; apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf); if (!win_valid(win)) return FAIL; win->w_closing = FALSE; if (last_window()) return FAIL; } win->w_closing = TRUE; apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf); if (!win_valid(win)) return FAIL; win->w_closing = FALSE; if (last_window()) return FAIL; #ifdef FEAT_EVAL // autocmds may abort script processing if (aborting()) return FAIL; #endif } #ifdef FEAT_GUI // Avoid trouble with scrollbars that are going to be deleted in // win_free(). if (gui.in_use) out_flush(); #endif #ifdef FEAT_PROP_POPUP if (popup_win_closed(win) && !win_valid(win)) return FAIL; #endif // Trigger WinClosed just before starting to free window-related resources. trigger_winclosed(win); // autocmd may have freed the window already. if (!win_valid_any_tab(win)) return OK; win_close_buffer(win, free_buf ? DOBUF_UNLOAD : 0, TRUE); if (only_one_window() && win_valid(win) && win->w_buffer == NULL && (last_window() || curtab != prev_curtab || close_last_window_tabpage(win, free_buf, prev_curtab))) { // Autocommands have closed all windows, quit now. Restore // curwin->w_buffer, otherwise writing viminfo may fail. if (curwin->w_buffer == NULL) curwin->w_buffer = curbuf; getout(0); } // Autocommands may have moved to another tab page. if (curtab != prev_curtab && win_valid_any_tab(win) && win->w_buffer == NULL) { // Need to close the window anyway, since the buffer is NULL. win_close_othertab(win, FALSE, prev_curtab); return FAIL; } // Autocommands may have closed the window already or closed the only // other window. if (!win_valid(win) || last_window() || close_last_window_tabpage(win, free_buf, prev_curtab)) return FAIL; // Now we are really going to close the window. Disallow any autocommand // to split a window to avoid trouble. // Also bail out of parse_queued_messages() to avoid it tries to update the // screen. ++split_disallowed; #ifdef MESSAGE_QUEUE ++dont_parse_messages; #endif // Free the memory used for the window and get the window that received // the screen space. wp = win_free_mem(win, &dir, NULL); if (help_window) { // Closing the help window moves the cursor back to the current window // of the snapshot. win_T *prev_win = get_snapshot_curwin(SNAP_HELP_IDX); if (win_valid(prev_win)) wp = prev_win; } // Make sure curwin isn't invalid. It can cause severe trouble when // printing an error message. For win_equal() curbuf needs to be valid // too. if (win == curwin) { curwin = wp; #ifdef FEAT_QUICKFIX if (wp->w_p_pvw || bt_quickfix(wp->w_buffer)) { /* * If the cursor goes to the preview or the quickfix window, try * finding another window to go to. */ for (;;) { if (wp->w_next == NULL) wp = firstwin; else wp = wp->w_next; if (wp == curwin) break; if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer)) { curwin = wp; break; } } } #endif curbuf = curwin->w_buffer; close_curwin = TRUE; // The cursor position may be invalid if the buffer changed after last // using the window. check_cursor(); } if (p_ea && (*p_ead == 'b' || *p_ead == dir)) // If the frame of the closed window contains the new current window, // only resize that frame. Otherwise resize all windows. win_equal(curwin, curwin->w_frame->fr_parent == win_frame, dir); else win_comp_pos(); if (close_curwin) { // Pass WEE_ALLOW_PARSE_MESSAGES to decrement dont_parse_messages // before autocommands. #ifdef MESSAGE_QUEUE did_decrement = #else (void) #endif win_enter_ext(wp, WEE_CURWIN_INVALID | WEE_TRIGGER_ENTER_AUTOCMDS | WEE_TRIGGER_LEAVE_AUTOCMDS | WEE_ALLOW_PARSE_MESSAGES); if (other_buffer) // careful: after this wp and win may be invalid! apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf); } --split_disallowed; #ifdef MESSAGE_QUEUE if (!did_decrement) --dont_parse_messages; #endif /* * If last window has a status line now and we don't want one, * remove the status line. */ last_status(FALSE); // After closing the help window, try restoring the window layout from // before it was opened. if (help_window) restore_snapshot(SNAP_HELP_IDX, close_curwin); #ifdef FEAT_DIFF // If the window had 'diff' set and now there is only one window left in // the tab page with 'diff' set, and "closeoff" is in 'diffopt', then // execute ":diffoff!". if (diffopt_closeoff() && had_diffmode && curtab == prev_curtab) { int diffcount = 0; win_T *dwin; FOR_ALL_WINDOWS(dwin) if (dwin->w_p_diff) ++diffcount; if (diffcount == 1) do_cmdline_cmd((char_u *)"diffoff!"); } #endif #if defined(FEAT_GUI) // When 'guioptions' includes 'L' or 'R' may have to remove scrollbars. if (gui.in_use && !win_hasvertsplit()) gui_init_which_components(NULL); #endif redraw_all_later(NOT_VALID); return OK; }
null
null
210,511
76712974762584451592714996998045790637
268
patch 9.0.0017: accessing memory beyond the end of the line Problem: Accessing memory beyond the end of the line. Solution: Stop Visual mode when closing a window.
other
vim
8eba2bd291b347e3008aa9e565652d51ad638cfa
1
get_lisp_indent(void) { pos_T *pos, realpos, paren; int amount; char_u *that; colnr_T col; colnr_T firsttry; int parencount, quotecount; int vi_lisp; // Set vi_lisp to use the vi-compatible method vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL); realpos = curwin->w_cursor; curwin->w_cursor.col = 0; if ((pos = findmatch(NULL, '(')) == NULL) pos = findmatch(NULL, '['); else { paren = *pos; pos = findmatch(NULL, '['); if (pos == NULL || LT_POSP(pos, &paren)) pos = &paren; } if (pos != NULL) { // Extra trick: Take the indent of the first previous non-white // line that is at the same () level. amount = -1; parencount = 0; while (--curwin->w_cursor.lnum >= pos->lnum) { if (linewhite(curwin->w_cursor.lnum)) continue; for (that = ml_get_curline(); *that != NUL; ++that) { if (*that == ';') { while (*(that + 1) != NUL) ++that; continue; } if (*that == '\\') { if (*(that + 1) != NUL) ++that; continue; } if (*that == '"' && *(that + 1) != NUL) { while (*++that && *that != '"') { // skipping escaped characters in the string if (*that == '\\') { if (*++that == NUL) break; if (that[1] == NUL) { ++that; break; } } } if (*that == NUL) break; } if (*that == '(' || *that == '[') ++parencount; else if (*that == ')' || *that == ']') --parencount; } if (parencount == 0) { amount = get_indent(); break; } } if (amount == -1) { curwin->w_cursor.lnum = pos->lnum; curwin->w_cursor.col = pos->col; col = pos->col; that = ml_get_curline(); if (vi_lisp && get_indent() == 0) amount = 2; else { char_u *line = that; amount = 0; while (*that && col) { amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount); col--; } // Some keywords require "body" indenting rules (the // non-standard-lisp ones are Scheme special forms): // // (let ((a 1)) instead (let ((a 1)) // (...)) of (...)) if (!vi_lisp && (*that == '(' || *that == '[') && lisp_match(that + 1)) amount += 2; else { that++; amount++; firsttry = amount; while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize(line, that, (colnr_T)amount); ++that; } if (*that && *that != ';') // not a comment line { // test *that != '(' to accommodate first let/do // argument if it is more than one line if (!vi_lisp && *that != '(' && *that != '[') firsttry++; parencount = 0; quotecount = 0; if (vi_lisp || (*that != '"' && *that != '\'' && *that != '#' && (*that < '0' || *that > '9'))) { while (*that && (!VIM_ISWHITE(*that) || quotecount || parencount) && (!((*that == '(' || *that == '[') && !quotecount && !parencount && vi_lisp))) { if (*that == '"') quotecount = !quotecount; if ((*that == '(' || *that == '[') && !quotecount) ++parencount; if ((*that == ')' || *that == ']') && !quotecount) --parencount; if (*that == '\\' && *(that+1) != NUL) amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); amount += lbr_chartabsize_adv( line, &that, (colnr_T)amount); } } while (VIM_ISWHITE(*that)) { amount += lbr_chartabsize( line, that, (colnr_T)amount); that++; } if (!*that || *that == ';') amount = firsttry; } } } } } else amount = 0; // no matching '(' or '[' found, use zero indent curwin->w_cursor = realpos; return amount; }
null
null
210,520
229569421335583981332854288547873342077
183
patch 8.2.5151: reading beyond the end of the line with lisp indenting Problem: Reading beyond the end of the line with lisp indenting. Solution: Avoid going over the NUL at the end of the line.
other
linux
04c9b00ba83594a29813d6b1fb8fdc93a3915174
1
static netdev_tx_t mcba_usb_start_xmit(struct sk_buff *skb, struct net_device *netdev) { struct mcba_priv *priv = netdev_priv(netdev); struct can_frame *cf = (struct can_frame *)skb->data; struct mcba_usb_ctx *ctx = NULL; struct net_device_stats *stats = &priv->netdev->stats; u16 sid; int err; struct mcba_usb_msg_can usb_msg = { .cmd_id = MBCA_CMD_TRANSMIT_MESSAGE_EV }; if (can_dropped_invalid_skb(netdev, skb)) return NETDEV_TX_OK; ctx = mcba_usb_get_free_ctx(priv, cf); if (!ctx) return NETDEV_TX_BUSY; if (cf->can_id & CAN_EFF_FLAG) { /* SIDH | SIDL | EIDH | EIDL * 28 - 21 | 20 19 18 x x x 17 16 | 15 - 8 | 7 - 0 */ sid = MCBA_SIDL_EXID_MASK; /* store 28-18 bits */ sid |= (cf->can_id & 0x1ffc0000) >> 13; /* store 17-16 bits */ sid |= (cf->can_id & 0x30000) >> 16; put_unaligned_be16(sid, &usb_msg.sid); /* store 15-0 bits */ put_unaligned_be16(cf->can_id & 0xffff, &usb_msg.eid); } else { /* SIDH | SIDL * 10 - 3 | 2 1 0 x x x x x */ put_unaligned_be16((cf->can_id & CAN_SFF_MASK) << 5, &usb_msg.sid); usb_msg.eid = 0; } usb_msg.dlc = cf->len; memcpy(usb_msg.data, cf->data, usb_msg.dlc); if (cf->can_id & CAN_RTR_FLAG) usb_msg.dlc |= MCBA_DLC_RTR_MASK; can_put_echo_skb(skb, priv->netdev, ctx->ndx, 0); err = mcba_usb_xmit(priv, (struct mcba_usb_msg *)&usb_msg, ctx); if (err) goto xmit_failed; return NETDEV_TX_OK; xmit_failed: can_free_echo_skb(priv->netdev, ctx->ndx, NULL); mcba_usb_free_ctx(ctx); dev_kfree_skb(skb); stats->tx_dropped++; return NETDEV_TX_OK; }
null
null
210,527
273216865611265197222085391246765638267
65
can: mcba_usb: mcba_usb_start_xmit(): fix double dev_kfree_skb in error path There is no need to call dev_kfree_skb() when usb_submit_urb() fails because can_put_echo_skb() deletes original skb and can_free_echo_skb() deletes the cloned skb. Fixes: 51f3baad7de9 ("can: mcba_usb: Add support for Microchip CAN BUS Analyzer") Link: https://lore.kernel.org/all/[email protected] Signed-off-by: Hangyu Hua <[email protected]> Signed-off-by: Marc Kleine-Budde <[email protected]>
other
oniguruma
4d461376bd85e7994835677b2ff453a43c49cd28
1
expand_case_fold_string(Node* node, regex_t* reg) { #define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION 8 int r, n, len, alt_num; UChar *start, *end, *p; Node *top_root, *root, *snode, *prev_node; OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; StrNode* sn = STR_(node); if (NODE_STRING_IS_AMBIG(node)) return 0; start = sn->s; end = sn->end; if (start >= end) return 0; r = 0; top_root = root = prev_node = snode = NULL_NODE; alt_num = 1; p = start; while (p < end) { n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end, items); if (n < 0) { r = n; goto err; } len = enclen(reg->enc, p); if (n == 0) { if (IS_NULL(snode)) { if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } prev_node = snode = onig_node_new_str(NULL, NULL); if (IS_NULL(snode)) goto mem_err; if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, snode))) { onig_node_free(snode); goto mem_err; } } } r = onig_node_str_cat(snode, p, p + len); if (r != 0) goto err; } else { alt_num *= (n + 1); if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break; if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node); if (r < 0) goto mem_err; if (r == 1) { if (IS_NULL(root)) { top_root = prev_node; } else { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } root = NODE_CAR(prev_node); } else { /* r == 0 */ if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } } snode = NULL_NODE; } p += len; } if (p < end) { Node *srem; r = expand_case_fold_make_rem_string(&srem, p, end, reg); if (r != 0) goto mem_err; if (IS_NOT_NULL(prev_node) && IS_NULL(root)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(srem); onig_node_free(prev_node); goto mem_err; } } if (IS_NULL(root)) { prev_node = srem; } else { if (IS_NULL(onig_node_list_add(root, srem))) { onig_node_free(srem); goto mem_err; } } } /* ending */ top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node); swap_node(node, top_root); onig_node_free(top_root); return 0; mem_err: r = ONIGERR_MEMORY; err: onig_node_free(top_root); return r; }
null
null
210,551
123951362429471974733093076542745134514
134
don't expand string case folds to alternatives if code length == 1 and byte length is same
other
dpdk
d87f1a1cb7b666550bb53e39c1d85d9f7b861e6f
1
vhost_backend_cleanup(struct virtio_net *dev) { if (dev->mem) { free_mem_region(dev); rte_free(dev->mem); dev->mem = NULL; } free(dev->guest_pages); dev->guest_pages = NULL; if (dev->log_addr) { munmap((void *)(uintptr_t)dev->log_addr, dev->log_size); dev->log_addr = 0; } if (dev->slave_req_fd >= 0) { close(dev->slave_req_fd); dev->slave_req_fd = -1; } if (dev->postcopy_ufd >= 0) { close(dev->postcopy_ufd); dev->postcopy_ufd = -1; } dev->postcopy_listening = 0; }
null
null
210,555
127062956025419189387943517300154259824
28
vhost: support inflight info sharing This patch introduces two new messages VHOST_USER_GET_INFLIGHT_FD and VHOST_USER_SET_INFLIGHT_FD to support transferring a shared buffer between qemu and backend. Signed-off-by: Lin Li <[email protected]> Signed-off-by: Xun Ni <[email protected]> Signed-off-by: Yu Zhang <[email protected]> Signed-off-by: Jin Yu <[email protected]> Reviewed-by: Maxime Coquelin <[email protected]>
other
radare2
d4ce40b516ffd70cf2e9e36832d8de139117d522
1
static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) { D eprintf ("Dragons at 0x%x\n", off); ut64 size = r_buf_size (buf); if (off >= size) { return NULL; } size -= off; if (!size) { return NULL; } ut8 *b = malloc (size); if (!b) { return NULL; } int available = r_buf_read_at (buf, off, b, size); if (available != size) { eprintf ("Warning: r_buf_read_at failed\n"); return NULL; } #if 0 // after the list of sections, there's a bunch of unknown // data, brobably dwords, and then the same section list again // this function aims to parse it. 0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U.. n_segments ----. .--- how many sections ? 0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U.......... .---- how many symbols? 0xc7 0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................ 0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U.. 0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F.. 0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............ 0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................ 0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT.. 0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................ 0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA.. 0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................ 0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM.. 0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................ 0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED 0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i.. #endif // eprintf ("Dragon's magic:\n"); int magicCombo = 0; if (!memcmp ("\x1a\x2b\xb2\xa1", b, 4)) { // 0x130 ? magicCombo++; } if (!memcmp ("\x1a\x2b\xb2\xa1", b + 8, 4)) { magicCombo++; } if (magicCombo != 2) { // hack for C22F7494 available = r_buf_read_at (buf, off - 8, b, size); if (available != size) { eprintf ("Warning: r_buf_read_at failed\n"); return NULL; } if (!memcmp ("\x1a\x2b\xb2\xa1", b, 4)) { // 0x130 ? off -= 8; } else { eprintf ("0x%08x parsing error: invalid magic retry\n", off); } } D eprintf ("0x%08x magic OK\n", off); D { const int e0ss = r_read_le32 (b + 12); eprintf ("0x%08x eoss 0x%x\n", off + 12, e0ss); } free (b); return r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name); }
null
null
210,570
24542425389279788586551565536652509227
70
Fix oobread in symbols header parsing ##bin
other
linux
a7b2df76b42bdd026e3106cf2ba97db41345a177
1
int cx23888_ir_probe(struct cx23885_dev *dev) { struct cx23888_ir_state *state; struct v4l2_subdev *sd; struct v4l2_subdev_ir_parameters default_params; int ret; state = kzalloc(sizeof(struct cx23888_ir_state), GFP_KERNEL); if (state == NULL) return -ENOMEM; spin_lock_init(&state->rx_kfifo_lock); if (kfifo_alloc(&state->rx_kfifo, CX23888_IR_RX_KFIFO_SIZE, GFP_KERNEL)) return -ENOMEM; state->dev = dev; sd = &state->sd; v4l2_subdev_init(sd, &cx23888_ir_controller_ops); v4l2_set_subdevdata(sd, state); /* FIXME - fix the formatting of dev->v4l2_dev.name and use it */ snprintf(sd->name, sizeof(sd->name), "%s/888-ir", dev->name); sd->grp_id = CX23885_HW_888_IR; ret = v4l2_device_register_subdev(&dev->v4l2_dev, sd); if (ret == 0) { /* * Ensure no interrupts arrive from '888 specific conditions, * since we ignore them in this driver to have commonality with * similar IR controller cores. */ cx23888_ir_write4(dev, CX23888_IR_IRQEN_REG, 0); mutex_init(&state->rx_params_lock); default_params = default_rx_params; v4l2_subdev_call(sd, ir, rx_s_parameters, &default_params); mutex_init(&state->tx_params_lock); default_params = default_tx_params; v4l2_subdev_call(sd, ir, tx_s_parameters, &default_params); } else { kfifo_free(&state->rx_kfifo); } return ret; }
null
null
210,571
33168082100273919267709527716978692450
45
media: rc: prevent memory leak in cx23888_ir_probe In cx23888_ir_probe if kfifo_alloc fails the allocated memory for state should be released. Signed-off-by: Navid Emamdoost <[email protected]> Signed-off-by: Sean Young <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]>
other
vim
8d02ce1ed75d008c34a5c9aaa51b67cbb9d33baa
1
u_undo_end( int did_undo, // just did an undo int absolute) // used ":undo N" { char *msgstr; u_header_T *uhp; char_u msgbuf[80]; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_UNDO) && KeyTyped) foldOpenCursor(); #endif if (global_busy // no messages now, wait until global is finished || !messaging()) // 'lazyredraw' set, don't do messages now return; if (curbuf->b_ml.ml_flags & ML_EMPTY) --u_newcount; u_oldcount -= u_newcount; if (u_oldcount == -1) msgstr = N_("more line"); else if (u_oldcount < 0) msgstr = N_("more lines"); else if (u_oldcount == 1) msgstr = N_("line less"); else if (u_oldcount > 1) msgstr = N_("fewer lines"); else { u_oldcount = u_newcount; if (u_newcount == 1) msgstr = N_("change"); else msgstr = N_("changes"); } if (curbuf->b_u_curhead != NULL) { // For ":undo N" we prefer a "after #N" message. if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL) { uhp = curbuf->b_u_curhead->uh_next.ptr; did_undo = FALSE; } else if (did_undo) uhp = curbuf->b_u_curhead; else uhp = curbuf->b_u_curhead->uh_next.ptr; } else uhp = curbuf->b_u_newhead; if (uhp == NULL) *msgbuf = NUL; else add_time(msgbuf, sizeof(msgbuf), uhp->uh_time); #ifdef FEAT_CONCEAL { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == curbuf && wp->w_p_cole > 0) redraw_win_later(wp, NOT_VALID); } } #endif smsg_attr_keep(0, _("%ld %s; %s #%ld %s"), u_oldcount < 0 ? -u_oldcount : u_oldcount, _(msgstr), did_undo ? _("before") : _("after"), uhp == NULL ? 0L : uhp->uh_seq, msgbuf); }
null
null
210,619
242494549291499323425962437820517169187
78
patch 8.2.4217: illegal memory access when undo makes Visual area invalid Problem: Illegal memory access when undo makes Visual area invalid. Solution: Correct the Visual area after undo.
other
linux
1680939e9ecf7764fba8689cfb3429c2fe2bb23c
1
static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev) { struct virtproc_info *vrp = vdev->priv; struct virtio_rpmsg_channel *vch; struct rpmsg_device *rpdev_ctrl; int err = 0; vch = kzalloc(sizeof(*vch), GFP_KERNEL); if (!vch) return ERR_PTR(-ENOMEM); /* Link the channel to the vrp */ vch->vrp = vrp; /* Assign public information to the rpmsg_device */ rpdev_ctrl = &vch->rpdev; rpdev_ctrl->ops = &virtio_rpmsg_ops; rpdev_ctrl->dev.parent = &vrp->vdev->dev; rpdev_ctrl->dev.release = virtio_rpmsg_release_device; rpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev); err = rpmsg_ctrldev_register_device(rpdev_ctrl); if (err) { kfree(vch); return ERR_PTR(err); } return rpdev_ctrl; }
null
null
210,620
335658023613701687732052520719637347357
30
rpmsg: virtio: Fix possible double free in rpmsg_virtio_add_ctrl_dev() vch will be free in virtio_rpmsg_release_device() when rpmsg_ctrldev_register_device() fails. There is no need to call kfree() again. Fixes: c486682ae1e2 ("rpmsg: virtio: Register the rpmsg_char device") Signed-off-by: Hangyu Hua <[email protected]> Tested-by: Arnaud Pouliquen <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Mathieu Poirier <[email protected]>
other
linux
b2f37aead1b82a770c48b5d583f35ec22aabb61e
1
static void mkiss_close(struct tty_struct *tty) { struct mkiss *ax; write_lock_irq(&disc_data_lock); ax = tty->disc_data; tty->disc_data = NULL; write_unlock_irq(&disc_data_lock); if (!ax) return; /* * We have now ensured that nobody can start using ap from now on, but * we have to wait for all existing users to finish. */ if (!refcount_dec_and_test(&ax->refcnt)) wait_for_completion(&ax->dead); /* * Halt the transmit queue so that a new transmit cannot scribble * on our buffers */ netif_stop_queue(ax->dev); ax->tty = NULL; unregister_netdev(ax->dev); /* Free all AX25 frame buffers after unreg. */ kfree(ax->rbuff); kfree(ax->xbuff); free_netdev(ax->dev); }
null
null
210,636
311832995251136563250671423907114180999
34
hamradio: improve the incomplete fix to avoid NPD The previous commit 3e0588c291d6 ("hamradio: defer ax25 kfree after unregister_netdev") reorder the kfree operations and unregister_netdev operation to prevent UAF. This commit improves the previous one by also deferring the nullify of the ax->tty pointer. Otherwise, a NULL pointer dereference bug occurs. Partial of the stack trace is shown below. BUG: kernel NULL pointer dereference, address: 0000000000000538 RIP: 0010:ax_xmit+0x1f9/0x400 ... Call Trace: dev_hard_start_xmit+0xec/0x320 sch_direct_xmit+0xea/0x240 __qdisc_run+0x166/0x5c0 __dev_queue_xmit+0x2c7/0xaf0 ax25_std_establish_data_link+0x59/0x60 ax25_connect+0x3a0/0x500 ? security_socket_connect+0x2b/0x40 __sys_connect+0x96/0xc0 ? __hrtimer_init+0xc0/0xc0 ? common_nsleep+0x2e/0x50 ? switch_fpu_return+0x139/0x1a0 __x64_sys_connect+0x11/0x20 do_syscall_64+0x33/0x40 entry_SYSCALL_64_after_hwframe+0x44/0xa9 The crash point is shown as below static void ax_encaps(...) { ... set_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags); // ax->tty = NULL! ... } By placing the nullify action after the unregister_netdev, the ax->tty pointer won't be assigned as NULL net_device framework layer is well synchronized. Signed-off-by: Lin Ma <[email protected]> Signed-off-by: David S. Miller <[email protected]>
other
ImageMagick6
210474b2fac6a661bfa7ed563213920e93e76395
1
static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { LongPixelPacket shift; PixelPacket quantum_bits; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->matte == MagickFalse) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->matte=MagickTrue; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red > 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green > 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue > 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) { shift.opacity++; if (shift.opacity > 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f), &index,exception); SetPixelIndex(indexes+x,index); (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index, exception); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf), &index,exception); SetPixelIndex(indexes+(x++),index); p++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
null
null
210,669
122530564995758758331356823224815174971
974
Fix ultra rare but potential memory-leak
other
ImageMagick6
b268ce7a59440972f4476b9fd98104b6a836d971
1
static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { LongPixelPacket shift; PixelPacket quantum_bits; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " File_size in header: %u bytes",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if (bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->matte == MagickFalse) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->matte=MagickTrue; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red > 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green > 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue > 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) { shift.opacity++; if (shift.opacity > 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample > 32U) break; } quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0x0f), &index,exception); SetPixelIndex(indexes+x,index); (void) IsValidColormapIndex(image,(ssize_t) (*p & 0x0f),&index, exception); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { (void) IsValidColormapIndex(image,(ssize_t) ((*p >> 4) & 0xf), &index,exception); SetPixelIndex(indexes+(x++),index); p++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { (void) IsValidColormapIndex(image,(ssize_t) *p,&index,exception); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) { alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
null
null
210,692
189174082665805527300926335479072601407
978
https://github.com/ImageMagick/ImageMagick/issues/1337
other
squashfs-tools
79b5a555058eef4e1e7ff220c344d39f8cd09646
1
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_2 dirh; char buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer; long long start; int bytes; int dir_count, size; struct dir_ent *new_dir; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) EXIT_UNSQUASH("squashfs_opendir: malloc failed!\n"); dir->dir_count = 0; dir->cur_entry = 0; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 0) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; bytes = lookup_entry(directory_table_hash, start); if(bytes == -1) EXIT_UNSQUASH("squashfs_opendir: directory block %d not " "found!\n", block_start); bytes += (*i)->offset; size = (*i)->data + bytes; while(bytes < size) { if(swap) { squashfs_dir_header_2 sdirh; memcpy(&sdirh, directory_table + bytes, sizeof(sdirh)); SQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh); } else memcpy(&dirh, directory_table + bytes, sizeof(dirh)); dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_2 sdire; memcpy(&sdire, directory_table + bytes, sizeof(sdire)); SQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire); } else memcpy(dire, directory_table + bytes, sizeof(*dire)); bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } memcpy(dire->name, directory_table + bytes, dire->size + 1); dire->name[dire->size + 1] = '\0'; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if(new_dir == NULL) EXIT_UNSQUASH("squashfs_opendir: " "realloc failed!\n"); dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].start_block = dirh.start_block; dir->dirs[dir->dir_count].offset = dire->offset; dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: free(dir->dirs); free(dir); return NULL; }
null
null
210,700
293299768591891428521225727570486378743
116
Unsquashfs: fix write outside destination directory exploit An issue on Github (https://github.com/plougher/squashfs-tools/issues/72) shows how some specially crafted Squashfs filesystems containing invalid file names (with '/' and ..) can cause Unsquashfs to write files outside of the destination directory. This commit fixes this exploit by checking all names for validity. In doing so I have also added checks for '.' and for names that are shorter than they should be (names in the file system should not have '\0' terminators). Signed-off-by: Phillip Lougher <[email protected]>
other
squashfs-tools
79b5a555058eef4e1e7ff220c344d39f8cd09646
1
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_3 dirh; char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer; long long start; int bytes; int dir_count, size; struct dir_ent *new_dir; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) EXIT_UNSQUASH("squashfs_opendir: malloc failed!\n"); dir->dir_count = 0; dir->cur_entry = 0; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; bytes = lookup_entry(directory_table_hash, start); if(bytes == -1) EXIT_UNSQUASH("squashfs_opendir: directory block %d not " "found!\n", block_start); bytes += (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { if(swap) { squashfs_dir_header_3 sdirh; memcpy(&sdirh, directory_table + bytes, sizeof(sdirh)); SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh); } else memcpy(&dirh, directory_table + bytes, sizeof(dirh)); dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_3 sdire; memcpy(&sdire, directory_table + bytes, sizeof(sdire)); SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire); } else memcpy(dire, directory_table + bytes, sizeof(*dire)); bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } memcpy(dire->name, directory_table + bytes, dire->size + 1); dire->name[dire->size + 1] = '\0'; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if(new_dir == NULL) EXIT_UNSQUASH("squashfs_opendir: " "realloc failed!\n"); dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].start_block = dirh.start_block; dir->dirs[dir->dir_count].offset = dire->offset; dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: free(dir->dirs); free(dir); return NULL; }
null
null
210,701
84788405315542553885310338439631637350
117
Unsquashfs: fix write outside destination directory exploit An issue on Github (https://github.com/plougher/squashfs-tools/issues/72) shows how some specially crafted Squashfs filesystems containing invalid file names (with '/' and ..) can cause Unsquashfs to write files outside of the destination directory. This commit fixes this exploit by checking all names for validity. In doing so I have also added checks for '.' and for names that are shorter than they should be (names in the file system should not have '\0' terminators). Signed-off-by: Phillip Lougher <[email protected]>
other
squashfs-tools
79b5a555058eef4e1e7ff220c344d39f8cd09646
1
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { struct squashfs_dir_header dirh; char buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); struct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer; long long start; long long bytes; int dir_count, size; struct dir_ent *new_dir; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) EXIT_UNSQUASH("squashfs_opendir: malloc failed!\n"); dir->dir_count = 0; dir->cur_entry = 0; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; bytes = lookup_entry(directory_table_hash, start); if(bytes == -1) EXIT_UNSQUASH("squashfs_opendir: directory block %lld not " "found!\n", start); bytes += (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { SQUASHFS_SWAP_DIR_HEADER(directory_table + bytes, &dirh); dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { SQUASHFS_SWAP_DIR_ENTRY(directory_table + bytes, dire); bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } memcpy(dire->name, directory_table + bytes, dire->size + 1); dire->name[dire->size + 1] = '\0'; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if(new_dir == NULL) EXIT_UNSQUASH("squashfs_opendir: " "realloc failed!\n"); dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].start_block = dirh.start_block; dir->dirs[dir->dir_count].offset = dire->offset; dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: free(dir->dirs); free(dir); return NULL; }
null
null
210,702
310712408194917529486811680216130594590
106
Unsquashfs: fix write outside destination directory exploit An issue on Github (https://github.com/plougher/squashfs-tools/issues/72) shows how some specially crafted Squashfs filesystems containing invalid file names (with '/' and ..) can cause Unsquashfs to write files outside of the destination directory. This commit fixes this exploit by checking all names for validity. In doing so I have also added checks for '.' and for names that are shorter than they should be (names in the file system should not have '\0' terminators). Signed-off-by: Phillip Lougher <[email protected]>
other
php-src
630f9c33c23639de85c3fd306b209b538b73b4c9
1
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } zval_dtor(key); FREE_ZVAL(key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } return 1; }
null
null
210,762
65975281674857601116891561324473234749
62
Fix bug #68594 - Use after free vulnerability in unserialize()
other
vim
baefde14550231f6468ac2ed2ed495bc381c0c92
1
ins_compl_add( char_u *str, int len, char_u *fname, char_u **cptext, // extra text for popup menu or NULL typval_T *user_data UNUSED, // "user_data" entry or NULL int cdir, int flags_arg, int adup) // accept duplicate match { compl_T *match; int dir = (cdir == 0 ? compl_direction : cdir); int flags = flags_arg; if (flags & CP_FAST) fast_breakcheck(); else ui_breakcheck(); if (got_int) return FAIL; if (len < 0) len = (int)STRLEN(str); // If the same match is already present, don't add it. if (compl_first_match != NULL && !adup) { match = compl_first_match; do { if (!match_at_original_text(match) && STRNCMP(match->cp_str, str, len) == 0 && match->cp_str[len] == NUL) return NOTDONE; match = match->cp_next; } while (match != NULL && !is_first_match(match)); } // Remove any popup menu before changing the list of matches. ins_compl_del_pum(); // Allocate a new match structure. // Copy the values to the new match structure. match = ALLOC_CLEAR_ONE(compl_T); if (match == NULL) return FAIL; match->cp_number = -1; if (flags & CP_ORIGINAL_TEXT) match->cp_number = 0; if ((match->cp_str = vim_strnsave(str, len)) == NULL) { vim_free(match); return FAIL; } // match-fname is: // - compl_curr_match->cp_fname if it is a string equal to fname. // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem. // - NULL otherwise. --Acevedo if (fname != NULL && compl_curr_match != NULL && compl_curr_match->cp_fname != NULL && STRCMP(fname, compl_curr_match->cp_fname) == 0) match->cp_fname = compl_curr_match->cp_fname; else if (fname != NULL) { match->cp_fname = vim_strsave(fname); flags |= CP_FREE_FNAME; } else match->cp_fname = NULL; match->cp_flags = flags; if (cptext != NULL) { int i; for (i = 0; i < CPT_COUNT; ++i) if (cptext[i] != NULL && *cptext[i] != NUL) match->cp_text[i] = vim_strsave(cptext[i]); } #ifdef FEAT_EVAL if (user_data != NULL) match->cp_user_data = *user_data; #endif // Link the new match structure after (FORWARD) or before (BACKWARD) the // current match in the list of matches . if (compl_first_match == NULL) match->cp_next = match->cp_prev = NULL; else if (dir == FORWARD) { match->cp_next = compl_curr_match->cp_next; match->cp_prev = compl_curr_match; } else // BACKWARD { match->cp_next = compl_curr_match; match->cp_prev = compl_curr_match->cp_prev; } if (match->cp_next) match->cp_next->cp_prev = match; if (match->cp_prev) match->cp_prev->cp_next = match; else // if there's nothing before, it is the first match compl_first_match = match; compl_curr_match = match; // Find the longest common string if still doing that. if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0) ins_compl_longest_match(match); return OK; }
null
null
210,814
124913140477127526640235568896196720383
113
patch 9.0.0046: reading past end of completion with duplicate match Problem: Reading past end of completion with duplicate match. Solution: Check string length
other
xserver
da15c7413916f754708c62c2089265528cd661e2
1
LogFilePrep(const char *fname, const char *backup, const char *idstring) { char *logFileName = NULL; if (asprintf(&logFileName, fname, idstring) == -1) FatalError("Cannot allocate space for the log file name\n"); if (backup && *backup) { struct stat buf; if (!stat(logFileName, &buf) && S_ISREG(buf.st_mode)) { char *suffix; char *oldLog; if ((asprintf(&suffix, backup, idstring) == -1) || (asprintf(&oldLog, "%s%s", logFileName, suffix) == -1)) { FatalError("Cannot allocate space for the log file name\n"); } free(suffix); if (rename(logFileName, oldLog) == -1) { FatalError("Cannot move old log file \"%s\" to \"%s\"\n", logFileName, oldLog); } free(oldLog); } } else { if (remove(logFileName) != 0 && errno != ENOENT) { FatalError("Cannot remove old log file \"%s\": %s\n", logFileName, strerror(errno)); } } return logFileName; }
null
null
210,834
56456244053678581768053709472605633090
36
LogFilePrep: add a comment to the unsafe format string. CVE-2018-14665 also made it possible to exploit this to access memory. With -logfile forbidden when running with elevated privileges this is no longer an issue. Signed-off-by: Matthieu Herrb <[email protected]> Reviewed-by: Adam Jackson <[email protected]> (cherry picked from commit 248d164eae27f1f310266d78e52f13f64362f81e)
other
xserver
144849ea27230962227e62a943b399e2ab304787
1
SProcXkbSelectEvents(ClientPtr client) { REQUEST(xkbSelectEventsReq); swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq); swaps(&stuff->deviceSpec); swaps(&stuff->affectWhich); swaps(&stuff->clear); swaps(&stuff->selectAll); swaps(&stuff->affectMap); swaps(&stuff->map); if ((stuff->affectWhich & (~XkbMapNotifyMask)) != 0) { union { BOOL *b; CARD8 *c8; CARD16 *c16; CARD32 *c32; } from; register unsigned bit, ndx, maskLeft, dataLeft, size; from.c8 = (CARD8 *) &stuff[1]; dataLeft = (stuff->length * 4) - SIZEOF(xkbSelectEventsReq); maskLeft = (stuff->affectWhich & (~XkbMapNotifyMask)); for (ndx = 0, bit = 1; (maskLeft != 0); ndx++, bit <<= 1) { if (((bit & maskLeft) == 0) || (ndx == XkbMapNotify)) continue; maskLeft &= ~bit; if ((stuff->selectAll & bit) || (stuff->clear & bit)) continue; switch (ndx) { case XkbNewKeyboardNotify: case XkbStateNotify: case XkbNamesNotify: case XkbAccessXNotify: case XkbExtensionDeviceNotify: size = 2; break; case XkbControlsNotify: case XkbIndicatorStateNotify: case XkbIndicatorMapNotify: size = 4; break; case XkbBellNotify: case XkbActionMessage: case XkbCompatMapNotify: size = 1; break; default: client->errorValue = _XkbErrCode2(0x1, bit); return BadValue; } if (dataLeft < (size * 2)) return BadLength; if (size == 2) { swaps(&from.c16[0]); swaps(&from.c16[1]); } else if (size == 4) { swapl(&from.c32[0]); swapl(&from.c32[1]); } else { size = 2; } from.c8 += (size * 2); dataLeft -= (size * 2); } if (dataLeft > 2) { ErrorF("[xkb] Extra data (%d bytes) after SelectEvents\n", dataLeft); return BadLength; } } return ProcXkbSelectEvents(client); }
null
null
210,866
194230322423455889604876083163878294077
76
Fix XkbSelectEvents() integer underflow CVE-2020-14361 ZDI-CAN 11573 This vulnerability was discovered by: Jan-Niklas Sohn working with Trend Micro Zero Day Initiative Signed-off-by: Matthieu Herrb <[email protected]>
other
qemu
1caff0340f49c93d535c6558a5138d20d475315c
1
e1000_send_packet(E1000State *s, const uint8_t *buf, int size) { static const int PTCregs[6] = { PTC64, PTC127, PTC255, PTC511, PTC1023, PTC1522 }; NetClientState *nc = qemu_get_queue(s->nic); if (s->phy_reg[PHY_CTRL] & MII_CR_LOOPBACK) { nc->info->receive(nc, buf, size); } else { qemu_send_packet(nc, buf, size); } inc_tx_bcast_or_mcast_count(s, buf); e1000x_increase_size_stats(s->mac_reg, PTCregs, size); }
null
null
210,887
217225372257001861692199094880241428891
14
e1000: switch to use qemu_receive_packet() for loopback This patch switches to use qemu_receive_packet() which can detect reentrancy and return early. This is intended to address CVE-2021-3416. Cc: Prasad J Pandit <[email protected]> Cc: [email protected] Reviewed-by: Philippe Mathieu-Daudé <[email protected]> Signed-off-by: Jason Wang <[email protected]>
other
spice
a4a16ac42d2f19a17e36556546aa94d5cd83745f
1
void *memslot_get_virt(RedMemSlotInfo *info, QXLPHYSICAL addr, uint32_t add_size, int group_id) { int slot_id; int generation; unsigned long h_virt; MemSlot *slot; if (group_id > info->num_memslots_groups) { spice_critical("group_id too big"); return NULL; } slot_id = memslot_get_id(info, addr); if (slot_id > info->num_memslots) { print_memslots(info); spice_critical("slot_id %d too big, addr=%" PRIx64, slot_id, addr); return NULL; } slot = &info->mem_slots[group_id][slot_id]; generation = memslot_get_generation(info, addr); if (generation != slot->generation) { print_memslots(info); spice_critical("address generation is not valid, group_id %d, slot_id %d, " "gen %d, slot_gen %d", group_id, slot_id, generation, slot->generation); return NULL; } h_virt = __get_clean_virt(info, addr); h_virt += slot->address_delta; if (!memslot_validate_virt(info, h_virt, slot_id, add_size, group_id)) { return NULL; } return (void*)(uintptr_t)h_virt; }
null
null
210,896
22732492738183493974471155318046714999
42
memslot: Fix off-by-one error in group/slot boundary check RedMemSlotInfo keeps an array of groups, and each group contains an array of slots. Unfortunately, these checks are off by 1, they check that the index is greater or equal to the number of elements in the array, while these arrays are 0 based. The check should only check for strictly greater than the number of elements. For the group array, this is not a big issue, as these memslot groups are created by spice-server users (eg QEMU), and the group ids used to index that array are also generated by the spice-server user, so it should not be possible for the guest to set them to arbitrary values. The slot id is more problematic, as it's calculated from a QXLPHYSICAL address, and such addresses are usually set by the guest QXL driver, so the guest can set these to arbitrary values, including malicious values, which are probably easy to build from the guest PCI configuration. This patch fixes the arrays bound check, and adds a test case for this. This fixes CVE-2019-3813. Signed-off-by: Christophe Fergeau <[email protected]> Acked-by: Frediano Ziglio <[email protected]>
other
curl
70b1900dd13d16f2e83f571407a614541d5ac9ba
1
static void warnf(struct Configurable *config, const char *fmt, ...) { if(!(config->conf & CONF_MUTE)) { va_list ap; int len; char *ptr; char print_buffer[256]; va_start(ap, fmt); va_start(ap, fmt); len = vsnprintf(print_buffer, sizeof(print_buffer), fmt, ap); va_end(ap); ptr = print_buffer; while(len > 0) { fputs(WARN_PREFIX, config->errors); if(len > (int)WARN_TEXTWIDTH) { int cut = WARN_TEXTWIDTH-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } fwrite(ptr, cut + 1, 1, config->errors); fputs("\n", config->errors); ptr += cut+1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } } }
null
null
210,904
323844165589095153020492698584769188446
36
'mytx' in bug report #1723194 (http://curl.haxx.se/bug/view.cgi?id=1723194) pointed out that the warnf() function in the curl tool didn't properly deal with the cases when excessively long words were used in the string to chop up.
other
vim
de05bb25733c3319e18dca44e9b59c6ee389eb26
1
win_redr_status(win_T *wp, int ignore_pum UNUSED) { int row; char_u *p; int len; int fillchar; int attr; int this_ru_col; static int busy = FALSE; // It's possible to get here recursively when 'statusline' (indirectly) // invokes ":redrawstatus". Simply ignore the call then. if (busy) return; busy = TRUE; row = statusline_row(wp); wp->w_redr_status = FALSE; if (wp->w_status_height == 0) { // no status line, can only be last window redraw_cmdline = TRUE; } else if (!redrawing() // don't update status line when popup menu is visible and may be // drawn over it, unless it will be redrawn later || (!ignore_pum && pum_visible())) { // Don't redraw right now, do it later. wp->w_redr_status = TRUE; } #ifdef FEAT_STL_OPT else if (*p_stl != NUL || *wp->w_p_stl != NUL) { // redraw custom status line redraw_custom_statusline(wp); } #endif else { fillchar = fillchar_status(&attr, wp); get_trans_bufname(wp->w_buffer); p = NameBuff; len = (int)STRLEN(p); if (bt_help(wp->w_buffer) #ifdef FEAT_QUICKFIX || wp->w_p_pvw #endif || bufIsChanged(wp->w_buffer) || wp->w_buffer->b_p_ro) *(p + len++) = ' '; if (bt_help(wp->w_buffer)) { vim_snprintf((char *)p + len, MAXPATHL - len, "%s", _("[Help]")); len += (int)STRLEN(p + len); } #ifdef FEAT_QUICKFIX if (wp->w_p_pvw) { vim_snprintf((char *)p + len, MAXPATHL - len, "%s", _("[Preview]")); len += (int)STRLEN(p + len); } #endif if (bufIsChanged(wp->w_buffer) #ifdef FEAT_TERMINAL && !bt_terminal(wp->w_buffer) #endif ) { vim_snprintf((char *)p + len, MAXPATHL - len, "%s", "[+]"); len += (int)STRLEN(p + len); } if (wp->w_buffer->b_p_ro) { vim_snprintf((char *)p + len, MAXPATHL - len, "%s", _("[RO]")); len += (int)STRLEN(p + len); } this_ru_col = ru_col - (Columns - wp->w_width); if (this_ru_col < (wp->w_width + 1) / 2) this_ru_col = (wp->w_width + 1) / 2; if (this_ru_col <= 1) { p = (char_u *)"<"; // No room for file name! len = 1; } else if (has_mbyte) { int clen = 0, i; // Count total number of display cells. clen = mb_string2cells(p, -1); // Find first character that will fit. // Going from start to end is much faster for DBCS. for (i = 0; p[i] != NUL && clen >= this_ru_col - 1; i += (*mb_ptr2len)(p + i)) clen -= (*mb_ptr2cells)(p + i); len = clen; if (i > 0) { p = p + i - 1; *p = '<'; ++len; } } else if (len > this_ru_col - 1) { p += len - (this_ru_col - 1); *p = '<'; len = this_ru_col - 1; } screen_puts(p, row, wp->w_wincol, attr); screen_fill(row, row + 1, len + wp->w_wincol, this_ru_col + wp->w_wincol, fillchar, fillchar, attr); if (get_keymap_str(wp, (char_u *)"<%s>", NameBuff, MAXPATHL) && (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1)) screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff) - 1 + wp->w_wincol), attr); #ifdef FEAT_CMDL_INFO win_redr_ruler(wp, TRUE, ignore_pum); #endif } /* * May need to draw the character below the vertical separator. */ if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing()) { if (stl_connected(wp)) fillchar = fillchar_status(&attr, wp); else fillchar = fillchar_vsep(&attr); screen_putchar(fillchar, row, W_ENDCOL(wp), attr); } busy = FALSE; }
null
null
210,910
331009826509289756713716014178894780155
144
patch 8.2.4074: going over the end of NameBuff Problem: Going over the end of NameBuff. Solution: Check length when appending a space.
other
linux
a53046291020ec41e09181396c1e829287b48d47
1
void jfs_evict_inode(struct inode *inode) { struct jfs_inode_info *ji = JFS_IP(inode); jfs_info("In jfs_evict_inode, inode = 0x%p", inode); if (!inode->i_nlink && !is_bad_inode(inode)) { dquot_initialize(inode); if (JFS_IP(inode)->fileset == FILESYSTEM_I) { truncate_inode_pages_final(&inode->i_data); if (test_cflag(COMMIT_Freewmap, inode)) jfs_free_zero_link(inode); if (JFS_SBI(inode->i_sb)->ipimap) diFree(inode); /* * Free the inode from the quota allocation. */ dquot_free_inode(inode); } } else { truncate_inode_pages_final(&inode->i_data); } clear_inode(inode); dquot_drop(inode); BUG_ON(!list_empty(&ji->anon_inode_list)); spin_lock_irq(&ji->ag_lock); if (ji->active_ag != -1) { struct bmap *bmap = JFS_SBI(inode->i_sb)->bmap; atomic_dec(&bmap->db_active[ji->active_ag]); ji->active_ag = -1; } spin_unlock_irq(&ji->ag_lock); }
null
null
210,928
213539838542964788210455971336605042309
39
jfs: prevent NULL deref in diFree Add validation check for JFS_IP(ipimap)->i_imap to prevent a NULL deref in diFree since diFree uses it without do any validations. When function jfs_mount calls diMount to initialize fileset inode allocation map, it can fail and JFS_IP(ipimap)->i_imap won't be initialized. Then it calls diFreeSpecial to close fileset inode allocation map inode and it will flow into jfs_evict_inode. Function jfs_evict_inode just validates JFS_SBI(inode->i_sb)->ipimap, then calls diFree. diFree use JFS_IP(ipimap)->i_imap directly, then it will cause a NULL deref. Reported-by: TCS Robot <[email protected]> Signed-off-by: Haimin Zhang <[email protected]> Signed-off-by: Dave Kleikamp <[email protected]>
other
vim
35d21c6830fc2d68aca838424a0e786821c5891c
1
do_cmdline( char_u *cmdline, char_u *(*fgetline)(int, void *, int, getline_opt_T), void *cookie, // argument for fgetline() int flags) { char_u *next_cmdline; // next cmd to execute char_u *cmdline_copy = NULL; // copy of cmd line int used_getline = FALSE; // used "fgetline" to obtain command static int recursive = 0; // recursive depth int msg_didout_before_start = 0; int count = 0; // line number count int did_inc = FALSE; // incremented RedrawingDisabled int retval = OK; #ifdef FEAT_EVAL cstack_T cstack; // conditional stack garray_T lines_ga; // keep lines for ":while"/":for" int current_line = 0; // active line in lines_ga int current_line_before = 0; char_u *fname = NULL; // function or script name linenr_T *breakpoint = NULL; // ptr to breakpoint field in cookie int *dbg_tick = NULL; // ptr to dbg_tick field in cookie struct dbg_stuff debug_saved; // saved things for debug mode int initial_trylevel; msglist_T **saved_msg_list = NULL; msglist_T *private_msg_list = NULL; // "fgetline" and "cookie" passed to do_one_cmd() char_u *(*cmd_getline)(int, void *, int, getline_opt_T); void *cmd_cookie; struct loop_cookie cmd_loop_cookie; void *real_cookie; int getline_is_func; #else # define cmd_getline fgetline # define cmd_cookie cookie #endif static int call_depth = 0; // recursiveness #ifdef FEAT_EVAL // For every pair of do_cmdline()/do_one_cmd() calls, use an extra memory // location for storing error messages to be converted to an exception. // This ensures that the do_errthrow() call in do_one_cmd() does not // combine the messages stored by an earlier invocation of do_one_cmd() // with the command name of the later one. This would happen when // BufWritePost autocommands are executed after a write error. saved_msg_list = msg_list; msg_list = &private_msg_list; #endif // It's possible to create an endless loop with ":execute", catch that // here. The value of 200 allows nested function calls, ":source", etc. // Allow 200 or 'maxfuncdepth', whatever is larger. if (call_depth >= 200 #ifdef FEAT_EVAL && call_depth >= p_mfd #endif ) { emsg(_(e_command_too_recursive)); #ifdef FEAT_EVAL // When converting to an exception, we do not include the command name // since this is not an error of the specific command. do_errthrow((cstack_T *)NULL, (char_u *)NULL); msg_list = saved_msg_list; #endif return FAIL; } ++call_depth; #ifdef FEAT_EVAL CLEAR_FIELD(cstack); cstack.cs_idx = -1; ga_init2(&lines_ga, sizeof(wcmd_T), 10); real_cookie = getline_cookie(fgetline, cookie); // Inside a function use a higher nesting level. getline_is_func = getline_equal(fgetline, cookie, get_func_line); if (getline_is_func && ex_nesting_level == func_level(real_cookie)) ++ex_nesting_level; // Get the function or script name and the address where the next breakpoint // line and the debug tick for a function or script are stored. if (getline_is_func) { fname = func_name(real_cookie); breakpoint = func_breakpoint(real_cookie); dbg_tick = func_dbg_tick(real_cookie); } else if (getline_equal(fgetline, cookie, getsourceline)) { fname = SOURCING_NAME; breakpoint = source_breakpoint(real_cookie); dbg_tick = source_dbg_tick(real_cookie); } /* * Initialize "force_abort" and "suppress_errthrow" at the top level. */ if (!recursive) { force_abort = FALSE; suppress_errthrow = FALSE; } /* * If requested, store and reset the global values controlling the * exception handling (used when debugging). Otherwise clear it to avoid * a bogus compiler warning when the optimizer uses inline functions... */ if (flags & DOCMD_EXCRESET) save_dbg_stuff(&debug_saved); else CLEAR_FIELD(debug_saved); initial_trylevel = trylevel; /* * "did_throw" will be set to TRUE when an exception is being thrown. */ did_throw = FALSE; #endif /* * "did_emsg" will be set to TRUE when emsg() is used, in which case we * cancel the whole command line, and any if/endif or loop. * If force_abort is set, we cancel everything. */ #ifdef FEAT_EVAL did_emsg_cumul += did_emsg; #endif did_emsg = FALSE; /* * KeyTyped is only set when calling vgetc(). Reset it here when not * calling vgetc() (sourced command lines). */ if (!(flags & DOCMD_KEYTYPED) && !getline_equal(fgetline, cookie, getexline)) KeyTyped = FALSE; /* * Continue executing command lines: * - when inside an ":if", ":while" or ":for" * - for multiple commands on one line, separated with '|' * - when repeating until there are no more lines (for ":source") */ next_cmdline = cmdline; do { #ifdef FEAT_EVAL getline_is_func = getline_equal(fgetline, cookie, get_func_line); #endif // stop skipping cmds for an error msg after all endif/while/for if (next_cmdline == NULL #ifdef FEAT_EVAL && !force_abort && cstack.cs_idx < 0 && !(getline_is_func && func_has_abort(real_cookie)) #endif ) { #ifdef FEAT_EVAL did_emsg_cumul += did_emsg; #endif did_emsg = FALSE; } /* * 1. If repeating a line in a loop, get a line from lines_ga. * 2. If no line given: Get an allocated line with fgetline(). * 3. If a line is given: Make a copy, so we can mess with it. */ #ifdef FEAT_EVAL // 1. If repeating, get a previous line from lines_ga. if (cstack.cs_looplevel > 0 && current_line < lines_ga.ga_len) { // Each '|' separated command is stored separately in lines_ga, to // be able to jump to it. Don't use next_cmdline now. VIM_CLEAR(cmdline_copy); // Check if a function has returned or, unless it has an unclosed // try conditional, aborted. if (getline_is_func) { # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(real_cookie); # endif if (func_has_ended(real_cookie)) { retval = FAIL; break; } } #ifdef FEAT_PROFILE else if (do_profiling == PROF_YES && getline_equal(fgetline, cookie, getsourceline)) script_line_end(); #endif // Check if a sourced file hit a ":finish" command. if (source_finished(fgetline, cookie)) { retval = FAIL; break; } // If breakpoints have been added/deleted need to check for it. if (breakpoint != NULL && dbg_tick != NULL && *dbg_tick != debug_tick) { *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, SOURCING_LNUM); *dbg_tick = debug_tick; } next_cmdline = ((wcmd_T *)(lines_ga.ga_data))[current_line].line; SOURCING_LNUM = ((wcmd_T *)(lines_ga.ga_data))[current_line].lnum; // Did we encounter a breakpoint? if (breakpoint != NULL && *breakpoint != 0 && *breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fname, SOURCING_LNUM); // Find next breakpoint. *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, SOURCING_LNUM); *dbg_tick = debug_tick; } # ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { if (getline_is_func) func_line_start(real_cookie, SOURCING_LNUM); else if (getline_equal(fgetline, cookie, getsourceline)) script_line_start(); } # endif } #endif // 2. If no line given, get an allocated line with fgetline(). if (next_cmdline == NULL) { /* * Need to set msg_didout for the first line after an ":if", * otherwise the ":if" will be overwritten. */ if (count == 1 && getline_equal(fgetline, cookie, getexline)) msg_didout = TRUE; if (fgetline == NULL || (next_cmdline = fgetline(':', cookie, #ifdef FEAT_EVAL cstack.cs_idx < 0 ? 0 : (cstack.cs_idx + 1) * 2 #else 0 #endif , in_vim9script() ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT)) == NULL) { // Don't call wait_return() for aborted command line. The NULL // returned for the end of a sourced file or executed function // doesn't do this. if (KeyTyped && !(flags & DOCMD_REPEAT)) need_wait_return = FALSE; retval = FAIL; break; } used_getline = TRUE; /* * Keep the first typed line. Clear it when more lines are typed. */ if (flags & DOCMD_KEEPLINE) { vim_free(repeat_cmdline); if (count == 0) repeat_cmdline = vim_strsave(next_cmdline); else repeat_cmdline = NULL; } } // 3. Make a copy of the command so we can mess with it. else if (cmdline_copy == NULL) { next_cmdline = vim_strsave(next_cmdline); if (next_cmdline == NULL) { emsg(_(e_out_of_memory)); retval = FAIL; break; } } cmdline_copy = next_cmdline; #ifdef FEAT_EVAL /* * Inside a while/for loop, and when the command looks like a ":while" * or ":for", the line is stored, because we may need it later when * looping. * * When there is a '|' and another command, it is stored separately, * because we need to be able to jump back to it from an * :endwhile/:endfor. * * Pass a different "fgetline" function to do_one_cmd() below, * that it stores lines in or reads them from "lines_ga". Makes it * possible to define a function inside a while/for loop and handles * line continuation. */ if ((cstack.cs_looplevel > 0 || has_loop_cmd(next_cmdline))) { cmd_getline = get_loop_line; cmd_cookie = (void *)&cmd_loop_cookie; cmd_loop_cookie.lines_gap = &lines_ga; cmd_loop_cookie.current_line = current_line; cmd_loop_cookie.getline = fgetline; cmd_loop_cookie.cookie = cookie; cmd_loop_cookie.repeating = (current_line < lines_ga.ga_len); // Save the current line when encountering it the first time. if (current_line == lines_ga.ga_len && store_loop_line(&lines_ga, next_cmdline) == FAIL) { retval = FAIL; break; } current_line_before = current_line; } else { cmd_getline = fgetline; cmd_cookie = cookie; } did_endif = FALSE; #endif if (count++ == 0) { /* * All output from the commands is put below each other, without * waiting for a return. Don't do this when executing commands * from a script or when being called recursive (e.g. for ":e * +command file"). */ if (!(flags & DOCMD_NOWAIT) && !recursive) { msg_didout_before_start = msg_didout; msg_didany = FALSE; // no output yet msg_start(); msg_scroll = TRUE; // put messages below each other ++no_wait_return; // don't wait for return until finished ++RedrawingDisabled; did_inc = TRUE; } } if ((p_verbose >= 15 && SOURCING_NAME != NULL) || p_verbose >= 16) msg_verbose_cmd(SOURCING_LNUM, cmdline_copy); /* * 2. Execute one '|' separated command. * do_one_cmd() will return NULL if there is no trailing '|'. * "cmdline_copy" can change, e.g. for '%' and '#' expansion. */ ++recursive; next_cmdline = do_one_cmd(&cmdline_copy, flags, #ifdef FEAT_EVAL &cstack, #endif cmd_getline, cmd_cookie); --recursive; #ifdef FEAT_EVAL if (cmd_cookie == (void *)&cmd_loop_cookie) // Use "current_line" from "cmd_loop_cookie", it may have been // incremented when defining a function. current_line = cmd_loop_cookie.current_line; #endif if (next_cmdline == NULL) { VIM_CLEAR(cmdline_copy); /* * If the command was typed, remember it for the ':' register. * Do this AFTER executing the command to make :@: work. */ if (getline_equal(fgetline, cookie, getexline) && new_last_cmdline != NULL) { vim_free(last_cmdline); last_cmdline = new_last_cmdline; new_last_cmdline = NULL; } } else { // need to copy the command after the '|' to cmdline_copy, for the // next do_one_cmd() STRMOVE(cmdline_copy, next_cmdline); next_cmdline = cmdline_copy; } #ifdef FEAT_EVAL // reset did_emsg for a function that is not aborted by an error if (did_emsg && !force_abort && getline_equal(fgetline, cookie, get_func_line) && !func_has_abort(real_cookie)) { // did_emsg_cumul is not set here did_emsg = FALSE; } if (cstack.cs_looplevel > 0) { ++current_line; /* * An ":endwhile", ":endfor" and ":continue" is handled here. * If we were executing commands, jump back to the ":while" or * ":for". * If we were not executing commands, decrement cs_looplevel. */ if (cstack.cs_lflags & (CSL_HAD_CONT | CSL_HAD_ENDLOOP)) { cstack.cs_lflags &= ~(CSL_HAD_CONT | CSL_HAD_ENDLOOP); // Jump back to the matching ":while" or ":for". Be careful // not to use a cs_line[] from an entry that isn't a ":while" // or ":for": It would make "current_line" invalid and can // cause a crash. if (!did_emsg && !got_int && !did_throw && cstack.cs_idx >= 0 && (cstack.cs_flags[cstack.cs_idx] & (CSF_WHILE | CSF_FOR)) && cstack.cs_line[cstack.cs_idx] >= 0 && (cstack.cs_flags[cstack.cs_idx] & CSF_ACTIVE)) { current_line = cstack.cs_line[cstack.cs_idx]; // remember we jumped there cstack.cs_lflags |= CSL_HAD_LOOP; line_breakcheck(); // check if CTRL-C typed // Check for the next breakpoint at or after the ":while" // or ":for". if (breakpoint != NULL) { *breakpoint = dbg_find_breakpoint( getline_equal(fgetline, cookie, getsourceline), fname, ((wcmd_T *)lines_ga.ga_data)[current_line].lnum-1); *dbg_tick = debug_tick; } } else { // can only get here with ":endwhile" or ":endfor" if (cstack.cs_idx >= 0) rewind_conditionals(&cstack, cstack.cs_idx - 1, CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); } } /* * For a ":while" or ":for" we need to remember the line number. */ else if (cstack.cs_lflags & CSL_HAD_LOOP) { cstack.cs_lflags &= ~CSL_HAD_LOOP; cstack.cs_line[cstack.cs_idx] = current_line_before; } } // Check for the next breakpoint after a watchexpression if (breakpoint != NULL && has_watchexpr()) { *breakpoint = dbg_find_breakpoint(FALSE, fname, SOURCING_LNUM); *dbg_tick = debug_tick; } /* * When not inside any ":while" loop, clear remembered lines. */ if (cstack.cs_looplevel == 0) { if (lines_ga.ga_len > 0) { SOURCING_LNUM = ((wcmd_T *)lines_ga.ga_data)[lines_ga.ga_len - 1].lnum; free_cmdlines(&lines_ga); } current_line = 0; } /* * A ":finally" makes did_emsg, got_int, and did_throw pending for * being restored at the ":endtry". Reset them here and set the * ACTIVE and FINALLY flags, so that the finally clause gets executed. * This includes the case where a missing ":endif", ":endwhile" or * ":endfor" was detected by the ":finally" itself. */ if (cstack.cs_lflags & CSL_HAD_FINA) { cstack.cs_lflags &= ~CSL_HAD_FINA; report_make_pending(cstack.cs_pending[cstack.cs_idx] & (CSTP_ERROR | CSTP_INTERRUPT | CSTP_THROW), did_throw ? (void *)current_exception : NULL); did_emsg = got_int = did_throw = FALSE; cstack.cs_flags[cstack.cs_idx] |= CSF_ACTIVE | CSF_FINALLY; } // Update global "trylevel" for recursive calls to do_cmdline() from // within this loop. trylevel = initial_trylevel + cstack.cs_trylevel; /* * If the outermost try conditional (across function calls and sourced * files) is aborted because of an error, an interrupt, or an uncaught * exception, cancel everything. If it is left normally, reset * force_abort to get the non-EH compatible abortion behavior for * the rest of the script. */ if (trylevel == 0 && !did_emsg && !got_int && !did_throw) force_abort = FALSE; // Convert an interrupt to an exception if appropriate. (void)do_intthrow(&cstack); #endif // FEAT_EVAL } /* * Continue executing command lines when: * - no CTRL-C typed, no aborting error, no exception thrown or try * conditionals need to be checked for executing finally clauses or * catching an interrupt exception * - didn't get an error message or lines are not typed * - there is a command after '|', inside a :if, :while, :for or :try, or * looping for ":source" command or function call. */ while (!((got_int #ifdef FEAT_EVAL || (did_emsg && (force_abort || in_vim9script())) || did_throw #endif ) #ifdef FEAT_EVAL && cstack.cs_trylevel == 0 #endif ) && !(did_emsg #ifdef FEAT_EVAL // Keep going when inside try/catch, so that the error can be // deal with, except when it is a syntax error, it may cause // the :endtry to be missed. && (cstack.cs_trylevel == 0 || did_emsg_syntax) #endif && used_getline && (getline_equal(fgetline, cookie, getexmodeline) || getline_equal(fgetline, cookie, getexline))) && (next_cmdline != NULL #ifdef FEAT_EVAL || cstack.cs_idx >= 0 #endif || (flags & DOCMD_REPEAT))); vim_free(cmdline_copy); did_emsg_syntax = FALSE; #ifdef FEAT_EVAL free_cmdlines(&lines_ga); ga_clear(&lines_ga); if (cstack.cs_idx >= 0) { /* * If a sourced file or executed function ran to its end, report the * unclosed conditional. * In Vim9 script do not give a second error, executing aborts after * the first one. */ if (!got_int && !did_throw && !aborting() && !(did_emsg && in_vim9script()) && ((getline_equal(fgetline, cookie, getsourceline) && !source_finished(fgetline, cookie)) || (getline_equal(fgetline, cookie, get_func_line) && !func_has_ended(real_cookie)))) { if (cstack.cs_flags[cstack.cs_idx] & CSF_TRY) emsg(_(e_missing_endtry)); else if (cstack.cs_flags[cstack.cs_idx] & CSF_WHILE) emsg(_(e_missing_endwhile)); else if (cstack.cs_flags[cstack.cs_idx] & CSF_FOR) emsg(_(e_missing_endfor)); else emsg(_(e_missing_endif)); } /* * Reset "trylevel" in case of a ":finish" or ":return" or a missing * ":endtry" in a sourced file or executed function. If the try * conditional is in its finally clause, ignore anything pending. * If it is in a catch clause, finish the caught exception. * Also cleanup any "cs_forinfo" structures. */ do { int idx = cleanup_conditionals(&cstack, 0, TRUE); if (idx >= 0) --idx; // remove try block not in its finally clause rewind_conditionals(&cstack, idx, CSF_WHILE | CSF_FOR, &cstack.cs_looplevel); } while (cstack.cs_idx >= 0); trylevel = initial_trylevel; } // If a missing ":endtry", ":endwhile", ":endfor", or ":endif" or a memory // lack was reported above and the error message is to be converted to an // exception, do this now after rewinding the cstack. do_errthrow(&cstack, getline_equal(fgetline, cookie, get_func_line) ? (char_u *)"endfunction" : (char_u *)NULL); if (trylevel == 0) { // Just in case did_throw got set but current_exception wasn't. if (current_exception == NULL) did_throw = FALSE; /* * When an exception is being thrown out of the outermost try * conditional, discard the uncaught exception, disable the conversion * of interrupts or errors to exceptions, and ensure that no more * commands are executed. */ if (did_throw) handle_did_throw(); /* * On an interrupt or an aborting error not converted to an exception, * disable the conversion of errors to exceptions. (Interrupts are not * converted anymore, here.) This enables also the interrupt message * when force_abort is set and did_emsg unset in case of an interrupt * from a finally clause after an error. */ else if (got_int || (did_emsg && force_abort)) suppress_errthrow = TRUE; } /* * The current cstack will be freed when do_cmdline() returns. An uncaught * exception will have to be rethrown in the previous cstack. If a function * has just returned or a script file was just finished and the previous * cstack belongs to the same function or, respectively, script file, it * will have to be checked for finally clauses to be executed due to the * ":return" or ":finish". This is done in do_one_cmd(). */ if (did_throw) need_rethrow = TRUE; if ((getline_equal(fgetline, cookie, getsourceline) && ex_nesting_level > source_level(real_cookie)) || (getline_equal(fgetline, cookie, get_func_line) && ex_nesting_level > func_level(real_cookie) + 1)) { if (!did_throw) check_cstack = TRUE; } else { // When leaving a function, reduce nesting level. if (getline_equal(fgetline, cookie, get_func_line)) --ex_nesting_level; /* * Go to debug mode when returning from a function in which we are * single-stepping. */ if ((getline_equal(fgetline, cookie, getsourceline) || getline_equal(fgetline, cookie, get_func_line)) && ex_nesting_level + 1 <= debug_break_level) do_debug(getline_equal(fgetline, cookie, getsourceline) ? (char_u *)_("End of sourced file") : (char_u *)_("End of function")); } /* * Restore the exception environment (done after returning from the * debugger). */ if (flags & DOCMD_EXCRESET) restore_dbg_stuff(&debug_saved); msg_list = saved_msg_list; // Cleanup if "cs_emsg_silent_list" remains. if (cstack.cs_emsg_silent_list != NULL) { eslist_T *elem, *temp; for (elem = cstack.cs_emsg_silent_list; elem != NULL; elem = temp) { temp = elem->next; vim_free(elem); } } #endif // FEAT_EVAL /* * If there was too much output to fit on the command line, ask the user to * hit return before redrawing the screen. With the ":global" command we do * this only once after the command is finished. */ if (did_inc) { --RedrawingDisabled; --no_wait_return; msg_scroll = FALSE; /* * When just finished an ":if"-":else" which was typed, no need to * wait for hit-return. Also for an error situation. */ if (retval == FAIL #ifdef FEAT_EVAL || (did_endif && KeyTyped && !did_emsg) #endif ) { need_wait_return = FALSE; msg_didany = FALSE; // don't wait when restarting edit } else if (need_wait_return) { /* * The msg_start() above clears msg_didout. The wait_return() we do * here should not overwrite the command that may be shown before * doing that. */ msg_didout |= msg_didout_before_start; wait_return(FALSE); } } #ifdef FEAT_EVAL did_endif = FALSE; // in case do_cmdline used recursively #else /* * Reset if_level, in case a sourced script file contains more ":if" than * ":endif" (could be ":if x | foo | endif"). */ if_level = 0; #endif --call_depth; return retval; }
null
null
210,944
202802206003074497779105527029274291027
761
patch 9.0.0360: crash when invalid line number on :for is ignored Problem: Crash when invalid line number on :for is ignored. Solution: Do not check breakpoint for non-existing line.
other
linux
fecf31ee395b0295f2d7260aa29946b7605f7c85
1
static int nft_set_desc_concat_parse(const struct nlattr *attr, struct nft_set_desc *desc) { struct nlattr *tb[NFTA_SET_FIELD_MAX + 1]; u32 len; int err; err = nla_parse_nested_deprecated(tb, NFTA_SET_FIELD_MAX, attr, nft_concat_policy, NULL); if (err < 0) return err; if (!tb[NFTA_SET_FIELD_LEN]) return -EINVAL; len = ntohl(nla_get_be32(tb[NFTA_SET_FIELD_LEN])); if (len * BITS_PER_BYTE / 32 > NFT_REG32_COUNT) return -E2BIG; desc->field_len[desc->field_count++] = len; return 0; }
null
null
210,961
256651510499433454905782371638059194994
24
netfilter: nf_tables: sanitize nft_set_desc_concat_parse() Add several sanity checks for nft_set_desc_concat_parse(): - validate desc->field_count not larger than desc->field_len array. - field length cannot be larger than desc->field_len (ie. U8_MAX) - total length of the concatenation cannot be larger than register array. Joint work with Florian Westphal. Fixes: f3a2181e16f1 ("netfilter: nf_tables: Support for sets with multiple ranged fields") Reported-by: <[email protected]> Reviewed-by: Stefano Brivio <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
other
php-src
b6fe458ef9ac1372b60c3d3810b0358e2e20840d
1
utf32be_mbc_to_code(const UChar* p, const UChar* end ARG_UNUSED) { return (OnigCodePoint )(((p[0] * 256 + p[1]) * 256 + p[2]) * 256 + p[3]); }
null
null
210,963
75748348724321570219010812663511082435
4
Fix bug #77418 - Heap overflow in utf32be_mbc_to_code (cherry picked from commit aeec40cb50eca6a97975765e2bacc28a5950cfa9)
other
cifs-utils
f6eae44a3d05b6515a59651e6bed8b6dde689aec
1
add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype) { int rc = 0; uid_t uid; char *mount_user = NULL; struct mntent mountent; FILE *pmntfile; sigset_t mask, oldmask; uid = getuid(); if (uid != 0) mount_user = getusername(uid); /* * Set the real uid to the effective uid. This prevents unprivileged * users from sending signals to this process, though ^c on controlling * terminal should still work. */ rc = setreuid(geteuid(), -1); if (rc != 0) { fprintf(stderr, "Unable to set real uid to effective uid: %s\n", strerror(errno)); return EX_FILEIO; } rc = sigfillset(&mask); if (rc) { fprintf(stderr, "Unable to set filled signal mask\n"); return EX_FILEIO; } rc = sigprocmask(SIG_SETMASK, &mask, &oldmask); if (rc) { fprintf(stderr, "Unable to make process ignore signals\n"); return EX_FILEIO; } rc = toggle_dac_capability(1, 1); if (rc) return EX_FILEIO; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); rc = EX_FILEIO; goto add_mtab_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto add_mtab_exit; } mountent.mnt_fsname = devname; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)fstype; mountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1); if (mountent.mnt_opts) { if (flags & MS_RDONLY) strlcat(mountent.mnt_opts, "ro", MTAB_OPTIONS_LEN); else strlcat(mountent.mnt_opts, "rw", MTAB_OPTIONS_LEN); if (flags & MS_MANDLOCK) strlcat(mountent.mnt_opts, ",mand", MTAB_OPTIONS_LEN); if (flags & MS_NOEXEC) strlcat(mountent.mnt_opts, ",noexec", MTAB_OPTIONS_LEN); if (flags & MS_NOSUID) strlcat(mountent.mnt_opts, ",nosuid", MTAB_OPTIONS_LEN); if (flags & MS_NODEV) strlcat(mountent.mnt_opts, ",nodev", MTAB_OPTIONS_LEN); if (flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts, ",sync", MTAB_OPTIONS_LEN); if (mount_user) { strlcat(mountent.mnt_opts, ",user=", MTAB_OPTIONS_LEN); strlcat(mountent.mnt_opts, mount_user, MTAB_OPTIONS_LEN); } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile, &mountent); if (rc) { fprintf(stderr, "unable to add mount entry to mtab\n"); rc = EX_FILEIO; } endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); add_mtab_exit: toggle_dac_capability(1, 0); sigprocmask(SIG_SETMASK, &oldmask, NULL); return rc; }
null
null
211,090
115806152015103871231635752211035804321
99
mtab: handle ENOSPC/EFBIG condition properly when altering mtab It's possible that when mount.cifs goes to append the mtab that there won't be enough space to do so, and the mntent won't be appended to the file in its entirety. Add a my_endmntent routine that will fflush and then fsync the FILE if that succeeds. If either fails then it will truncate the file back to its provided size. It will then call endmntent unconditionally. Have add_mtab call fstat on the opened mtab file in order to get the size of the file before it has been appended. Assuming that that succeeds, use my_endmntent to ensure that the file is not corrupted before closing it. It's possible that we'll have a small race window where the mtab is incorrect, but it should be quickly corrected. This was reported some time ago as CVE-2011-1678: http://openwall.com/lists/oss-security/2011/03/04/9 ...and it seems to fix the reproducer that I was able to come up with. Signed-off-by: Jeff Layton <[email protected]> Reviewed-by: Suresh Jayaraman <[email protected]>
other
file-roller
b147281293a8307808475e102a14857055f81631
1
extract_archive_thread (GSimpleAsyncResult *result, GObject *object, GCancellable *cancellable) { ExtractData *extract_data; LoadData *load_data; GHashTable *checked_folders; struct archive *a; struct archive_entry *entry; int r; extract_data = g_simple_async_result_get_op_res_gpointer (result); load_data = LOAD_DATA (extract_data); checked_folders = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL); fr_archive_progress_set_total_files (load_data->archive, extract_data->n_files_to_extract); a = archive_read_new (); archive_read_support_filter_all (a); archive_read_support_format_all (a); archive_read_open (a, load_data, load_data_open, load_data_read, load_data_close); while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) { const char *pathname; char *fullpath; GFile *file; GFile *parent; GOutputStream *ostream; const void *buffer; size_t buffer_size; int64_t offset; GError *local_error = NULL; __LA_MODE_T filetype; if (g_cancellable_is_cancelled (cancellable)) break; pathname = archive_entry_pathname (entry); if (! extract_data_get_extraction_requested (extract_data, pathname)) { archive_read_data_skip (a); continue; } fullpath = (*pathname == '/') ? g_strdup (pathname) : g_strconcat ("/", pathname, NULL); file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (fullpath, extract_data->base_dir, extract_data->junk_paths)); /* honor the skip_older and overwrite options */ if (extract_data->skip_older || ! extract_data->overwrite) { GFileInfo *info; info = g_file_query_info (file, G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME "," G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, cancellable, &local_error); if (info != NULL) { gboolean skip = FALSE; if (! extract_data->overwrite) { skip = TRUE; } else if (extract_data->skip_older) { GTimeVal modification_time; g_file_info_get_modification_time (info, &modification_time); if (archive_entry_mtime (entry) < modification_time.tv_sec) skip = TRUE; } g_object_unref (info); if (skip) { g_object_unref (file); archive_read_data_skip (a); fr_archive_progress_inc_completed_bytes (load_data->archive, archive_entry_size_is_set (entry) ? archive_entry_size (entry) : 0); if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) { r = ARCHIVE_EOF; break; } continue; } } else { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { load_data->error = local_error; g_object_unref (info); break; } g_error_free (local_error); } } fr_archive_progress_inc_completed_files (load_data->archive, 1); /* create the file parents */ parent = g_file_get_parent (file); if ((parent != NULL) && (g_hash_table_lookup (checked_folders, parent) == NULL) && ! g_file_query_exists (parent, cancellable)) { if (g_file_make_directory_with_parents (parent, cancellable, &load_data->error)) { GFile *grandparent; grandparent = g_object_ref (parent); while (grandparent != NULL) { if (g_hash_table_lookup (checked_folders, grandparent) == NULL) g_hash_table_insert (checked_folders, grandparent, GINT_TO_POINTER (1)); grandparent = g_file_get_parent (grandparent); } } } g_object_unref (parent); /* create the file */ filetype = archive_entry_filetype (entry); if (load_data->error == NULL) { const char *linkname; linkname = archive_entry_hardlink (entry); if (linkname != NULL) { char *link_fullpath; GFile *link_file; char *oldname; char *newname; int r; link_fullpath = (*linkname == '/') ? g_strdup (linkname) : g_strconcat ("/", linkname, NULL); link_file = g_file_get_child (extract_data->destination, _g_path_get_relative_basename (link_fullpath, extract_data->base_dir, extract_data->junk_paths)); oldname = g_file_get_path (link_file); newname = g_file_get_path (file); if ((oldname != NULL) && (newname != NULL)) r = link (oldname, newname); else r = -1; if (r == 0) { __LA_INT64_T filesize; if (archive_entry_size_is_set (entry)) filesize = archive_entry_size (entry); else filesize = -1; if (filesize > 0) filetype = AE_IFREG; /* treat as a regular file to save the data */ } else { char *uri; char *msg; uri = g_file_get_uri (file); msg = g_strdup_printf ("Could not create the hard link %s", uri); load_data->error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED, msg); g_free (msg); g_free (uri); } g_free (newname); g_free (oldname); g_object_unref (link_file); g_free (link_fullpath); } } if (load_data->error == NULL) { switch (filetype) { case AE_IFDIR: if (! g_file_make_directory (file, cancellable, &local_error)) { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS)) load_data->error = g_error_copy (local_error); g_error_free (local_error); } else _g_file_set_attributes_from_entry (file, entry, extract_data, cancellable); archive_read_data_skip (a); break; case AE_IFREG: ostream = (GOutputStream *) g_file_replace (file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, &load_data->error); if (ostream == NULL) break; while ((r = archive_read_data_block (a, &buffer, &buffer_size, &offset)) == ARCHIVE_OK) { if (g_output_stream_write (ostream, buffer, buffer_size, cancellable, &load_data->error) == -1) break; fr_archive_progress_inc_completed_bytes (load_data->archive, buffer_size); } _g_object_unref (ostream); if (r != ARCHIVE_EOF) load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a)); else _g_file_set_attributes_from_entry (file, entry, extract_data, cancellable); break; case AE_IFLNK: if (! g_file_make_symbolic_link (file, archive_entry_symlink (entry), cancellable, &local_error)) { if (! g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_EXISTS)) load_data->error = g_error_copy (local_error); g_error_free (local_error); } archive_read_data_skip (a); break; default: archive_read_data_skip (a); break; } } g_object_unref (file); g_free (fullpath); if (load_data->error != NULL) break; if ((extract_data->file_list != NULL) && (--extract_data->n_files_to_extract == 0)) { r = ARCHIVE_EOF; break; } } if ((load_data->error == NULL) && (r != ARCHIVE_EOF)) load_data->error = g_error_new_literal (FR_ERROR, FR_ERROR_COMMAND_ERROR, archive_error_string (a)); if (load_data->error == NULL) g_cancellable_set_error_if_cancelled (cancellable, &load_data->error); if (load_data->error != NULL) g_simple_async_result_set_from_error (result, load_data->error); g_hash_table_unref (checked_folders); archive_read_free (a); extract_data_free (extract_data); }
null
null
211,102
146521485464683242231569868140802651647
242
libarchive: sanitize filenames before extracting
other
file-roller
b147281293a8307808475e102a14857055f81631
1
_fr_window_ask_overwrite_dialog (OverwriteData *odata) { if ((odata->edata->overwrite == FR_OVERWRITE_ASK) && (odata->current_file != NULL)) { const char *base_name; GFile *destination; base_name = _g_path_get_relative_basename ((char *) odata->current_file->data, odata->edata->base_dir, odata->edata->junk_paths); destination = g_file_get_child (odata->edata->destination, base_name); g_file_query_info_async (destination, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_NAME "," G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, G_PRIORITY_DEFAULT, odata->window->priv->cancellable, query_info_ready_for_overwrite_dialog_cb, odata); g_object_unref (destination); return; } if (odata->edata->file_list != NULL) { /* speed optimization: passing NULL when extracting all the * files is faster if the command supports the * propCanExtractAll property. */ if (odata->extract_all) { _g_string_list_free (odata->edata->file_list); odata->edata->file_list = NULL; } odata->edata->overwrite = FR_OVERWRITE_YES; _fr_window_archive_extract_from_edata (odata->window, odata->edata); } else { GtkWidget *d; d = _gtk_message_dialog_new (GTK_WINDOW (odata->window), 0, GTK_STOCK_DIALOG_WARNING, _("Extraction not performed"), NULL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); gtk_dialog_set_default_response (GTK_DIALOG (d), GTK_RESPONSE_OK); fr_window_show_error_dialog (odata->window, d, GTK_WINDOW (odata->window), _("Extraction not performed")); fr_window_stop_batch (odata->window); } g_free (odata); }
null
null
211,103
1868168910819853230293213295641486824
50
libarchive: sanitize filenames before extracting
other
libtiff
58a898cb4459055bb488ca815c23b880c242a27d
1
LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecodeCompat"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded " "string: data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } assert(occ >= codep->length); op += codep->length; occ -= codep->length; tp = op; do { *--tp = codep->value; } while( (codep = codep->next) != NULL ); } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); }
null
null
211,110
156819288691016584514751251322851290256
197
LZWDecodeCompat(): fix potential index-out-of-bounds write. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2780 / CVE-2018-8905 The fix consists in using the similar code LZWDecode() to validate we don't write outside of the output buffer.
other
linux
7fd25e6fc035f4b04b75bca6d7e8daa069603a76
1
static void atusb_disconnect(struct usb_interface *interface) { struct atusb *atusb = usb_get_intfdata(interface); dev_dbg(&atusb->usb_dev->dev, "%s\n", __func__); atusb->shutdown = 1; cancel_delayed_work_sync(&atusb->work); usb_kill_anchored_urbs(&atusb->rx_urbs); atusb_free_urbs(atusb); usb_kill_urb(atusb->tx_urb); usb_free_urb(atusb->tx_urb); ieee802154_unregister_hw(atusb->hw); ieee802154_free_hw(atusb->hw); usb_set_intfdata(interface, NULL); usb_put_dev(atusb->usb_dev); pr_debug("%s done\n", __func__); }
null
null
211,113
267064650077885177982562711259078440803
23
ieee802154: atusb: fix use-after-free at disconnect The disconnect callback was accessing the hardware-descriptor private data after having having freed it. Fixes: 7490b008d123 ("ieee802154: add support for atusb transceiver") Cc: stable <[email protected]> # 4.2 Cc: Alexander Aring <[email protected]> Reported-by: [email protected] Signed-off-by: Johan Hovold <[email protected]> Signed-off-by: Stefan Schmidt <[email protected]>
other
libmobi
612562bc1ea38f1708b044e7a079c47a05b1291d
1
static MOBI_RET mobi_parse_index_entry(MOBIIndx *indx, const MOBIIdxt idxt, const MOBITagx *tagx, const MOBIOrdt *ordt, MOBIBuffer *buf, const size_t curr_number) { if (indx == NULL) { debug_print("%s", "INDX structure not initialized\n"); return MOBI_INIT_FAILED; } const size_t entry_offset = indx->entries_count; const size_t entry_length = idxt.offsets[curr_number + 1] - idxt.offsets[curr_number]; mobi_buffer_setpos(buf, idxt.offsets[curr_number]); size_t entry_number = curr_number + entry_offset; if (entry_number >= indx->total_entries_count) { debug_print("Entry number beyond array: %zu\n", entry_number); return MOBI_DATA_CORRUPT; } /* save original record maxlen */ const size_t buf_maxlen = buf->maxlen; if (buf->offset + entry_length >= buf_maxlen) { debug_print("Entry length too long: %zu\n", entry_length); return MOBI_DATA_CORRUPT; } buf->maxlen = buf->offset + entry_length; size_t label_length = mobi_buffer_get8(buf); if (label_length > entry_length) { debug_print("Label length too long: %zu\n", label_length); return MOBI_DATA_CORRUPT; } char text[INDX_LABEL_SIZEMAX]; /* FIXME: what is ORDT1 for? */ if (ordt->ordt2) { label_length = mobi_getstring_ordt(ordt, buf, (unsigned char*) text, label_length); } else { label_length = mobi_indx_get_label((unsigned char*) text, buf, label_length, indx->ligt_entries_count); } indx->entries[entry_number].label = malloc(label_length + 1); if (indx->entries[entry_number].label == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", label_length); return MOBI_MALLOC_FAILED; } strncpy(indx->entries[entry_number].label, text, label_length + 1); //debug_print("tag label[%zu]: %s\n", entry_number, indx->entries[entry_number].label); unsigned char *control_bytes; control_bytes = buf->data + buf->offset; mobi_buffer_seek(buf, (int) tagx->control_byte_count); indx->entries[entry_number].tags_count = 0; indx->entries[entry_number].tags = NULL; if (tagx->tags_count > 0) { typedef struct { uint8_t tag; uint8_t tag_value_count; uint32_t value_count; uint32_t value_bytes; } MOBIPtagx; MOBIPtagx *ptagx = malloc(tagx->tags_count * sizeof(MOBIPtagx)); if (ptagx == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", tagx->tags_count * sizeof(MOBIPtagx)); return MOBI_MALLOC_FAILED; } uint32_t ptagx_count = 0; size_t len; size_t i = 0; while (i < tagx->tags_count) { if (tagx->tags[i].control_byte == 1) { control_bytes++; i++; continue; } uint32_t value = control_bytes[0] & tagx->tags[i].bitmask; if (value != 0) { /* FIXME: is it safe to use MOBI_NOTSET? */ uint32_t value_count = MOBI_NOTSET; uint32_t value_bytes = MOBI_NOTSET; /* all bits of masked value are set */ if (value == tagx->tags[i].bitmask) { /* more than 1 bit set */ if (mobi_bitcount(tagx->tags[i].bitmask) > 1) { /* read value bytes from entry */ len = 0; value_bytes = mobi_buffer_get_varlen(buf, &len); } else { value_count = 1; } } else { uint8_t mask = tagx->tags[i].bitmask; while ((mask & 1) == 0) { mask >>= 1; value >>= 1; } value_count = value; } ptagx[ptagx_count].tag = tagx->tags[i].tag; ptagx[ptagx_count].tag_value_count = tagx->tags[i].values_count; ptagx[ptagx_count].value_count = value_count; ptagx[ptagx_count].value_bytes = value_bytes; ptagx_count++; } i++; } indx->entries[entry_number].tags = malloc(tagx->tags_count * sizeof(MOBIIndexTag)); if (indx->entries[entry_number].tags == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", tagx->tags_count * sizeof(MOBIIndexTag)); free(ptagx); return MOBI_MALLOC_FAILED; } i = 0; while (i < ptagx_count) { uint32_t tagvalues_count = 0; /* FIXME: is it safe to use MOBI_NOTSET? */ /* value count is set */ uint32_t tagvalues[INDX_TAGVALUES_MAX]; if (ptagx[i].value_count != MOBI_NOTSET) { size_t count = ptagx[i].value_count * ptagx[i].tag_value_count; while (count-- && tagvalues_count < INDX_TAGVALUES_MAX) { len = 0; const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len); tagvalues[tagvalues_count++] = value_bytes; } /* value count is not set */ } else { /* read value_bytes bytes */ len = 0; while (len < ptagx[i].value_bytes && tagvalues_count < INDX_TAGVALUES_MAX) { const uint32_t value_bytes = mobi_buffer_get_varlen(buf, &len); tagvalues[tagvalues_count++] = value_bytes; } } if (tagvalues_count) { const size_t arr_size = tagvalues_count * sizeof(*indx->entries[entry_number].tags[i].tagvalues); indx->entries[entry_number].tags[i].tagvalues = malloc(arr_size); if (indx->entries[entry_number].tags[i].tagvalues == NULL) { debug_print("Memory allocation failed (%zu bytes)\n", arr_size); free(ptagx); return MOBI_MALLOC_FAILED; } memcpy(indx->entries[entry_number].tags[i].tagvalues, tagvalues, arr_size); } else { indx->entries[entry_number].tags[i].tagvalues = NULL; } indx->entries[entry_number].tags[i].tagid = ptagx[i].tag; indx->entries[entry_number].tags[i].tagvalues_count = tagvalues_count; indx->entries[entry_number].tags_count++; i++; } free(ptagx); } /* restore buffer maxlen */ buf->maxlen = buf_maxlen; return MOBI_SUCCESS; }
null
null
211,126
182245659604830683696012469856833384738
147
Fix: index entry label not being zero-terminated with corrupt input
other
rizin
556ca2f9eef01ec0f4a76d1fbacfcf3a87a44810
1
static RzDyldRebaseInfos *get_rebase_infos(RzDyldCache *cache) { RzDyldRebaseInfos *result = RZ_NEW0(RzDyldRebaseInfos); if (!result) { return NULL; } if (!cache->hdr->slideInfoOffset || !cache->hdr->slideInfoSize) { ut32 total_slide_infos = 0; ut32 n_slide_infos[MAX_N_HDR]; ut32 i; for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) { ut64 hdr_offset = cache->hdr_offset[i]; if (!rz_buf_read_le32_at(cache->buf, 0x13c + hdr_offset, &n_slide_infos[i])) { goto beach; } total_slide_infos += n_slide_infos[i]; } if (!total_slide_infos) { goto beach; } RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, total_slide_infos); if (!infos) { goto beach; } ut32 k = 0; for (i = 0; i < cache->n_hdr && i < MAX_N_HDR; i++) { ut64 hdr_offset = cache->hdr_offset[i]; if (!n_slide_infos[i]) { continue; } ut32 sio; if (!rz_buf_read_le32_at(cache->buf, 0x138 + hdr_offset, &sio)) { continue; } ut64 slide_infos_offset = sio; if (!slide_infos_offset) { continue; } slide_infos_offset += hdr_offset; ut32 j; RzDyldRebaseInfo *prev_info = NULL; for (j = 0; j < n_slide_infos[i]; j++) { ut64 offset = slide_infos_offset + j * sizeof(cache_mapping_slide); cache_mapping_slide entry; if (rz_buf_fread_at(cache->buf, offset, (ut8 *)&entry, "6lii", 1) != sizeof(cache_mapping_slide)) { break; } if (entry.slideInfoOffset && entry.slideInfoSize) { infos[k].start = entry.fileOffset + hdr_offset; infos[k].end = infos[k].start + entry.size; ut64 slide = prev_info ? prev_info->slide : UT64_MAX; infos[k].info = get_rebase_info(cache, entry.slideInfoOffset + hdr_offset, entry.slideInfoSize, entry.fileOffset + hdr_offset, slide); prev_info = infos[k].info; k++; } } } if (!k) { free(infos); goto beach; } if (k < total_slide_infos) { RzDyldRebaseInfosEntry *pruned_infos = RZ_NEWS0(RzDyldRebaseInfosEntry, k); if (!pruned_infos) { free(infos); goto beach; } memcpy(pruned_infos, infos, sizeof(RzDyldRebaseInfosEntry) * k); free(infos); infos = pruned_infos; } result->entries = infos; result->length = k; return result; } if (cache->hdr->mappingCount > 1) { RzDyldRebaseInfosEntry *infos = RZ_NEWS0(RzDyldRebaseInfosEntry, 1); if (!infos) { goto beach; } infos[0].start = cache->maps[1].fileOffset; infos[0].end = infos[0].start + cache->maps[1].size; infos[0].info = get_rebase_info(cache, cache->hdr->slideInfoOffset, cache->hdr->slideInfoSize, infos[0].start, UT64_MAX); result->entries = infos; result->length = 1; return result; } beach: free(result); return NULL; }
null
null
211,136
331393579711700994828367435682320006305
105
Fix oob write in dyldcache When the individual n_slide_infos were too high, the sum would overflow and too few entries would be allocated.
other
libslirp
2655fffed7a9e765bcb4701dd876e9dab975f289
1
int tcp_emu(struct socket *so, struct mbuf *m) { Slirp *slirp = so->slirp; unsigned n1, n2, n3, n4, n5, n6; char buff[257]; uint32_t laddr; unsigned lport; char *bptr; DEBUG_CALL("tcp_emu"); DEBUG_ARG("so = %p", so); DEBUG_ARG("m = %p", m); switch (so->so_emu) { int x, i; /* TODO: IPv6 */ case EMU_IDENT: /* * Identification protocol as per rfc-1413 */ { struct socket *tmpso; struct sockaddr_in addr; socklen_t addrlen = sizeof(struct sockaddr_in); char *eol = g_strstr_len(m->m_data, m->m_len, "\r\n"); if (!eol) { return 1; } *eol = '\0'; if (sscanf(m->m_data, "%u%*[ ,]%u", &n1, &n2) == 2) { HTONS(n1); HTONS(n2); /* n2 is the one on our host */ for (tmpso = slirp->tcb.so_next; tmpso != &slirp->tcb; tmpso = tmpso->so_next) { if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr && tmpso->so_lport == n2 && tmpso->so_faddr.s_addr == so->so_faddr.s_addr && tmpso->so_fport == n1) { if (getsockname(tmpso->s, (struct sockaddr *)&addr, &addrlen) == 0) n2 = addr.sin_port; break; } } NTOHS(n1); NTOHS(n2); m_inc(m, snprintf(NULL, 0, "%d,%d\r\n", n1, n2) + 1); m->m_len = snprintf(m->m_data, M_ROOM(m), "%d,%d\r\n", n1, n2); assert(m->m_len < M_ROOM(m)); } else { *eol = '\r'; } return 1; } case EMU_FTP: /* ftp */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NUL terminate for strstr */ if ((bptr = (char *)strstr(m->m_data, "ORT")) != NULL) { /* * Need to emulate the PORT command */ x = sscanf(bptr, "ORT %u,%u,%u,%u,%u,%u\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "ORT %d,%d,%d,%d,%d,%d\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } else if ((bptr = (char *)strstr(m->m_data, "27 Entering")) != NULL) { /* * Need to emulate the PASV response */ x = sscanf( bptr, "27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } return 1; case EMU_KSH: /* * The kshell (Kerberos rsh) and shell services both pass * a local port port number to carry signals to the server * and stderr to the client. It is passed at the beginning * of the connection as a NUL-terminated decimal ASCII string. */ so->so_emu = 0; for (lport = 0, i = 0; i < m->m_len - 1; ++i) { if (m->m_data[i] < '0' || m->m_data[i] > '9') return 1; /* invalid number */ lport *= 10; lport += m->m_data[i] - '0'; } if (m->m_data[m->m_len - 1] == '\0' && lport != 0 && (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) != NULL) m->m_len = snprintf(m->m_data, m->m_size, "%d", ntohs(so->so_fport)) + 1; return 1; case EMU_IRC: /* * Need to emulate DCC CHAT, DCC SEND and DCC MOVE */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NULL terminate the string for strstr */ if ((bptr = (char *)strstr(m->m_data, "DCC")) == NULL) return 1; /* The %256s is for the broken mIRC */ if (sscanf(bptr, "DCC CHAT %256s %u %u", buff, &laddr, &lport) == 3) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC CHAT chat %lu %u%c\n", (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), 1); } else if (sscanf(bptr, "DCC SEND %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC SEND %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } else if (sscanf(bptr, "DCC MOVE %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC MOVE %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } return 1; case EMU_REALAUDIO: /* * RealAudio emulation - JP. We must try to parse the incoming * data and try to find the two characters that contain the * port number. Then we redirect an udp port and replace the * number with the real port we got. * * The 1.0 beta versions of the player are not supported * any more. * * A typical packet for player version 1.0 (release version): * * 0000:50 4E 41 00 05 * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB * * Now the port number 0x1BD7 is found at offset 0x04 of the * Now the port number 0x1BD7 is found at offset 0x04 of the * second packet. This time we received five bytes first and * then the rest. You never know how many bytes you get. * * A typical packet for player version 2.0 (beta): * * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA............. * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0 * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/ * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B * * Port number 0x1BC1 is found at offset 0x0d. * * This is just a horrible switch statement. Variable ra tells * us where we're going. */ bptr = m->m_data; while (bptr < m->m_data + m->m_len) { uint16_t p; static int ra = 0; char ra_tbl[4]; ra_tbl[0] = 0x50; ra_tbl[1] = 0x4e; ra_tbl[2] = 0x41; ra_tbl[3] = 0; switch (ra) { case 0: case 2: case 3: if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 1: /* * We may get 0x50 several times, ignore them */ if (*bptr == 0x50) { ra = 1; bptr++; continue; } else if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 4: /* * skip version number */ bptr++; break; case 5: /* * The difference between versions 1.0 and * 2.0 is here. For future versions of * the player this may need to be modified. */ if (*(bptr + 1) == 0x02) bptr += 8; else bptr += 4; break; case 6: /* This is the field containing the port * number that RA-player is listening to. */ lport = (((uint8_t *)bptr)[0] << 8) + ((uint8_t *)bptr)[1]; if (lport < 6970) lport += 256; /* don't know why */ if (lport < 6970 || lport > 7170) return 1; /* failed */ /* try to get udp port between 6970 - 7170 */ for (p = 6970; p < 7071; p++) { if (udp_listen(slirp, INADDR_ANY, htons(p), so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) { break; } } if (p == 7071) p = 0; *(uint8_t *)bptr++ = (p >> 8) & 0xff; *(uint8_t *)bptr = p & 0xff; ra = 0; return 1; /* port redirected, we're done */ break; default: ra = 0; } ra++; } return 1; default: /* Ooops, not emulated, won't call tcp_emu again */ so->so_emu = 0; return 1; } }
null
null
211,155
26501264989908130245423904711555774475
333
tcp_emu: Fix oob access The main loop only checks for one available byte, while we sometimes need two bytes.
other
exiv2
6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97
1
void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth) { depth++; bool bFirst = true ; // buffer const size_t dirSize = 32; DataBuf dir(dirSize); bool bPrint = option == kpsBasic || option == kpsRecursive; do { // Read top of directory io.seek(start,BasicIo::beg); io.read(dir.pData_, 2); uint16_t dirLength = byteSwap2(dir,0,bSwap); bool tooBig = dirLength > 500; if ( tooBig ) throw Error(55); if ( bFirst && bPrint ) { out << Internal::indent(depth) << Internal::stringFormat("STRUCTURE OF TIFF FILE (%c%c): ",c,c) << io.path() << std::endl; if ( tooBig ) out << Internal::indent(depth) << "dirLength = " << dirLength << std::endl; } // Read the dictionary for ( int i = 0 ; i < dirLength ; i ++ ) { if ( bFirst && bPrint ) { out << Internal::indent(depth) << " address | tag | " << " type | count | offset | value\n"; } bFirst = false; io.read(dir.pData_, 12); uint16_t tag = byteSwap2(dir,0,bSwap); uint16_t type = byteSwap2(dir,2,bSwap); uint32_t count = byteSwap4(dir,4,bSwap); uint32_t offset = byteSwap4(dir,8,bSwap); // Break for unknown tag types else we may segfault. if ( !typeValid(type) ) { std::cerr << "invalid type value detected in Image::printIFDStructure: " << type << std::endl; start = 0; // break from do loop throw Error(56); break; // break from for loop } std::string sp = "" ; // output spacer //prepare to print the value uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data : isPrintICC(tag,option) ? count // ditto : isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays : count > 5 ? 5 : count ; uint32_t pad = isStringType(type) ? 1 : 0; uint32_t size = isStringType(type) ? 1 : is2ByteType(type) ? 2 : is4ByteType(type) ? 4 : is8ByteType(type) ? 8 : 1 ; // if ( offset > io.size() ) offset = 0; // Denial of service? DataBuf buf(size*count + pad+20); // allocate a buffer std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings) const bool bOffsetIsPointer = count*size > 4; if ( bOffsetIsPointer ) { // read into buffer size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position io.read(buf.pData_,count*size);// read io.seek(restore,BasicIo::beg); // restore } if ( bPrint ) { const uint32_t address = start + 2 + i*12 ; const std::string offsetString = bOffsetIsPointer? Internal::stringFormat("%10u", offset): ""; out << Internal::indent(depth) << Internal::stringFormat("%8u | %#06x %-28s |%10s |%9u |%10s | " ,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str()); if ( isShortType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap2(buf,k*size,bSwap); sp = " "; } } else if ( isLongType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { out << sp << byteSwap4(buf,k*size,bSwap); sp = " "; } } else if ( isRationalType(type) ){ for ( size_t k = 0 ; k < kount ; k++ ) { uint32_t a = byteSwap4(buf,k*size+0,bSwap); uint32_t b = byteSwap4(buf,k*size+4,bSwap); out << sp << a << "/" << b; sp = " "; } } else if ( isStringType(type) ) { out << sp << Internal::binaryToString(buf, kount); } sp = kount == count ? "" : " ..."; out << sp << std::endl; if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) { for ( size_t k = 0 ; k < count ; k++ ) { size_t restore = io.tell(); uint32_t offset = byteSwap4(buf,k*size,bSwap); printIFDStructure(io,out,option,offset,bSwap,c,depth); io.seek(restore,BasicIo::beg); } } else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) { size_t restore = io.tell(); // save io.seek(offset,BasicIo::beg); // position byte* bytes=new byte[count] ; // allocate memory io.read(bytes,count) ; // read io.seek(restore,BasicIo::beg); // restore IptcData::printStructure(out,bytes,count,depth); delete[] bytes; // free } else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) { size_t restore = io.tell(); // save uint32_t jump= 10 ; byte bytes[20] ; const char* chars = (const char*) &bytes[0] ; io.seek(offset,BasicIo::beg); // position io.read(bytes,jump ) ; // read bytes[jump]=0 ; if ( ::strcmp("Nikon",chars) == 0 ) { // tag is an embedded tiff byte* bytes=new byte[count-jump] ; // allocate memory io.read(bytes,count-jump) ; // read MemIo memIo(bytes,count-jump) ; // create a file printTiffStructure(memIo,out,option,depth); delete[] bytes ; // free } else { // tag is an IFD io.seek(0,BasicIo::beg); // position printIFDStructure(io,out,option,offset,bSwap,c,depth); } io.seek(restore,BasicIo::beg); // restore } } if ( isPrintXMP(tag,option) ) { buf.pData_[count]=0; out << (char*) buf.pData_; } if ( isPrintICC(tag,option) ) { out.write((const char*)buf.pData_,count); } } if ( start ) { io.read(dir.pData_, 4); start = tooBig ? 0 : byteSwap4(dir,0,bSwap); } } while (start) ; if ( bPrint ) { out << Internal::indent(depth) << "END " << io.path() << std::endl; } out.flush(); depth--; }
null
null
211,179
56103337669506849163981774491363468429
171
Fix https://github.com/Exiv2/exiv2/issues/55
other
php-src
a72cd07f2983dc43a6bb35209dc4687852e53c09
1
apprentice_load(struct magic_set *ms, const char *fn, int action) { int errs = 0; uint32_t i, j; size_t files = 0, maxfiles = 0; char **filearr = NULL; struct stat st; struct magic_map *map; struct magic_entry_set mset[MAGIC_SETS]; php_stream *dir; php_stream_dirent d; TSRMLS_FETCH(); memset(mset, 0, sizeof(mset)); ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */ if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) { file_oomem(ms, sizeof(*map)); return NULL; } /* print silly verbose header for USG compat. */ if (action == FILE_CHECK) (void)fprintf(stderr, "%s\n", usg_hdr); /* load directory or file */ /* FIXME: Read file names and sort them to prevent non-determinism. See Debian bug #488562. */ if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) { int mflen; char mfn[MAXPATHLEN]; dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL); if (!dir) { errs++; goto out; } while (php_stream_readdir(dir, &d)) { if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) { file_oomem(ms, strlen(fn) + strlen(d.d_name) + 2); errs++; php_stream_closedir(dir); goto out; } if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) { continue; } if (files >= maxfiles) { size_t mlen; maxfiles = (maxfiles + 1) * 2; mlen = maxfiles * sizeof(*filearr); if ((filearr = CAST(char **, erealloc(filearr, mlen))) == NULL) { file_oomem(ms, mlen); efree(mfn); php_stream_closedir(dir); errs++; goto out; } } filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen); } php_stream_closedir(dir); qsort(filearr, files, sizeof(*filearr), cmpstrp); for (i = 0; i < files; i++) { load_1(ms, action, filearr[i], &errs, mset); efree(filearr[i]); } efree(filearr); } else load_1(ms, action, fn, &errs, mset); if (errs) goto out; for (j = 0; j < MAGIC_SETS; j++) { /* Set types of tests */ for (i = 0; i < mset[j].count; ) { if (mset[j].me[i].mp->cont_level != 0) { i++; continue; } i = set_text_binary(ms, mset[j].me, mset[j].count, i); } qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me), apprentice_sort); /* * Make sure that any level 0 "default" line is last * (if one exists). */ set_last_default(ms, mset[j].me, mset[j].count); /* coalesce per file arrays into a single one */ if (coalesce_entries(ms, mset[j].me, mset[j].count, &map->magic[j], &map->nmagic[j]) == -1) { errs++; goto out; } } out: for (j = 0; j < MAGIC_SETS; j++) magic_entry_free(mset[j].me, mset[j].count); if (errs) { for (j = 0; j < MAGIC_SETS; j++) { if (map->magic[j]) efree(map->magic[j]); } efree(map); return NULL; } return map; }
null
null
211,181
204060393707753772749089343291180225194
118
Fixed bug #68665 (Invalid free)
other
qemu
b9f79858a614d95f5de875d0ca31096eaab72c3b
1
vg_resource_attach_backing(VuGpu *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_simple_resource *res; struct virtio_gpu_resource_attach_backing ab; int ret; VUGPU_FILL_CMD(ab); virtio_gpu_bswap_32(&ab, sizeof(ab)); res = virtio_gpu_find_resource(g, ab.resource_id); if (!res) { g_critical("%s: illegal resource specified %d", __func__, ab.resource_id); cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID; return; } ret = vg_create_mapping_iov(g, &ab, cmd, &res->iov); if (ret != 0) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } res->iov_cnt = ab.nr_entries; }
null
null
211,455
166163401118056465443381004681333507729
26
vhost-user-gpu: fix memory leak in vg_resource_attach_backing (CVE-2021-3544) Check whether the 'res' has already been attach_backing to avoid memory leak. Fixes: CVE-2021-3544 Reported-by: Li Qiang <[email protected]> virtio-gpu fix: 204f01b309 ("virtio-gpu: fix memory leak in resource attach backing") Signed-off-by: Li Qiang <[email protected]> Reviewed-by: Marc-André Lureau <[email protected]> Message-Id: <[email protected]> Signed-off-by: Gerd Hoffmann <[email protected]>
other
vim
f7c7c3fad6d2135d558f3b36d0d1a943118aeb5e
1
parse_cmd_address(exarg_T *eap, char **errormsg, int silent) { int address_count = 1; linenr_T lnum; int need_check_cursor = FALSE; int ret = FAIL; // Repeat for all ',' or ';' separated addresses. for (;;) { eap->line1 = eap->line2; eap->line2 = default_address(eap); eap->cmd = skipwhite(eap->cmd); lnum = get_address(eap, &eap->cmd, eap->addr_type, eap->skip, silent, eap->addr_count == 0, address_count++); if (eap->cmd == NULL) // error detected goto theend; if (lnum == MAXLNUM) { if (*eap->cmd == '%') // '%' - all lines { ++eap->cmd; switch (eap->addr_type) { case ADDR_LINES: case ADDR_OTHER: eap->line1 = 1; eap->line2 = curbuf->b_ml.ml_line_count; break; case ADDR_LOADED_BUFFERS: { buf_T *buf = firstbuf; while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_next; eap->line1 = buf->b_fnum; buf = lastbuf; while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_prev; eap->line2 = buf->b_fnum; break; } case ADDR_BUFFERS: eap->line1 = firstbuf->b_fnum; eap->line2 = lastbuf->b_fnum; break; case ADDR_WINDOWS: case ADDR_TABS: if (IS_USER_CMDIDX(eap->cmdidx)) { eap->line1 = 1; eap->line2 = eap->addr_type == ADDR_WINDOWS ? LAST_WIN_NR : LAST_TAB_NR; } else { // there is no Vim command which uses '%' and // ADDR_WINDOWS or ADDR_TABS *errormsg = _(e_invalid_range); goto theend; } break; case ADDR_TABS_RELATIVE: case ADDR_UNSIGNED: case ADDR_QUICKFIX: *errormsg = _(e_invalid_range); goto theend; case ADDR_ARGUMENTS: if (ARGCOUNT == 0) eap->line1 = eap->line2 = 0; else { eap->line1 = 1; eap->line2 = ARGCOUNT; } break; case ADDR_QUICKFIX_VALID: #ifdef FEAT_QUICKFIX eap->line1 = 1; eap->line2 = qf_get_valid_size(eap); if (eap->line2 == 0) eap->line2 = 1; #endif break; case ADDR_NONE: // Will give an error later if a range is found. break; } ++eap->addr_count; } else if (*eap->cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL) { pos_T *fp; // '*' - visual area if (eap->addr_type != ADDR_LINES) { *errormsg = _(e_invalid_range); goto theend; } ++eap->cmd; if (!eap->skip) { fp = getmark('<', FALSE); if (check_mark(fp) == FAIL) goto theend; eap->line1 = fp->lnum; fp = getmark('>', FALSE); if (check_mark(fp) == FAIL) goto theend; eap->line2 = fp->lnum; ++eap->addr_count; } } } else eap->line2 = lnum; eap->addr_count++; if (*eap->cmd == ';') { if (!eap->skip) { curwin->w_cursor.lnum = eap->line2; // Don't leave the cursor on an illegal line or column, but do // accept zero as address, so 0;/PATTERN/ works correctly. // Check the cursor position before returning. if (eap->line2 > 0) check_cursor(); need_check_cursor = TRUE; } } else if (*eap->cmd != ',') break; ++eap->cmd; } // One address given: set start and end lines. if (eap->addr_count == 1) { eap->line1 = eap->line2; // ... but only implicit: really no address given if (lnum == MAXLNUM) eap->addr_count = 0; } ret = OK; theend: if (need_check_cursor) check_cursor(); return ret; }
null
null
211,461
99282211244571883695249134491416318119
156
patch 8.2.5150: read past the end of the first line with ":0;'{" Problem: Read past the end of the first line with ":0;'{". Solution: When on line zero check the column is valid for line one.
other
frr
ff6db1027f8f36df657ff2e5ea167773752537ed
1
static int bgp_capability_msg_parse(struct peer *peer, uint8_t *pnt, bgp_size_t length) { uint8_t *end; struct capability_mp_data mpc; struct capability_header *hdr; uint8_t action; iana_afi_t pkt_afi; afi_t afi; iana_safi_t pkt_safi; safi_t safi; end = pnt + length; while (pnt < end) { /* We need at least action, capability code and capability * length. */ if (pnt + 3 > end) { zlog_info("%s Capability length error", peer->host); bgp_notify_send(peer, BGP_NOTIFY_CEASE, BGP_NOTIFY_SUBCODE_UNSPECIFIC); return BGP_Stop; } action = *pnt; hdr = (struct capability_header *)(pnt + 1); /* Action value check. */ if (action != CAPABILITY_ACTION_SET && action != CAPABILITY_ACTION_UNSET) { zlog_info("%s Capability Action Value error %d", peer->host, action); bgp_notify_send(peer, BGP_NOTIFY_CEASE, BGP_NOTIFY_SUBCODE_UNSPECIFIC); return BGP_Stop; } if (bgp_debug_neighbor_events(peer)) zlog_debug( "%s CAPABILITY has action: %d, code: %u, length %u", peer->host, action, hdr->code, hdr->length); /* Capability length check. */ if ((pnt + hdr->length + 3) > end) { zlog_info("%s Capability length error", peer->host); bgp_notify_send(peer, BGP_NOTIFY_CEASE, BGP_NOTIFY_SUBCODE_UNSPECIFIC); return BGP_Stop; } /* Fetch structure to the byte stream. */ memcpy(&mpc, pnt + 3, sizeof(struct capability_mp_data)); pnt += hdr->length + 3; /* We know MP Capability Code. */ if (hdr->code == CAPABILITY_CODE_MP) { pkt_afi = ntohs(mpc.afi); pkt_safi = mpc.safi; /* Ignore capability when override-capability is set. */ if (CHECK_FLAG(peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY)) continue; /* Convert AFI, SAFI to internal values. */ if (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi, &safi)) { if (bgp_debug_neighbor_events(peer)) zlog_debug( "%s Dynamic Capability MP_EXT afi/safi invalid (%s/%s)", peer->host, iana_afi2str(pkt_afi), iana_safi2str(pkt_safi)); continue; } /* Address family check. */ if (bgp_debug_neighbor_events(peer)) zlog_debug( "%s CAPABILITY has %s MP_EXT CAP for afi/safi: %s/%s", peer->host, action == CAPABILITY_ACTION_SET ? "Advertising" : "Removing", iana_afi2str(pkt_afi), iana_safi2str(pkt_safi)); if (action == CAPABILITY_ACTION_SET) { peer->afc_recv[afi][safi] = 1; if (peer->afc[afi][safi]) { peer->afc_nego[afi][safi] = 1; bgp_announce_route(peer, afi, safi, false); } } else { peer->afc_recv[afi][safi] = 0; peer->afc_nego[afi][safi] = 0; if (peer_active_nego(peer)) bgp_clear_route(peer, afi, safi); else return BGP_Stop; } } else { flog_warn( EC_BGP_UNRECOGNIZED_CAPABILITY, "%s unrecognized capability code: %d - ignored", peer->host, hdr->code); } } /* No FSM action necessary */ return BGP_PACKET_NOOP; }
null
null
211,471
20056543425113649640670382065398431452
113
bgpd: Make sure hdr length is at a minimum of what is expected Ensure that if the capability length specified is enough data. Signed-off-by: Donald Sharp <[email protected]>
other
gdk-pixbuf
4f0f465f991cd454d03189497f923eb40c170c22
1
read_bitmap_file_data (FILE *fstream, guint *width, guint *height, guchar **data, int *x_hot, int *y_hot) { guchar *bits = NULL; /* working variable */ char line[MAX_SIZE]; /* input line from file */ int size; /* number of bytes of data */ char name_and_type[MAX_SIZE]; /* an input line */ char *type; /* for parsing */ int value; /* from an input line */ int version10p; /* boolean, old format */ int padding; /* to handle alignment */ int bytes_per_line; /* per scanline of data */ guint ww = 0; /* width */ guint hh = 0; /* height */ int hx = -1; /* x hotspot */ int hy = -1; /* y hotspot */ /* first time initialization */ if (!initialized) { init_hex_table (); } /* error cleanup and return macro */ #define RETURN(code) { g_free (bits); return code; } while (fgets (line, MAX_SIZE, fstream)) { if (strlen (line) == MAX_SIZE-1) RETURN (FALSE); if (sscanf (line,"#define %s %d",name_and_type,&value) == 2) { if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else { type++; } if (!strcmp ("width", type)) ww = (unsigned int) value; if (!strcmp ("height", type)) hh = (unsigned int) value; if (!strcmp ("hot", type)) { if (type-- == name_and_type || type-- == name_and_type) continue; if (!strcmp ("x_hot", type)) hx = value; if (!strcmp ("y_hot", type)) hy = value; } continue; } if (sscanf (line, "static short %s = {", name_and_type) == 1) version10p = 1; else if (sscanf (line,"static const unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line,"static unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf (line, "static const char %s = {", name_and_type) == 1) version10p = 0; else if (sscanf (line, "static char %s = {", name_and_type) == 1) version10p = 0; else continue; if (!(type = strrchr (name_and_type, '_'))) type = name_and_type; else type++; if (strcmp ("bits[]", type)) continue; if (!ww || !hh) RETURN (FALSE); if ((ww % 16) && ((ww % 16) < 9) && version10p) padding = 1; else padding = 0; bytes_per_line = (ww+7)/8 + padding; size = bytes_per_line * hh; bits = g_malloc (size); if (version10p) { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; (bytes += 2)) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *(ptr++) = value; if (!padding || ((bytes+2) % bytes_per_line)) *(ptr++) = value >> 8; } } else { unsigned char *ptr; int bytes; for (bytes = 0, ptr = bits; bytes < size; bytes++, ptr++) { if ((value = next_int (fstream)) < 0) RETURN (FALSE); *ptr=value; } } break; } if (!bits) RETURN (FALSE); *data = bits; *width = ww; *height = hh; if (x_hot) *x_hot = hx; if (y_hot) *y_hot = hy; return TRUE; }
null
null
211,473
70165411011067571586761169769193194588
126
Avoid an integer overflow in the xbm loader At the same time, reject some silly input, such as negative width or height. https://bugzilla.gnome.org/show_bug.cgi?id=672811
other
zlib
eff308af425b67093bab25f80f1ae950166bece1
1
int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; z_const unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (inflateStateCheck(strm) || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ if (state->wbits == 0) state->wbits = 15; state->check = crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; if (len > 15 || len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; state->flags = 0; /* indicate zlib header */ Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = TIME; /* fallthrough */ case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC4(state->check, hold); INITBITS(); state->mode = OS; /* fallthrough */ case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; /* fallthrough */ case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if ((state->flags & 0x0200) && (state->wrap & 4)) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; /* fallthrough */ case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; /* fallthrough */ case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; /* fallthrough */ case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = (Bytef)len; } while (len && copy < have); if ((state->flags & 0x0200) && (state->wrap & 4)) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; /* fallthrough */ case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if ((state->wrap & 4) && hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; /* fallthrough */ case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = TYPE; /* fallthrough */ case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; /* fallthrough */ case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case COPY_: state->mode = COPY; /* fallthrough */ case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; /* fallthrough */ case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; /* fallthrough */ case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (const code FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (const code FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; /* fallthrough */ case LEN_: state->mode = LEN; /* fallthrough */ case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; /* fallthrough */ case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; /* fallthrough */ case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; /* fallthrough */ case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; /* fallthrough */ case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, put - out, out); out = left; if ((state->wrap & 4) && ( #ifdef GUNZIP state->flags ? hold : #endif ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; /* fallthrough */ case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; /* fallthrough */ case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* fallthrough */ default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (out != strm->avail_out && state->mode < BAD && (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if ((state->wrap & 4) && out) strm->adler = state->check = UPDATE_CHECK(state->check, strm->next_out - out, out); strm->data_type = (int)state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; }
null
null
211,506
330974561915036366259999836164111519497
677
Fix a bug when getting a gzip header extra field with inflate(). If the extra field was larger than the space the user provided with inflateGetHeader(), and if multiple calls of inflate() delivered the extra header data, then there could be a buffer overflow of the provided space. This commit assures that provided space is not exceeded.
other
linux
d6c763afab142a85e4770b4bc2a5f40f256d5c5d
1
static unsigned long mmap_rnd(void) { unsigned long rnd = 0; if (current->flags & PF_RANDOMIZE) rnd = (long)get_random_int() & (STACK_RND_MASK >> 1); return rnd << (PAGE_SHIFT + 1); }
null
null
211,508
214525712708861150605921567081196886272
9
arm64/mm: Remove hack in mmap randomize layout Since commit 8a0a9bd4db63 ('random: make get_random_int() more random'), get_random_int() returns a random value for each call, so comment and hack introduced in mmap_rnd() as part of commit 1d18c47c735e ('arm64: MMU fault handling and page table management') are incorrects. Commit 1d18c47c735e seems to use the same hack introduced by commit a5adc91a4b44 ('powerpc: Ensure random space between stack and mmaps'), latter copied in commit 5a0efea09f42 ('sparc64: Sharpen address space randomization calculations.'). But both architectures were cleaned up as part of commit fa8cbaaf5a68 ('powerpc+sparc64/mm: Remove hack in mmap randomize layout') as hack is no more needed since commit 8a0a9bd4db63. So the present patch removes the comment and the hack around get_random_int() on AArch64's mmap_rnd(). Cc: David S. Miller <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Benjamin Herrenschmidt <[email protected]> Acked-by: Will Deacon <[email protected]> Acked-by: Dan McGee <[email protected]> Signed-off-by: Yann Droneaud <[email protected]> Signed-off-by: Will Deacon <[email protected]>
other
vim
4d97a565ae8be0d4debba04ebd2ac3e75a0c8010
1
parse_cmd_address(exarg_T *eap, char **errormsg, int silent) { int address_count = 1; linenr_T lnum; // Repeat for all ',' or ';' separated addresses. for (;;) { eap->line1 = eap->line2; eap->line2 = default_address(eap); eap->cmd = skipwhite(eap->cmd); lnum = get_address(eap, &eap->cmd, eap->addr_type, eap->skip, silent, eap->addr_count == 0, address_count++); if (eap->cmd == NULL) // error detected return FAIL; if (lnum == MAXLNUM) { if (*eap->cmd == '%') // '%' - all lines { ++eap->cmd; switch (eap->addr_type) { case ADDR_LINES: case ADDR_OTHER: eap->line1 = 1; eap->line2 = curbuf->b_ml.ml_line_count; break; case ADDR_LOADED_BUFFERS: { buf_T *buf = firstbuf; while (buf->b_next != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_next; eap->line1 = buf->b_fnum; buf = lastbuf; while (buf->b_prev != NULL && buf->b_ml.ml_mfp == NULL) buf = buf->b_prev; eap->line2 = buf->b_fnum; break; } case ADDR_BUFFERS: eap->line1 = firstbuf->b_fnum; eap->line2 = lastbuf->b_fnum; break; case ADDR_WINDOWS: case ADDR_TABS: if (IS_USER_CMDIDX(eap->cmdidx)) { eap->line1 = 1; eap->line2 = eap->addr_type == ADDR_WINDOWS ? LAST_WIN_NR : LAST_TAB_NR; } else { // there is no Vim command which uses '%' and // ADDR_WINDOWS or ADDR_TABS *errormsg = _(e_invalid_range); return FAIL; } break; case ADDR_TABS_RELATIVE: case ADDR_UNSIGNED: case ADDR_QUICKFIX: *errormsg = _(e_invalid_range); return FAIL; case ADDR_ARGUMENTS: if (ARGCOUNT == 0) eap->line1 = eap->line2 = 0; else { eap->line1 = 1; eap->line2 = ARGCOUNT; } break; case ADDR_QUICKFIX_VALID: #ifdef FEAT_QUICKFIX eap->line1 = 1; eap->line2 = qf_get_valid_size(eap); if (eap->line2 == 0) eap->line2 = 1; #endif break; case ADDR_NONE: // Will give an error later if a range is found. break; } ++eap->addr_count; } else if (*eap->cmd == '*' && vim_strchr(p_cpo, CPO_STAR) == NULL) { pos_T *fp; // '*' - visual area if (eap->addr_type != ADDR_LINES) { *errormsg = _(e_invalid_range); return FAIL; } ++eap->cmd; if (!eap->skip) { fp = getmark('<', FALSE); if (check_mark(fp) == FAIL) return FAIL; eap->line1 = fp->lnum; fp = getmark('>', FALSE); if (check_mark(fp) == FAIL) return FAIL; eap->line2 = fp->lnum; ++eap->addr_count; } } } else eap->line2 = lnum; eap->addr_count++; if (*eap->cmd == ';') { if (!eap->skip) { curwin->w_cursor.lnum = eap->line2; // Don't leave the cursor on an illegal line or column, but do // accept zero as address, so 0;/PATTERN/ works correctly. if (eap->line2 > 0) check_cursor(); } } else if (*eap->cmd != ',') break; ++eap->cmd; } // One address given: set start and end lines. if (eap->addr_count == 1) { eap->line1 = eap->line2; // ... but only implicit: really no address given if (lnum == MAXLNUM) eap->addr_count = 0; } return OK; }
null
null
211,522
262368515683715361306240115626304801557
146
patch 8.2.5037: cursor position may be invalid after "0;" range Problem: Cursor position may be invalid after "0;" range. Solution: Check the cursor position when it was set by ";" in the range.
other
vim
a062006b9de0b2947ab5fb376c6e67ef92a8cd69
1
n_start_visual_mode(int c) { #ifdef FEAT_CONCEAL int cursor_line_was_concealed = curwin->w_p_cole > 0 && conceal_cursor_line(curwin); #endif VIsual_mode = c; VIsual_active = TRUE; VIsual_reselect = TRUE; trigger_modechanged(); // Corner case: the 0 position in a tab may change when going into // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting. if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB) { validate_virtcol(); coladvance(curwin->w_virtcol); } VIsual = curwin->w_cursor; #ifdef FEAT_FOLDING foldAdjustVisual(); #endif setmouse(); #ifdef FEAT_CONCEAL // Check if redraw is needed after changing the state. conceal_check_cursor_line(cursor_line_was_concealed); #endif if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end may still be the same, and the selection needs to be owned clip_star.vmode = NUL; #endif // Only need to redraw this line, unless still need to redraw an old // Visual area (when 'lazyredraw' is set). if (curwin->w_redr_type < INVERTED) { curwin->w_old_cursor_lnum = curwin->w_cursor.lnum; curwin->w_old_visual_lnum = curwin->w_cursor.lnum; } }
null
null
211,563
50861159610133694982233083024002607438
47
patch 8.2.3610: crash when ModeChanged triggered too early Problem: Crash when ModeChanged triggered too early. Solution: Trigger ModeChanged after setting VIsual.
other
clamav-devel
c6870a6c857dd722dffaf6d37ae52ec259d12492
1
static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) { char *name; uint32_t i; if (!len) return NULL; if (len>400) len=400; name = cli_malloc(len); if (!name) { cli_dbgmsg("SIS: OOM\n"); return NULL; } fseek(f, ptr, SEEK_SET); if (fread(name, len, 1, f)!=1) { cli_dbgmsg("SIS: Unable to read string\n"); free(name); return NULL; } for (i = 0 ; i < len; i+=2) name[i/2] = name[i]; name[i/2]='\0'; return name; }
null
null
211,567
327528814995255199799968936205654694179
21
bb #6808
other
ImageMagick
4e378ea8fb99e869768f34e900105e8c769adfcd
1
static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); }
null
null
211,594
92614938296467182510039407621377821412
615
...
other
linux
89f3594d0de58e8a57d92d497dea9fee3d4b9cda
1
dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t value, length = len; unsigned total; u32 tag; char *kbuf; spin_lock_irq(&dev->lock); if (dev->state > STATE_DEV_OPENED) { value = ep0_write(fd, buf, len, ptr); spin_unlock_irq(&dev->lock); return value; } spin_unlock_irq(&dev->lock); if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) || (len > PAGE_SIZE * 4)) return -EINVAL; /* we might need to change message format someday */ if (copy_from_user (&tag, buf, 4)) return -EFAULT; if (tag != 0) return -EINVAL; buf += 4; length -= 4; kbuf = memdup_user(buf, length); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); spin_lock_irq (&dev->lock); value = -EINVAL; if (dev->buf) { kfree(kbuf); goto fail; } dev->buf = kbuf; /* full or low speed config */ dev->config = (void *) kbuf; total = le16_to_cpu(dev->config->wTotalLength); if (!is_valid_config(dev->config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; /* optional high speed config */ if (kbuf [1] == USB_DT_CONFIG) { dev->hs_config = (void *) kbuf; total = le16_to_cpu(dev->hs_config->wTotalLength); if (!is_valid_config(dev->hs_config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; } else { dev->hs_config = NULL; } /* could support multiple configs, using another encoding! */ /* device descriptor (tweaked for paranoia) */ if (length != USB_DT_DEVICE_SIZE) goto fail; dev->dev = (void *)kbuf; if (dev->dev->bLength != USB_DT_DEVICE_SIZE || dev->dev->bDescriptorType != USB_DT_DEVICE || dev->dev->bNumConfigurations != 1) goto fail; dev->dev->bcdUSB = cpu_to_le16 (0x0200); /* triggers gadgetfs_bind(); then we can enumerate. */ spin_unlock_irq (&dev->lock); if (dev->hs_config) gadgetfs_driver.max_speed = USB_SPEED_HIGH; else gadgetfs_driver.max_speed = USB_SPEED_FULL; value = usb_gadget_probe_driver(&gadgetfs_driver); if (value != 0) { kfree (dev->buf); dev->buf = NULL; } else { /* at this point "good" hardware has for the first time * let the USB the host see us. alternatively, if users * unplug/replug that will clear all the error state. * * note: everything running before here was guaranteed * to choke driver model style diagnostics. from here * on, they can work ... except in cleanup paths that * kick in after the ep0 descriptor is closed. */ value = len; dev->gadget_registered = true; } return value; fail: spin_unlock_irq (&dev->lock); pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev); kfree (dev->buf); dev->buf = NULL; return value; }
null
null
211,650
182318114915089365572042937695601411290
107
usb: gadget: don't release an existing dev->buf dev->buf does not need to be released if it already exists before executing dev_config. Acked-by: Alan Stern <[email protected]> Signed-off-by: Hangyu Hua <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
other
vim
4c13e5e6763c6eb36a343a2b8235ea227202e952
1
reg_match_visual(void) { pos_T top, bot; linenr_T lnum; colnr_T col; win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win; int mode; colnr_T start, end; colnr_T start2, end2; colnr_T cols; colnr_T curswant; // Check if the buffer is the current buffer. if (rex.reg_buf != curbuf || VIsual.lnum == 0) return FALSE; if (VIsual_active) { if (LT_POS(VIsual, wp->w_cursor)) { top = VIsual; bot = wp->w_cursor; } else { top = wp->w_cursor; bot = VIsual; } mode = VIsual_mode; curswant = wp->w_curswant; } else { if (LT_POS(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end)) { top = curbuf->b_visual.vi_start; bot = curbuf->b_visual.vi_end; } else { top = curbuf->b_visual.vi_end; bot = curbuf->b_visual.vi_start; } mode = curbuf->b_visual.vi_mode; curswant = curbuf->b_visual.vi_curswant; } lnum = rex.lnum + rex.reg_firstlnum; if (lnum < top.lnum || lnum > bot.lnum) return FALSE; if (mode == 'v') { col = (colnr_T)(rex.input - rex.line); if ((lnum == top.lnum && col < top.col) || (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e'))) return FALSE; } else if (mode == Ctrl_V) { getvvcol(wp, &top, &start, NULL, &end); getvvcol(wp, &bot, &start2, NULL, &end2); if (start2 < start) start = start2; if (end2 > end) end = end2; if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL) end = MAXCOL; cols = win_linetabsize(wp, rex.line, (colnr_T)(rex.input - rex.line)); if (cols < start || cols > end - (*p_sel == 'e')) return FALSE; } return TRUE; }
null
null
211,695
22765245964168680632689736727313063902
73
patch 8.2.3949: using freed memory with /\%V Problem: Using freed memory with /\%V. Solution: Get the line again after getvvcol().
other
gnulib
2d1bd71ec70a31b01d01b734faa66bb1ed28961f
1
glob (const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob) { const char *filename; char *dirname = NULL; size_t dirlen; int status; size_t oldcount; int meta; int dirname_modified; int malloc_dirname = 0; glob_t dirs; int retval = 0; size_t alloca_used = 0; if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0) { __set_errno (EINVAL); return -1; } /* POSIX requires all slashes to be matched. This means that with a trailing slash we must match only directories. */ if (pattern[0] && pattern[strlen (pattern) - 1] == '/') flags |= GLOB_ONLYDIR; if (!(flags & GLOB_DOOFFS)) /* Have to do this so 'globfree' knows where to start freeing. It also makes all the code that uses gl_offs simpler. */ pglob->gl_offs = 0; if (!(flags & GLOB_APPEND)) { pglob->gl_pathc = 0; if (!(flags & GLOB_DOOFFS)) pglob->gl_pathv = NULL; else { size_t i; if (pglob->gl_offs >= ~((size_t) 0) / sizeof (char *)) return GLOB_NOSPACE; pglob->gl_pathv = (char **) malloc ((pglob->gl_offs + 1) * sizeof (char *)); if (pglob->gl_pathv == NULL) return GLOB_NOSPACE; for (i = 0; i <= pglob->gl_offs; ++i) pglob->gl_pathv[i] = NULL; } } if (flags & GLOB_BRACE) { const char *begin; if (flags & GLOB_NOESCAPE) begin = strchr (pattern, '{'); else { begin = pattern; while (1) { if (*begin == '\0') { begin = NULL; break; } if (*begin == '\\' && begin[1] != '\0') ++begin; else if (*begin == '{') break; ++begin; } } if (begin != NULL) { /* Allocate working buffer large enough for our work. Note that we have at least an opening and closing brace. */ size_t firstc; char *alt_start; const char *p; const char *next; const char *rest; size_t rest_len; char *onealt; size_t pattern_len = strlen (pattern) - 1; int alloca_onealt = glob_use_alloca (alloca_used, pattern_len); if (alloca_onealt) onealt = alloca_account (pattern_len, alloca_used); else { onealt = malloc (pattern_len); if (onealt == NULL) return GLOB_NOSPACE; } /* We know the prefix for all sub-patterns. */ alt_start = mempcpy (onealt, pattern, begin - pattern); /* Find the first sub-pattern and at the same time find the rest after the closing brace. */ next = next_brace_sub (begin + 1, flags); if (next == NULL) { /* It is an invalid expression. */ illegal_brace: if (__glibc_unlikely (!alloca_onealt)) free (onealt); flags &= ~GLOB_BRACE; goto no_brace; } /* Now find the end of the whole brace expression. */ rest = next; while (*rest != '}') { rest = next_brace_sub (rest + 1, flags); if (rest == NULL) /* It is an illegal expression. */ goto illegal_brace; } /* Please note that we now can be sure the brace expression is well-formed. */ rest_len = strlen (++rest) + 1; /* We have a brace expression. BEGIN points to the opening {, NEXT points past the terminator of the first element, and END points past the final }. We will accumulate result names from recursive runs for each brace alternative in the buffer using GLOB_APPEND. */ firstc = pglob->gl_pathc; p = begin + 1; while (1) { int result; /* Construct the new glob expression. */ mempcpy (mempcpy (alt_start, p, next - p), rest, rest_len); result = glob (onealt, ((flags & ~(GLOB_NOCHECK | GLOB_NOMAGIC)) | GLOB_APPEND), errfunc, pglob); /* If we got an error, return it. */ if (result && result != GLOB_NOMATCH) { if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (!(flags & GLOB_APPEND)) { globfree (pglob); pglob->gl_pathc = 0; } return result; } if (*next == '}') /* We saw the last entry. */ break; p = next + 1; next = next_brace_sub (p, flags); assert (next != NULL); } if (__glibc_unlikely (!alloca_onealt)) free (onealt); if (pglob->gl_pathc != firstc) /* We found some entries. */ return 0; else if (!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC))) return GLOB_NOMATCH; } } no_brace: oldcount = pglob->gl_pathc + pglob->gl_offs; /* Find the filename. */ filename = strrchr (pattern, '/'); #if defined __MSDOS__ || defined WINDOWS32 /* The case of "d:pattern". Since ':' is not allowed in file names, we can safely assume that wherever it happens in pattern, it signals the filename part. This is so we could some day support patterns like "[a-z]:foo". */ if (filename == NULL) filename = strchr (pattern, ':'); #endif /* __MSDOS__ || WINDOWS32 */ dirname_modified = 0; if (filename == NULL) { /* This can mean two things: a simple name or "~name". The latter case is nothing but a notation for a directory. */ if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && pattern[0] == '~') { dirname = (char *) pattern; dirlen = strlen (pattern); /* Set FILENAME to NULL as a special flag. This is ugly but other solutions would require much more code. We test for this special case below. */ filename = NULL; } else { if (__glibc_unlikely (pattern[0] == '\0')) { dirs.gl_pathv = NULL; goto no_matches; } filename = pattern; dirname = (char *) "."; dirlen = 0; } } else if (filename == pattern || (filename == pattern + 1 && pattern[0] == '\\' && (flags & GLOB_NOESCAPE) == 0)) { /* "/pattern" or "\\/pattern". */ dirname = (char *) "/"; dirlen = 1; ++filename; } else { char *newp; dirlen = filename - pattern; #if defined __MSDOS__ || defined WINDOWS32 if (*filename == ':' || (filename > pattern + 1 && filename[-1] == ':')) { char *drive_spec; ++dirlen; drive_spec = __alloca (dirlen + 1); *((char *) mempcpy (drive_spec, pattern, dirlen)) = '\0'; /* For now, disallow wildcards in the drive spec, to prevent infinite recursion in glob. */ if (__glob_pattern_p (drive_spec, !(flags & GLOB_NOESCAPE))) return GLOB_NOMATCH; /* If this is "d:pattern", we need to copy ':' to DIRNAME as well. If it's "d:/pattern", don't remove the slash from "d:/", since "d:" and "d:/" are not the same.*/ } #endif if (glob_use_alloca (alloca_used, dirlen + 1)) newp = alloca_account (dirlen + 1, alloca_used); else { newp = malloc (dirlen + 1); if (newp == NULL) return GLOB_NOSPACE; malloc_dirname = 1; } *((char *) mempcpy (newp, pattern, dirlen)) = '\0'; dirname = newp; ++filename; #if defined __MSDOS__ || defined WINDOWS32 bool drive_root = (dirlen > 1 && (dirname[dirlen - 1] == ':' || (dirlen > 2 && dirname[dirlen - 2] == ':' && dirname[dirlen - 1] == '/'))); #else bool drive_root = false; #endif if (filename[0] == '\0' && dirlen > 1 && !drive_root) /* "pattern/". Expand "pattern", appending slashes. */ { int orig_flags = flags; if (!(flags & GLOB_NOESCAPE) && dirname[dirlen - 1] == '\\') { /* "pattern\\/". Remove the final backslash if it hasn't been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) { *(char *) &dirname[--dirlen] = '\0'; flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); } } int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob); if (val == 0) pglob->gl_flags = ((pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK)); else if (val == GLOB_NOMATCH && flags != orig_flags) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; oldcount = pglob->gl_pathc + pglob->gl_offs; goto no_matches; } retval = val; goto out; } } if ((flags & (GLOB_TILDE|GLOB_TILDE_CHECK)) && dirname[0] == '~') { if (dirname[1] == '\0' || dirname[1] == '/' || (!(flags & GLOB_NOESCAPE) && dirname[1] == '\\' && (dirname[2] == '\0' || dirname[2] == '/'))) { /* Look up home directory. */ char *home_dir = getenv ("HOME"); int malloc_home_dir = 0; if (home_dir == NULL || home_dir[0] == '\0') { #ifdef WINDOWS32 /* Windows NT defines HOMEDRIVE and HOMEPATH. But give preference to HOME, because the user can change HOME. */ const char *home_drive = getenv ("HOMEDRIVE"); const char *home_path = getenv ("HOMEPATH"); if (home_drive != NULL && home_path != NULL) { size_t home_drive_len = strlen (home_drive); size_t home_path_len = strlen (home_path); char *mem = alloca (home_drive_len + home_path_len + 1); memcpy (mem, home_drive, home_drive_len); memcpy (mem + home_drive_len, home_path, home_path_len + 1); home_dir = mem; } else home_dir = "c:/users/default"; /* poor default */ #else int err; struct passwd *p; struct passwd pwbuf; struct scratch_buffer s; scratch_buffer_init (&s); while (true) { p = NULL; err = __getlogin_r (s.data, s.length); if (err == 0) { # if defined HAVE_GETPWNAM_R || defined _LIBC size_t ssize = strlen (s.data) + 1; err = getpwnam_r (s.data, &pwbuf, s.data + ssize, s.length - ssize, &p); # else p = getpwnam (s.data); if (p == NULL) err = errno; # endif } if (err != ERANGE) break; if (!scratch_buffer_grow (&s)) { retval = GLOB_NOSPACE; goto out; } } if (err == 0) { home_dir = strdup (p->pw_dir); malloc_home_dir = 1; } scratch_buffer_free (&s); if (err == 0 && home_dir == NULL) { retval = GLOB_NOSPACE; goto out; } #endif /* WINDOWS32 */ } if (home_dir == NULL || home_dir[0] == '\0') { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); if (flags & GLOB_TILDE_CHECK) { retval = GLOB_NOMATCH; goto out; } else { home_dir = (char *) "~"; /* No luck. */ malloc_home_dir = 0; } } /* Now construct the full directory. */ if (dirname[1] == '\0') { if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = home_dir; dirlen = strlen (dirname); malloc_dirname = malloc_home_dir; } else { char *newp; size_t home_len = strlen (home_dir); int use_alloca = glob_use_alloca (alloca_used, home_len + dirlen); if (use_alloca) newp = alloca_account (home_len + dirlen, alloca_used); else { newp = malloc (home_len + dirlen); if (newp == NULL) { if (__glibc_unlikely (malloc_home_dir)) free (home_dir); retval = GLOB_NOSPACE; goto out; } } mempcpy (mempcpy (newp, home_dir, home_len), &dirname[1], dirlen); if (__glibc_unlikely (malloc_dirname)) free (dirname); dirname = newp; dirlen += home_len - 1; malloc_dirname = !use_alloca; if (__glibc_unlikely (malloc_home_dir)) free (home_dir); } dirname_modified = 1; } else { #ifndef WINDOWS32 char *end_name = strchr (dirname, '/'); char *user_name; int malloc_user_name = 0; char *unescape = NULL; if (!(flags & GLOB_NOESCAPE)) { if (end_name == NULL) { unescape = strchr (dirname, '\\'); if (unescape) end_name = strchr (unescape, '\0'); } else unescape = memchr (dirname, '\\', end_name - dirname); } if (end_name == NULL) user_name = dirname + 1; else { char *newp; if (glob_use_alloca (alloca_used, end_name - dirname)) newp = alloca_account (end_name - dirname, alloca_used); else { newp = malloc (end_name - dirname); if (newp == NULL) { retval = GLOB_NOSPACE; goto out; } malloc_user_name = 1; } if (unescape != NULL) { char *p = mempcpy (newp, dirname + 1, unescape - dirname - 1); char *q = unescape; while (*q != '\0') { if (*q == '\\') { if (q[1] == '\0') { /* "~fo\\o\\" unescape to user_name "foo\\", but "~fo\\o\\/" unescape to user_name "foo". */ if (filename == NULL) *p++ = '\\'; break; } ++q; } *p++ = *q++; } *p = '\0'; } else *((char *) mempcpy (newp, dirname + 1, end_name - dirname)) = '\0'; user_name = newp; } /* Look up specific user's home directory. */ { struct passwd *p; struct scratch_buffer pwtmpbuf; scratch_buffer_init (&pwtmpbuf); # if defined HAVE_GETPWNAM_R || defined _LIBC struct passwd pwbuf; while (getpwnam_r (user_name, &pwbuf, pwtmpbuf.data, pwtmpbuf.length, &p) == ERANGE) { if (!scratch_buffer_grow (&pwtmpbuf)) { retval = GLOB_NOSPACE; goto out; } } # else p = getpwnam (user_name); # endif if (__glibc_unlikely (malloc_user_name)) free (user_name); /* If we found a home directory use this. */ if (p != NULL) { size_t home_len = strlen (p->pw_dir); size_t rest_len = end_name == NULL ? 0 : strlen (end_name); char *d; if (__glibc_unlikely (malloc_dirname)) free (dirname); malloc_dirname = 0; if (glob_use_alloca (alloca_used, home_len + rest_len + 1)) dirname = alloca_account (home_len + rest_len + 1, alloca_used); else { dirname = malloc (home_len + rest_len + 1); if (dirname == NULL) { scratch_buffer_free (&pwtmpbuf); retval = GLOB_NOSPACE; goto out; } malloc_dirname = 1; } d = mempcpy (dirname, p->pw_dir, home_len); if (end_name != NULL) d = mempcpy (d, end_name, rest_len); *d = '\0'; dirlen = home_len + rest_len; dirname_modified = 1; } else { if (flags & GLOB_TILDE_CHECK) { /* We have to regard it as an error if we cannot find the home directory. */ retval = GLOB_NOMATCH; goto out; } } scratch_buffer_free (&pwtmpbuf); } #endif /* !WINDOWS32 */ } } /* Now test whether we looked for "~" or "~NAME". In this case we can give the answer now. */ if (filename == NULL) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace: free (pglob->gl_pathv); pglob->gl_pathv = NULL; pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace; pglob->gl_pathv = new_gl_pathv; if (flags & GLOB_MARK && is_dir (dirname, flags, pglob)) { char *p; pglob->gl_pathv[newcount] = malloc (dirlen + 2); if (pglob->gl_pathv[newcount] == NULL) goto nospace; p = mempcpy (pglob->gl_pathv[newcount], dirname, dirlen); p[0] = '/'; p[1] = '\0'; if (__glibc_unlikely (malloc_dirname)) free (dirname); } else { if (__glibc_unlikely (malloc_dirname)) pglob->gl_pathv[newcount] = dirname; else { pglob->gl_pathv[newcount] = strdup (dirname); if (pglob->gl_pathv[newcount] == NULL) goto nospace; } } pglob->gl_pathv[++newcount] = NULL; ++pglob->gl_pathc; pglob->gl_flags = flags; return 0; } meta = __glob_pattern_type (dirname, !(flags & GLOB_NOESCAPE)); /* meta is 1 if correct glob pattern containing metacharacters. If meta has bit (1 << 2) set, it means there was an unterminated [ which we handle the same, using fnmatch. Broken unterminated pattern bracket expressions ought to be rare enough that it is not worth special casing them, fnmatch will do the right thing. */ if (meta & (GLOBPAT_SPECIAL | GLOBPAT_BRACKET)) { /* The directory name contains metacharacters, so we have to glob for the directory, and then glob for the pattern in each directory found. */ size_t i; if (!(flags & GLOB_NOESCAPE) && dirlen > 0 && dirname[dirlen - 1] == '\\') { /* "foo\\/bar". Remove the final backslash from dirname if it has not been quoted. */ char *p = (char *) &dirname[dirlen - 1]; while (p > dirname && p[-1] == '\\') --p; if ((&dirname[dirlen] - p) & 1) *(char *) &dirname[--dirlen] = '\0'; } if (__glibc_unlikely ((flags & GLOB_ALTDIRFUNC) != 0)) { /* Use the alternative access functions also in the recursive call. */ dirs.gl_opendir = pglob->gl_opendir; dirs.gl_readdir = pglob->gl_readdir; dirs.gl_closedir = pglob->gl_closedir; dirs.gl_stat = pglob->gl_stat; dirs.gl_lstat = pglob->gl_lstat; } status = glob (dirname, ((flags & (GLOB_ERR | GLOB_NOESCAPE | GLOB_ALTDIRFUNC)) | GLOB_NOSORT | GLOB_ONLYDIR), errfunc, &dirs); if (status != 0) { if ((flags & GLOB_NOCHECK) == 0 || status != GLOB_NOMATCH) { retval = status; goto out; } goto no_matches; } /* We have successfully globbed the preceding directory name. For each name we found, call glob_in_dir on it and FILENAME, appending the results to PGLOB. */ for (i = 0; i < dirs.gl_pathc; ++i) { size_t old_pathc; old_pathc = pglob->gl_pathc; status = glob_in_dir (filename, dirs.gl_pathv[i], ((flags | GLOB_APPEND) & ~(GLOB_NOCHECK | GLOB_NOMAGIC)), errfunc, pglob, alloca_used); if (status == GLOB_NOMATCH) /* No matches in this directory. Try the next. */ continue; if (status != 0) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = status; goto out; } /* Stick the directory on the front of each name. */ if (prefix_array (dirs.gl_pathv[i], &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } flags |= GLOB_MAGCHAR; /* We have ignored the GLOB_NOCHECK flag in the 'glob_in_dir' calls. But if we have not found any matching entry and the GLOB_NOCHECK flag was set we must return the input pattern itself. */ if (pglob->gl_pathc + pglob->gl_offs == oldcount) { no_matches: /* No matches. */ if (flags & GLOB_NOCHECK) { size_t newcount = pglob->gl_pathc + pglob->gl_offs; char **new_gl_pathv; if (newcount > SIZE_MAX / sizeof (char *) - 2) { nospace2: globfree (&dirs); retval = GLOB_NOSPACE; goto out; } new_gl_pathv = realloc (pglob->gl_pathv, (newcount + 2) * sizeof (char *)); if (new_gl_pathv == NULL) goto nospace2; pglob->gl_pathv = new_gl_pathv; pglob->gl_pathv[newcount] = strdup (pattern); if (pglob->gl_pathv[newcount] == NULL) { globfree (&dirs); globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } ++pglob->gl_pathc; ++newcount; pglob->gl_pathv[newcount] = NULL; pglob->gl_flags = flags; } else { globfree (&dirs); retval = GLOB_NOMATCH; goto out; } } globfree (&dirs); } else { size_t old_pathc = pglob->gl_pathc; int orig_flags = flags; if (meta & GLOBPAT_BACKSLASH) { char *p = strchr (dirname, '\\'), *q; /* We need to unescape the dirname string. It is certainly allocated by alloca, as otherwise filename would be NULL or dirname wouldn't contain backslashes. */ q = p; do { if (*p == '\\') { *q = *++p; --dirlen; } else *q = *p; ++q; } while (*p++ != '\0'); dirname_modified = 1; } if (dirname_modified) flags &= ~(GLOB_NOCHECK | GLOB_NOMAGIC); status = glob_in_dir (filename, dirname, flags, errfunc, pglob, alloca_used); if (status != 0) { if (status == GLOB_NOMATCH && flags != orig_flags && pglob->gl_pathc + pglob->gl_offs == oldcount) { /* Make sure globfree (&dirs); is a nop. */ dirs.gl_pathv = NULL; flags = orig_flags; goto no_matches; } retval = status; goto out; } if (dirlen > 0) { /* Stick the directory on the front of each name. */ if (prefix_array (dirname, &pglob->gl_pathv[old_pathc + pglob->gl_offs], pglob->gl_pathc - old_pathc)) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } } } if (flags & GLOB_MARK) { /* Append slashes to directory names. */ size_t i; for (i = oldcount; i < pglob->gl_pathc + pglob->gl_offs; ++i) if (is_dir (pglob->gl_pathv[i], flags, pglob)) { size_t len = strlen (pglob->gl_pathv[i]) + 2; char *new = realloc (pglob->gl_pathv[i], len); if (new == NULL) { globfree (pglob); pglob->gl_pathc = 0; retval = GLOB_NOSPACE; goto out; } strcpy (&new[len - 2], "/"); pglob->gl_pathv[i] = new; } } if (!(flags & GLOB_NOSORT)) { /* Sort the vector. */ qsort (&pglob->gl_pathv[oldcount], pglob->gl_pathc + pglob->gl_offs - oldcount, sizeof (char *), collated_compare); } out: if (__glibc_unlikely (malloc_dirname)) free (dirname); return retval; }
null
null
211,699
81204469815108347288274529577404178778
876
glob: fix heap buffer overflow * lib/glob.c (glob): Fix off-by-one error introduced into glibc in commit dd7d45e838a42b0ed470c44b55901ea98d0c2bab dated 1997-10-29 20:33:40. Problem reported by Tim Rühsen in: https://sourceware.org/bugzilla/show_bug.cgi?id=22320 Fix suggested by Bruno Haible.
other
linux
4fbcc1a4cb20fe26ad0225679c536c80f1648221
1
int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host, u8 event, struct sk_buff *skb) { int r = 0; struct device *dev = &hdev->ndev->dev; struct nfc_evt_transaction *transaction; pr_debug("connectivity gate event: %x\n", event); switch (event) { case ST21NFCA_EVT_CONNECTIVITY: r = nfc_se_connectivity(hdev->ndev, host); break; case ST21NFCA_EVT_TRANSACTION: /* * According to specification etsi 102 622 * 11.2.2.4 EVT_TRANSACTION Table 52 * Description Tag Length * AID 81 5 to 16 * PARAMETERS 82 0 to 255 */ if (skb->len < NFC_MIN_AID_LENGTH + 2 && skb->data[0] != NFC_EVT_TRANSACTION_AID_TAG) return -EPROTO; transaction = devm_kzalloc(dev, skb->len - 2, GFP_KERNEL); if (!transaction) return -ENOMEM; transaction->aid_len = skb->data[1]; memcpy(transaction->aid, &skb->data[2], transaction->aid_len); /* Check next byte is PARAMETERS tag (82) */ if (skb->data[transaction->aid_len + 2] != NFC_EVT_TRANSACTION_PARAMS_TAG) return -EPROTO; transaction->params_len = skb->data[transaction->aid_len + 3]; memcpy(transaction->params, skb->data + transaction->aid_len + 4, transaction->params_len); r = nfc_se_transaction(hdev->ndev, host, transaction); break; default: nfc_err(&hdev->ndev->dev, "Unexpected event on connectivity gate\n"); return 1; } kfree_skb(skb); return r; }
null
null
211,700
213748705583574003698694195183346748796
51
nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION It appears that there are some buffer overflows in EVT_TRANSACTION. This happens because the length parameters that are passed to memcpy come directly from skb->data and are not guarded in any way. Signed-off-by: Jordy Zomer <[email protected]> Reviewed-by: Krzysztof Kozlowski <[email protected]> Signed-off-by: David S. Miller <[email protected]>
other
ntp
07a5b8141e354a998a52994c3c9cd547927e56ce
1
cookedprint( int datatype, int length, const char *data, int status, int quiet, FILE *fp ) { char *name; char *value; char output_raw; int fmt; l_fp lfp; sockaddr_u hval; u_long uval; int narr; size_t len; l_fp lfparr[8]; char b[12]; char bn[2 * MAXVARLEN]; char bv[2 * MAXVALLEN]; UNUSED_ARG(datatype); if (!quiet) fprintf(fp, "status=%04x %s,\n", status, statustoa(datatype, status)); startoutput(); while (nextvar(&length, &data, &name, &value)) { fmt = varfmt(name); output_raw = 0; switch (fmt) { case PADDING: output_raw = '*'; break; case TS: if (!decodets(value, &lfp)) output_raw = '?'; else output(fp, name, prettydate(&lfp)); break; case HA: /* fallthru */ case NA: if (!decodenetnum(value, &hval)) { output_raw = '?'; } else if (fmt == HA){ output(fp, name, nntohost(&hval)); } else { output(fp, name, stoa(&hval)); } break; case RF: if (decodenetnum(value, &hval)) { if (ISREFCLOCKADR(&hval)) output(fp, name, refnumtoa(&hval)); else output(fp, name, stoa(&hval)); } else if (strlen(value) <= 4) { output(fp, name, value); } else { output_raw = '?'; } break; case LP: if (!decodeuint(value, &uval) || uval > 3) { output_raw = '?'; } else { b[0] = (0x2 & uval) ? '1' : '0'; b[1] = (0x1 & uval) ? '1' : '0'; b[2] = '\0'; output(fp, name, b); } break; case OC: if (!decodeuint(value, &uval)) { output_raw = '?'; } else { snprintf(b, sizeof(b), "%03lo", uval); output(fp, name, b); } break; case AR: if (!decodearr(value, &narr, lfparr)) output_raw = '?'; else outputarr(fp, name, narr, lfparr); break; case FX: if (!decodeuint(value, &uval)) output_raw = '?'; else output(fp, name, tstflags(uval)); break; default: fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n", name, value, fmt); output_raw = '?'; break; } if (output_raw != 0) { atoascii(name, MAXVARLEN, bn, sizeof(bn)); atoascii(value, MAXVALLEN, bv, sizeof(bv)); if (output_raw != '*') { len = strlen(bv); bv[len] = output_raw; bv[len+1] = '\0'; } output(fp, bn, bv); } } endoutput(fp); }
null
null
211,773
296400942991299280347301932041460046093
129
[TALOS-CAN-0063] avoid buffer overrun in ntpq
other
jasper
4cd52b5daac62b00a0a328451544807ddecf775f
1
static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) { goto error; } unsigned cmptno; for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); if (cp->rawsize == 0) { /* prevent division by zero in cp_create() */ goto error; } cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1), sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; }
null
null
211,785
181232699919937488567474720086554483482
431
Avoid maxrlvls more than upper bound to cause heap-buffer-overflow
other
php-src
1744be2d17befc69bf00033993f4081852a747d6
1
static void xsl_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */ { xsltTransformContextPtr tctxt; zval **args; zval *retval; int result, i, ret; int error = 0; zend_fcall_info fci; zval handler; xmlXPathObjectPtr obj; char *str; char *callable = NULL; xsl_object *intern; TSRMLS_FETCH(); if (! zend_is_executing(TSRMLS_C)) { xsltGenericError(xsltGenericErrorContext, "xsltExtFunctionTest: Function called from outside of PHP\n"); error = 1; } else { tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltGenericError(xsltGenericErrorContext, "xsltExtFunctionTest: failed to get the transformation context\n"); error = 1; } else { intern = (xsl_object *) tctxt->_private; if (intern == NULL) { xsltGenericError(xsltGenericErrorContext, "xsltExtFunctionTest: failed to get the internal object\n"); error = 1; } else if (intern->registerPhpFunctions == 0) { xsltGenericError(xsltGenericErrorContext, "xsltExtFunctionTest: PHP Object did not register PHP functions\n"); error = 1; } } } if (error == 1) { for (i = nargs - 1; i >= 0; i--) { obj = valuePop(ctxt); xmlXPathFreeObject(obj); } return; } fci.param_count = nargs - 1; if (fci.param_count > 0) { fci.params = safe_emalloc(fci.param_count, sizeof(zval**), 0); args = safe_emalloc(fci.param_count, sizeof(zval *), 0); } /* Reverse order to pop values off ctxt stack */ for (i = nargs - 2; i >= 0; i--) { obj = valuePop(ctxt); MAKE_STD_ZVAL(args[i]); switch (obj->type) { case XPATH_STRING: ZVAL_STRING(args[i], obj->stringval, 1); break; case XPATH_BOOLEAN: ZVAL_BOOL(args[i], obj->boolval); break; case XPATH_NUMBER: ZVAL_DOUBLE(args[i], obj->floatval); break; case XPATH_NODESET: if (type == 1) { str = xmlXPathCastToString(obj); ZVAL_STRING(args[i], str, 1); xmlFree(str); } else if (type == 2) { int j; dom_object *domintern = (dom_object *)intern->doc; array_init(args[i]); if (obj->nodesetval && obj->nodesetval->nodeNr > 0) { for (j = 0; j < obj->nodesetval->nodeNr; j++) { xmlNodePtr node = obj->nodesetval->nodeTab[j]; zval *child; MAKE_STD_ZVAL(child); /* not sure, if we need this... it's copied from xpath.c */ if (node->type == XML_NAMESPACE_DECL) { xmlNsPtr curns; xmlNodePtr nsparent; nsparent = node->_private; curns = xmlNewNs(NULL, node->name, NULL); if (node->children) { curns->prefix = xmlStrdup((char *) node->children); } if (node->children) { node = xmlNewDocNode(node->doc, NULL, (char *) node->children, node->name); } else { node = xmlNewDocNode(node->doc, NULL, "xmlns", node->name); } node->type = XML_NAMESPACE_DECL; node->parent = nsparent; node->ns = curns; } else { node = xmlDocCopyNodeList(domintern->document->ptr, node); } child = php_dom_create_object(node, &ret, child, domintern TSRMLS_CC); add_next_index_zval(args[i], child); } } } break; default: str = xmlXPathCastToString(obj); ZVAL_STRING(args[i], str, 1); xmlFree(str); } xmlXPathFreeObject(obj); fci.params[i] = &args[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); obj = valuePop(ctxt); if (obj->stringval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string"); xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewString("")); if (fci.param_count > 0) { for (i = 0; i < nargs - 1; i++) { zval_ptr_dtor(&args[i]); } efree(args); efree(fci.params); } return; } INIT_PZVAL(&handler); ZVAL_STRING(&handler, obj->stringval, 1); xmlXPathFreeObject(obj); fci.function_name = &handler; fci.symbol_table = NULL; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ if (!zend_make_callable(&handler, &callable TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable); valuePush(ctxt, xmlXPathNewString("")); } else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable, strlen(callable) + 1) == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'", callable); /* Push an empty string, so that we at least have an xslt result... */ valuePush(ctxt, xmlXPathNewString("")); } else { result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { if (Z_TYPE(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(&handler)); valuePush(ctxt, xmlXPathNewString("")); } /* retval is == NULL, when an exception occurred, don't report anything, because PHP itself will handle that */ } else if (retval == NULL) { } else { if (retval->type == IS_OBJECT && instanceof_function( Z_OBJCE_P(retval), dom_node_class_entry TSRMLS_CC)) { xmlNode *nodep; dom_object *obj; if (intern->node_list == NULL) { ALLOC_HASHTABLE(intern->node_list); zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0); } zval_add_ref(&retval); zend_hash_next_index_insert(intern->node_list, &retval, sizeof(zval *), NULL); obj = (dom_object *)zend_object_store_get_object(retval TSRMLS_CC); nodep = dom_object_get_node(obj); valuePush(ctxt, xmlXPathNewNodeSet(nodep)); } else if (retval->type == IS_BOOL) { valuePush(ctxt, xmlXPathNewBoolean(retval->value.lval)); } else if (retval->type == IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string"); valuePush(ctxt, xmlXPathNewString("")); } else { convert_to_string_ex(&retval); valuePush(ctxt, xmlXPathNewString( Z_STRVAL_P(retval))); } zval_ptr_dtor(&retval); } } efree(callable); zval_dtor(&handler); if (fci.param_count > 0) { for (i = 0; i < nargs - 1; i++) { zval_ptr_dtor(&args[i]); } efree(args); efree(fci.params); } }
null
null
211,810
166937765955710490140933898378014635515
197
Fix for bug #69782
other
ghostpdl
78911a01b67d590b4a91afac2e8417360b934156
1
z2restore(i_ctx_t *i_ctx_p) { while (gs_gstate_saved(gs_gstate_saved(igs))) { if (restore_page_device(igs, gs_gstate_saved(igs))) return push_callout(i_ctx_p, "%restore1pagedevice"); gs_grestore(igs); } if (restore_page_device(igs, gs_gstate_saved(igs))) return push_callout(i_ctx_p, "%restorepagedevice"); return zrestore(i_ctx_p); }
null
null
211,831
337854342133306426565204271772415332642
11
Bug 699654: Check the restore operand type The primary function that implements restore correctly checked its parameter, but a function that does some preliminary work for the restore (gstate and device handling) did not check. So, even though the restore correctly errored out, it left things partially done and, in particular, the device in partially restored state. Meaning the LockSafetyParams was not correctly set.
other
ndjbdns
ef1875907a0e3cf632f66c3add91f08543c74f3c
1
doit (struct query *z, int state) { char key[257]; char misc[20], header[12]; char *buf = 0, *cached = 0; const char *whichserver = 0; unsigned int rcode = 0; unsigned int posanswers = 0; unsigned int len = 0, cachedlen = 0; uint16 numanswers = 0; uint16 numauthority = 0; unsigned int posauthority = 0; uint16 numglue = 0; unsigned int posglue = 0; unsigned int pos = 0, pos2 = 0; uint16 datalen = 0; char *control = 0, *d = 0; const char *dtype = 0; unsigned int dlen = 0; int flagout = 0, flagcname = 0; int flagreferral = 0, flagsoa = 0; int i = 0, j = 0, k = 0, p = 0, q = 0; uint32 ttl = 0, soattl = 0, cnamettl = 0; errno = error_io; if (state == 1) goto HAVEPACKET; if (state == -1) { if (debug_level > 1) log_servfail (z->name[z->level]); goto SERVFAIL; } NEWNAME: if (++z->loop == 100) goto DIE; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; dlen = dns_domain_length (d); if (globalip (d, misc)) { if (z->level) { for (k = 0; k < 64; k += 4) { if (byte_equal (z->servers[z->level - 1] + k, 4, "\0\0\0\0")) { byte_copy (z->servers[z->level - 1] + k, 4, misc); break; } } goto LOWERLEVEL; } if (!rqa (z)) goto DIE; if (typematch (DNS_T_A, dtype)) { if (!response_rstart (d, DNS_T_A, 655360)) goto DIE; if (!response_addbytes (misc, 4)) goto DIE; response_rfinish (RESPONSE_ANSWER); } cleanup (z); return 1; } if (dns_domain_equal (d, "\0011\0010\0010\003127\7in-addr\4arpa\0")) { if (z->level) goto LOWERLEVEL; if (!rqa (z)) goto DIE; if (typematch (DNS_T_PTR, dtype)) { if (!response_rstart (d, DNS_T_PTR, 655360)) goto DIE; if (!response_addname ("\011localhost\0")) goto DIE; response_rfinish (RESPONSE_ANSWER); } cleanup (z); if (debug_level > 2) log_stats (); return 1; } if (dlen <= 255) { byte_copy (key, 2, DNS_T_ANY); byte_copy (key + 2, dlen, d); case_lowerb (key + 2, dlen); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached) { if (debug_level > 2) log_cachednxdomain (d); goto NXDOMAIN; } byte_copy (key, 2, DNS_T_CNAME); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached) { if (typematch (DNS_T_CNAME, dtype)) { if (debug_level > 2) log_cachedanswer (d, DNS_T_CNAME); if (!rqa (z)) goto DIE; if (!response_cname (z->name[0], cached, ttl)) goto DIE; cleanup (z); return 1; } if (debug_level > 2) log_cachedcname (d, cached); if (!dns_domain_copy (&cname, cached)) goto DIE; goto CNAME; } if (typematch (DNS_T_NS, dtype)) { byte_copy (key, 2, DNS_T_NS); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY))) { if (debug_level > 2) log_cachedanswer (d, DNS_T_NS); if (!rqa (z)) goto DIE; pos = 0; while ((pos=dns_packet_getname (cached, cachedlen, pos, &t2))) { if (!response_rstart (d, DNS_T_NS, ttl)) goto DIE; if (!response_addname (t2)) goto DIE; response_rfinish (RESPONSE_ANSWER); } cleanup (z); return 1; } } if (typematch (DNS_T_PTR, dtype)) { byte_copy (key, 2, DNS_T_PTR); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && (cachedlen || byte_diff(dtype, 2, DNS_T_ANY))) { if (debug_level > 2) log_cachedanswer (d, DNS_T_PTR); if (!rqa (z)) goto DIE; pos = 0; while ((pos=dns_packet_getname (cached, cachedlen, pos, &t2))) { if (!response_rstart (d, DNS_T_PTR, ttl)) goto DIE; if (!response_addname (t2)) goto DIE; response_rfinish (RESPONSE_ANSWER); } cleanup(z); return 1; } } if (typematch (DNS_T_MX, dtype)) { byte_copy (key, 2, DNS_T_MX); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY))) { if (debug_level > 2) log_cachedanswer (d, DNS_T_MX); if (!rqa (z)) goto DIE; pos = 0; while ((pos=dns_packet_copy (cached, cachedlen, pos, misc, 2))) { pos = dns_packet_getname (cached, cachedlen, pos, &t2); if (!pos) break; if (!response_rstart (d, DNS_T_MX, ttl)) goto DIE; if (!response_addbytes (misc, 2)) goto DIE; if (!response_addname (t2)) goto DIE; response_rfinish (RESPONSE_ANSWER); } cleanup (z); return 1; } } if (typematch (DNS_T_A, dtype)) { byte_copy (key,2,DNS_T_A); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY))) { if (z->level) { if (debug_level > 2) log_cachedanswer (d, DNS_T_A); while (cachedlen >= 4) { for (k = 0; k < 64; k += 4) { if (byte_equal (z->servers[z->level - 1] + k, 4, "\0\0\0\0")) { byte_copy (z->servers[z->level - 1] + k, 4, cached); break; } } cached += 4; cachedlen -= 4; } goto LOWERLEVEL; } if (debug_level > 2) log_cachedanswer (d, DNS_T_A); if (!rqa (z)) goto DIE; while (cachedlen >= 4) { if (!response_rstart (d, DNS_T_A, ttl)) goto DIE; if (!response_addbytes (cached, 4)) goto DIE; response_rfinish (RESPONSE_ANSWER); cached += 4; cachedlen -= 4; } cleanup (z); return 1; } } if (!typematch (DNS_T_ANY, dtype) && !typematch (DNS_T_AXFR, dtype) && !typematch (DNS_T_CNAME, dtype) && !typematch (DNS_T_NS, dtype) && !typematch (DNS_T_PTR, dtype) && !typematch (DNS_T_A, dtype) && !typematch (DNS_T_MX, dtype)) { byte_copy (key, 2, dtype); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && (cachedlen || byte_diff (dtype, 2, DNS_T_ANY))) { if (debug_level > 2) log_cachedanswer (d, dtype); if (!rqa (z)) goto DIE; while (cachedlen >= 2) { uint16_unpack_big (cached, &datalen); cached += 2; cachedlen -= 2; if (datalen > cachedlen) goto DIE; if (!response_rstart (d, dtype, ttl)) goto DIE; if (!response_addbytes (cached, datalen)) goto DIE; response_rfinish (RESPONSE_ANSWER); cached += datalen; cachedlen -= datalen; } cleanup (z); return 1; } } } for (;;) { if (roots (z->servers[z->level], d)) { for (j = 0; j < QUERY_MAXNS; ++j) dns_domain_free (&z->ns[z->level][j]); z->control[z->level] = d; break; } if (!flagforwardonly && (z->level < 2)) { if (dlen < 255) { byte_copy (key,2,DNS_T_NS); byte_copy (key + 2,dlen,d); case_lowerb (key + 2,dlen); cached = cache_get (key, dlen + 2, &cachedlen, &ttl); if (cached && cachedlen) { z->control[z->level] = d; byte_zero (z->servers[z->level],64); for (j = 0; j < QUERY_MAXNS; ++j) dns_domain_free (&z->ns[z->level][j]); j = pos = 0; pos = dns_packet_getname (cached, cachedlen, pos, &t1); while (pos) { if (debug_level > 2) log_cachedns (d, t1); if (j < QUERY_MAXNS) if (!dns_domain_copy (&z->ns[z->level][j++], t1)) goto DIE; pos = dns_packet_getname (cached, cachedlen, pos, &t1); } break; } } } if (!*d) goto DIE; j = 1 + (unsigned int) (unsigned char) *d; dlen -= j; d += j; } HAVENS: for (j = 0; j < QUERY_MAXNS; ++j) { if (z->ns[z->level][j]) { if (z->level + 1 < QUERY_MAXLEVEL) { int dc = dns_domain_copy (&z->name[z->level + 1], z->ns[z->level][j]); if (!dc) goto DIE; dns_domain_free (&z->ns[z->level][j]); ++z->level; goto NEWNAME; } dns_domain_free (&z->ns[z->level][j]); } } for (j = 0; j < 64; j += 4) if (byte_diff (z->servers[z->level] + j, 4, "\0\0\0\0")) break; if (j == 64) goto SERVFAIL; dns_sortip (z->servers[z->level], 64); if (z->level) { if (debug_level > 2) log_tx (z->name[z->level], DNS_T_A, z->control[z->level], z->servers[z->level],z->level); if (dns_transmit_start (&z->dt, z->servers[z->level], flagforwardonly, z->name[z->level], DNS_T_A,z->localip) == -1) goto DIE; } else { if (debug_level > 2) log_tx (z->name[0], z->type, z->control[0], z->servers[0], 0); if (dns_transmit_start (&z->dt, z->servers[0], flagforwardonly, z->name[0], z->type, z->localip) == -1) goto DIE; } return 0; LOWERLEVEL: dns_domain_free (&z->name[z->level]); for (j = 0; j < QUERY_MAXNS; ++j) dns_domain_free (&z->ns[z->level][j]); --z->level; goto HAVENS; HAVEPACKET: if (++z->loop == 100) goto DIE; buf = z->dt.packet; len = z->dt.packetlen; whichserver = z->dt.servers + 4 * z->dt.curserver; control = z->control[z->level]; d = z->name[z->level]; dtype = z->level ? DNS_T_A : z->type; if (!(pos = dns_packet_copy (buf, len, 0, header, 12))) goto DIE; if (!(pos = dns_packet_skipname (buf, len, pos))) goto DIE; pos += 4; posanswers = pos; uint16_unpack_big (header + 6, &numanswers); uint16_unpack_big (header + 8, &numauthority); uint16_unpack_big (header + 10, &numglue); rcode = header[3] & 15; if (rcode && (rcode != 3)) goto DIE; /* impossible; see irrelevant() */ flagsoa = soattl = cnamettl = 0; flagout = flagcname = flagreferral = 0; for (j = 0; j < numanswers; ++j) { pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; if (dns_domain_equal (t1, d)) { if (byte_equal (header + 2, 2, DNS_C_IN)) { /* should always be true */ if (typematch (header, dtype)) flagout = 1; else if (typematch (header, DNS_T_CNAME)) { if (!dns_packet_getname (buf, len, pos, &cname)) goto DIE; flagcname = 1; cnamettl = ttlget (header + 4); } } } uint16_unpack_big (header + 8, &datalen); pos += datalen; } posauthority = pos; for (j = 0; j < numauthority; ++j) { pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; if (typematch (header, DNS_T_SOA)) { flagsoa = 1; soattl = ttlget (header + 4); if (soattl > 3600) soattl = 3600; } else if (typematch (header, DNS_T_NS)) { flagreferral = 1; if (!dns_domain_copy (&referral, t1)) goto DIE; } uint16_unpack_big (header + 8, &datalen); pos += datalen; } posglue = pos; if (!flagcname && !rcode && !flagout && flagreferral && !flagsoa) { if (dns_domain_equal (referral, control) || !dns_domain_suffix (referral, control)) { if (debug_level > 2) log_lame (whichserver, control, referral); byte_zero (whichserver, 4); goto HAVENS; } } if (records) { alloc_free (records); records = 0; } k = numanswers + numauthority + numglue; records = (unsigned int *) alloc (k * sizeof (unsigned int)); if (!records) goto DIE; pos = posanswers; for (j = 0; j < k; ++j) { records[j] = pos; pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; uint16_unpack_big (header + 8, &datalen); pos += datalen; } i = j = k; while (j > 1) { if (i > 1) { --i; pos = records[i - 1]; } else { pos = records[j - 1]; records[j - 1] = records[i - 1]; --j; } q = i; while ((p = q * 2) < j) { if (!smaller (buf, len, records[p], records[p - 1])) ++p; records[q - 1] = records[p - 1]; q = p; } if (p == j) { records[q - 1] = records[p - 1]; q = p; } while ((q > i) && smaller (buf, len, records[(p = q/2) - 1], pos)) { records[q - 1] = records[p - 1]; q = p; } records[q - 1] = pos; } i = 0; while (i < k) { char type[2]; if (!(pos = dns_packet_getname (buf, len, records[i], &t1))) goto DIE; if (!(pos = dns_packet_copy (buf, len, pos, header, 10))) goto DIE; ttl = ttlget (header + 4); byte_copy (type, 2, header); if (byte_diff (header + 2, 2, DNS_C_IN)) { ++i; continue; } for (j = i + 1; j < k; ++j) { pos = dns_packet_getname (buf, len, records[j], &t2); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; if (!dns_domain_equal (t1, t2)) break; if (byte_diff (header, 2, type)) break; if (byte_diff (header + 2, 2, DNS_C_IN)) break; } if (!dns_domain_suffix (t1, control)) { i = j; continue; } if (!roots_same (t1, control)) { i = j; continue; } if (byte_equal (type, 2, DNS_T_ANY)) ; else if (byte_equal(type, 2, DNS_T_AXFR)) ; else if (byte_equal (type, 2, DNS_T_SOA)) { while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos + 10, &t2); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos, &t3); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, misc, 20); if (!pos) goto DIE; if (records[i] < posauthority && debug_level > 2) log_rrsoa (whichserver, t1, t2, t3, misc, ttl); ++i; } } else if (byte_equal (type, 2, DNS_T_CNAME)) { pos = dns_packet_skipname (buf, len, records[j - 1]); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos + 10, &t2); if (!pos) goto DIE; if (debug_level > 2) log_rrcname (whichserver, t1, t2, ttl); cachegeneric (DNS_T_CNAME, t1, t2, dns_domain_length (t2), ttl); } else if (byte_equal (type, 2, DNS_T_PTR)) { save_start (); while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos + 10, &t2); if (!pos) goto DIE; if (debug_level > 2) log_rrptr (whichserver, t1, t2, ttl); save_data (t2, dns_domain_length (t2)); ++i; } save_finish (DNS_T_PTR, t1, ttl); } else if (byte_equal (type, 2, DNS_T_NS)) { save_start (); while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos + 10, &t2); if (!pos) goto DIE; if (debug_level > 2) log_rrns (whichserver, t1, t2, ttl); save_data (t2, dns_domain_length (t2)); ++i; } save_finish (DNS_T_NS, t1, ttl); } else if (byte_equal (type, 2, DNS_T_MX)) { save_start (); while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos + 10, misc, 2); if (!pos) goto DIE; pos = dns_packet_getname (buf, len, pos, &t2); if (!pos) goto DIE; if (debug_level > 2) log_rrmx (whichserver, t1, t2, misc, ttl); save_data (misc, 2); save_data (t2, dns_domain_length (t2)); ++i; } save_finish (DNS_T_MX, t1, ttl); } else if (byte_equal (type, 2, DNS_T_A)) { save_start (); while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; if (byte_equal (header + 8, 2, "\0\4")) { pos = dns_packet_copy (buf, len, pos, header, 4); if (!pos) goto DIE; save_data (header, 4); if (debug_level > 2) log_rr (whichserver, t1, DNS_T_A, header, 4, ttl); } ++i; } save_finish (DNS_T_A, t1, ttl); } else { save_start (); while (i < j) { pos = dns_packet_skipname (buf, len, records[i]); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; uint16_unpack_big (header + 8, &datalen); if (datalen > len - pos) goto DIE; save_data (header + 8, 2); save_data (buf + pos, datalen); if (debug_level > 2) log_rr (whichserver, t1, type, buf + pos, datalen, ttl); ++i; } save_finish (type, t1, ttl); } i = j; } alloc_free (records); records = 0; if (flagcname) { ttl = cnamettl; CNAME: if (!z->level) { if (z->alias[QUERY_MAXALIAS - 1]) goto DIE; for (j = QUERY_MAXALIAS - 1; j > 0; --j) z->alias[j] = z->alias[j - 1]; for (j = QUERY_MAXALIAS - 1; j > 0; --j) z->aliasttl[j] = z->aliasttl[j - 1]; z->alias[0] = z->name[0]; z->aliasttl[0] = ttl; z->name[0] = 0; } if (!dns_domain_copy (&z->name[z->level], cname)) goto DIE; goto NEWNAME; } if (rcode == 3) { if (debug_level > 2) log_nxdomain (whichserver, d, soattl); cachegeneric (DNS_T_ANY, d, "", 0, soattl); NXDOMAIN: if (z->level) goto LOWERLEVEL; if (!rqa (z)) goto DIE; response_nxdomain (); cleanup (z); return 1; } if (!flagout && flagsoa) if (byte_diff (DNS_T_ANY, 2, dtype)) if (byte_diff (DNS_T_AXFR, 2, dtype)) if (byte_diff (DNS_T_CNAME, 2, dtype)) { save_start (); save_finish (dtype, d, soattl); if (debug_level > 2) log_nodata (whichserver, d, dtype, soattl); } if (debug_level > 2) log_stats (); if (flagout || flagsoa || !flagreferral) { if (z->level) { pos = posanswers; for (j = 0; j < numanswers; ++j) { pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; uint16_unpack_big (header + 8, &datalen); if (dns_domain_equal (t1, d)) if (typematch (header, DNS_T_A)) if (byte_equal (header + 2, 2, DNS_C_IN)) /* should always be true */ if (datalen == 4) for (k = 0; k < 64; k += 4) { if (byte_equal (z->servers[z->level - 1] + k, 4, "\0\0\0\0")) { if (!dns_packet_copy (buf, len, pos, z->servers[z->level - 1] + k, 4)) goto DIE; break; } } pos += datalen; } goto LOWERLEVEL; } if (!rqa (z)) goto DIE; pos = posanswers; for (j = 0; j < numanswers; ++j) { pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; ttl = ttlget (header + 4); uint16_unpack_big (header + 8, &datalen); if (dns_domain_equal (t1, d)) { if (byte_equal (header + 2, 2, DNS_C_IN)) { /* should always be true */ if (typematch (header, dtype)) { if (!response_rstart (t1, header, ttl)) goto DIE; if (typematch (header, DNS_T_NS) || typematch (header, DNS_T_CNAME) || typematch (header, DNS_T_PTR)) { if (!dns_packet_getname (buf, len, pos, &t2)) goto DIE; if (!response_addname (t2)) goto DIE; } else if (typematch (header, DNS_T_MX)) { pos2 = dns_packet_copy (buf, len, pos, misc, 2); if (!pos2) goto DIE; if (!response_addbytes (misc, 2)) goto DIE; if (!dns_packet_getname (buf, len, pos2, &t2)) goto DIE; if (!response_addname (t2)) goto DIE; } else if (typematch (header, DNS_T_SOA)) { pos2 = dns_packet_getname (buf, len, pos, &t2); if (!pos2) goto DIE; if (!response_addname (t2)) goto DIE; pos2 = dns_packet_getname (buf, len, pos2, &t3); if (!pos2) goto DIE; if (!response_addname (t3)) goto DIE; pos2 = dns_packet_copy (buf, len, pos2, misc, 20); if (!pos2) goto DIE; if (!response_addbytes (misc, 20)) goto DIE; } else { if (pos + datalen > len) goto DIE; if (!response_addbytes (buf + pos, datalen)) goto DIE; } response_rfinish(RESPONSE_ANSWER); } } } pos += datalen; } cleanup (z); return 1; } if (!dns_domain_suffix (d, referral)) goto DIE; control = d + dns_domain_suffixpos (d, referral); z->control[z->level] = control; byte_zero (z->servers[z->level], 64); for (j = 0; j < QUERY_MAXNS; ++j) dns_domain_free (&z->ns[z->level][j]); k = 0; pos = posauthority; for (j = 0; j < numauthority; ++j) { pos = dns_packet_getname (buf, len, pos, &t1); if (!pos) goto DIE; pos = dns_packet_copy (buf, len, pos, header, 10); if (!pos) goto DIE; uint16_unpack_big (header + 8, &datalen); if (dns_domain_equal (referral, t1)) /* should always be true */ if (typematch (header, DNS_T_NS)) /* should always be true */ /* should always be true */ if (byte_equal (header + 2, 2, DNS_C_IN)) if (k < QUERY_MAXNS) if (!dns_packet_getname (buf, len, pos, &z->ns[z->level][k++])) goto DIE; pos += datalen; } goto HAVENS; SERVFAIL: if (z->level) goto LOWERLEVEL; if (!rqa (z)) goto DIE; response_servfail (); cleanup (z); return 1; DIE: cleanup (z); if (records) { alloc_free (records); records = 0; } return -1; }
null
null
211,832
79765666770204763498367880503715409942
1,000
Make Start of Authority(SOA) responses cache-able. This patch fixes dnscache to cache SOA responses sent to clients. This fixes one of the cache poisoning vulnerability reported by Mr Mark Johnson -> https://bugzilla.redhat.com/show_bug.cgi?id=838965. Nonetheless the original patch for this issue was created by Mr Jeff king -> http://www.your.org/dnscache/ Sincere thanks to Mr Mark for reporting this issue and Mr Jeff for creating the patch and releasing it under public domain.
other
vim
e3537aec2f8d6470010547af28dcbd83d41461b8
1
do_buffer_ext( int action, int start, int dir, // FORWARD or BACKWARD int count, // buffer number or number of buffers int flags) // DOBUF_FORCEIT etc. { buf_T *buf; buf_T *bp; int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL || action == DOBUF_WIPE || action == DOBUF_WIPE_REUSE); switch (start) { case DOBUF_FIRST: buf = firstbuf; break; case DOBUF_LAST: buf = lastbuf; break; default: buf = curbuf; break; } if (start == DOBUF_MOD) // find next modified buffer { while (count-- > 0) { do { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } while (buf != curbuf && !bufIsChanged(buf)); } if (!bufIsChanged(buf)) { emsg(_(e_no_modified_buffer_found)); return FAIL; } } else if (start == DOBUF_FIRST && count) // find specified buffer number { while (buf != NULL && buf->b_fnum != count) buf = buf->b_next; } else { bp = NULL; while (count > 0 || (!unload && !buf->b_p_bl && bp != buf)) { // remember the buffer where we start, we come back there when all // buffers are unlisted. if (bp == NULL) bp = buf; if (dir == FORWARD) { buf = buf->b_next; if (buf == NULL) buf = firstbuf; } else { buf = buf->b_prev; if (buf == NULL) buf = lastbuf; } // don't count unlisted buffers if (unload || buf->b_p_bl) { --count; bp = NULL; // use this buffer as new starting point } if (bp == buf) { // back where we started, didn't find anything. emsg(_(e_there_is_no_listed_buffer)); return FAIL; } } } if (buf == NULL) // could not find it { if (start == DOBUF_FIRST) { // don't warn when deleting if (!unload) semsg(_(e_buffer_nr_does_not_exist), count); } else if (dir == FORWARD) emsg(_(e_cannot_go_beyond_last_buffer)); else emsg(_(e_cannot_go_before_first_buffer)); return FAIL; } #ifdef FEAT_PROP_POPUP if ((flags & DOBUF_NOPOPUP) && bt_popup(buf) # ifdef FEAT_TERMINAL && !bt_terminal(buf) #endif ) return OK; #endif #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif /* * delete buffer "buf" from memory and/or the list */ if (unload) { int forward; bufref_T bufref; if (!can_unload_buffer(buf)) return FAIL; set_bufref(&bufref, buf); // When unloading or deleting a buffer that's already unloaded and // unlisted: fail silently. if (action != DOBUF_WIPE && action != DOBUF_WIPE_REUSE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) return FAIL; if ((flags & DOBUF_FORCEIT) == 0 && bufIsChanged(buf)) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) { dialog_changed(buf, FALSE); if (!bufref_valid(&bufref)) // Autocommand deleted buffer, oops! It's not changed // now. return FAIL; // If it's still changed fail silently, the dialog already // mentioned why it fails. if (bufIsChanged(buf)) return FAIL; } else #endif { semsg(_(e_no_write_since_last_change_for_buffer_nr_add_bang_to_override), buf->b_fnum); return FAIL; } } // When closing the current buffer stop Visual mode. if (buf == curbuf && VIsual_active) end_visual_mode(); // If deleting the last (listed) buffer, make it empty. // The last (listed) buffer cannot be unloaded. FOR_ALL_BUFFERS(bp) if (bp->b_p_bl && bp != buf) break; if (bp == NULL && buf == curbuf) return empty_curbuf(TRUE, (flags & DOBUF_FORCEIT), action); // If the deleted buffer is the current one, close the current window // (unless it's the only window). Repeat this so long as we end up in // a window with this buffer. while (buf == curbuf && !(curwin->w_closing || curwin->w_buffer->b_locked > 0) && (!ONE_WINDOW || first_tabpage->tp_next != NULL)) { if (win_close(curwin, FALSE) == FAIL) break; } // If the buffer to be deleted is not the current one, delete it here. if (buf != curbuf) { close_windows(buf, FALSE); if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0) close_buffer(NULL, buf, action, FALSE, FALSE); return OK; } /* * Deleting the current buffer: Need to find another buffer to go to. * There should be another, otherwise it would have been handled * above. However, autocommands may have deleted all buffers. * First use au_new_curbuf.br_buf, if it is valid. * Then prefer the buffer we most recently visited. * Else try to find one that is loaded, after the current buffer, * then before the current buffer. * Finally use any buffer. */ buf = NULL; // selected buffer bp = NULL; // used when no loaded buffer found if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf)) buf = au_new_curbuf.br_buf; else if (curwin->w_jumplistlen > 0) { int jumpidx; jumpidx = curwin->w_jumplistidx - 1; if (jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; forward = jumpidx; while (jumpidx != curwin->w_jumplistidx) { buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum); if (buf != NULL) { if (buf == curbuf || !buf->b_p_bl) buf = NULL; // skip current and unlisted bufs else if (buf->b_ml.ml_mfp == NULL) { // skip unloaded buf, but may keep it for later if (bp == NULL) bp = buf; buf = NULL; } } if (buf != NULL) // found a valid buffer: stop searching break; // advance to older entry in jump list if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) break; if (--jumpidx < 0) jumpidx = curwin->w_jumplistlen - 1; if (jumpidx == forward) // List exhausted for sure break; } } if (buf == NULL) // No previous buffer, Try 2'nd approach { forward = TRUE; buf = curbuf->b_next; for (;;) { if (buf == NULL) { if (!forward) // tried both directions break; buf = curbuf->b_prev; forward = FALSE; continue; } // in non-help buffer, try to skip help buffers, and vv if (buf->b_help == curbuf->b_help && buf->b_p_bl) { if (buf->b_ml.ml_mfp != NULL) // found loaded buffer break; if (bp == NULL) // remember unloaded buf for later bp = buf; } if (forward) buf = buf->b_next; else buf = buf->b_prev; } } if (buf == NULL) // No loaded buffer, use unloaded one buf = bp; if (buf == NULL) // No loaded buffer, find listed one { FOR_ALL_BUFFERS(buf) if (buf->b_p_bl && buf != curbuf) break; } if (buf == NULL) // Still no buffer, just take one { if (curbuf->b_next != NULL) buf = curbuf->b_next; else buf = curbuf->b_prev; } } if (buf == NULL) { // Autocommands must have wiped out all other buffers. Only option // now is to make the current buffer empty. return empty_curbuf(FALSE, (flags & DOBUF_FORCEIT), action); } /* * make "buf" the current buffer */ if (action == DOBUF_SPLIT) // split window first { // If 'switchbuf' contains "useopen": jump to first window containing // "buf" if one exists if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf)) return OK; // If 'switchbuf' contains "usetab": jump to first window in any tab // page containing "buf" if one exists if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf)) return OK; if (win_split(0, 0) == FAIL) return FAIL; } // go to current buffer - nothing to do if (buf == curbuf) return OK; // Check if the current buffer may be abandoned. if (action == DOBUF_GOTO && !can_abandon(curbuf, (flags & DOBUF_FORCEIT))) { #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG) if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) { bufref_T bufref; set_bufref(&bufref, buf); dialog_changed(curbuf, FALSE); if (!bufref_valid(&bufref)) // Autocommand deleted buffer, oops! return FAIL; } if (bufIsChanged(curbuf)) #endif { no_write_message(); return FAIL; } } // Go to the other buffer. set_curbuf(buf, action); if (action == DOBUF_SPLIT) RESET_BINDING(curwin); // reset 'scrollbind' and 'cursorbind' #if defined(FEAT_EVAL) if (aborting()) // autocmds may abort script processing return FAIL; #endif return OK; }
null
null
211,839
216423663569045638499778463707888891660
337
patch 8.2.4327: may end up with no current buffer Problem: May end up with no current buffer. Solution: When deleting the current buffer to not pick a quickfix buffer as the new current buffer.
other
vim
4e889f98e95ac05d7c8bd3ee933ab4d47820fdfa
1
change_indent( int type, int amount, int round, int replaced, // replaced character, put on replace stack int call_changed_bytes) // call changed_bytes() { int vcol; int last_vcol; int insstart_less; // reduction for Insstart.col int new_cursor_col; int i; char_u *ptr; int save_p_list; int start_col; colnr_T vc; colnr_T orig_col = 0; // init for GCC char_u *new_line, *orig_line = NULL; // init for GCC // VREPLACE mode needs to know what the line was like before changing if (State & VREPLACE_FLAG) { orig_line = vim_strsave(ml_get_curline()); // Deal with NULL below orig_col = curwin->w_cursor.col; } // for the following tricks we don't want list mode save_p_list = curwin->w_p_list; curwin->w_p_list = FALSE; vc = getvcol_nolist(&curwin->w_cursor); vcol = vc; // For Replace mode we need to fix the replace stack later, which is only // possible when the cursor is in the indent. Remember the number of // characters before the cursor if it's possible. start_col = curwin->w_cursor.col; // determine offset from first non-blank new_cursor_col = curwin->w_cursor.col; beginline(BL_WHITE); new_cursor_col -= curwin->w_cursor.col; insstart_less = curwin->w_cursor.col; // If the cursor is in the indent, compute how many screen columns the // cursor is to the left of the first non-blank. if (new_cursor_col < 0) vcol = get_indent() - vcol; if (new_cursor_col > 0) // can't fix replace stack start_col = -1; // Set the new indent. The cursor will be put on the first non-blank. if (type == INDENT_SET) (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0); else { int save_State = State; // Avoid being called recursively. if (State & VREPLACE_FLAG) State = INSERT; shift_line(type == INDENT_DEC, round, 1, call_changed_bytes); State = save_State; } insstart_less -= curwin->w_cursor.col; // Try to put cursor on same character. // If the cursor is at or after the first non-blank in the line, // compute the cursor column relative to the column of the first // non-blank character. // If we are not in insert mode, leave the cursor on the first non-blank. // If the cursor is before the first non-blank, position it relative // to the first non-blank, counted in screen columns. if (new_cursor_col >= 0) { // When changing the indent while the cursor is touching it, reset // Insstart_col to 0. if (new_cursor_col == 0) insstart_less = MAXCOL; new_cursor_col += curwin->w_cursor.col; } else if (!(State & INSERT)) new_cursor_col = curwin->w_cursor.col; else { // Compute the screen column where the cursor should be. vcol = get_indent() - vcol; curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol); // Advance the cursor until we reach the right screen column. vcol = last_vcol = 0; new_cursor_col = -1; ptr = ml_get_curline(); while (vcol <= (int)curwin->w_virtcol) { last_vcol = vcol; if (has_mbyte && new_cursor_col >= 0) new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col); else ++new_cursor_col; vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol); } vcol = last_vcol; // May need to insert spaces to be able to position the cursor on // the right screen column. if (vcol != (int)curwin->w_virtcol) { curwin->w_cursor.col = (colnr_T)new_cursor_col; i = (int)curwin->w_virtcol - vcol; ptr = alloc(i + 1); if (ptr != NULL) { new_cursor_col += i; ptr[i] = NUL; while (--i >= 0) ptr[i] = ' '; ins_str(ptr); vim_free(ptr); } } // When changing the indent while the cursor is in it, reset // Insstart_col to 0. insstart_less = MAXCOL; } curwin->w_p_list = save_p_list; if (new_cursor_col <= 0) curwin->w_cursor.col = 0; else curwin->w_cursor.col = (colnr_T)new_cursor_col; curwin->w_set_curswant = TRUE; changed_cline_bef_curs(); // May have to adjust the start of the insert. if (State & INSERT) { if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0) { if ((int)Insstart.col <= insstart_less) Insstart.col = 0; else Insstart.col -= insstart_less; } if ((int)ai_col <= insstart_less) ai_col = 0; else ai_col -= insstart_less; } // For REPLACE mode, may have to fix the replace stack, if it's possible. // If the number of characters before the cursor decreased, need to pop a // few characters from the replace stack. // If the number of characters before the cursor increased, need to push a // few NULs onto the replace stack. if (REPLACE_NORMAL(State) && start_col >= 0) { while (start_col > (int)curwin->w_cursor.col) { replace_join(0); // remove a NUL from the replace stack --start_col; } while (start_col < (int)curwin->w_cursor.col || replaced) { replace_push(NUL); if (replaced) { replace_push(replaced); replaced = NUL; } ++start_col; } } // For VREPLACE mode, we also have to fix the replace stack. In this case // it is always possible because we backspace over the whole line and then // put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // If orig_line didn't allocate, just return. At least we did the job, // even if you can't backspace. if (orig_line == NULL) return; // Save new line new_line = vim_strsave(ml_get_curline()); if (new_line == NULL) return; // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; // Put back original line ml_replace(curwin->w_cursor.lnum, orig_line, FALSE); curwin->w_cursor.col = orig_col; // Backspace from cursor to start of line backspace_until_column(0); // Insert new stuff into line again ins_bytes(new_line); vim_free(new_line); } }
null
null
211,842
88004527876502782974499238285292837322
208
patch 8.2.4436: crash with weird 'vartabstop' value Problem: Crash with weird 'vartabstop' value. Solution: Check for running into the end of the line.
other
ImageMagick6
1aea203eb36409ce6903b9e41fe7cb70030e8750
1
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define MaxPixelChannels 32 #define ThrowTIFFException(severity,message) \ { \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity = (float *) NULL, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status = 0; MagickBooleanType more_frames; MagickStatusType status; MemoryInfo *pixel_info = (MemoryInfo *) NULL; QuantumInfo *quantum_info; QuantumType quantum_type; size_t number_pixels; ssize_t i, scanline_size, y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag = 0, bits_per_sample = 0, endian = 0, extra_samples = 0, interlace = 0, max_sample_value = 0, min_sample_value = 0, orientation = 0, pages = 0, photometric = 0, *sample_info = NULL, sample_format = 0, samples_per_pixel = 0, units = 0, value = 0; uint32 height, rows_per_strip, width; unsigned char *pixels; void *sans[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (IsEventLogging() != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { if (exception->severity == UndefinedException) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); image=DestroyImageList(image); return((Image *) NULL); } if (exception->severity > ErrorException) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { /* TIFFPrintDirectory(tiff,stdout,MagickFalse); */ photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && ((bits_per_sample <= 0) || (bits_per_sample > 32))) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); } if (samples_per_pixel > MaxPixelChannels) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) image->colorspace=GRAYColorspace; if (photometric == PHOTOMETRIC_SEPARATED) image->colorspace=CMYKColorspace; if (photometric == PHOTOMETRIC_CIELAB) image->colorspace=LabColorspace; if ((photometric == PHOTOMETRIC_YCBCR) && (compress_tag != COMPRESSION_OJPEG) && (compress_tag != COMPRESSION_JPEG)) image->colorspace=YCbCrColorspace; status=TIFFGetProfiles(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=TIFFGetProperties(tiff,image); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetEXIFProperties(tiff,image); option=GetImageOption(image_info,"tiff:gps-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) (void) TIFFGetGPSProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution,sans) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units,sans,sans) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position,sans) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position,sans) == 1)) { image->page.x=CastDoubleToLong(ceil(x_position* image->x_resolution-0.5)); image->page.y=CastDoubleToLong(ceil(y_position* image->y_resolution-0.5)); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation,sans) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if ((chromaticity != (float *) NULL) && (*chromaticity != 0.0)) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; #if defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: image->compression=WebPCompression; break; #endif #if defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: image->compression=ZstdCompression; break; #endif default: image->compression=RLECompression; break; } quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages,sans) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap = (uint16 *) NULL, *green_colormap = (uint16 *) NULL, *red_colormap = (uint16 *) NULL; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=SetImageColorspace(image,image->colorspace); status&=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } extra_samples=0; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info,sans); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } } if (image->matte != MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); method=ReadStripMethod; if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; } if (TIFFIsTiled(tiff) != MagickFalse) { uint32 columns, rows; if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); method=ReadTileMethod; } if ((photometric == PHOTOMETRIC_LOGLUV) || (compress_tag == COMPRESSION_CCITTFAX3)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); quantum_info->endian=LSBEndian; scanline_size=TIFFScanlineSize(tiff); if (scanline_size <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=MagickMax((MagickSizeType) image->columns*samples_per_pixel* pow(2.0,ceil(log(bits_per_sample)/log(2.0))),image->columns* rows_per_strip); if ((double) scanline_size > 1.5*number_pixels) ThrowTIFFException(CorruptImageError,"CorruptImage"); number_pixels=MagickMax((MagickSizeType) scanline_size,number_pixels); pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,number_pixels*sizeof(uint32)); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; if (interlace != PLANARCONFIG_SEPARATE) { size_t pad; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class == PseudoClass) quantum_type=IndexAlphaQuantum; else quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; } if ((samples_per_pixel > 2) && (interlace != PLANARCONFIG_SEPARATE)) { quantum_type=RGBQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-3,0); if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); } if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-4,0); if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel+ extra_samples-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); } } switch (method) { case ReadYCCKMethod: { /* Convert YCC TIFF image. */ for (y=0; y < (ssize_t) image->rows; y++) { int status; IndexPacket *indexes; PixelPacket *magick_restrict q; ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { unsigned char *p; size_t extent; ssize_t stride, strip_id; tsize_t strip_size; unsigned char *strip_pixels; /* Convert stripped TIFF image. */ extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff); strip_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*strip_pixels)); if (strip_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(strip_pixels,0,extent*sizeof(*strip_pixels)); stride=TIFFVStripSize(tiff,1); strip_id=0; p=strip_pixels; for (i=0; i < (ssize_t) samples_per_pixel; i++) { size_t rows_remaining; switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } rows_remaining=0; for (y=0; y < (ssize_t) image->rows; y++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (rows_remaining == 0) { strip_size=TIFFReadEncodedStrip(tiff,strip_id,strip_pixels, TIFFStripSize(tiff)); if (strip_size == -1) break; rows_remaining=rows_per_strip; if ((y+rows_per_strip) > (ssize_t) image->rows) rows_remaining=(rows_per_strip-(y+rows_per_strip- image->rows)); p=strip_pixels; strip_id++; } (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=stride; rows_remaining--; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; } strip_pixels=(unsigned char *) RelinquishMagickMemory(strip_pixels); break; } case ReadTileMethod: { unsigned char *p; size_t extent; uint32 columns, rows; unsigned char *tile_pixels; /* Convert tiled TIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); extent=4*(samples_per_pixel+1)*MagickMax(rows*TIFFTileRowSize(tiff), TIFFTileSize(tiff)); tile_pixels=(unsigned char *) AcquireQuantumMemory(extent, sizeof(*tile_pixels)); if (tile_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(tile_pixels,0,extent*sizeof(*tile_pixels)); for (i=0; i < (ssize_t) samples_per_pixel; i++) { switch (i) { case 0: break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: { quantum_type=AlphaQuantum; if (image->colorspace == CMYKColorspace) quantum_type=BlackQuantum; break; } case 4: quantum_type=AlphaQuantum; break; default: break; } for (y=0; y < (ssize_t) image->rows; y+=rows) { ssize_t x; size_t rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t columns_remaining, row; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; tiff_status=TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y, 0,i); if (tiff_status == -1) break; p=tile_pixels; for (row=0; row < rows_remaining; row++) { PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,x,y+row,columns_remaining,1, exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL, quantum_info,quantum_type,p,exception); p+=TIFFTileRowSize(tiff); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if ((samples_per_pixel > 1) && (interlace != PLANARCONFIG_SEPARATE)) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) i, samples_per_pixel); if (status == MagickFalse) break; } } tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *generic_info = (MemoryInfo *) NULL; uint32 *p; uint32 *pixels; /* Convert generic TIFF image. */ if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; generic_info=AcquireVirtualMemory(number_pixels,sizeof(*pixels)); if (generic_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(generic_info); tiff_status=TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); if (tiff_status == -1) { generic_info=RelinquishVirtualMemory(generic_info); break; } p=pixels+(image->columns*image->rows)-1; for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } generic_info=RelinquishVirtualMemory(generic_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (tiff_status == -1) { status=MagickFalse; break; } if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); TIFFReadPhotoshopLayers(image_info,image,exception); return(GetFirstImageInList(image)); }
null
null
211,845
164015677145852304771528670634766341126
1,024
squash heap-buffer-overflow, PoC TIFF from Hardik
other
nf
b1a5983f56e371046dcf164f90bfaf704d2b89f6
1
struct nft_flow_rule *nft_flow_rule_create(struct net *net, const struct nft_rule *rule) { struct nft_offload_ctx *ctx; struct nft_flow_rule *flow; int num_actions = 0, err; struct nft_expr *expr; expr = nft_expr_first(rule); while (nft_expr_more(rule, expr)) { if (expr->ops->offload_flags & NFT_OFFLOAD_F_ACTION) num_actions++; expr = nft_expr_next(expr); } if (num_actions == 0) return ERR_PTR(-EOPNOTSUPP); flow = nft_flow_rule_alloc(num_actions); if (!flow) return ERR_PTR(-ENOMEM); expr = nft_expr_first(rule); ctx = kzalloc(sizeof(struct nft_offload_ctx), GFP_KERNEL); if (!ctx) { err = -ENOMEM; goto err_out; } ctx->net = net; ctx->dep.type = NFT_OFFLOAD_DEP_UNSPEC; while (nft_expr_more(rule, expr)) { if (!expr->ops->offload) { err = -EOPNOTSUPP; goto err_out; } err = expr->ops->offload(ctx, flow, expr); if (err < 0) goto err_out; expr = nft_expr_next(expr); } nft_flow_rule_transfer_vlan(ctx, flow); flow->proto = ctx->dep.l3num; kfree(ctx); return flow; err_out: kfree(ctx); nft_flow_rule_destroy(flow); return ERR_PTR(err); }
null
null
211,868
285772030524236179188013149460232600295
56
netfilter: nf_tables_offload: incorrect flow offload action array size immediate verdict expression needs to allocate one slot in the flow offload action array, however, immediate data expression does not need to do so. fwd and dup expression need to allocate one slot, this is missing. Add a new offload_action interface to report if this expression needs to allocate one slot in the flow offload action array. Fixes: be2861dc36d7 ("netfilter: nft_{fwd,dup}_netdev: add offload support") Reported-and-tested-by: Nick Gregory <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
other
libexpat
a2fe525e660badd64b6c557c2b1ec26ddc07f6e4
1
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, const XML_Char *uri, BINDING **bindingsPtr) { static const XML_Char xmlNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'}; static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1; static const XML_Char xmlnsNamespace[] = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'}; static const int xmlnsLen = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1; XML_Bool mustBeXML = XML_FALSE; XML_Bool isXML = XML_TRUE; XML_Bool isXMLNS = XML_TRUE; BINDING *b; int len; /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ if (*uri == XML_T('\0') && prefix->name) return XML_ERROR_UNDECLARING_PREFIX; if (prefix->name && prefix->name[0] == XML_T(ASCII_x) && prefix->name[1] == XML_T(ASCII_m) && prefix->name[2] == XML_T(ASCII_l)) { /* Not allowed to bind xmlns */ if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s) && prefix->name[5] == XML_T('\0')) return XML_ERROR_RESERVED_PREFIX_XMLNS; if (prefix->name[3] == XML_T('\0')) mustBeXML = XML_TRUE; } for (len = 0; uri[len]; len++) { if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) isXML = XML_FALSE; if (! mustBeXML && isXMLNS && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) isXMLNS = XML_FALSE; } isXML = isXML && len == xmlLen; isXMLNS = isXMLNS && len == xmlnsLen; if (mustBeXML != isXML) return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML : XML_ERROR_RESERVED_NAMESPACE_URI; if (isXMLNS) return XML_ERROR_RESERVED_NAMESPACE_URI; if (parser->m_namespaceSeparator) len++; if (parser->m_freeBindingList) { b = parser->m_freeBindingList; if (len > b->uriAlloc) { /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif XML_Char *temp = (XML_Char *)REALLOC( parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (temp == NULL) return XML_ERROR_NO_MEMORY; b->uri = temp; b->uriAlloc = len + EXPAND_SPARE; } parser->m_freeBindingList = b->nextTagBinding; } else { b = (BINDING *)MALLOC(parser, sizeof(BINDING)); if (! b) return XML_ERROR_NO_MEMORY; /* Detect and prevent integer overflow */ if (len > INT_MAX - EXPAND_SPARE) { return XML_ERROR_NO_MEMORY; } /* Detect and prevent integer overflow. * The preprocessor guard addresses the "always false" warning * from -Wtype-limits on platforms where * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */ #if UINT_MAX >= SIZE_MAX if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) { return XML_ERROR_NO_MEMORY; } #endif b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); if (! b->uri) { FREE(parser, b); return XML_ERROR_NO_MEMORY; } b->uriAlloc = len + EXPAND_SPARE; } b->uriLen = len; memcpy(b->uri, uri, len * sizeof(XML_Char)); if (parser->m_namespaceSeparator) b->uri[len - 1] = parser->m_namespaceSeparator; b->prefix = prefix; b->attId = attId; b->prevPrefixBinding = prefix->binding; /* NULL binding when default namespace undeclared */ if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) prefix->binding = NULL; else prefix->binding = b; b->nextTagBinding = *bindingsPtr; *bindingsPtr = b; /* if attId == NULL then we are not starting a namespace scope */ if (attId && parser->m_startNamespaceDeclHandler) parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, prefix->binding ? uri : 0); return XML_ERROR_NONE; }
null
null
211,877
271163481122620107772263700560380402337
137
lib: Protect against malicious namespace declarations (CVE-2022-25236)
other
jasper
839b1bcf0450ff036c28e8db40a7abf886e02891
1
jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr)); if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf("error: cannot get box\n"); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf("error: expecting signature box\n"); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf("incorrect magic number\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf("expecting file type box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf("got box type %s\n", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf("error: no code stream found\n"); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf("error: cannot decode code stream\n"); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf("error: missing IHDR box\n"); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf("warning: component data type mismatch\n"); } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf("error: unsupported compression type\n"); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts( dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf("warning: component data type mismatch\n"); } } } else { jas_eprintf("warning: superfluous BPCC box\n"); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf("error: no COLR box\n"); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf("error: failed to parse ICC profile\n"); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); assert(dec->image->cmprof_); jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: invalid component number in CMAP box\n"); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf("error: invalid CMAP LUT index\n"); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, sizeof(uint_fast16_t)))) { jas_eprintf("error: no memory\n"); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #endif } } } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf("error: invalid channel number in CDEF box\n"); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } #if 0 jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; }
null
null
211,915
116524198483996818863220715270541847054
358
jp2_dec: fix `numchans` mixup When iterating over `dec->cdef->data.cdef.ents`, we need to use its `numchans` variable, not the one in `jp2_dec_t`. Fixes CVE-2018-19543 Fixes CVE-2017-9782 Closes https://github.com/jasper-maint/jasper/issues/13 Closes https://github.com/jasper-maint/jasper/issues/18 Closes https://github.com/mdadams/jasper/issues/140 Closes https://github.com/mdadams/jasper/issues/182
other
linux
690b2549b19563ec5ad53e5c82f6a944d910086e
1
static int ismt_access(struct i2c_adapter *adap, u16 addr, unsigned short flags, char read_write, u8 command, int size, union i2c_smbus_data *data) { int ret; unsigned long time_left; dma_addr_t dma_addr = 0; /* address of the data buffer */ u8 dma_size = 0; enum dma_data_direction dma_direction = 0; struct ismt_desc *desc; struct ismt_priv *priv = i2c_get_adapdata(adap); struct device *dev = &priv->pci_dev->dev; u8 *dma_buffer = PTR_ALIGN(&priv->buffer[0], 16); desc = &priv->hw[priv->head]; /* Initialize the DMA buffer */ memset(priv->buffer, 0, sizeof(priv->buffer)); /* Initialize the descriptor */ memset(desc, 0, sizeof(struct ismt_desc)); desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, read_write); /* Always clear the log entries */ memset(priv->log, 0, ISMT_LOG_ENTRIES * sizeof(u32)); /* Initialize common control bits */ if (likely(pci_dev_msi_enabled(priv->pci_dev))) desc->control = ISMT_DESC_INT | ISMT_DESC_FAIR; else desc->control = ISMT_DESC_FAIR; if ((flags & I2C_CLIENT_PEC) && (size != I2C_SMBUS_QUICK) && (size != I2C_SMBUS_I2C_BLOCK_DATA)) desc->control |= ISMT_DESC_PEC; switch (size) { case I2C_SMBUS_QUICK: dev_dbg(dev, "I2C_SMBUS_QUICK\n"); break; case I2C_SMBUS_BYTE: if (read_write == I2C_SMBUS_WRITE) { /* * Send Byte * The command field contains the write data */ dev_dbg(dev, "I2C_SMBUS_BYTE: WRITE\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; } else { /* Receive Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE: READ\n"); dma_size = 1; dma_direction = DMA_FROM_DEVICE; desc->rd_len = 1; } break; case I2C_SMBUS_BYTE_DATA: if (read_write == I2C_SMBUS_WRITE) { /* * Write Byte * Command plus 1 data byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: WRITE\n"); desc->wr_len_cmd = 2; dma_size = 2; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->byte; } else { /* Read Byte */ dev_dbg(dev, "I2C_SMBUS_BYTE_DATA: READ\n"); desc->control |= ISMT_DESC_CWRL; desc->wr_len_cmd = command; desc->rd_len = 1; dma_size = 1; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_WORD_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Write Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: WRITE\n"); desc->wr_len_cmd = 3; dma_size = 3; dma_direction = DMA_TO_DEVICE; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; } else { /* Read Word */ dev_dbg(dev, "I2C_SMBUS_WORD_DATA: READ\n"); desc->wr_len_cmd = command; desc->control |= ISMT_DESC_CWRL; desc->rd_len = 2; dma_size = 2; dma_direction = DMA_FROM_DEVICE; } break; case I2C_SMBUS_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_PROC_CALL\n"); desc->wr_len_cmd = 3; desc->rd_len = 2; dma_size = 3; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; dma_buffer[1] = data->word & 0xff; dma_buffer[2] = data->word >> 8; break; case I2C_SMBUS_BLOCK_DATA: if (read_write == I2C_SMBUS_WRITE) { /* Block Write */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_BLK; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* Block Read */ dev_dbg(dev, "I2C_SMBUS_BLOCK_DATA: READ\n"); dma_size = I2C_SMBUS_BLOCK_MAX; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_BLK | ISMT_DESC_CWRL); } break; case I2C_SMBUS_BLOCK_PROC_CALL: dev_dbg(dev, "I2C_SMBUS_BLOCK_PROC_CALL\n"); dma_size = I2C_SMBUS_BLOCK_MAX; desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 1); desc->wr_len_cmd = data->block[0] + 1; desc->rd_len = dma_size; desc->control |= ISMT_DESC_BLK; dma_direction = DMA_BIDIRECTIONAL; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], data->block[0]); break; case I2C_SMBUS_I2C_BLOCK_DATA: /* Make sure the length is valid */ if (data->block[0] < 1) data->block[0] = 1; if (data->block[0] > I2C_SMBUS_BLOCK_MAX) data->block[0] = I2C_SMBUS_BLOCK_MAX; if (read_write == I2C_SMBUS_WRITE) { /* i2c Block Write */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: WRITE\n"); dma_size = data->block[0] + 1; dma_direction = DMA_TO_DEVICE; desc->wr_len_cmd = dma_size; desc->control |= ISMT_DESC_I2C; dma_buffer[0] = command; memcpy(&dma_buffer[1], &data->block[1], dma_size - 1); } else { /* i2c Block Read */ dev_dbg(dev, "I2C_SMBUS_I2C_BLOCK_DATA: READ\n"); dma_size = data->block[0]; dma_direction = DMA_FROM_DEVICE; desc->rd_len = dma_size; desc->wr_len_cmd = command; desc->control |= (ISMT_DESC_I2C | ISMT_DESC_CWRL); /* * Per the "Table 15-15. I2C Commands", * in the External Design Specification (EDS), * (Document Number: 508084, Revision: 2.0), * the _rw bit must be 0 */ desc->tgtaddr_rw = ISMT_DESC_ADDR_RW(addr, 0); } break; default: dev_err(dev, "Unsupported transaction %d\n", size); return -EOPNOTSUPP; } /* map the data buffer */ if (dma_size != 0) { dev_dbg(dev, " dev=%p\n", dev); dev_dbg(dev, " data=%p\n", data); dev_dbg(dev, " dma_buffer=%p\n", dma_buffer); dev_dbg(dev, " dma_size=%d\n", dma_size); dev_dbg(dev, " dma_direction=%d\n", dma_direction); dma_addr = dma_map_single(dev, dma_buffer, dma_size, dma_direction); if (dma_mapping_error(dev, dma_addr)) { dev_err(dev, "Error in mapping dma buffer %p\n", dma_buffer); return -EIO; } dev_dbg(dev, " dma_addr = %pad\n", &dma_addr); desc->dptr_low = lower_32_bits(dma_addr); desc->dptr_high = upper_32_bits(dma_addr); } reinit_completion(&priv->cmp); /* Add the descriptor */ ismt_submit_desc(priv); /* Now we wait for interrupt completion, 1s */ time_left = wait_for_completion_timeout(&priv->cmp, HZ*1); /* unmap the data buffer */ if (dma_size != 0) dma_unmap_single(dev, dma_addr, dma_size, dma_direction); if (unlikely(!time_left)) { dev_err(dev, "completion wait timed out\n"); ret = -ETIMEDOUT; goto out; } /* do any post processing of the descriptor here */ ret = ismt_process_desc(desc, data, priv, size, read_write); out: /* Update the ring pointer */ priv->head++; priv->head %= ISMT_DESC_ENTRIES; return ret; }
null
null
212,083
218082028726825778448502302966621907044
241
i2c: ismt: prevent memory corruption in ismt_access() The "data->block[0]" variable comes from the user and is a number between 0-255. It needs to be capped to prevent writing beyond the end of dma_buffer[]. Fixes: 5e9a97b1f449 ("i2c: ismt: Adding support for I2C_SMBUS_BLOCK_PROC_CALL") Reported-and-tested-by: Zheyu Ma <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Mika Westerberg <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
other
libmobi
fb1ab50e448ddbed746fd27ae07469bc506d838b
1
MOBI_RET mobi_reconstruct_infl(char *outstring, const MOBIIndx *infl, const MOBIIndexEntry *orth_entry) { const char *label = orth_entry->label; uint32_t *infl_groups = NULL; size_t infl_count = mobi_get_indxentry_tagarray(&infl_groups, orth_entry, INDX_TAGARR_ORTH_INFL); if (infl_count == 0 || !infl_groups) { return MOBI_SUCCESS; } const char *start_tag = "<idx:infl>"; const char *end_tag = "</idx:infl>"; const char *iform_tag = "<idx:iform%s value=\"%s\"/>"; char name_attr[INDX_INFLBUF_SIZEMAX + 1]; char infl_tag[INDX_INFLBUF_SIZEMAX + 1]; strcpy(outstring, start_tag); size_t initlen = strlen(start_tag) + strlen(end_tag); size_t outlen = initlen; size_t label_length = strlen(label); if (label_length > INDX_INFLBUF_SIZEMAX) { debug_print("Entry label too long (%s)\n", label); return MOBI_DATA_CORRUPT; } if (infl->cncx_record == NULL) { debug_print("%s\n", "Missing cncx record"); return MOBI_DATA_CORRUPT; } for (size_t i = 0; i < infl_count; i++) { size_t offset = infl_groups[i]; if (offset >= infl->entries_count) { debug_print("%s\n", "Invalid entry offset"); return MOBI_DATA_CORRUPT; } uint32_t *groups; size_t group_cnt = mobi_get_indxentry_tagarray(&groups, &infl->entries[offset], INDX_TAGARR_INFL_GROUPS); uint32_t *parts; size_t part_cnt = mobi_get_indxentry_tagarray(&parts, &infl->entries[offset], INDX_TAGARR_INFL_PARTS_V2); if (group_cnt != part_cnt) { return MOBI_DATA_CORRUPT; } for (size_t j = 0; j < part_cnt; j++) { name_attr[0] = '\0'; char *group_name = mobi_get_cncx_string(infl->cncx_record, groups[j]); if (group_name == NULL) { debug_print("%s\n", "Memory allocation failed"); return MOBI_MALLOC_FAILED; } if (strlen(group_name)) { snprintf(name_attr, INDX_INFLBUF_SIZEMAX, " name=\"%s\"", group_name); } free(group_name); unsigned char decoded[INDX_INFLBUF_SIZEMAX + 1]; memset(decoded, 0, INDX_INFLBUF_SIZEMAX + 1); unsigned char *rule = (unsigned char *) infl->entries[parts[j]].label; memcpy(decoded, label, label_length); int decoded_length = (int) label_length; MOBI_RET ret = mobi_decode_infl(decoded, &decoded_length, rule); if (ret != MOBI_SUCCESS) { return ret; } if (decoded_length == 0) { continue; } int n = snprintf(infl_tag, INDX_INFLBUF_SIZEMAX, iform_tag, name_attr, decoded); if (n > INDX_INFLBUF_SIZEMAX) { debug_print("Skipping truncated tag: %s\n", infl_tag); continue; } outlen += strlen(infl_tag); if (outlen > INDX_INFLTAG_SIZEMAX) { debug_print("Inflections text in %s too long (%zu)\n", label, outlen); return MOBI_ERROR; } strcat(outstring, infl_tag); } } if (outlen == initlen) { outstring[0] = '\0'; } else { strcat(outstring, end_tag); } return MOBI_SUCCESS; }
null
null
212,095
308778925981838546847974342798871389238
82
Fix array boundary check when parsing inflections which could result in buffer over-read with corrupt input
other
libmobi
c78e186739b50d156cb3da5d08d70294f0490853
1
MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) { MOBI_RET ret; const size_t offset = mobi_get_kf8offset(m); if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) { debug_print("%s", "HUFF/CDIC records metadata not found in MOBI header\n"); return MOBI_DATA_CORRUPT; } const size_t huff_rec_index = *m->mh->huff_rec_index + offset; const size_t huff_rec_count = *m->mh->huff_rec_count; if (huff_rec_count > HUFF_RECORD_MAXCNT) { debug_print("Too many HUFF record (%zu)\n", huff_rec_count); return MOBI_DATA_CORRUPT; } const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index); if (curr == NULL || huff_rec_count < 2) { debug_print("%s", "HUFF/CDIC record not found\n"); return MOBI_DATA_CORRUPT; } if (curr->size < HUFF_RECORD_MINSIZE) { debug_print("HUFF record too short (%zu b)\n", curr->size); return MOBI_DATA_CORRUPT; } ret = mobi_parse_huff(huffcdic, curr); if (ret != MOBI_SUCCESS) { debug_print("%s", "HUFF parsing failed\n"); return ret; } curr = curr->next; /* allocate memory for symbols data in each CDIC record */ huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols)); if (huffcdic->symbols == NULL) { debug_print("%s\n", "Memory allocation failed"); return MOBI_MALLOC_FAILED; } /* get following CDIC records */ size_t i = 0; while (i < huff_rec_count - 1) { if (curr == NULL) { debug_print("%s\n", "CDIC record not found"); return MOBI_DATA_CORRUPT; } ret = mobi_parse_cdic(huffcdic, curr, i++); if (ret != MOBI_SUCCESS) { debug_print("%s", "CDIC parsing failed\n"); return ret; } curr = curr->next; } return MOBI_SUCCESS; }
null
null
212,144
98306075060249719327803160157583197600
50
Fix potential out-of-buffer read while parsing corrupt file, closes #38
other
bash
951bdaad7a18cc0dc1036bba86b18b90874d39ff
1
disable_priv_mode () { int e; if (setuid (current_user.uid) < 0) { e = errno; sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid); #if defined (EXIT_ON_SETUID_FAILURE) if (e == EAGAIN) exit (e); #endif } if (setgid (current_user.gid) < 0) sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid); current_user.euid = current_user.uid; current_user.egid = current_user.gid; }
null
null
212,152
269777037163188215565274726505513038468
19
commit bash-20190628 snapshot
other
linux
ee457001ed6c6f31ddad69c24c1da8f377d8472d
1
xfs_iget_cache_miss( struct xfs_mount *mp, struct xfs_perag *pag, xfs_trans_t *tp, xfs_ino_t ino, struct xfs_inode **ipp, int flags, int lock_flags) { struct xfs_inode *ip; int error; xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino); int iflags; ip = xfs_inode_alloc(mp, ino); if (!ip) return -ENOMEM; error = xfs_iread(mp, tp, ip, flags); if (error) goto out_destroy; if (!xfs_inode_verify_forks(ip)) { error = -EFSCORRUPTED; goto out_destroy; } trace_xfs_iget_miss(ip); if ((VFS_I(ip)->i_mode == 0) && !(flags & XFS_IGET_CREATE)) { error = -ENOENT; goto out_destroy; } /* * Preload the radix tree so we can insert safely under the * write spinlock. Note that we cannot sleep inside the preload * region. Since we can be called from transaction context, don't * recurse into the file system. */ if (radix_tree_preload(GFP_NOFS)) { error = -EAGAIN; goto out_destroy; } /* * Because the inode hasn't been added to the radix-tree yet it can't * be found by another thread, so we can do the non-sleeping lock here. */ if (lock_flags) { if (!xfs_ilock_nowait(ip, lock_flags)) BUG(); } /* * These values must be set before inserting the inode into the radix * tree as the moment it is inserted a concurrent lookup (allowed by the * RCU locking mechanism) can find it and that lookup must see that this * is an inode currently under construction (i.e. that XFS_INEW is set). * The ip->i_flags_lock that protects the XFS_INEW flag forms the * memory barrier that ensures this detection works correctly at lookup * time. */ iflags = XFS_INEW; if (flags & XFS_IGET_DONTCACHE) iflags |= XFS_IDONTCACHE; ip->i_udquot = NULL; ip->i_gdquot = NULL; ip->i_pdquot = NULL; xfs_iflags_set(ip, iflags); /* insert the new inode */ spin_lock(&pag->pag_ici_lock); error = radix_tree_insert(&pag->pag_ici_root, agino, ip); if (unlikely(error)) { WARN_ON(error != -EEXIST); XFS_STATS_INC(mp, xs_ig_dup); error = -EAGAIN; goto out_preload_end; } spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); *ipp = ip; return 0; out_preload_end: spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); if (lock_flags) xfs_iunlock(ip, lock_flags); out_destroy: __destroy_inode(VFS_I(ip)); xfs_inode_free(ip); return error; }
null
null
212,158
100525632602230649416090729102853910182
96
xfs: catch inode allocation state mismatch corruption We recently came across a V4 filesystem causing memory corruption due to a newly allocated inode being setup twice and being added to the superblock inode list twice. From code inspection, the only way this could happen is if a newly allocated inode was not marked as free on disk (i.e. di_mode wasn't zero). Running the metadump on an upstream debug kernel fails during inode allocation like so: XFS: Assertion failed: ip->i_d.di_nblocks == 0, file: fs/xfs/xfs_inod= e.c, line: 838 ------------[ cut here ]------------ kernel BUG at fs/xfs/xfs_message.c:114! invalid opcode: 0000 [#1] PREEMPT SMP CPU: 11 PID: 3496 Comm: mkdir Not tainted 4.16.0-rc5-dgc #442 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1 04/0= 1/2014 RIP: 0010:assfail+0x28/0x30 RSP: 0018:ffffc9000236fc80 EFLAGS: 00010202 RAX: 00000000ffffffea RBX: 0000000000004000 RCX: 0000000000000000 RDX: 00000000ffffffc0 RSI: 000000000000000a RDI: ffffffff8227211b RBP: ffffc9000236fce8 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000bec R11: f000000000000000 R12: ffffc9000236fd30 R13: ffff8805c76bab80 R14: ffff8805c77ac800 R15: ffff88083fb12e10 FS: 00007fac8cbff040(0000) GS:ffff88083fd00000(0000) knlGS:0000000000000= 000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007fffa6783ff8 CR3: 00000005c6e2b003 CR4: 00000000000606e0 Call Trace: xfs_ialloc+0x383/0x570 xfs_dir_ialloc+0x6a/0x2a0 xfs_create+0x412/0x670 xfs_generic_create+0x1f7/0x2c0 ? capable_wrt_inode_uidgid+0x3f/0x50 vfs_mkdir+0xfb/0x1b0 SyS_mkdir+0xcf/0xf0 do_syscall_64+0x73/0x1a0 entry_SYSCALL_64_after_hwframe+0x42/0xb7 Extracting the inode number we crashed on from an event trace and looking at it with xfs_db: xfs_db> inode 184452204 xfs_db> p core.magic = 0x494e core.mode = 0100644 core.version = 2 core.format = 2 (extents) core.nlinkv2 = 1 core.onlink = 0 ..... Confirms that it is not a free inode on disk. xfs_repair also trips over this inode: ..... zero length extent (off = 0, fsbno = 0) in ino 184452204 correcting nextents for inode 184452204 bad attribute fork in inode 184452204, would clear attr fork bad nblocks 1 for inode 184452204, would reset to 0 bad anextents 1 for inode 184452204, would reset to 0 imap claims in-use inode 184452204 is free, would correct imap would have cleared inode 184452204 ..... disconnected inode 184452204, would move to lost+found And so we have a situation where the directory structure and the inobt thinks the inode is free, but the inode on disk thinks it is still in use. Where this corruption came from is not possible to diagnose, but we can detect it and prevent the kernel from oopsing on lookup. The reproducer now results in: $ sudo mkdir /mnt/scratch/{0,1,2,3,4,5}{0,1,2,3,4,5} mkdir: cannot create directory =E2=80=98/mnt/scratch/00=E2=80=99: File ex= ists mkdir: cannot create directory =E2=80=98/mnt/scratch/01=E2=80=99: File ex= ists mkdir: cannot create directory =E2=80=98/mnt/scratch/03=E2=80=99: Structu= re needs cleaning mkdir: cannot create directory =E2=80=98/mnt/scratch/04=E2=80=99: Input/o= utput error mkdir: cannot create directory =E2=80=98/mnt/scratch/05=E2=80=99: Input/o= utput error .... And this corruption shutdown: [ 54.843517] XFS (loop0): Corruption detected! Free inode 0xafe846c not= marked free on disk [ 54.845885] XFS (loop0): Internal error xfs_trans_cancel at line 1023 = of file fs/xfs/xfs_trans.c. Caller xfs_create+0x425/0x670 [ 54.848994] CPU: 10 PID: 3541 Comm: mkdir Not tainted 4.16.0-rc5-dgc #= 443 [ 54.850753] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIO= S 1.10.2-1 04/01/2014 [ 54.852859] Call Trace: [ 54.853531] dump_stack+0x85/0xc5 [ 54.854385] xfs_trans_cancel+0x197/0x1c0 [ 54.855421] xfs_create+0x425/0x670 [ 54.856314] xfs_generic_create+0x1f7/0x2c0 [ 54.857390] ? capable_wrt_inode_uidgid+0x3f/0x50 [ 54.858586] vfs_mkdir+0xfb/0x1b0 [ 54.859458] SyS_mkdir+0xcf/0xf0 [ 54.860254] do_syscall_64+0x73/0x1a0 [ 54.861193] entry_SYSCALL_64_after_hwframe+0x42/0xb7 [ 54.862492] RIP: 0033:0x7fb73bddf547 [ 54.863358] RSP: 002b:00007ffdaa553338 EFLAGS: 00000246 ORIG_RAX: 0000= 000000000053 [ 54.865133] RAX: ffffffffffffffda RBX: 00007ffdaa55449a RCX: 00007fb73= bddf547 [ 54.866766] RDX: 0000000000000001 RSI: 00000000000001ff RDI: 00007ffda= a55449a [ 54.868432] RBP: 00007ffdaa55449a R08: 00000000000001ff R09: 00005623a= 8670dd0 [ 54.870110] R10: 00007fb73be72d5b R11: 0000000000000246 R12: 000000000= 00001ff [ 54.871752] R13: 00007ffdaa5534b0 R14: 0000000000000000 R15: 00007ffda= a553500 [ 54.873429] XFS (loop0): xfs_do_force_shutdown(0x8) called from line 1= 024 of file fs/xfs/xfs_trans.c. Return address = ffffffff814cd050 [ 54.882790] XFS (loop0): Corruption of in-memory data detected. Shutt= ing down filesystem [ 54.884597] XFS (loop0): Please umount the filesystem and rectify the = problem(s) Note that this crash is only possible on v4 filesystemsi or v5 filesystems mounted with the ikeep mount option. For all other V5 filesystems, this problem cannot occur because we don't read inodes we are allocating from disk - we simply overwrite them with the new inode information. Signed-Off-By: Dave Chinner <[email protected]> Reviewed-by: Carlos Maiolino <[email protected]> Tested-by: Carlos Maiolino <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> Signed-off-by: Darrick J. Wong <[email protected]>
other
linux
7ec37d1cbe17d8189d9562178d8b29167fe1c31a
1
static int synic_set_irq(struct kvm_vcpu_hv_synic *synic, u32 sint) { struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic); struct kvm_lapic_irq irq; int ret, vector; if (sint >= ARRAY_SIZE(synic->sint)) return -EINVAL; vector = synic_get_sint_vector(synic_read_sint(synic, sint)); if (vector < 0) return -ENOENT; memset(&irq, 0, sizeof(irq)); irq.shorthand = APIC_DEST_SELF; irq.dest_mode = APIC_DEST_PHYSICAL; irq.delivery_mode = APIC_DM_FIXED; irq.vector = vector; irq.level = 1; ret = kvm_irq_delivery_to_apic(vcpu->kvm, vcpu->arch.apic, &irq, NULL); trace_kvm_hv_synic_set_irq(vcpu->vcpu_id, sint, irq.vector, ret); return ret; }
null
null
212,165
214768374966779687489672213124686296024
24
KVM: x86: Check lapic_in_kernel() before attempting to set a SynIC irq When KVM_CAP_HYPERV_SYNIC{,2} is activated, KVM already checks for irqchip_in_kernel() so normally SynIC irqs should never be set. It is, however, possible for a misbehaving VMM to write to SYNIC/STIMER MSRs causing erroneous behavior. The immediate issue being fixed is that kvm_irq_delivery_to_apic() (kvm_irq_delivery_to_apic_fast()) crashes when called with 'irq.shorthand = APIC_DEST_SELF' and 'src == NULL'. Signed-off-by: Vitaly Kuznetsov <[email protected]> Message-Id: <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]>
other
icecast-server
03ea74c04a5966114c2fe66e4e6892d11a68181e
1
static size_t handle_returned_header (void *ptr, size_t size, size_t nmemb, void *stream) { auth_client *auth_user = stream; size_t bytes = size * nmemb; client_t *client = auth_user->client; if (client) { auth_t *auth = client->auth; auth_url *url = auth->state; if (strncasecmp (ptr, url->auth_header, url->auth_header_len) == 0) client->authenticated = 1; if (strncasecmp (ptr, url->timelimit_header, url->timelimit_header_len) == 0) { unsigned int limit = 0; sscanf ((char *)ptr+url->timelimit_header_len, "%u\r\n", &limit); client->con->discon_time = time(NULL) + limit; } if (strncasecmp (ptr, "icecast-auth-message: ", 22) == 0) { char *eol; snprintf (url->errormsg, sizeof (url->errormsg), "%s", (char*)ptr+22); eol = strchr (url->errormsg, '\r'); if (eol == NULL) eol = strchr (url->errormsg, '\n'); if (eol) *eol = '\0'; } } return bytes; }
null
null
212,339
244473335174490870029088323656762531395
32
Fix: Worked around buffer overflows in URL auth's cURL interface This is only a workaround that keeps compatibility with 2.4.x mainline. A real fix has been implemented in 2.5.x (master).
other
gegl
bfce470f0f2f37968862129d5038b35429f2909b
1
load_cache (GeglProperties *op_magick_load) { if (!op_magick_load->user_data) { gchar *filename; gchar *cmd; GeglNode *graph, *sink, *loader; GeglBuffer *newbuf = NULL; /* ImageMagick backed fallback FIXME: make this robust. * maybe use pipes in a manner similar to the raw loader, * or at least use a properly unique filename */ filename = g_build_filename (g_get_tmp_dir (), "gegl-magick.png", NULL); cmd = g_strdup_printf ("convert \"%s\"'[0]' \"%s\"", op_magick_load->path, filename); if (system (cmd) == -1) g_warning ("Error executing ImageMagick convert program"); graph = gegl_node_new (); sink = gegl_node_new_child (graph, "operation", "gegl:buffer-sink", "buffer", &newbuf, NULL); loader = gegl_node_new_child (graph, "operation", "gegl:png-load", "path", filename, NULL); gegl_node_link_many (loader, sink, NULL); gegl_node_process (sink); op_magick_load->user_data = (gpointer) newbuf; g_object_unref (graph); g_free (cmd); g_free (filename); } }
null
null
212,346
128207149302076836420080513313021708603
35
magick-load: use more robust g_spawn_async() instead of system() This fixes issue #298 by avoiding the shell parsing being invoked at all, this less brittle than any forms of escaping characters, while retaining the ability to address all existing files.
other
vim
44a3f3353e0407e9fffee138125a6927d1c9e7e5
1
append_command(char_u *cmd) { char_u *s = cmd; char_u *d; STRCAT(IObuff, ": "); d = IObuff + STRLEN(IObuff); while (*s != NUL && d - IObuff + 5 < IOSIZE) { if (enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : *s == 0xa0) { s += enc_utf8 ? 2 : 1; STRCPY(d, "<a0>"); d += 4; } else if (d - IObuff + (*mb_ptr2len)(s) + 1 >= IOSIZE) break; else MB_COPY_CHAR(s, d); } *d = NUL; }
null
null
212,347
39175087291679701080412148819554872675
22
patch 8.2.5063: error for a command may go over the end of IObuff Problem: Error for a command may go over the end of IObuff. Solution: Truncate the message.
other
logrotate
addbd293242b0b78aa54f054e6c1d249451f137d
1
static int writeState(const char *stateFilename) { struct logState *p; FILE *f; char *chptr; unsigned int i = 0; int error = 0; int bytes = 0; int fdcurr; int fdsave; struct stat sb; char *tmpFilename = NULL; struct tm now; time_t now_time, last_time; char *prevCtx; if (!strcmp(stateFilename, "/dev/null")) /* explicitly asked not to write the state file */ return 0; localtime_r(&nowSecs, &now); tmpFilename = malloc(strlen(stateFilename) + 5 ); if (tmpFilename == NULL) { message_OOM(); return 1; } strcpy(tmpFilename, stateFilename); strcat(tmpFilename, ".tmp"); /* Remove possible tmp state file from previous run */ error = unlink(tmpFilename); if (error == -1 && errno != ENOENT) { message(MESS_ERROR, "error removing old temporary state file %s: %s\n", tmpFilename, strerror(errno)); free(tmpFilename); return 1; } error = 0; fdcurr = open(stateFilename, O_RDONLY); if (fdcurr == -1) { /* the statefile should exist, lockState() already created an empty * state file in case it did not exist initially */ message(MESS_ERROR, "error opening state file %s: %s\n", stateFilename, strerror(errno)); free(tmpFilename); return 1; } /* get attributes, to assign them to the new state file */ if (setSecCtx(fdcurr, stateFilename, &prevCtx) != 0) { /* error msg already printed */ free(tmpFilename); close(fdcurr); return 1; } #ifdef WITH_ACL if ((prev_acl = acl_get_fd(fdcurr)) == NULL) { if (is_acl_well_supported(errno)) { message(MESS_ERROR, "getting file ACL %s: %s\n", stateFilename, strerror(errno)); restoreSecCtx(&prevCtx); free(tmpFilename); close(fdcurr); return 1; } } #endif if (fstat(fdcurr, &sb) == -1) { message(MESS_ERROR, "error stating %s: %s\n", stateFilename, strerror(errno)); restoreSecCtx(&prevCtx); free(tmpFilename); #ifdef WITH_ACL if (prev_acl) { acl_free(prev_acl); prev_acl = NULL; } #endif return 1; } close(fdcurr); /* drop world-readable flag to prevent others from locking */ sb.st_mode &= ~(mode_t)S_IROTH; fdsave = createOutputFile(tmpFilename, O_RDWR, &sb, prev_acl, 0); #ifdef WITH_ACL if (prev_acl) { acl_free(prev_acl); prev_acl = NULL; } #endif restoreSecCtx(&prevCtx); if (fdsave < 0) { free(tmpFilename); return 1; } f = fdopen(fdsave, "w"); if (!f) { message(MESS_ERROR, "error creating temp state file %s: %s\n", tmpFilename, strerror(errno)); free(tmpFilename); return 1; } bytes = fprintf(f, "logrotate state -- version 2\n"); if (bytes < 0) error = bytes; /* * Time in seconds it takes earth to go around sun. The value is * astronomical measurement (solar year) rather than something derived from * a convention (calendar year). */ #define SECONDS_IN_YEAR 31556926 for (i = 0; i < hashSize && error == 0; i++) { for (p = states[i]->head.lh_first; p != NULL && error == 0; p = p->list.le_next) { /* Skip states which are not used for more than a year. */ now_time = mktime(&now); last_time = mktime(&p->lastRotated); if (!p->isUsed && difftime(now_time, last_time) > SECONDS_IN_YEAR) { message(MESS_DEBUG, "Removing %s from state file, " "because it does not exist and has not been rotated for one year\n", p->fn); continue; } error = fputc('"', f) == EOF; for (chptr = p->fn; *chptr && error == 0; chptr++) { switch (*chptr) { case '"': case '\\': error = fputc('\\', f) == EOF; break; case '\n': error = fputc('\\', f) == EOF; if (error == 0) { error = fputc('n', f) == EOF; } continue; default: break; } if (error == 0 && fputc(*chptr, f) == EOF) { error = 1; } } if (error == 0 && fputc('"', f) == EOF) error = 1; if (error == 0) { bytes = fprintf(f, " %d-%d-%d-%d:%d:%d\n", p->lastRotated.tm_year + 1900, p->lastRotated.tm_mon + 1, p->lastRotated.tm_mday, p->lastRotated.tm_hour, p->lastRotated.tm_min, p->lastRotated.tm_sec); if (bytes < 0) error = bytes; } } } if (error == 0) error = fflush(f); if (error == 0) error = fsync(fdsave); if (error == 0) error = fclose(f); else fclose(f); if (error == 0) { if (rename(tmpFilename, stateFilename)) { message(MESS_ERROR, "error renaming temp state file %s to %s: %s\n", tmpFilename, stateFilename, strerror(errno)); unlink(tmpFilename); error = 1; } } else { if (errno) message(MESS_ERROR, "error creating temp state file %s: %s\n", tmpFilename, strerror(errno)); else message(MESS_ERROR, "error creating temp state file %s%s\n", tmpFilename, error == ENOMEM ? ": Insufficient storage space is available." : "" ); unlink(tmpFilename); } free(tmpFilename); return error; }
null
null
212,371
219455995060029614601757195681914479713
206
drop world-readable permission on state file ... even when ACLs are enabled. This is a follow-up to the fix of CVE-2022-1348. It has no impact on security but makes the state file locking work again in more cases. Closes: https://github.com/logrotate/logrotate/pull/446
other