project
stringclasses 791
values | commit_id
stringlengths 6
81
| CVE ID
stringlengths 13
16
| CWE ID
stringclasses 127
values | func
stringlengths 5
484k
| vul
int8 0
1
|
---|---|---|---|---|---|
linux | 0b760113a3a155269a3fba93a409c640031dd68f | NOT_APPLICABLE | NOT_APPLICABLE | void rpc_free(void *buffer)
{
size_t size;
struct rpc_buffer *buf;
if (!buffer)
return;
buf = container_of(buffer, struct rpc_buffer, data);
size = buf->len;
dprintk("RPC: freeing buffer of size %zu at %p\n",
size, buf);
if (size <= RPC_BUFFER_MAXSIZE)
mempool_free(buf, rpc_buffer_mempool);
else
kfree(buf);
}
| 0 |
linux | c95eb3184ea1a3a2551df57190c81da695e2144b | NOT_APPLICABLE | NOT_APPLICABLE | validate_event(struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
struct pmu *leader_pmu = event->group_leader->pmu;
if (is_software_event(event))
return 1;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
return armpmu->get_event_idx(hw_events, event) >= 0;
}
| 0 |
linux | f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5 | NOT_APPLICABLE | NOT_APPLICABLE | * non-zero.
*/
struct iscsi_cls_conn *
iscsi_create_conn(struct iscsi_cls_session *session, int dd_size, uint32_t cid)
{
struct iscsi_transport *transport = session->transport;
struct iscsi_cls_conn *conn;
unsigned long flags;
int err;
conn = kzalloc(sizeof(*conn) + dd_size, GFP_KERNEL);
if (!conn)
return NULL;
if (dd_size)
conn->dd_data = &conn[1];
mutex_init(&conn->ep_mutex);
INIT_LIST_HEAD(&conn->conn_list);
INIT_LIST_HEAD(&conn->conn_list_err);
conn->transport = transport;
conn->cid = cid;
conn->state = ISCSI_CONN_DOWN;
/* this is released in the dev's release function */
if (!get_device(&session->dev))
goto free_conn;
dev_set_name(&conn->dev, "connection%d:%u", session->sid, cid);
conn->dev.parent = &session->dev;
conn->dev.release = iscsi_conn_release;
err = device_register(&conn->dev);
if (err) {
iscsi_cls_session_printk(KERN_ERR, session, "could not "
"register connection's dev\n");
goto release_parent_ref;
}
err = transport_register_device(&conn->dev);
if (err) {
iscsi_cls_session_printk(KERN_ERR, session, "could not "
"register transport's dev\n");
goto release_conn_ref;
}
spin_lock_irqsave(&connlock, flags);
list_add(&conn->conn_list, &connlist);
spin_unlock_irqrestore(&connlock, flags);
ISCSI_DBG_TRANS_CONN(conn, "Completed conn creation\n");
return conn;
release_conn_ref:
device_unregister(&conn->dev);
put_device(&session->dev);
return NULL;
release_parent_ref:
put_device(&session->dev);
free_conn: | 0 |
radare2 | 65000a7fd9eea62359e6d6714f17b94a99a82edd | NOT_APPLICABLE | NOT_APPLICABLE | static void* empty (int sz) {
void *p = malloc (sz);
if (p) memset (p, '\0', sz);
return p;
}
| 0 |
flatpak | 8279c5818425b6812523e3805bbe242fb6a5d961 | NOT_APPLICABLE | NOT_APPLICABLE | flatpak_dir_install_bundle (FlatpakDir *self,
GFile *file,
const char *remote,
FlatpakDecomposed **out_ref,
GCancellable *cancellable,
GError **error)
{
g_autofree char *ref_str = NULL;
g_autoptr(FlatpakDecomposed) ref = NULL;
g_autoptr(GBytes) deploy_data = NULL;
g_autoptr(GVariant) metadata = NULL;
g_autofree char *origin = NULL;
g_autofree char *to_checksum = NULL;
gboolean gpg_verify;
if (!flatpak_dir_check_add_remotes_config_dir (self, error))
return FALSE;
if (flatpak_dir_use_system_helper (self, NULL))
{
const char *installation = flatpak_dir_get_id (self);
if (!flatpak_dir_system_helper_call_install_bundle (self,
flatpak_file_get_path_cached (file),
0, remote,
installation ? installation : "",
&ref_str,
cancellable,
error))
return FALSE;
ref = flatpak_decomposed_new_from_ref (ref_str, error);
if (ref == NULL)
return FALSE;
if (out_ref)
*out_ref = g_steal_pointer (&ref);
return TRUE;
}
if (!flatpak_dir_ensure_repo (self, cancellable, error))
return FALSE;
metadata = flatpak_bundle_load (file, &to_checksum,
&ref,
&origin,
NULL, NULL,
NULL, NULL, NULL,
error);
if (metadata == NULL)
return FALSE;
deploy_data = flatpak_dir_get_deploy_data (self, ref, FLATPAK_DEPLOY_VERSION_ANY, cancellable, NULL);
if (deploy_data != NULL)
{
if (strcmp (flatpak_deploy_data_get_commit (deploy_data), to_checksum) == 0)
{
g_autofree char *id = flatpak_decomposed_dup_id (ref);
g_set_error (error, FLATPAK_ERROR, FLATPAK_ERROR_ALREADY_INSTALLED,
_("This version of %s is already installed"), id);
return FALSE;
}
if (strcmp (remote, flatpak_deploy_data_get_origin (deploy_data)) != 0)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Can't change remote during bundle install"));
return FALSE;
}
}
if (!ostree_repo_remote_get_gpg_verify (self->repo, remote,
&gpg_verify, error))
return FALSE;
if (!flatpak_pull_from_bundle (self->repo,
file,
remote,
flatpak_decomposed_get_ref (ref),
gpg_verify,
cancellable,
error))
return FALSE;
if (deploy_data != NULL)
{
g_autofree char *group = g_strdup_printf ("remote \"%s\"", remote);
g_autofree char *old_url = NULL;
g_autoptr(GKeyFile) new_config = NULL;
/* The pull succeeded, and this is an update. So, we need to update the repo config
if anything changed */
ostree_repo_remote_get_url (self->repo,
remote,
&old_url,
NULL);
if (origin != NULL &&
(old_url == NULL || strcmp (old_url, origin) != 0))
{
if (new_config == NULL)
new_config = ostree_repo_copy_config (self->repo);
g_key_file_set_value (new_config, group, "url", origin);
}
if (new_config)
{
if (!flatpak_dir_cleanup_remote_for_url_change (self, remote,
origin, cancellable, error))
return FALSE;
if (!ostree_repo_write_config (self->repo, new_config, error))
return FALSE;
}
}
if (deploy_data)
{
if (!flatpak_dir_deploy_update (self, ref, NULL, NULL, NULL, cancellable, error))
return FALSE;
}
else
{
if (!flatpak_dir_deploy_install (self, ref, remote, NULL, NULL, FALSE, cancellable, error))
return FALSE;
}
if (out_ref)
*out_ref = g_steal_pointer (&ref);
return TRUE;
} | 0 |
php-src | c395c6e5d7e8df37a21265ff76e48fe75ceb5ae6?w=1 | NOT_APPLICABLE | NOT_APPLICABLE | void gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c)
{
int i;
int y;
int miny, maxy, pmaxy;
int x1, y1;
int x2, y2;
int ind1, ind2;
int ints;
int fill_color;
if (n <= 0) {
return;
}
if (overflow2(sizeof(int), n)) {
return;
}
if (c == gdAntiAliased) {
fill_color = im->AA_color;
} else {
fill_color = c;
}
if (!im->polyAllocated) {
im->polyInts = (int *) gdMalloc(sizeof(int) * n);
im->polyAllocated = n;
}
if (im->polyAllocated < n) {
while (im->polyAllocated < n) {
im->polyAllocated *= 2;
}
if (overflow2(sizeof(int), im->polyAllocated)) {
return;
}
im->polyInts = (int *) gdRealloc(im->polyInts, sizeof(int) * im->polyAllocated);
}
miny = p[0].y;
maxy = p[0].y;
for (i = 1; i < n; i++) {
if (p[i].y < miny) {
miny = p[i].y;
}
if (p[i].y > maxy) {
maxy = p[i].y;
}
}
pmaxy = maxy;
/* 2.0.16: Optimization by Ilia Chipitsine -- don't waste time offscreen */
if (miny < 0) {
miny = 0;
}
if (maxy >= gdImageSY(im)) {
maxy = gdImageSY(im) - 1;
}
/* Fix in 1.3: count a vertex only once */
for (y = miny; y <= maxy; y++) {
/*1.4 int interLast = 0; */
/* int dirLast = 0; */
/* int interFirst = 1; */
ints = 0;
for (i = 0; i < n; i++) {
if (!i) {
ind1 = n - 1;
ind2 = 0;
} else {
ind1 = i - 1;
ind2 = i;
}
y1 = p[ind1].y;
y2 = p[ind2].y;
if (y1 < y2) {
x1 = p[ind1].x;
x2 = p[ind2].x;
} else if (y1 > y2) {
y2 = p[ind1].y;
y1 = p[ind2].y;
x2 = p[ind1].x;
x1 = p[ind2].x;
} else {
continue;
}
/* Do the following math as float intermediately, and round to ensure
* that Polygon and FilledPolygon for the same set of points have the
* same footprint.
*/
if (y >= y1 && y < y2) {
im->polyInts[ints++] = (float) ((y - y1) * (x2 - x1)) / (float) (y2 - y1) + 0.5 + x1;
} else if (y == pmaxy && y == y2) {
im->polyInts[ints++] = x2;
}
}
qsort(im->polyInts, ints, sizeof(int), gdCompareInt);
for (i = 0; i < ints - 1; i += 2) {
gdImageLine(im, im->polyInts[i], y, im->polyInts[i + 1], y, fill_color);
}
}
/* If we are drawing this AA, then redraw the border with AA lines. */
if (c == gdAntiAliased) {
gdImagePolygon(im, p, n, c);
}
}
| 0 |
cpio | dd96882877721703e19272fe25034560b794061b | NOT_APPLICABLE | NOT_APPLICABLE | stat_to_cpio (struct cpio_file_stat *hdr, struct stat *st)
{
get_inode_and_dev (hdr, st);
/* For POSIX systems that don't define the S_IF macros,
we can't assume that S_ISfoo means the standard Unix
S_IFfoo bit(s) are set. So do it manually, with a
different name. Bleah. */
hdr->c_mode = (st->st_mode & 07777);
if (S_ISREG (st->st_mode))
hdr->c_mode |= CP_IFREG;
else if (S_ISDIR (st->st_mode))
hdr->c_mode |= CP_IFDIR;
#ifdef S_ISBLK
else if (S_ISBLK (st->st_mode))
hdr->c_mode |= CP_IFBLK;
#endif
#ifdef S_ISCHR
else if (S_ISCHR (st->st_mode))
hdr->c_mode |= CP_IFCHR;
#endif
#ifdef S_ISFIFO
else if (S_ISFIFO (st->st_mode))
hdr->c_mode |= CP_IFIFO;
#endif
#ifdef S_ISLNK
else if (S_ISLNK (st->st_mode))
hdr->c_mode |= CP_IFLNK;
#endif
#ifdef S_ISSOCK
else if (S_ISSOCK (st->st_mode))
hdr->c_mode |= CP_IFSOCK;
#endif
#ifdef S_ISNWK
else if (S_ISNWK (st->st_mode))
hdr->c_mode |= CP_IFNWK;
#endif
hdr->c_nlink = st->st_nlink;
hdr->c_uid = CPIO_UID (st->st_uid);
hdr->c_gid = CPIO_GID (st->st_gid);
if (S_ISBLK (st->st_mode) || S_ISCHR (st->st_mode))
{
hdr->c_rdev_maj = major (st->st_rdev);
hdr->c_rdev_min = minor (st->st_rdev);
}
else
{
hdr->c_rdev_maj = 0;
hdr->c_rdev_min = 0;
}
hdr->c_mtime = st->st_mtime;
hdr->c_filesize = st->st_size;
hdr->c_chksum = 0;
hdr->c_tar_linkname = NULL;
} | 0 |
Chrome | e3aa8a56706c4abe208934d5c294f7b594b8b693 | NOT_APPLICABLE | NOT_APPLICABLE | void UsbChooserContext::GetDevices(
device::mojom::UsbDeviceManager::GetDevicesCallback callback) {
EnsureConnectionWithDeviceManager();
device_manager_->GetDevices(nullptr, std::move(callback));
}
| 0 |
radare2 | 4d3811681a80f92a53e795f6a64c4b0fc2c8dd22 | NOT_APPLICABLE | NOT_APPLICABLE | static void cmd_anal_abt(RCore *core, const char *input) {
switch (*input) {
case 'e':
{
int n = 1;
char *p = strchr (input + 1, ' ');
if (!p) {
eprintf ("Usage: abte [addr] # emulate from beginning of function to the given address.\n");
return;
}
ut64 addr = r_num_math (core->num, p + 1);
RList *paths = r_core_anal_graph_to (core, addr, n);
if (paths) {
RAnalBlock *bb;
RList *path;
RListIter *pathi;
RListIter *bbi;
r_cons_printf ("f orip=`dr?PC`\n");
r_list_foreach (paths, pathi, path) {
r_list_foreach (path, bbi, bb) {
r_cons_printf ("# 0x%08" PFMT64x "\n", bb->addr);
if (addr >= bb->addr && addr < bb->addr + bb->size) {
r_cons_printf ("aepc 0x%08"PFMT64x"\n", bb->addr);
r_cons_printf ("aesou 0x%08"PFMT64x"\n", addr);
} else {
r_cons_printf ("aepc 0x%08"PFMT64x"\n", bb->addr);
r_cons_printf ("aesou 0x%08"PFMT64x"\n", bb->addr + bb->size);
}
}
r_cons_newline ();
r_list_purge (path);
free (path);
}
r_list_purge (paths);
r_cons_printf ("aepc orip\n");
free (paths);
}
}
break;
case '?':
r_core_cmd_help (core, help_msg_abt);
break;
case 'j': {
ut64 addr = r_num_math (core->num, input + 1);
RAnalBlock *block = r_anal_get_block_at (core->anal, core->offset);
if (!block) {
break;
}
RList *path = r_anal_block_shortest_path (block, addr);
PJ *pj = pj_new ();
if (pj) {
pj_a (pj);
if (path) {
RListIter *it;
r_list_foreach (path, it, block) {
pj_n (pj, block->addr);
}
}
pj_end (pj);
r_cons_println (pj_string (pj));
pj_free (pj);
}
r_list_free (path);
break;
}
case ' ': {
ut64 addr = r_num_math (core->num, input + 1);
RAnalBlock *block = r_anal_get_block_at (core->anal, core->offset);
if (!block) {
break;
}
RList *path = r_anal_block_shortest_path (block, addr);
if (path) {
RListIter *it;
r_list_foreach (path, it, block) {
r_cons_printf ("0x%08" PFMT64x "\n", block->addr);
}
r_list_free (path);
}
break;
}
case '\0':
eprintf ("Usage abt?\n");
break;
}
} | 0 |
libgit2 | 3f7851eadca36a99627ad78cbe56a40d3776ed01 | NOT_APPLICABLE | NOT_APPLICABLE | bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
} | 0 |
libxml2 | 90ccb58242866b0ba3edbef8fe44214a101c2b3e | NOT_APPLICABLE | NOT_APPLICABLE | xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParsePEReference: no name\n");
return;
}
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
/*
* TODO !!!
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
if (ctxt->errNo ==
XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing
* right here
*/
xmlHaltParser(ctxt);
return;
}
}
}
}
ctxt->hasPErefs = 1;
} | 0 |
linux | 6ec82562ffc6f297d0de36d65776cff8e5704867 | NOT_APPLICABLE | NOT_APPLICABLE | static void softnet_seq_stop(struct seq_file *seq, void *v)
{
}
| 0 |
linux | 9c52057c698fb96f8f07e7a4bcf4801a092bda89 | NOT_APPLICABLE | NOT_APPLICABLE | static int btrfs_flush_all_pending_stuffs(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int flush_on_commit = btrfs_test_opt(root, FLUSHONCOMMIT);
int snap_pending = 0;
int ret;
if (!flush_on_commit) {
spin_lock(&root->fs_info->trans_lock);
if (!list_empty(&trans->transaction->pending_snapshots))
snap_pending = 1;
spin_unlock(&root->fs_info->trans_lock);
}
if (flush_on_commit || snap_pending) {
btrfs_start_delalloc_inodes(root, 1);
btrfs_wait_ordered_extents(root, 1);
}
ret = btrfs_run_delayed_items(trans, root);
if (ret)
return ret;
/*
* running the delayed items may have added new refs. account
* them now so that they hinder processing of more delayed refs
* as little as possible.
*/
btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
/*
* rename don't use btrfs_join_transaction, so, once we
* set the transaction to blocked above, we aren't going
* to get any new ordered operations. We can safely run
* it here and no for sure that nothing new will be added
* to the list
*/
btrfs_run_ordered_operations(root, 1);
return 0;
}
| 0 |
linux | f6fb8f100b807378fda19e83e5ac6828b638603a | NOT_APPLICABLE | NOT_APPLICABLE | static inline void *__prb_previous_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = prb_previous_blk_num(rb);
return prb_lookup_block(po, rb, previous, status);
} | 0 |
systemd | 5ba6985b6c8ef85a8bcfeb1b65239c863436e75b | NOT_APPLICABLE | NOT_APPLICABLE | void manager_free(Manager *m) {
UnitType c;
int i;
assert(m);
manager_clear_jobs_and_units(m);
for (c = 0; c < _UNIT_TYPE_MAX; c++)
if (unit_vtable[c]->shutdown)
unit_vtable[c]->shutdown(m);
/* If we reexecute ourselves, we keep the root cgroup
* around */
manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
manager_undo_generators(m);
bus_done(m);
hashmap_free(m->units);
hashmap_free(m->jobs);
hashmap_free(m->watch_pids1);
hashmap_free(m->watch_pids2);
hashmap_free(m->watch_bus);
sd_event_source_unref(m->signal_event_source);
sd_event_source_unref(m->notify_event_source);
sd_event_source_unref(m->time_change_event_source);
sd_event_source_unref(m->jobs_in_progress_event_source);
sd_event_source_unref(m->idle_pipe_event_source);
sd_event_source_unref(m->run_queue_event_source);
if (m->signal_fd >= 0)
close_nointr_nofail(m->signal_fd);
if (m->notify_fd >= 0)
close_nointr_nofail(m->notify_fd);
if (m->time_change_fd >= 0)
close_nointr_nofail(m->time_change_fd);
if (m->kdbus_fd >= 0)
close_nointr_nofail(m->kdbus_fd);
manager_close_idle_pipe(m);
udev_unref(m->udev);
sd_event_unref(m->event);
free(m->notify_socket);
lookup_paths_free(&m->lookup_paths);
strv_free(m->environment);
hashmap_free(m->cgroup_unit);
set_free_free(m->unit_path_cache);
free(m->switch_root);
free(m->switch_root_init);
for (i = 0; i < RLIMIT_NLIMITS; i++)
free(m->rlimit[i]);
assert(hashmap_isempty(m->units_requiring_mounts_for));
hashmap_free(m->units_requiring_mounts_for);
free(m);
} | 0 |
lua | a2195644d89812e5b157ce7bac35543e06db05e3 | NOT_APPLICABLE | NOT_APPLICABLE | CallInfo *luaE_extendCI (lua_State *L) {
CallInfo *ci;
lua_assert(L->ci->next == NULL);
luaE_enterCcall(L);
ci = luaM_new(L, CallInfo);
lua_assert(L->ci->next == NULL);
L->ci->next = ci;
ci->previous = L->ci;
ci->next = NULL;
ci->u.l.trap = 0;
L->nci++;
return ci;
} | 0 |
linux | c70422f760c120480fee4de6c38804c72aa26bc1 | CVE-2017-9059 | CWE-404 | static int send_write_chunks(struct svcxprt_rdma *xprt,
struct rpcrdma_write_array *wr_ary,
struct rpcrdma_msg *rdma_resp,
struct svc_rqst *rqstp,
struct svc_rdma_req_map *vec)
{
u32 xfer_len = rqstp->rq_res.page_len;
int write_len;
u32 xdr_off;
int chunk_off;
int chunk_no;
int nchunks;
struct rpcrdma_write_array *res_ary;
int ret;
res_ary = (struct rpcrdma_write_array *)
&rdma_resp->rm_body.rm_chunks[1];
/* Write chunks start at the pagelist */
nchunks = be32_to_cpu(wr_ary->wc_nchunks);
for (xdr_off = rqstp->rq_res.head[0].iov_len, chunk_no = 0;
xfer_len && chunk_no < nchunks;
chunk_no++) {
struct rpcrdma_segment *arg_ch;
u64 rs_offset;
arg_ch = &wr_ary->wc_array[chunk_no].wc_target;
write_len = min(xfer_len, be32_to_cpu(arg_ch->rs_length));
/* Prepare the response chunk given the length actually
* written */
xdr_decode_hyper((__be32 *)&arg_ch->rs_offset, &rs_offset);
svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no,
arg_ch->rs_handle,
arg_ch->rs_offset,
write_len);
chunk_off = 0;
while (write_len) {
ret = send_write(xprt, rqstp,
be32_to_cpu(arg_ch->rs_handle),
rs_offset + chunk_off,
xdr_off,
write_len,
vec);
if (ret <= 0)
goto out_err;
chunk_off += ret;
xdr_off += ret;
xfer_len -= ret;
write_len -= ret;
}
}
/* Update the req with the number of chunks actually used */
svc_rdma_xdr_encode_write_list(rdma_resp, chunk_no);
return rqstp->rq_res.page_len;
out_err:
pr_err("svcrdma: failed to send write chunks, rc=%d\n", ret);
return -EIO;
}
| 1 |
ImageMagick | f6e9d0d9955e85bdd7540b251cd50d598dacc5e6 | NOT_APPLICABLE | NOT_APPLICABLE | static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
}
| 0 |
rpm | 25a435e90844ea98fe5eb7bef22c1aecf3a9c033 | NOT_APPLICABLE | NOT_APPLICABLE | static int fsmMkdir(int dirfd, const char *path, mode_t mode)
{
int rc = mkdirat(dirfd, path, (mode & 07777));
if (_fsm_debug)
rpmlog(RPMLOG_DEBUG, " %8s (%d %s, 0%04o) %s\n", __func__,
dirfd, path, (unsigned)(mode & 07777),
(rc < 0 ? strerror(errno) : ""));
if (rc < 0) rc = RPMERR_MKDIR_FAILED;
return rc;
} | 0 |
qemu | 362786f14a753d8a5256ef97d7c10ed576d6572b | NOT_APPLICABLE | NOT_APPLICABLE | uint16_t net_checksum_finish(uint32_t sum)
{
while (sum>>16)
sum = (sum & 0xFFFF)+(sum >> 16);
return ~sum;
}
| 0 |
linux | 870aaff92e959e29d40f9cfdb5ed06ba2fc2dae0 | NOT_APPLICABLE | NOT_APPLICABLE | static long vhost_vdpa_unlocked_ioctl(struct file *filep,
unsigned int cmd, unsigned long arg)
{
struct vhost_vdpa *v = filep->private_data;
struct vhost_dev *d = &v->vdev;
void __user *argp = (void __user *)arg;
u64 __user *featurep = argp;
u64 features;
long r = 0;
if (cmd == VHOST_SET_BACKEND_FEATURES) {
if (copy_from_user(&features, featurep, sizeof(features)))
return -EFAULT;
if (features & ~VHOST_VDPA_BACKEND_FEATURES)
return -EOPNOTSUPP;
vhost_set_backend_features(&v->vdev, features);
return 0;
}
mutex_lock(&d->mutex);
switch (cmd) {
case VHOST_VDPA_GET_DEVICE_ID:
r = vhost_vdpa_get_device_id(v, argp);
break;
case VHOST_VDPA_GET_STATUS:
r = vhost_vdpa_get_status(v, argp);
break;
case VHOST_VDPA_SET_STATUS:
r = vhost_vdpa_set_status(v, argp);
break;
case VHOST_VDPA_GET_CONFIG:
r = vhost_vdpa_get_config(v, argp);
break;
case VHOST_VDPA_SET_CONFIG:
r = vhost_vdpa_set_config(v, argp);
break;
case VHOST_GET_FEATURES:
r = vhost_vdpa_get_features(v, argp);
break;
case VHOST_SET_FEATURES:
r = vhost_vdpa_set_features(v, argp);
break;
case VHOST_VDPA_GET_VRING_NUM:
r = vhost_vdpa_get_vring_num(v, argp);
break;
case VHOST_SET_LOG_BASE:
case VHOST_SET_LOG_FD:
r = -ENOIOCTLCMD;
break;
case VHOST_VDPA_SET_CONFIG_CALL:
r = vhost_vdpa_set_config_call(v, argp);
break;
case VHOST_GET_BACKEND_FEATURES:
features = VHOST_VDPA_BACKEND_FEATURES;
if (copy_to_user(featurep, &features, sizeof(features)))
r = -EFAULT;
break;
case VHOST_VDPA_GET_IOVA_RANGE:
r = vhost_vdpa_get_iova_range(v, argp);
break;
default:
r = vhost_dev_ioctl(&v->vdev, cmd, argp);
if (r == -ENOIOCTLCMD)
r = vhost_vdpa_vring_ioctl(v, cmd, argp);
break;
}
mutex_unlock(&d->mutex);
return r;
} | 0 |
linux | c4c896e1471aec3b004a693c689f60be3b17ac86 | NOT_APPLICABLE | NOT_APPLICABLE | static void sco_sock_set_timer(struct sock *sk, long timeout)
{
BT_DBG("sock %p state %d timeout %ld", sk, sk->sk_state, timeout);
sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout);
}
| 0 |
LibRaw | 4feaed4dea636cee4fee010f615881ccf76a096d | NOT_APPLICABLE | NOT_APPLICABLE | int LibRaw::setMakeFromIndex(unsigned makei)
{
if (makei <= LIBRAW_CAMERAMAKER_Unknown || makei >= LIBRAW_CAMERAMAKER_TheLastOne) return 0;
for (int i = 0; i < int(sizeof CorpTable / sizeof *CorpTable); i++)
if ((unsigned)CorpTable[i].CorpId == makei)
{
strcpy(normalized_make, CorpTable[i].CorpName);
maker_index = makei;
return 1;
}
return 0;
} | 0 |
linux | a21b7f0cff1906a93a0130b74713b15a0b36481d | NOT_APPLICABLE | NOT_APPLICABLE | static ssize_t qrtr_tun_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct file *filp = iocb->ki_filp;
struct qrtr_tun *tun = filp->private_data;
struct sk_buff *skb;
int count;
while (!(skb = skb_dequeue(&tun->queue))) {
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
/* Wait until we get data or the endpoint goes away */
if (wait_event_interruptible(tun->readq,
!skb_queue_empty(&tun->queue)))
return -ERESTARTSYS;
}
count = min_t(size_t, iov_iter_count(to), skb->len);
if (copy_to_iter(skb->data, count, to) != count)
count = -EFAULT;
kfree_skb(skb);
return count;
} | 0 |
FFmpeg | 2b46ebdbff1d8dec7a3d8ea280a612b91a582869 | NOT_APPLICABLE | NOT_APPLICABLE | static int asf_read_stream_properties(AVFormatContext *s, const GUIDParseTable *g)
{
ASFContext *asf = s->priv_data;
AVIOContext *pb = s->pb;
uint64_t size;
uint32_t err_data_len, ts_data_len; // type specific data length
uint16_t flags;
ff_asf_guid stream_type;
enum AVMediaType type;
int i, ret;
uint8_t stream_index;
AVStream *st;
ASFStream *asf_st;
if (asf->nb_streams >= ASF_MAX_STREAMS)
return AVERROR_INVALIDDATA;
size = avio_rl64(pb);
ff_get_guid(pb, &stream_type);
if (!ff_guidcmp(&stream_type, &ff_asf_audio_stream))
type = AVMEDIA_TYPE_AUDIO;
else if (!ff_guidcmp(&stream_type, &ff_asf_video_stream))
type = AVMEDIA_TYPE_VIDEO;
else if (!ff_guidcmp(&stream_type, &ff_asf_jfif_media))
type = AVMEDIA_TYPE_VIDEO;
else if (!ff_guidcmp(&stream_type, &ff_asf_command_stream))
type = AVMEDIA_TYPE_DATA;
else if (!ff_guidcmp(&stream_type,
&ff_asf_ext_stream_embed_stream_header))
type = AVMEDIA_TYPE_UNKNOWN;
else
return AVERROR_INVALIDDATA;
ff_get_guid(pb, &stream_type); // error correction type
avio_skip(pb, 8); // skip the time offset
ts_data_len = avio_rl32(pb);
err_data_len = avio_rl32(pb);
flags = avio_rl16(pb); // bit 15 - Encrypted Content
stream_index = flags & ASF_STREAM_NUM;
for (i = 0; i < asf->nb_streams; i++)
if (stream_index == asf->asf_st[i]->stream_index) {
av_log(s, AV_LOG_WARNING,
"Duplicate stream found, this stream will be ignored.\n");
align_position(pb, asf->offset, size);
return 0;
}
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
avpriv_set_pts_info(st, 32, 1, 1000); // pts should be dword, in milliseconds
st->codecpar->codec_type = type;
asf->asf_st[asf->nb_streams] = av_mallocz(sizeof(*asf_st));
if (!asf->asf_st[asf->nb_streams])
return AVERROR(ENOMEM);
asf_st = asf->asf_st[asf->nb_streams];
asf->nb_streams++;
asf_st->stream_index = stream_index;
asf_st->index = st->index;
asf_st->indexed = 0;
st->id = flags & ASF_STREAM_NUM;
av_init_packet(&asf_st->pkt.avpkt);
asf_st->pkt.data_size = 0;
avio_skip(pb, 4); // skip reserved field
switch (type) {
case AVMEDIA_TYPE_AUDIO:
asf_st->type = AVMEDIA_TYPE_AUDIO;
if ((ret = ff_get_wav_header(s, pb, st->codecpar, ts_data_len, 0)) < 0)
return ret;
break;
case AVMEDIA_TYPE_VIDEO:
asf_st->type = AVMEDIA_TYPE_VIDEO;
if ((ret = parse_video_info(pb, st)) < 0)
return ret;
break;
default:
avio_skip(pb, ts_data_len);
break;
}
if (err_data_len) {
if (type == AVMEDIA_TYPE_AUDIO) {
uint8_t span = avio_r8(pb);
if (span > 1) {
asf_st->span = span;
asf_st->virtual_pkt_len = avio_rl16(pb);
asf_st->virtual_chunk_len = avio_rl16(pb);
if (!asf_st->virtual_chunk_len || !asf_st->virtual_pkt_len)
return AVERROR_INVALIDDATA;
avio_skip(pb, err_data_len - 5);
} else
avio_skip(pb, err_data_len - 1);
} else
avio_skip(pb, err_data_len);
}
align_position(pb, asf->offset, size);
return 0;
}
| 0 |
bind9 | 6ed167ad0a647dff20c8cb08c944a7967df2d415 | NOT_APPLICABLE | NOT_APPLICABLE | wrong_priority(dns_rdataset_t *rds, int pass, dns_rdatatype_t preferred_glue) {
int pass_needed;
/*
* If we are not rendering class IN, this ordering is bogus.
*/
if (rds->rdclass != dns_rdataclass_in)
return (false);
switch (rds->type) {
case dns_rdatatype_a:
case dns_rdatatype_aaaa:
if (preferred_glue == rds->type)
pass_needed = 4;
else
pass_needed = 3;
break;
case dns_rdatatype_rrsig:
case dns_rdatatype_dnskey:
pass_needed = 2;
break;
default:
pass_needed = 1;
}
if (pass_needed >= pass)
return (false);
return (true);
} | 0 |
xserver | 215f894965df5fb0bb45b107d84524e700d2073c | NOT_APPLICABLE | NOT_APPLICABLE | DeactivatePointerGrab(DeviceIntPtr mouse)
{
GrabPtr grab = mouse->deviceGrab.grab;
DeviceIntPtr dev;
Bool wasPassive = mouse->deviceGrab.fromPassiveGrab;
Bool wasImplicit = (mouse->deviceGrab.fromPassiveGrab &&
mouse->deviceGrab.implicitGrab);
XID grab_resource = grab->resource;
int i;
/* If an explicit grab was deactivated, we must remove it from the head of
* all the touches' listener lists. */
for (i = 0; !wasPassive && mouse->touch && i < mouse->touch->num_touches; i++) {
TouchPointInfoPtr ti = mouse->touch->touches + i;
if (ti->active && TouchResourceIsOwner(ti, grab_resource)) {
int mode = XIRejectTouch;
/* Rejecting will generate a TouchEnd, but we must not
emulate a ButtonRelease here. So pretend the listener
already has the end event */
if (grab->grabtype == CORE || grab->grabtype == XI ||
!xi2mask_isset(mouse->deviceGrab.grab->xi2mask, mouse, XI_TouchBegin)) {
mode = XIAcceptTouch;
/* NOTE: we set the state here, but
* ProcessTouchOwnershipEvent() will still call
* TouchEmitTouchEnd for this listener. The other half of
* this hack is in DeliverTouchEndEvent */
ti->listeners[0].state = LISTENER_HAS_END;
}
TouchListenerAcceptReject(mouse, ti, 0, mode);
}
}
TouchRemovePointerGrab(mouse);
mouse->valuator->motionHintWindow = NullWindow;
mouse->deviceGrab.grab = NullGrab;
mouse->deviceGrab.sync.state = NOT_GRABBED;
mouse->deviceGrab.fromPassiveGrab = FALSE;
for (dev = inputInfo.devices; dev; dev = dev->next) {
if (dev->deviceGrab.sync.other == grab)
dev->deviceGrab.sync.other = NullGrab;
}
DoEnterLeaveEvents(mouse, mouse->id, grab->window,
mouse->spriteInfo->sprite->win, NotifyUngrab);
if (grab->confineTo)
ConfineCursorToWindow(mouse, GetCurrentRootWindow(mouse), FALSE, FALSE);
PostNewCursor(mouse);
if (!wasImplicit && grab->grabtype == XI2)
ReattachToOldMaster(mouse);
ComputeFreezes();
FreeGrab(grab);
}
| 0 |
linux | 84ac7260236a49c79eede91617700174c2c19b0c | NOT_APPLICABLE | NOT_APPLICABLE | static unsigned int fanout_demux_bpf(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
struct bpf_prog *prog;
unsigned int ret = 0;
rcu_read_lock();
prog = rcu_dereference(f->bpf_prog);
if (prog)
ret = bpf_prog_run_clear_cb(prog, skb) % num;
rcu_read_unlock();
return ret;
}
| 0 |
Chrome | c6f0d22d508a551a40fc8bd7418941b77435aac3 | NOT_APPLICABLE | NOT_APPLICABLE | void OmniboxViewViews::OnBeforePossibleChange() {
GetState(&state_before_change_);
ime_composing_before_change_ = IsIMEComposing();
ClearAccessibilityLabel();
}
| 0 |
ghostscript | 83d4dae44c71816c084a635550acc1a51529b881 | NOT_APPLICABLE | NOT_APPLICABLE | static void fast_rgb_to_gray(fz_context *ctx, fz_pixmap *dst, fz_pixmap *src, fz_colorspace *prf, const fz_default_colorspaces *default_cs, const fz_color_params *color_params, int copy_spots)
{
unsigned char *s = src->samples;
unsigned char *d = dst->samples;
size_t w = src->w;
int h = src->h;
int sn = src->n;
int ss = src->s;
int sa = src->alpha;
int dn = dst->n;
int ds = dst->s;
int da = dst->alpha;
ptrdiff_t d_line_inc = dst->stride - w * dn;
ptrdiff_t s_line_inc = src->stride - w * sn;
/* If copying spots, they must match, and we can never drop alpha (but we can invent it) */
if ((copy_spots && ss != ds) || (!da && sa))
{
assert("This should never happen" == NULL);
fz_throw(ctx, FZ_ERROR_GENERIC, "Cannot convert between incompatible pixmaps");
}
if ((int)w < 0 || h < 0)
return;
if (d_line_inc == 0 && s_line_inc == 0)
{
w *= h;
h = 1;
}
if (ss == 0 && ds == 0)
{
/* Common, no spots case */
if (da)
{
if (sa)
{
while (h--)
{
size_t ww = w;
while (ww--)
{
d[0] = ((s[0]+1) * 77 + (s[1]+1) * 150 + (s[2]+1) * 28) >> 8;
d[1] = s[3];
s += 4;
d += 2;
}
d += d_line_inc;
s += s_line_inc;
}
}
else
{
while (h--)
{
size_t ww = w;
while (ww--)
{
d[0] = ((s[0]+1) * 77 + (s[1]+1) * 150 + (s[2]+1) * 28) >> 8;
d[1] = 255;
s += 3;
d += 2;
}
d += d_line_inc;
s += s_line_inc;
}
}
}
else
{
while (h--)
{
size_t ww = w;
while (ww--)
{
d[0] = ((s[0]+1) * 77 + (s[1]+1) * 150 + (s[2]+1) * 28) >> 8;
s += 3;
d++;
}
d += d_line_inc;
s += s_line_inc;
}
}
}
else if (copy_spots)
{
/* Slower, spots capable version */
int i;
while (h--)
{
size_t ww = w;
while (ww--)
{
d[0] = ((s[0]+1) * 77 + (s[1]+1) * 150 + (s[2]+1) * 28) >> 8;
s += 3;
d++;
for (i=ss; i > 0; i--)
*d++ = *s++;
if (da)
*d++ = sa ? *s++ : 255;
}
d += d_line_inc;
s += s_line_inc;
}
}
else
{
while (h--)
{
size_t ww = w;
while (ww--)
{
d[0] = ((s[0]+1) * 77 + (s[1]+1) * 150 + (s[2]+1) * 28) >> 8;
s += sn;
d += dn;
if (da)
d[-1] = sa ? s[-1] : 255;
}
d += d_line_inc;
s += s_line_inc;
}
}
}
| 0 |
Chrome | a6f7726de20450074a01493e4e85409ce3f2595a | NOT_APPLICABLE | NOT_APPLICABLE | void DocumentLoader::setArchive(PassRefPtr<Archive> archive)
{
m_archive = archive;
addAllArchiveResources(m_archive.get());
}
| 0 |
hermes | fe52854cdf6725c2eaa9e125995da76e6ceb27da | NOT_APPLICABLE | NOT_APPLICABLE | TEST_P(JSITest, InstanceOfTest) {
auto ctor = function("function Rick() { this.say = 'wubalubadubdub'; }");
auto newObj = function("function (ctor) { return new ctor(); }");
auto instance = newObj.call(rt, ctor).getObject(rt);
EXPECT_TRUE(instance.instanceOf(rt, ctor));
EXPECT_EQ(
instance.getProperty(rt, "say").getString(rt).utf8(rt), "wubalubadubdub");
EXPECT_FALSE(Object(rt).instanceOf(rt, ctor));
EXPECT_TRUE(ctor.callAsConstructor(rt, nullptr, 0)
.getObject(rt)
.instanceOf(rt, ctor));
} | 0 |
qemu | 5193be3be35f29a35bc465036cd64ad60d43385f | CVE-2013-4539 | CWE-119 | static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
s->nextfunction = qemu_get_byte(f);
s->precision = qemu_get_byte(f);
s->nextprecision = qemu_get_byte(f);
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
| 1 |
linux | a2f18db0c68fec96631c10cad9384c196e9008ac | NOT_APPLICABLE | NOT_APPLICABLE | static struct nft_table *nf_tables_table_lookup(const struct nft_af_info *afi,
const struct nlattr *nla)
{
struct nft_table *table;
if (nla == NULL)
return ERR_PTR(-EINVAL);
table = nft_table_lookup(afi, nla);
if (table != NULL)
return table;
return ERR_PTR(-ENOENT);
}
| 0 |
ghostscript | 79cccf641486a6595c43f1de1cd7ade696020a31 | NOT_APPLICABLE | NOT_APPLICABLE | gx_device_close_output_file(const gx_device * dev, const char *fname,
FILE *file)
{
gs_parsed_file_name_t parsed;
const char *fmt;
int code = gx_parse_output_file_name(&parsed, &fmt, fname, strlen(fname),
dev->memory);
if (code < 0)
return code;
if (parsed.iodev) {
if (!strcmp(parsed.iodev->dname, "%stdout%"))
return 0;
/* NOTE: fname is unsubstituted if the name has any %nnd formats. */
if (parsed.iodev != iodev_default(dev->memory))
return parsed.iodev->procs.fclose(parsed.iodev, file);
}
gp_close_printer(dev->memory, file, (parsed.fname ? parsed.fname : fname));
return 0;
}
| 0 |
CImg | ac8003393569aba51048c9d67e1491559877b1d1 | NOT_APPLICABLE | NOT_APPLICABLE | template<typename t>
CImgList<T> get_split(const CImg<t>& values, const char axis=0, const bool keep_values=true) const {
typedef _cimg_Tt Tt;
CImgList<T> res;
if (is_empty()) return res;
const ulongT vsiz = values.size();
const char _axis = cimg::lowercase(axis);
if (!vsiz) return CImgList<T>(*this);
if (vsiz==1) { // Split according to a single value
const T value = (T)*values;
switch (_axis) {
case 'x' : {
unsigned int i0 = 0, i = 0;
do {
while (i<_width && (*this)(i)==value) ++i;
if (i>i0) { if (keep_values) get_columns(i0,i - 1).move_to(res); i0 = i; }
while (i<_width && (*this)(i)!=value) ++i;
if (i>i0) { get_columns(i0,i - 1).move_to(res); i0 = i; }
} while (i<_width);
} break;
case 'y' : {
unsigned int i0 = 0, i = 0;
do {
while (i<_height && (*this)(0,i)==value) ++i;
if (i>i0) { if (keep_values) get_rows(i0,i - 1).move_to(res); i0 = i; }
while (i<_height && (*this)(0,i)!=value) ++i;
if (i>i0) { get_rows(i0,i - 1).move_to(res); i0 = i; }
} while (i<_height);
} break;
case 'z' : {
unsigned int i0 = 0, i = 0;
do {
while (i<_depth && (*this)(0,0,i)==value) ++i;
if (i>i0) { if (keep_values) get_slices(i0,i - 1).move_to(res); i0 = i; }
while (i<_depth && (*this)(0,0,i)!=value) ++i;
if (i>i0) { get_slices(i0,i - 1).move_to(res); i0 = i; }
} while (i<_depth);
} break;
case 'c' : {
unsigned int i0 = 0, i = 0;
do {
while (i<_spectrum && (*this)(0,0,0,i)==value) ++i;
if (i>i0) { if (keep_values) get_channels(i0,i - 1).move_to(res); i0 = i; }
while (i<_spectrum && (*this)(0,0,0,i)!=value) ++i;
if (i>i0) { get_channels(i0,i - 1).move_to(res); i0 = i; }
} while (i<_spectrum);
} break;
default : {
const ulongT siz = size();
ulongT i0 = 0, i = 0;
do {
while (i<siz && (*this)[i]==value) ++i;
if (i>i0) { if (keep_values) CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; }
while (i<siz && (*this)[i]!=value) ++i;
if (i>i0) { CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; }
} while (i<siz);
}
}
} else { // Split according to multiple values
ulongT j = 0;
switch (_axis) {
case 'x' : {
unsigned int i0 = 0, i1 = 0, i = 0;
do {
if ((Tt)(*this)(i)==(Tt)*values) {
i1 = i; j = 0;
while (i<_width && (Tt)(*this)(i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; }
i-=j;
if (i>i1) {
if (i1>i0) get_columns(i0,i1 - 1).move_to(res);
if (keep_values) get_columns(i1,i - 1).move_to(res);
i0 = i;
} else ++i;
} else ++i;
} while (i<_width);
if (i0<_width) get_columns(i0,width() - 1).move_to(res);
} break;
case 'y' : {
unsigned int i0 = 0, i1 = 0, i = 0;
do {
if ((Tt)(*this)(0,i)==(Tt)*values) {
i1 = i; j = 0;
while (i<_height && (Tt)(*this)(0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; }
i-=j;
if (i>i1) {
if (i1>i0) get_rows(i0,i1 - 1).move_to(res);
if (keep_values) get_rows(i1,i - 1).move_to(res);
i0 = i;
} else ++i;
} else ++i;
} while (i<_height);
if (i0<_height) get_rows(i0,height() - 1).move_to(res);
} break;
case 'z' : {
unsigned int i0 = 0, i1 = 0, i = 0;
do {
if ((Tt)(*this)(0,0,i)==(Tt)*values) {
i1 = i; j = 0;
while (i<_depth && (Tt)(*this)(0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; }
i-=j;
if (i>i1) {
if (i1>i0) get_slices(i0,i1 - 1).move_to(res);
if (keep_values) get_slices(i1,i - 1).move_to(res);
i0 = i;
} else ++i;
} else ++i;
} while (i<_depth);
if (i0<_depth) get_slices(i0,depth() - 1).move_to(res);
} break;
case 'c' : {
unsigned int i0 = 0, i1 = 0, i = 0;
do {
if ((Tt)(*this)(0,0,0,i)==(Tt)*values) {
i1 = i; j = 0;
while (i<_spectrum && (Tt)(*this)(0,0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; }
i-=j;
if (i>i1) {
if (i1>i0) get_channels(i0,i1 - 1).move_to(res);
if (keep_values) get_channels(i1,i - 1).move_to(res);
i0 = i;
} else ++i;
} else ++i;
} while (i<_spectrum);
if (i0<_spectrum) get_channels(i0,spectrum() - 1).move_to(res);
} break;
default : {
ulongT i0 = 0, i1 = 0, i = 0;
const ulongT siz = size();
do {
if ((Tt)(*this)[i]==(Tt)*values) {
i1 = i; j = 0;
while (i<siz && (Tt)(*this)[i]==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; }
i-=j;
if (i>i1) {
if (i1>i0) CImg<T>(_data + i0,1,(unsigned int)(i1 - i0)).move_to(res);
if (keep_values) CImg<T>(_data + i1,1,(unsigned int)(i - i1)).move_to(res);
i0 = i;
} else ++i;
} else ++i;
} while (i<siz);
if (i0<siz) CImg<T>(_data + i0,1,(unsigned int)(siz - i0)).move_to(res);
} break;
}
}
return res; | 0 |
Chrome | 5f8671e7667b8b133bd3664100012a3906e92d65 | NOT_APPLICABLE | NOT_APPLICABLE | void GenerateTapDownGesture(RenderWidgetHost* rwh) {
blink::WebGestureEvent gesture_tap_down(
blink::WebGestureEvent::kGestureTapDown,
blink::WebInputEvent::kNoModifiers,
blink::WebInputEvent::GetStaticTimeStampForTests(),
blink::kWebGestureDeviceTouchscreen);
gesture_tap_down.is_source_touch_event_set_non_blocking = true;
rwh->ForwardGestureEvent(gesture_tap_down);
}
| 0 |
iperf | 91f2fa59e8ed80dfbf400add0164ee0e508e412a | CVE-2016-4303 | CWE-119 | static char *print_value( cJSON *item, int depth, int fmt )
{
char *out = 0;
if ( ! item )
return 0;
switch ( ( item->type ) & 255 ) {
case cJSON_NULL: out = cJSON_strdup( "null" ); break;
case cJSON_False: out = cJSON_strdup( "false" ); break;
case cJSON_True: out = cJSON_strdup( "true" ); break;
case cJSON_Number: out = print_number( item ); break;
case cJSON_String: out = print_string( item ); break;
case cJSON_Array: out = print_array( item, depth, fmt ); break;
case cJSON_Object: out = print_object( item, depth, fmt ); break;
}
return out;
}
| 1 |
ImageMagick | 4d6accd355119d54429a86a1859b8329f0130f30 | NOT_APPLICABLE | NOT_APPLICABLE | static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
s[2];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
if (image == (Image *) NULL)
return(MagickFalse);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" IM version = %s", im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Libpng version = %s", libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" running with %s", libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Zlib version = %s", zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" running with %s", zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%g", image->gamma);
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*s;
register Quantum
*q,
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,q) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image, q, opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (Magick_png_color_equal(image,q,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image, q, opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,q) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image, q, transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,q);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,q);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,q);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (Magick_png_color_equal(image,q,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,q,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,q,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (Magick_png_color_equal(image,q,semitransparent+i)
&& GetPixelAlpha(image,q) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image, q, semitransparent+i);
}
}
}
q+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||
GetPixelRed(image,s) != GetPixelBlue(image,s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != 0 &&
GetPixelRed(image,s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
IMimage->filename);
}
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,r);
SetPixelAlpha(image,TransparentAlpha,r);
}
else
SetPixelAlpha(image,OpaqueAlpha,r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR04PixelRGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR03RGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR02PixelBlue(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&
GetPixelAlpha(image,r) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),r);
}
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
png_write_info(ping,ping_info);
/* write orNT if image->orientation is defined */
if (image->orientation != UndefinedOrientation)
{
unsigned char
chunk[6];
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_orNT);
LogPNGChunk(logging,mng_orNT,1L);
/* PNG uses Exif orientation values */
chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation);
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const Quantum
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write eXIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' &&
*(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0')
{
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
data += 6;
}
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data,
(uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
} | 0 |
php | 6e25966544fb1d2f3d7596e060ce9c9269bbdcf8 | NOT_APPLICABLE | NOT_APPLICABLE | PHP_FUNCTION(snmp2_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c);
}
| 0 |
haproxy | 17514045e5d934dede62116216c1b016fe23dd06 | NOT_APPLICABLE | NOT_APPLICABLE | void free_http_res_rules(struct list *r)
{
struct act_rule *tr, *pr;
list_for_each_entry_safe(pr, tr, r, list) {
LIST_DEL(&pr->list);
regex_free(&pr->arg.hdr_add.re);
free(pr);
}
}
| 0 |
slurm | 92362a92fffe60187df61f99ab11c249d44120ee | NOT_APPLICABLE | NOT_APPLICABLE | _rpc_batch_job(slurm_msg_t *msg, bool new_msg)
{
batch_job_launch_msg_t *req = (batch_job_launch_msg_t *)msg->data;
bool first_job_run;
int rc = SLURM_SUCCESS;
bool replied = false, revoked;
slurm_addr_t *cli = &msg->orig_addr;
if (new_msg) {
uid_t req_uid = g_slurm_auth_get_uid(msg->auth_cred,
conf->auth_info);
if (!_slurm_authorized_user(req_uid)) {
error("Security violation, batch launch RPC from uid %d",
req_uid);
rc = ESLURM_USER_ID_MISSING; /* or bad in this case */
goto done;
}
}
if (_launch_job_test(req->job_id)) {
error("Job %u already running, do not launch second copy",
req->job_id);
rc = ESLURM_DUPLICATE_JOB_ID; /* job already running */
_launch_job_fail(req->job_id, rc);
goto done;
}
slurm_cred_handle_reissue(conf->vctx, req->cred);
if (slurm_cred_revoked(conf->vctx, req->cred)) {
error("Job %u already killed, do not launch batch job",
req->job_id);
rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */
goto done;
}
task_g_slurmd_batch_request(req->job_id, req); /* determine task affinity */
slurm_mutex_lock(&prolog_mutex);
first_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id);
/* BlueGene prolog waits for partition boot and is very slow.
* On any system we might need to load environment variables
* for Moab (see --get-user-env), which could also be slow.
* Just reply now and send a separate kill job request if the
* prolog or launch fail. */
replied = true;
if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {
/* The slurmctld is no longer waiting for a reply.
* This typically indicates that the slurmd was
* blocked from memory and/or CPUs and the slurmctld
* has requeued the batch job request. */
error("Could not confirm batch launch for job %u, "
"aborting request", req->job_id);
rc = SLURM_COMMUNICATIONS_SEND_ERROR;
slurm_mutex_unlock(&prolog_mutex);
goto done;
}
/*
* Insert jobid into credential context to denote that
* we've now "seen" an instance of the job
*/
if (first_job_run) {
job_env_t job_env;
slurm_cred_insert_jobid(conf->vctx, req->job_id);
_add_job_running_prolog(req->job_id);
slurm_mutex_unlock(&prolog_mutex);
memset(&job_env, 0, sizeof(job_env_t));
job_env.jobid = req->job_id;
job_env.step_id = req->step_id;
job_env.node_list = req->nodes;
job_env.partition = req->partition;
job_env.spank_job_env = req->spank_job_env;
job_env.spank_job_env_size = req->spank_job_env_size;
job_env.uid = req->uid;
job_env.user_name = req->user_name;
/*
* Run job prolog on this node
*/
#if defined(HAVE_BG)
select_g_select_jobinfo_get(req->select_jobinfo,
SELECT_JOBDATA_BLOCK_ID,
&job_env.resv_id);
#elif defined(HAVE_ALPS_CRAY)
job_env.resv_id = select_g_select_jobinfo_xstrdup(
req->select_jobinfo, SELECT_PRINT_RESV_ID);
#endif
if (container_g_create(req->job_id))
error("container_g_create(%u): %m", req->job_id);
rc = _run_prolog(&job_env, req->cred);
xfree(job_env.resv_id);
if (rc) {
int term_sig, exit_status;
if (WIFSIGNALED(rc)) {
exit_status = 0;
term_sig = WTERMSIG(rc);
} else {
exit_status = WEXITSTATUS(rc);
term_sig = 0;
}
error("[job %u] prolog failed status=%d:%d",
req->job_id, exit_status, term_sig);
_prolog_error(req, rc);
rc = ESLURMD_PROLOG_FAILED;
goto done;
}
} else {
slurm_mutex_unlock(&prolog_mutex);
_wait_for_job_running_prolog(req->job_id);
}
if (_get_user_env(req) < 0) {
bool requeue = _requeue_setup_env_fail();
if (requeue) {
rc = ESLURMD_SETUP_ENVIRONMENT_ERROR;
goto done;
}
}
_set_batch_job_limits(msg);
/* Since job could have been killed while the prolog was
* running (especially on BlueGene, which can take minutes
* for partition booting). Test if the credential has since
* been revoked and exit as needed. */
if (slurm_cred_revoked(conf->vctx, req->cred)) {
info("Job %u already killed, do not launch batch job",
req->job_id);
rc = ESLURMD_CREDENTIAL_REVOKED; /* job already ran */
goto done;
}
slurm_mutex_lock(&launch_mutex);
if (req->step_id == SLURM_BATCH_SCRIPT)
info("Launching batch job %u for UID %d",
req->job_id, req->uid);
else
info("Launching batch job %u.%u for UID %d",
req->job_id, req->step_id, req->uid);
debug3("_rpc_batch_job: call to _forkexec_slurmstepd");
rc = _forkexec_slurmstepd(LAUNCH_BATCH_JOB, (void *)req, cli, NULL,
(hostset_t)NULL, SLURM_PROTOCOL_VERSION);
debug3("_rpc_batch_job: return from _forkexec_slurmstepd: %d", rc);
slurm_mutex_unlock(&launch_mutex);
_launch_complete_add(req->job_id);
/* On a busy system, slurmstepd may take a while to respond,
* if the job was cancelled in the interim, run through the
* abort logic below. */
revoked = slurm_cred_revoked(conf->vctx, req->cred);
if (revoked)
_launch_complete_rm(req->job_id);
if (revoked && _is_batch_job_finished(req->job_id)) {
/* If configured with select/serial and the batch job already
* completed, consider the job sucessfully launched and do
* not repeat termination logic below, which in the worst case
* just slows things down with another message. */
revoked = false;
}
if (revoked) {
info("Job %u killed while launch was in progress",
req->job_id);
sleep(1); /* give slurmstepd time to create
* the communication socket */
_terminate_all_steps(req->job_id, true);
rc = ESLURMD_CREDENTIAL_REVOKED;
goto done;
}
done:
if (!replied) {
if (new_msg && (slurm_send_rc_msg(msg, rc) < 1)) {
/* The slurmctld is no longer waiting for a reply.
* This typically indicates that the slurmd was
* blocked from memory and/or CPUs and the slurmctld
* has requeued the batch job request. */
error("Could not confirm batch launch for job %u, "
"aborting request", req->job_id);
rc = SLURM_COMMUNICATIONS_SEND_ERROR;
} else {
/* No need to initiate separate reply below */
rc = SLURM_SUCCESS;
}
}
if (rc != SLURM_SUCCESS) {
/* prolog or job launch failure,
* tell slurmctld that the job failed */
if (req->step_id == SLURM_BATCH_SCRIPT)
_launch_job_fail(req->job_id, rc);
else
_abort_step(req->job_id, req->step_id);
}
/*
* If job prolog failed or we could not reply,
* initiate message to slurmctld with current state
*/
if ((rc == ESLURMD_PROLOG_FAILED)
|| (rc == SLURM_COMMUNICATIONS_SEND_ERROR)
|| (rc == ESLURMD_SETUP_ENVIRONMENT_ERROR)) {
send_registration_msg(rc, false);
}
}
| 0 |
Chrome | 0a57375ad73780e61e1770a9d88b0529b0dbd33b | NOT_APPLICABLE | NOT_APPLICABLE | void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
const std::vector<GURL>& links,
const std::vector<base::FilePath>& local_paths,
const base::FilePath& local_directory_name) {
WebVector<WebURL> weburl_links(links);
WebVector<WebString> webstring_paths(local_paths.size());
for (size_t i = 0; i < local_paths.size(); i++)
webstring_paths[i] = webkit_base::FilePathToWebString(local_paths[i]);
WebPageSerializer::serialize(webview()->mainFrame(), true, this, weburl_links,
webstring_paths,
webkit_base::FilePathToWebString(
local_directory_name));
}
| 0 |
linux | 499350a5a6e7512d9ed369ed63a4244b6536f4f8 | NOT_APPLICABLE | NOT_APPLICABLE | int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
{
struct scatterlist sg;
sg_init_one(&sg, key->key, key->keylen);
ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen);
return crypto_ahash_update(hp->md5_req);
}
| 0 |
Android | 4974dcbd0289a2530df2ee2a25b5f92775df80da | NOT_APPLICABLE | NOT_APPLICABLE | static vpx_codec_err_t ctrl_set_byte_alignment(vpx_codec_alg_priv_t *ctx,
va_list args) {
const int legacy_byte_alignment = 0;
const int min_byte_alignment = 32;
const int max_byte_alignment = 1024;
const int byte_alignment = va_arg(args, int);
if (byte_alignment != legacy_byte_alignment &&
(byte_alignment < min_byte_alignment ||
byte_alignment > max_byte_alignment ||
(byte_alignment & (byte_alignment - 1)) != 0))
return VPX_CODEC_INVALID_PARAM;
ctx->byte_alignment = byte_alignment;
if (ctx->frame_workers) {
VPxWorker *const worker = ctx->frame_workers;
FrameWorkerData *const frame_worker_data =
(FrameWorkerData *)worker->data1;
frame_worker_data->pbi->common.byte_alignment = byte_alignment;
}
return VPX_CODEC_OK;
}
| 0 |
ImageMagick | fe3066122ef72c82415811d25e9e3fad622c0a99 | NOT_APPLICABLE | NOT_APPLICABLE | ModuleExport size_t RegisterVIFFImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("VIFF","VIFF","Khoros Visualization image");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->magick=(IsImageFormatHandler *) IsVIFF;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("VIFF","XV","Khoros Visualization image");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 0 |
Chrome | b38064dbb21aaf32151073dcb7d594b240c68f73 | NOT_APPLICABLE | NOT_APPLICABLE | void FileSystemOperationRunner::DidWrite(const OperationID id,
const WriteCallback& callback,
base::File::Error rv,
int64_t bytes,
bool complete) {
if (is_beginning_operation_) {
finished_operations_.insert(id);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&FileSystemOperationRunner::DidWrite, weak_ptr_, id,
callback, rv, bytes, complete));
return;
}
callback.Run(rv, bytes, complete);
if (rv != base::File::FILE_OK || complete)
FinishOperation(id);
}
| 0 |
Chrome | fcd3a7a671ecf2d5f46ea34787d27507a914d2f5 | NOT_APPLICABLE | NOT_APPLICABLE | void ProfileSyncService::DeactivateDataType(syncable::ModelType type) {
if (!backend_.get())
return;
backend_->DeactivateDataType(type);
}
| 0 |
collectd | b589096f907052b3a4da2b9ccc9b0e2e888dfc18 | NOT_APPLICABLE | NOT_APPLICABLE | static void networt_send_buffer_signed (sockent_t *se, /* {{{ */
const char *in_buffer, size_t in_buffer_size)
{
part_signature_sha256_t ps;
char buffer[BUFF_SIG_SIZE + in_buffer_size];
size_t buffer_offset;
size_t username_len;
gcry_md_hd_t hd;
gcry_error_t err;
unsigned char *hash;
hd = NULL;
err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
if (err != 0)
{
ERROR ("network plugin: Creating HMAC object failed: %s",
gcry_strerror (err));
return;
}
err = gcry_md_setkey (hd, se->data.client.password,
strlen (se->data.client.password));
if (err != 0)
{
ERROR ("network plugin: gcry_md_setkey failed: %s",
gcry_strerror (err));
gcry_md_close (hd);
return;
}
username_len = strlen (se->data.client.username);
if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
{
ERROR ("network plugin: Username too long: %s",
se->data.client.username);
return;
}
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
se->data.client.username, username_len);
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
in_buffer, in_buffer_size);
/* Initialize the `ps' structure. */
memset (&ps, 0, sizeof (ps));
ps.head.type = htons (TYPE_SIGN_SHA256);
ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
/* Calculate the hash value. */
gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
username_len + in_buffer_size);
hash = gcry_md_read (hd, GCRY_MD_SHA256);
if (hash == NULL)
{
ERROR ("network plugin: gcry_md_read failed.");
gcry_md_close (hd);
return;
}
memcpy (ps.hash, hash, sizeof (ps.hash));
/* Add the header */
buffer_offset = 0;
BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
BUFFER_ADD (ps.hash, sizeof (ps.hash));
assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
gcry_md_close (hd);
hd = NULL;
buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
networt_send_buffer_plain (se, buffer, buffer_offset);
} /* }}} void networt_send_buffer_signed */
| 0 |
Chrome | e89cfcb9090e8c98129ae9160c513f504db74599 | NOT_APPLICABLE | NOT_APPLICABLE | SwichToMetroUIHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(default_browser_worker_(
new ShellIntegration::DefaultBrowserWorker(this))),
first_check_(true) {
default_browser_worker_->StartCheckIsDefault();
}
| 0 |
Chrome | f03ea5a5c2ff26e239dfd23e263b15da2d9cee93 | NOT_APPLICABLE | NOT_APPLICABLE | void RenderFrameImpl::OnUpdateOpener(int opener_routing_id) {
WebFrame* opener = ResolveOpener(opener_routing_id);
frame_->SetOpener(opener);
}
| 0 |
httpd | 78eb3b9235515652ed141353d98c239237030410 | NOT_APPLICABLE | NOT_APPLICABLE | void ap_lua_push_request(lua_State *L, request_rec *r)
{
lua_boxpointer(L, r);
luaL_getmetatable(L, "Apache2.Request");
lua_setmetatable(L, -2);
} | 0 |
mono | 65292a69c837b8a5f7a392d34db63de592153358 | NOT_APPLICABLE | NOT_APPLICABLE | stack_slot_get_type (ILStackDesc *value)
{
return value->stype & RAW_TYPE_MASK;
} | 0 |
Chrome | e5787005a9004d7be289cc649c6ae4f3051996cd | NOT_APPLICABLE | NOT_APPLICABLE | void RenderWidgetHostImpl::StartHangMonitorTimeout(base::TimeDelta delay) {
if (hang_monitor_timeout_)
hang_monitor_timeout_->Start(delay);
}
| 0 |
linux | 606142af57dad981b78707234cfbd15f9f7b7125 | NOT_APPLICABLE | NOT_APPLICABLE | static int s6x0_read_mac_address(struct dvb_usb_device *d, u8 mac[6])
{
int i, ret;
u8 ibuf[] = { 0 }, obuf[] = { 0 };
u8 eeprom[256], eepromline[16];
struct i2c_msg msg[] = {
{
.addr = 0xa0 >> 1,
.flags = 0,
.buf = obuf,
.len = 1,
}, {
.addr = 0xa0 >> 1,
.flags = I2C_M_RD,
.buf = ibuf,
.len = 1,
}
};
for (i = 0; i < 256; i++) {
obuf[0] = i;
ret = s6x0_i2c_transfer(&d->i2c_adap, msg, 2);
if (ret != 2) {
err("read eeprom failed.");
return -1;
} else {
eepromline[i % 16] = ibuf[0];
eeprom[i] = ibuf[0];
}
if ((i % 16) == 15) {
deb_xfer("%02x: ", i - 15);
debug_dump(eepromline, 16, deb_xfer);
}
}
memcpy(mac, eeprom + 16, 6);
return 0;
};
| 0 |
linux | b2853fd6c2d0f383dbdf7427e263eb576a633867 | NOT_APPLICABLE | NOT_APPLICABLE | static int cma_alloc_any_port(struct idr *ps, struct rdma_id_private *id_priv)
{
static unsigned int last_used_port;
int low, high, remaining;
unsigned int rover;
inet_get_local_port_range(&init_net, &low, &high);
remaining = (high - low) + 1;
rover = prandom_u32() % remaining + low;
retry:
if (last_used_port != rover &&
!idr_find(ps, (unsigned short) rover)) {
int ret = cma_alloc_port(ps, id_priv, rover);
/*
* Remember previously used port number in order to avoid
* re-using same port immediately after it is closed.
*/
if (!ret)
last_used_port = rover;
if (ret != -EADDRNOTAVAIL)
return ret;
}
if (--remaining) {
rover++;
if ((rover < low) || (rover > high))
rover = low;
goto retry;
}
return -EADDRNOTAVAIL;
}
| 0 |
Android | 3b1c9f692c4d4b7a683c2b358fc89e831a641b88 | NOT_APPLICABLE | NOT_APPLICABLE | status_t MediaHTTP::getSize(off64_t *size) {
if (mInitCheck != OK) {
return mInitCheck;
}
if (!mCachedSizeValid) {
mCachedSize = mHTTPConnection->getSize();
mCachedSizeValid = true;
}
*size = mCachedSize;
return *size < 0 ? *size : static_cast<status_t>(OK);
}
| 0 |
Chrome | 0bd1a6ddb5fb23dfea3e72d60e5e8df4cf5826bc | NOT_APPLICABLE | NOT_APPLICABLE | void XScopedCursor::reset(::Cursor cursor) {
if (cursor_)
XFreeCursor(display_, cursor_);
cursor_ = cursor;
}
| 0 |
openssl | 1421e0c584ae9120ca1b88098f13d6d2e90b83a3 | NOT_APPLICABLE | NOT_APPLICABLE | int ssl3_send_server_key_exchange(SSL *s)
{
#ifndef OPENSSL_NO_RSA
unsigned char *q;
int j,num;
RSA *rsa;
unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
unsigned int u;
#endif
#ifndef OPENSSL_NO_DH
DH *dh=NULL,*dhp;
#endif
#ifndef OPENSSL_NO_ECDH
EC_KEY *ecdh=NULL, *ecdhp;
unsigned char *encodedPoint = NULL;
int encodedlen = 0;
int curve_id = 0;
BN_CTX *bn_ctx = NULL;
#endif
EVP_PKEY *pkey;
const EVP_MD *md = NULL;
unsigned char *p,*d;
int al,i;
unsigned long type;
int n;
CERT *cert;
BIGNUM *r[4];
int nr[4],kn;
BUF_MEM *buf;
EVP_MD_CTX md_ctx;
EVP_MD_CTX_init(&md_ctx);
if (s->state == SSL3_ST_SW_KEY_EXCH_A)
{
type=s->s3->tmp.new_cipher->algorithm_mkey;
cert=s->cert;
buf=s->init_buf;
r[0]=r[1]=r[2]=r[3]=NULL;
n=0;
#ifndef OPENSSL_NO_RSA
if (type & SSL_kRSA)
{
rsa=cert->rsa_tmp;
if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
{
rsa=s->cert->rsa_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
if(rsa == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
goto f_err;
}
RSA_up_ref(rsa);
cert->rsa_tmp=rsa;
}
if (rsa == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
goto f_err;
}
r[0]=rsa->n;
r[1]=rsa->e;
s->s3->tmp.use_rsa_tmp=1;
}
else
#endif
#ifndef OPENSSL_NO_DH
if (type & SSL_kDHE)
{
if (s->cert->dh_tmp_auto)
{
dhp = ssl_get_auto_dh(s);
if (dhp == NULL)
{
al=SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto f_err;
}
}
else
dhp=cert->dh_tmp;
if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
dhp=s->cert->dh_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
if (dhp == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
goto f_err;
}
if (!ssl_security(s, SSL_SECOP_TMP_DH,
DH_security_bits(dhp), 0, dhp))
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL);
goto f_err;
}
if (s->s3->tmp.dh != NULL)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
if (s->cert->dh_tmp_auto)
dh = dhp;
else if ((dh=DHparams_dup(dhp)) == NULL)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
goto err;
}
s->s3->tmp.dh=dh;
if ((dhp->pub_key == NULL ||
dhp->priv_key == NULL ||
(s->options & SSL_OP_SINGLE_DH_USE)))
{
if(!DH_generate_key(dh))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
ERR_R_DH_LIB);
goto err;
}
}
else
{
dh->pub_key=BN_dup(dhp->pub_key);
dh->priv_key=BN_dup(dhp->priv_key);
if ((dh->pub_key == NULL) ||
(dh->priv_key == NULL))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
goto err;
}
}
r[0]=dh->p;
r[1]=dh->g;
r[2]=dh->pub_key;
}
else
#endif
#ifndef OPENSSL_NO_ECDH
if (type & SSL_kECDHE)
{
const EC_GROUP *group;
ecdhp=cert->ecdh_tmp;
if (s->cert->ecdh_tmp_auto)
{
/* Get NID of appropriate shared curve */
int nid = tls1_shared_curve(s, -2);
if (nid != NID_undef)
ecdhp = EC_KEY_new_by_curve_name(nid);
}
else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
{
ecdhp=s->cert->ecdh_tmp_cb(s,
SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
}
if (ecdhp == NULL)
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
goto f_err;
}
if (s->s3->tmp.ecdh != NULL)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Duplicate the ECDH structure. */
if (ecdhp == NULL)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
goto err;
}
if (s->cert->ecdh_tmp_auto)
ecdh = ecdhp;
else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
goto err;
}
s->s3->tmp.ecdh=ecdh;
if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
(EC_KEY_get0_private_key(ecdh) == NULL) ||
(s->options & SSL_OP_SINGLE_ECDH_USE))
{
if(!EC_KEY_generate_key(ecdh))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
goto err;
}
}
if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
(EC_KEY_get0_public_key(ecdh) == NULL) ||
(EC_KEY_get0_private_key(ecdh) == NULL))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
goto err;
}
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
(EC_GROUP_get_degree(group) > 163))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
goto err;
}
/* XXX: For now, we only support ephemeral ECDH
* keys over named (not generic) curves. For
* supported named curves, curve_id is non-zero.
*/
if ((curve_id =
tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
== 0)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
goto err;
}
/* Encode the public key.
* First check the size of encoding and
* allocate memory accordingly.
*/
encodedlen = EC_POINT_point2oct(group,
EC_KEY_get0_public_key(ecdh),
POINT_CONVERSION_UNCOMPRESSED,
NULL, 0, NULL);
encodedPoint = (unsigned char *)
OPENSSL_malloc(encodedlen*sizeof(unsigned char));
bn_ctx = BN_CTX_new();
if ((encodedPoint == NULL) || (bn_ctx == NULL))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
goto err;
}
encodedlen = EC_POINT_point2oct(group,
EC_KEY_get0_public_key(ecdh),
POINT_CONVERSION_UNCOMPRESSED,
encodedPoint, encodedlen, bn_ctx);
if (encodedlen == 0)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
goto err;
}
BN_CTX_free(bn_ctx); bn_ctx=NULL;
/* XXX: For now, we only support named (not
* generic) curves in ECDH ephemeral key exchanges.
* In this situation, we need four additional bytes
* to encode the entire ServerECDHParams
* structure.
*/
n = 4 + encodedlen;
/* We'll generate the serverKeyExchange message
* explicitly so we can set these to NULLs
*/
r[0]=NULL;
r[1]=NULL;
r[2]=NULL;
r[3]=NULL;
}
else
#endif /* !OPENSSL_NO_ECDH */
#ifndef OPENSSL_NO_PSK
if (type & SSL_kPSK)
{
/* reserve size for record length and PSK identity hint*/
n+=2+strlen(s->ctx->psk_identity_hint);
}
else
#endif /* !OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (type & SSL_kSRP)
{
if ((s->srp_ctx.N == NULL) ||
(s->srp_ctx.g == NULL) ||
(s->srp_ctx.s == NULL) ||
(s->srp_ctx.B == NULL))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
goto err;
}
r[0]=s->srp_ctx.N;
r[1]=s->srp_ctx.g;
r[2]=s->srp_ctx.s;
r[3]=s->srp_ctx.B;
}
else
#endif
{
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
goto f_err;
}
for (i=0; i < 4 && r[i] != NULL; i++)
{
nr[i]=BN_num_bytes(r[i]);
#ifndef OPENSSL_NO_SRP
if ((i == 2) && (type & SSL_kSRP))
n+=1+nr[i];
else
#endif
n+=2+nr[i];
}
if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
== NULL)
{
al=SSL_AD_DECODE_ERROR;
goto f_err;
}
kn=EVP_PKEY_size(pkey);
}
else
{
pkey=NULL;
kn=0;
}
if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
goto err;
}
d = p = ssl_handshake_start(s);
for (i=0; i < 4 && r[i] != NULL; i++)
{
#ifndef OPENSSL_NO_SRP
if ((i == 2) && (type & SSL_kSRP))
{
*p = nr[i];
p++;
}
else
#endif
s2n(nr[i],p);
BN_bn2bin(r[i],p);
p+=nr[i];
}
#ifndef OPENSSL_NO_ECDH
if (type & SSL_kECDHE)
{
/* XXX: For now, we only support named (not generic) curves.
* In this situation, the serverKeyExchange message has:
* [1 byte CurveType], [2 byte CurveName]
* [1 byte length of encoded point], followed by
* the actual encoded point itself
*/
*p = NAMED_CURVE_TYPE;
p += 1;
*p = 0;
p += 1;
*p = curve_id;
p += 1;
*p = encodedlen;
p += 1;
memcpy((unsigned char*)p,
(unsigned char *)encodedPoint,
encodedlen);
OPENSSL_free(encodedPoint);
encodedPoint = NULL;
p += encodedlen;
}
#endif
#ifndef OPENSSL_NO_PSK
if (type & SSL_kPSK)
{
/* copy PSK identity hint */
s2n(strlen(s->ctx->psk_identity_hint), p);
strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
p+=strlen(s->ctx->psk_identity_hint);
}
#endif
/* not anonymous */
if (pkey != NULL)
{
/* n is the length of the params, they start at &(d[4])
* and p points to the space at the end. */
#ifndef OPENSSL_NO_RSA
if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
{
q=md_buf;
j=0;
for (num=2; num > 0; num--)
{
EVP_MD_CTX_set_flags(&md_ctx,
EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
EVP_DigestInit_ex(&md_ctx,(num == 2)
?s->ctx->md5:s->ctx->sha1, NULL);
EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_DigestUpdate(&md_ctx,d,n);
EVP_DigestFinal_ex(&md_ctx,q,
(unsigned int *)&i);
q+=i;
j+=i;
}
if (RSA_sign(NID_md5_sha1, md_buf, j,
&(p[2]), &u, pkey->pkey.rsa) <= 0)
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
goto err;
}
s2n(u,p);
n+=u+2;
}
else
#endif
if (md)
{
/* send signature algorithm */
if (SSL_USE_SIGALGS(s))
{
if (!tls12_get_sigandhash(p, pkey, md))
{
/* Should never happen */
al=SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
goto f_err;
}
p+=2;
}
#ifdef SSL_DEBUG
fprintf(stderr, "Using hash %s\n",
EVP_MD_name(md));
#endif
EVP_SignInit_ex(&md_ctx, md, NULL);
EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
EVP_SignUpdate(&md_ctx,d,n);
if (!EVP_SignFinal(&md_ctx,&(p[2]),
(unsigned int *)&i,pkey))
{
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
goto err;
}
s2n(i,p);
n+=i+2;
if (SSL_USE_SIGALGS(s))
n+= 2;
}
else
{
/* Is this error check actually needed? */
al=SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
goto f_err;
}
}
ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
}
s->state = SSL3_ST_SW_KEY_EXCH_B;
EVP_MD_CTX_cleanup(&md_ctx);
return ssl_do_write(s);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
#ifndef OPENSSL_NO_ECDH
if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
BN_CTX_free(bn_ctx);
#endif
EVP_MD_CTX_cleanup(&md_ctx);
return(-1);
}
| 0 |
sqlite | 8654186b0236d556aa85528c2573ee0b6ab71be3 | NOT_APPLICABLE | NOT_APPLICABLE | int sqlite3VdbeList(
Vdbe *p /* The VDBE */
){
int nRow; /* Stop when row count reaches this */
int nSub = 0; /* Number of sub-vdbes seen so far */
SubProgram **apSub = 0; /* Array of sub-vdbes */
Mem *pSub = 0; /* Memory cell hold array of subprogs */
sqlite3 *db = p->db; /* The database connection */
int i; /* Loop counter */
int rc = SQLITE_OK; /* Return code */
Mem *pMem = &p->aMem[1]; /* First Mem of result set */
int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
Op *pOp = 0;
assert( p->explain );
assert( p->magic==VDBE_MAGIC_RUN );
assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
/* Even though this opcode does not use dynamic strings for
** the result, result columns may become dynamic if the user calls
** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
*/
releaseMemArray(pMem, 8);
p->pResultSet = 0;
if( p->rc==SQLITE_NOMEM ){
/* This happens if a malloc() inside a call to sqlite3_column_text() or
** sqlite3_column_text16() failed. */
sqlite3OomFault(db);
return SQLITE_ERROR;
}
/* When the number of output rows reaches nRow, that means the
** listing has finished and sqlite3_step() should return SQLITE_DONE.
** nRow is the sum of the number of rows in the main program, plus
** the sum of the number of rows in all trigger subprograms encountered
** so far. The nRow value will increase as new trigger subprograms are
** encountered, but p->pc will eventually catch up to nRow.
*/
nRow = p->nOp;
if( bListSubprogs ){
/* The first 8 memory cells are used for the result set. So we will
** commandeer the 9th cell to use as storage for an array of pointers
** to trigger subprograms. The VDBE is guaranteed to have at least 9
** cells. */
assert( p->nMem>9 );
pSub = &p->aMem[9];
if( pSub->flags&MEM_Blob ){
/* On the first call to sqlite3_step(), pSub will hold a NULL. It is
** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
nSub = pSub->n/sizeof(Vdbe*);
apSub = (SubProgram **)pSub->z;
}
for(i=0; i<nSub; i++){
nRow += apSub[i]->nOp;
}
}
while(1){ /* Loop exits via break */
i = p->pc++;
if( i>=nRow ){
p->rc = SQLITE_OK;
rc = SQLITE_DONE;
break;
}
if( i<p->nOp ){
/* The output line number is small enough that we are still in the
** main program. */
pOp = &p->aOp[i];
}else{
/* We are currently listing subprograms. Figure out which one and
** pick up the appropriate opcode. */
int j;
i -= p->nOp;
assert( apSub!=0 );
assert( nSub>0 );
for(j=0; i>=apSub[j]->nOp; j++){
i -= apSub[j]->nOp;
assert( i<apSub[j]->nOp || j+1<nSub );
}
pOp = &apSub[j]->aOp[i];
}
/* When an OP_Program opcode is encounter (the only opcode that has
** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
** kept in p->aMem[9].z to hold the new program - assuming this subprogram
** has not already been seen.
*/
if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
int nByte = (nSub+1)*sizeof(SubProgram*);
int j;
for(j=0; j<nSub; j++){
if( apSub[j]==pOp->p4.pProgram ) break;
}
if( j==nSub ){
p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
if( p->rc!=SQLITE_OK ){
rc = SQLITE_ERROR;
break;
}
apSub = (SubProgram **)pSub->z;
apSub[nSub++] = pOp->p4.pProgram;
pSub->flags |= MEM_Blob;
pSub->n = nSub*sizeof(SubProgram*);
nRow += pOp->p4.pProgram->nOp;
}
}
if( p->explain<2 ) break;
if( pOp->opcode==OP_Explain ) break;
if( pOp->opcode==OP_Init && p->pc>1 ) break;
}
if( rc==SQLITE_OK ){
if( db->u1.isInterrupted ){
p->rc = SQLITE_INTERRUPT;
rc = SQLITE_ERROR;
sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
}else{
char *zP4;
if( p->explain==1 ){
pMem->flags = MEM_Int;
pMem->u.i = i; /* Program counter */
pMem++;
pMem->flags = MEM_Static|MEM_Str|MEM_Term;
pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
pMem++;
}
pMem->flags = MEM_Int;
pMem->u.i = pOp->p1; /* P1 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p2; /* P2 */
pMem++;
pMem->flags = MEM_Int;
pMem->u.i = pOp->p3; /* P3 */
pMem++;
if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
if( zP4!=pMem->z ){
pMem->n = 0;
sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
}else{
assert( pMem->z!=0 );
pMem->n = sqlite3Strlen30(pMem->z);
pMem->enc = SQLITE_UTF8;
}
pMem++;
if( p->explain==1 ){
if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = 2;
sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
pMem->enc = SQLITE_UTF8;
pMem++;
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
assert( p->db->mallocFailed );
return SQLITE_ERROR;
}
pMem->flags = MEM_Str|MEM_Term;
pMem->n = displayComment(pOp, zP4, pMem->z, 500);
pMem->enc = SQLITE_UTF8;
#else
pMem->flags = MEM_Null; /* Comment */
#endif
}
p->nResColumn = 8 - 4*(p->explain-1);
p->pResultSet = &p->aMem[1];
p->rc = SQLITE_OK;
rc = SQLITE_ROW;
}
}
return rc;
} | 0 |
openssh-portable | 5e75f5198769056089fb06c4d738ab0e5abc66f7 | NOT_APPLICABLE | NOT_APPLICABLE | mm_answer_audit_event(int socket, Buffer *m)
{
ssh_audit_event_t event;
debug3("%s entering", __func__);
event = buffer_get_int(m);
switch(event) {
case SSH_AUTH_FAIL_PUBKEY:
case SSH_AUTH_FAIL_HOSTBASED:
case SSH_AUTH_FAIL_GSSAPI:
case SSH_LOGIN_EXCEED_MAXTRIES:
case SSH_LOGIN_ROOT_DENIED:
case SSH_CONNECTION_CLOSE:
case SSH_INVALID_USER:
audit_event(event);
break;
default:
fatal("Audit event type %d not permitted", event);
}
return (0);
}
| 0 |
Chrome | 4c19b042ea31bd393d2265656f94339d1c3d82ff | NOT_APPLICABLE | NOT_APPLICABLE | bool FileUtilProxy::Copy(scoped_refptr<MessageLoopProxy> message_loop_proxy,
const FilePath& src_file_path,
const FilePath& dest_file_path,
StatusCallback* callback) {
return Start(FROM_HERE, message_loop_proxy,
new RelayCopy(src_file_path, dest_file_path, callback));
}
| 0 |
linux | ca4da5dd1f99fe9c59f1709fb43e818b18ad20e0 | NOT_APPLICABLE | NOT_APPLICABLE | static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen)
{
struct keyring_read_iterator_context ctx;
unsigned long nr_keys;
int ret;
kenter("{%d},,%zu", key_serial(keyring), buflen);
if (buflen & (sizeof(key_serial_t) - 1))
return -EINVAL;
nr_keys = keyring->keys.nr_leaves_on_tree;
if (nr_keys == 0)
return 0;
/* Calculate how much data we could return */
ctx.qty = nr_keys * sizeof(key_serial_t);
if (!buffer || !buflen)
return ctx.qty;
if (buflen > ctx.qty)
ctx.qty = buflen;
/* Copy the IDs of the subscribed keys into the buffer */
ctx.buffer = (key_serial_t __user *)buffer;
ctx.count = 0;
ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx);
if (ret < 0) {
kleave(" = %d [iterate]", ret);
return ret;
}
kleave(" = %zu [ok]", ctx.count);
return ctx.count;
}
| 0 |
poco | bb7e5feece68ccfd8660caee93da25c5c39a4707 | NOT_APPLICABLE | NOT_APPLICABLE | void ZipTest::tearDown()
{
} | 0 |
linux | 81f9c4e4177d31ced6f52a89bb70e93bfb77ca03 | NOT_APPLICABLE | NOT_APPLICABLE | tracing_buffers_poll(struct file *filp, poll_table *poll_table)
{
struct ftrace_buffer_info *info = filp->private_data;
struct trace_iterator *iter = &info->iter;
return trace_poll(iter, filp, poll_table);
}
| 0 |
Chrome | 08cb718ba7c3961c1006176c9faba0a5841ec792 | NOT_APPLICABLE | NOT_APPLICABLE | void AdjustComponent(int delta, url::Component* component) {
if (!component->is_valid())
return;
DCHECK(delta >= 0 || component->begin >= -delta);
component->begin += delta;
}
| 0 |
Chrome | c442b3eda2f1fdd4d1d4864c34c43cbaf223acae | NOT_APPLICABLE | NOT_APPLICABLE | void TestingAutomationProvider::NetworkScan(DictionaryValue* args,
IPC::Message* reply_message) {
NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
network_library->RequestNetworkScan();
new NetworkScanObserver(this, reply_message);
}
| 0 |
poppler | 7b2d314a61fd0e12f47c62996cb49ec0d1ba747a | NOT_APPLICABLE | NOT_APPLICABLE | virtual JBIG2SegmentType getType() { return jbig2SegBitmap; }
| 0 |
Chrome | f8675cbb337440a11bf9afb10ea11bae42bb92cb | NOT_APPLICABLE | NOT_APPLICABLE | gfx::Rect GetSplitViewRightWindowBounds(aura::Window* window) {
return split_view_controller()->GetSnappedWindowBoundsInScreen(
window, SplitViewController::RIGHT);
}
| 0 |
postgres | 31400a673325147e1205326008e32135a78b4d8a | NOT_APPLICABLE | NOT_APPLICABLE | bitxor(PG_FUNCTION_ARGS)
{
VarBit *arg1 = PG_GETARG_VARBIT_P(0);
VarBit *arg2 = PG_GETARG_VARBIT_P(1);
VarBit *result;
int len,
bitlen1,
bitlen2,
i;
bits8 *p1,
*p2,
*r;
bits8 mask;
bitlen1 = VARBITLEN(arg1);
bitlen2 = VARBITLEN(arg2);
if (bitlen1 != bitlen2)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
errmsg("cannot XOR bit strings of different sizes")));
len = VARSIZE(arg1);
result = (VarBit *) palloc(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = bitlen1;
p1 = VARBITS(arg1);
p2 = VARBITS(arg2);
r = VARBITS(result);
for (i = 0; i < VARBITBYTES(arg1); i++)
*r++ = *p1++ ^ *p2++;
/* Pad the result */
mask = BITMASK << VARBITPAD(result);
if (mask)
{
r--;
*r &= mask;
}
PG_RETURN_VARBIT_P(result);
}
| 0 |
linux | 92964c79b357efd980812c4de5c1fd2ec8bb5520 | NOT_APPLICABLE | NOT_APPLICABLE | static int __netlink_remove_tap(struct netlink_tap *nt)
{
bool found = false;
struct netlink_tap *tmp;
spin_lock(&netlink_tap_lock);
list_for_each_entry(tmp, &netlink_tap_all, list) {
if (nt == tmp) {
list_del_rcu(&nt->list);
found = true;
goto out;
}
}
pr_warn("__netlink_remove_tap: %p not found\n", nt);
out:
spin_unlock(&netlink_tap_lock);
if (found)
module_put(nt->module);
return found ? 0 : -ENODEV;
}
| 0 |
mujs | 25821e6d74fab5fcc200fe5e818362e03e114428 | NOT_APPLICABLE | NOT_APPLICABLE | static diy_fp_t minus(diy_fp_t x, diy_fp_t y)
{
diy_fp_t r;
assert(x.e == y.e);
assert(x.f >= y.f);
r.f = x.f - y.f;
r.e = x.e;
return r;
} | 0 |
harfbuzz | 81c8ef785b079980ad5b46be4fe7c7bf156dbf65 | NOT_APPLICABLE | NOT_APPLICABLE | static HB_Error Load_PairSet ( HB_PairSet* ps,
HB_UShort format1,
HB_UShort format2,
HB_Stream stream )
{
HB_Error error;
HB_UShort n, m, count;
HB_UInt base_offset;
HB_PairValueRecord* pvr;
base_offset = FILE_Pos();
if ( ACCESS_Frame( 2L ) )
return error;
count = ps->PairValueCount = GET_UShort();
FORGET_Frame();
ps->PairValueRecord = NULL;
if ( ALLOC_ARRAY( ps->PairValueRecord, count, HB_PairValueRecord ) )
return error;
pvr = ps->PairValueRecord;
for ( n = 0; n < count; n++ )
{
if ( ACCESS_Frame( 2L ) )
goto Fail;
pvr[n].SecondGlyph = GET_UShort();
FORGET_Frame();
if ( format1 )
{
error = Load_ValueRecord( &pvr[n].Value1, format1,
base_offset, stream );
if ( error )
goto Fail;
}
if ( format2 )
{
error = Load_ValueRecord( &pvr[n].Value2, format2,
base_offset, stream );
if ( error )
{
if ( format1 )
Free_ValueRecord( &pvr[n].Value1, format1 );
goto Fail;
}
}
}
return HB_Err_Ok;
Fail:
for ( m = 0; m < n; m++ )
{
if ( format1 )
Free_ValueRecord( &pvr[m].Value1, format1 );
if ( format2 )
Free_ValueRecord( &pvr[m].Value2, format2 );
}
FREE( pvr );
return error;
}
| 0 |
nDPI | 1ec621c85b9411cc611652fd57a892cfef478af3 | NOT_APPLICABLE | NOT_APPLICABLE | static void checkTLSSubprotocol(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow) {
if(flow->detected_protocol_stack[1] == NDPI_PROTOCOL_UNKNOWN) {
/* Subprotocol not yet set */
if(ndpi_struct->tls_cert_cache && flow->packet.iph) {
u_int32_t key = flow->packet.iph->daddr + flow->packet.tcp->dest;
u_int16_t cached_proto;
if(ndpi_lru_find_cache(ndpi_struct->tls_cert_cache, key,
&cached_proto, 0 /* Don't remove it as it can be used for other connections */)) {
ndpi_protocol ret = { NDPI_PROTOCOL_TLS, cached_proto, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED };
flow->detected_protocol_stack[0] = cached_proto,
flow->detected_protocol_stack[1] = NDPI_PROTOCOL_TLS;
flow->category = ndpi_get_proto_category(ndpi_struct, ret);
ndpi_check_subprotocol_risk(flow, cached_proto);
}
}
}
} | 0 |
dbus | 954d75b2b64e4799f360d2a6bf9cff6d9fee37e7 | NOT_APPLICABLE | NOT_APPLICABLE | _dbus_full_duplex_pipe (int *fd1,
int *fd2,
dbus_bool_t blocking,
DBusError *error)
{
SOCKET temp, socket1 = -1, socket2 = -1;
struct sockaddr_in saddr;
int len;
u_long arg;
_dbus_win_startup_winsock ();
temp = socket (AF_INET, SOCK_STREAM, 0);
if (temp == INVALID_SOCKET)
{
DBUS_SOCKET_SET_ERRNO ();
goto out0;
}
_DBUS_ZERO (saddr);
saddr.sin_family = AF_INET;
saddr.sin_port = 0;
saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out0;
}
if (listen (temp, 1) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out0;
}
len = sizeof (saddr);
if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out0;
}
socket1 = socket (AF_INET, SOCK_STREAM, 0);
if (socket1 == INVALID_SOCKET)
{
DBUS_SOCKET_SET_ERRNO ();
goto out0;
}
if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out1;
}
socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
if (socket2 == INVALID_SOCKET)
{
DBUS_SOCKET_SET_ERRNO ();
goto out1;
}
if (!blocking)
{
arg = 1;
if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out2;
}
arg = 1;
if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
goto out2;
}
}
*fd1 = socket1;
*fd2 = socket2;
_dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
*fd1, socket1, *fd2, socket2);
closesocket (temp);
return TRUE;
out2:
closesocket (socket2);
out1:
closesocket (socket1);
out0:
closesocket (temp);
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not setup socket pair: %s",
_dbus_strerror_from_errno ());
return FALSE;
}
| 0 |
php-src | 0bfb970f43acd1e81d11be1154805f86655f15d5?w=1 | NOT_APPLICABLE | NOT_APPLICABLE | static int phar_zip_applysignature(phar_archive_data *phar, struct _phar_zip_pass *pass,
smart_str *metadata) /* {{{ */
{
/* add signature for executable tars or tars explicitly set with setSignatureAlgorithm */
if (!phar->is_data || phar->sig_flags) {
int signature_length;
char *signature, sigbuf[8];
phar_entry_info entry = {0};
php_stream *newfile;
zend_off_t tell, st;
newfile = php_stream_fopen_tmpfile();
if (newfile == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for the signature file");
return FAILURE;
}
st = tell = php_stream_tell(pass->filefp);
/* copy the local files, central directory, and the zip comment to generate the hash */
php_stream_seek(pass->filefp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->filefp, newfile, tell, NULL);
tell = php_stream_tell(pass->centralfp);
php_stream_seek(pass->centralfp, 0, SEEK_SET);
php_stream_copy_to_stream_ex(pass->centralfp, newfile, tell, NULL);
if (metadata->s) {
php_stream_write(newfile, ZSTR_VAL(metadata->s), ZSTR_LEN(metadata->s));
}
if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, pass->error)) {
if (pass->error) {
char *save = *(pass->error);
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar: %s", save);
efree(save);
}
php_stream_close(newfile);
return FAILURE;
}
entry.filename = ".phar/signature.bin";
entry.filename_len = sizeof(".phar/signature.bin")-1;
entry.fp = php_stream_fopen_tmpfile();
entry.fp_type = PHAR_MOD;
entry.is_modified = 1;
if (entry.fp == NULL) {
spprintf(pass->error, 0, "phar error: unable to create temporary file for signature");
return FAILURE;
}
PHAR_SET_32(sigbuf, phar->sig_flags);
PHAR_SET_32(sigbuf + 4, signature_length);
if (8 != (int)php_stream_write(entry.fp, sigbuf, 8) || signature_length != (int)php_stream_write(entry.fp, signature, signature_length)) {
efree(signature);
if (pass->error) {
spprintf(pass->error, 0, "phar error: unable to write signature to zip-based phar %s", phar->fname);
}
php_stream_close(newfile);
return FAILURE;
}
efree(signature);
entry.uncompressed_filesize = entry.compressed_filesize = signature_length + 8;
entry.phar = phar;
/* throw out return value and write the signature */
phar_zip_changed_apply_int(&entry, (void *)pass);
php_stream_close(newfile);
if (pass->error && *(pass->error)) {
/* error is set by writeheaders */
php_stream_close(newfile);
return FAILURE;
}
} /* signature */
return SUCCESS;
}
/* }}} */
| 0 |
jdk17u | f8eb9abe034f7c6bea4da05a9ea42017b3f80730 | NOT_APPLICABLE | NOT_APPLICABLE | void InstanceKlass::clean_method_data() {
for (int m = 0; m < methods()->length(); m++) {
MethodData* mdo = methods()->at(m)->method_data();
if (mdo != NULL) {
MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock());
mdo->clean_method_data(/*always_clean*/false);
}
}
} | 0 |
jsish | 430ea27accd4d4ffddc946c9402e7c9064835a18 | NOT_APPLICABLE | NOT_APPLICABLE | Jsi_Func *jsi_FuncNew(Jsi_Interp *interp)
{
Jsi_Func *func = (Jsi_Func*)Jsi_Calloc(1, sizeof(Jsi_Func));
SIGINIT(func, FUNC);
func->hPtr = Jsi_HashSet(interp->funcsTbl, func, func);
func->refCnt = 1;
interp->funcCnt++;
return func;
} | 0 |
ovs | 0befd1f3745055c32940f5faf9559be6a14395e6 | NOT_APPLICABLE | NOT_APPLICABLE | OVS_REQUIRES(ofproto_mutex)
{
struct oftable *table;
enum ofperr error = 0;
size_t n_readonly = 0;
rule_collection_init(rules);
if (!check_table_id(ofproto, criteria->table_id)) {
error = OFPERR_OFPBRC_BAD_TABLE_ID;
goto exit;
}
if (criteria->cookie_mask == OVS_BE64_MAX) {
struct rule *rule;
HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
hash_cookie(criteria->cookie),
&ofproto->cookies) {
if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
collect_rule(rule, criteria, rules, &n_readonly);
}
}
} else {
FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
struct rule *rule;
CLS_FOR_EACH_TARGET (rule, cr, &table->cls, &criteria->cr,
criteria->version) {
collect_rule(rule, criteria, rules, &n_readonly);
}
}
}
exit:
if (!error && !rule_collection_n(rules) && n_readonly) {
/* We didn't find any rules to modify. We did find some read-only
* rules that we're not allowed to modify, so report that. */
error = OFPERR_OFPBRC_EPERM;
}
if (error) {
rule_collection_destroy(rules);
}
return error;
}
| 0 |
Chrome | 9f6510f20ccd794c4a71d5779ae802241e6e3f9b | NOT_APPLICABLE | NOT_APPLICABLE | void OfflinePageModelTaskified::OnCreateArchiveDone(
const SavePageCallback& callback,
OfflinePageItem proposed_page,
OfflinePageArchiver* archiver,
ArchiverResult archiver_result,
const GURL& saved_url,
const base::FilePath& file_path,
const base::string16& title,
int64_t file_size,
const std::string& digest) {
pending_archivers_.erase(
std::find_if(pending_archivers_.begin(), pending_archivers_.end(),
[archiver](const std::unique_ptr<OfflinePageArchiver>& a) {
return a.get() == archiver;
}));
if (archiver_result != ArchiverResult::SUCCESSFULLY_CREATED) {
SavePageResult result = ArchiverResultToSavePageResult(archiver_result);
InformSavePageDone(callback, result, proposed_page);
return;
}
if (proposed_page.url != saved_url) {
DVLOG(1) << "Saved URL does not match requested URL.";
InformSavePageDone(callback, SavePageResult::ARCHIVE_CREATION_FAILED,
proposed_page);
return;
}
proposed_page.file_path = file_path;
proposed_page.file_size = file_size;
proposed_page.title = title;
proposed_page.digest = digest;
AddPage(proposed_page,
base::Bind(&OfflinePageModelTaskified::OnAddPageForSavePageDone,
weak_ptr_factory_.GetWeakPtr(), callback, proposed_page));
}
| 0 |
Chrome | 517ac71c9ee27f856f9becde8abea7d1604af9d4 | NOT_APPLICABLE | NOT_APPLICABLE | static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
int i;
Select *pNew;
Select *pX;
sqlite3 *db;
struct ExprList_item *a;
SrcList *pNewSrc;
Parse *pParse;
Token dummy;
if( p->pPrior==0 ) return WRC_Continue;
if( p->pOrderBy==0 ) return WRC_Continue;
for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
if( pX==0 ) return WRC_Continue;
a = p->pOrderBy->a;
for(i=p->pOrderBy->nExpr-1; i>=0; i--){
if( a[i].pExpr->flags & EP_Collate ) break;
}
if( i<0 ) return WRC_Continue;
/* If we reach this point, that means the transformation is required. */
pParse = pWalker->pParse;
db = pParse->db;
pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
if( pNew==0 ) return WRC_Abort;
memset(&dummy, 0, sizeof(dummy));
pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
if( pNewSrc==0 ) return WRC_Abort;
*pNew = *p;
p->pSrc = pNewSrc;
p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
p->op = TK_SELECT;
p->pWhere = 0;
pNew->pGroupBy = 0;
pNew->pHaving = 0;
pNew->pOrderBy = 0;
p->pPrior = 0;
p->pNext = 0;
p->pWith = 0;
p->selFlags &= ~SF_Compound;
assert( (p->selFlags & SF_Converted)==0 );
p->selFlags |= SF_Converted;
assert( pNew->pPrior!=0 );
pNew->pPrior->pNext = pNew;
pNew->pLimit = 0;
return WRC_Continue;
}
| 0 |
Android | 494561291a503840f385fbcd11d9bc5f4dc502b8 | CVE-2017-0538 | CWE-119 | WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec,
WORD32 num_mb_skip,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num,
pocstruct_t *ps_cur_poc,
WORD32 prev_slice_err)
{
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2;
UWORD32 u1_mb_idx = ps_dec->u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end;
UWORD32 u1_tfr_n_mb;
UWORD32 u1_decode_nmb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD16 u2_total_mbs_coded;
UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag;
parse_part_params_t *ps_part_info;
WORD32 ret;
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return 0;
}
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (num_mb_skip & 1))
{
num_mb_skip++;
}
ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0;
if(prev_slice_err == 1)
{
/* first slice - missing/header corruption */
ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num;
if(!ps_dec->u1_first_slice_in_stream)
{
ih264d_end_of_pic(ps_dec, u1_is_idr_slice,
ps_dec->ps_cur_slice->u2_frame_num);
ps_dec->s_cur_pic_poc.u2_frame_num =
ps_dec->ps_cur_slice->u2_frame_num;
}
{
WORD32 i, j, poc = 0;
ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0;
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
if(ps_dec->ps_cur_pic != NULL)
poc = ps_dec->ps_cur_pic->i4_poc + 2;
j = -1;
for(i = 0; i < MAX_NUM_PIC_PARAMS; i++)
{
if(ps_dec->ps_pps[i].u1_is_valid == TRUE)
{
if(ps_dec->ps_pps[i].ps_sps->u1_is_valid == TRUE)
{
j = i;
break;
}
}
}
if(j == -1)
{
return ERROR_INV_SLICE_HDR_T;
}
/* call ih264d_start_of_pic only if it was not called earlier*/
if(ps_dec->u4_pic_buf_got == 0)
{
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_cur_slice->u1_nal_ref_idc = 1;
ps_dec->ps_cur_slice->u1_nal_unit_type = 1;
ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc,
ps_dec->ps_cur_slice->u2_frame_num,
&ps_dec->ps_pps[j]);
if(ret != OK)
{
return ret;
}
}
ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0;
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
ps_dec->u4_first_slice_in_pic = 0;
}
else
{
dec_slice_struct_t *ps_parse_cur_slice;
ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num;
if(ps_dec->u1_slice_header_done
&& ps_parse_cur_slice == ps_dec->ps_parse_cur_slice)
{
if((u1_mbaff) && (ps_dec->u4_num_mbs_cur_nmb & 1))
{
ps_dec->u4_num_mbs_cur_nmb = ps_dec->u4_num_mbs_cur_nmb - 1;
ps_dec->u2_cur_mb_addr--;
}
u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb;
if(u1_num_mbs)
{
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1;
}
else
{
if(ps_dec->u1_separate_parse)
{
ps_cur_mb_info = ps_dec->ps_nmb_info;
}
else
{
ps_cur_mb_info = ps_dec->ps_nmb_info
+ ps_dec->u4_num_mbs_prev_nmb - 1;
}
}
ps_dec->u2_mby = ps_cur_mb_info->u2_mby;
ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx;
ps_dec->u1_mb_ngbr_availablity =
ps_cur_mb_info->u1_mb_ngbr_availablity;
if(u1_num_mbs)
{
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data;
ps_dec->u2_cur_mb_addr--;
ps_dec->i4_submb_ofst -= SUB_BLK_SIZE;
if (ps_dec->u1_pr_sl_type == P_SLICE
|| ps_dec->u1_pr_sl_type == B_SLICE)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next)
&& (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = 1;
u1_tfr_n_mb = 1;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
ps_dec->u1_mb_idx = 0;
ps_dec->u4_num_mbs_cur_nmb = 0;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
return 0;
}
/* Inserting new slice only if the current slice has atleast 1 MB*/
if(ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice <
(UWORD32)(ps_dec->u2_total_mbs_coded >> ps_slice->u1_mbaff_frame_flag))
{
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
ps_dec->u2_cur_slice_num++;
ps_dec->ps_parse_cur_slice++;
}
}
else
{
ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf
+ ps_dec->u2_cur_slice_num;
}
}
/******************************************************/
/* Initializations to new slice */
/******************************************************/
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf;
}
ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff;
ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_dec->ps_cur_slice->i1_slice_beta_offset = 0;
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff;
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd;
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
/******************************************************/
/* Initializations specific to P slice */
/******************************************************/
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_parse_cur_slice->slice_type = P_SLICE;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= u1_mbaff;
/******************************************************/
/* Parsing / decoding the slice */
/******************************************************/
ps_dec->u1_slice_header_done = 2;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
u1_num_mbs = u1_mb_idx;
u1_slice_end = 0;
u1_tfr_n_mb = 0;
u1_decode_nmb = 0;
u1_num_mbsNby2 = 0;
i2_cur_mb_addr = ps_dec->u2_total_mbs_coded;
i2_mb_skip_run = num_mb_skip;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
break;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/**************************************************************/
/* Get the required information for decoding of MB */
/**************************************************************/
/* mb_x, mb_y, neighbor availablity, */
if (u1_mbaff)
ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
else
ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/* Set the deblocking parameters for this MB */
if(ps_dec->u4_app_disable_deblk_frm == 0)
{
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
}
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
/* Storing Skip partition info */
ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if (u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !i2_mb_skip_run;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next,
u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice;
H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice);
/* incremented here only if first slice is inserted */
if(ps_dec->u4_first_slice_in_pic != 0)
{
ps_dec->ps_parse_cur_slice++;
ps_dec->u2_cur_slice_num++;
}
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
}
return 0;
}
| 1 |
libmicrohttpd | a110ae6276660bee3caab30e9ff3f12f85cf3241 | NOT_APPLICABLE | NOT_APPLICABLE | test_empty_value (void)
{
struct MHD_Connection connection;
struct MHD_HTTP_Header header;
struct MHD_PostProcessor *pp;
unsigned int want_off = URL_EMPTY_VALUE_START;
size_t i;
size_t delta;
size_t size;
memset (&connection, 0, sizeof (struct MHD_Connection));
memset (&header, 0, sizeof (struct MHD_HTTP_Header));
connection.headers_received = &header;
header.header = MHD_HTTP_HEADER_CONTENT_TYPE;
header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED;
header.header_size = strlen (header.header);
header.value_size = strlen (header.value);
header.kind = MHD_HEADER_KIND;
pp = MHD_create_post_processor (&connection,
1024, &value_checker, &want_off);
i = 0;
size = strlen (URL_EMPTY_VALUE_DATA);
while (i < size)
{
delta = 1 + MHD_random_ () % (size - i);
MHD_post_process (pp, &URL_EMPTY_VALUE_DATA[i], delta);
i += delta;
}
MHD_destroy_post_processor (pp);
if (want_off != URL_EMPTY_VALUE_END)
{
fprintf (stderr,
"Test failed in line %u at offset %d\n",
(unsigned int) __LINE__,
(int) want_off);
return 8;
}
return 0;
} | 0 |
linux | a4270d6795b0580287453ea55974d948393e66ef | NOT_APPLICABLE | NOT_APPLICABLE | */
static void netdev_wait_allrefs(struct net_device *dev)
{
unsigned long rebroadcast_time, warning_time;
int refcnt;
linkwatch_forget_dev(dev);
rebroadcast_time = warning_time = jiffies;
refcnt = netdev_refcnt_read(dev);
while (refcnt != 0) {
if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
rtnl_lock();
/* Rebroadcast unregister notification */
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
__rtnl_unlock();
rcu_barrier();
rtnl_lock();
if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
&dev->state)) {
/* We must not have linkwatch events
* pending on unregister. If this
* happens, we simply run the queue
* unscheduled, resulting in a noop
* for this device.
*/
linkwatch_run_queue();
}
__rtnl_unlock();
rebroadcast_time = jiffies;
}
msleep(250);
refcnt = netdev_refcnt_read(dev);
if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
dev->name, refcnt);
warning_time = jiffies;
}
} | 0 |
libgd | 4751b606fa38edc456d627140898a7ec679fcc24 | NOT_APPLICABLE | NOT_APPLICABLE | static inline void _gdContributionsFree(LineContribType * p)
{
unsigned int u;
for (u = 0; u < p->LineLength; u++) {
gdFree(p->ContribRow[u].Weights);
}
gdFree(p->ContribRow);
gdFree(p);
}
| 0 |
Chrome | 971548cdca2d4c0a6fedd3db0c94372c2a27eac3 | NOT_APPLICABLE | NOT_APPLICABLE | AddObservedFrame(RenderFrameHost* render_frame_host, int session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observed_frames_.emplace(render_frame_host, session_id);
}
| 0 |
Chrome | fbeba958bb83c05ec8cc54e285a4a9ca10d1b311 | NOT_APPLICABLE | NOT_APPLICABLE | int GlobalConfirmInfoBar::DelegateProxy::GetButtons() const {
return global_info_bar_ ? global_info_bar_->delegate_->GetButtons()
: 0;
}
| 0 |
mongo | 0a076417d1d7fba3632b73349a1fd29a83e68816 | NOT_APPLICABLE | NOT_APPLICABLE | TEST(ParseExpression, ShouldRejectExpressionArgumentsWhichAreNotInArray) {
ASSERT_THROWS(parseExpression(BSON("$strcasecmp"
<< "foo")),
AssertionException);
} | 0 |
Chrome | f2d26633cbd50735ac2af30436888b71ac0abad3 | NOT_APPLICABLE | NOT_APPLICABLE | ConstrainedWidthView::ConstrainedWidthView(views::View* child, int max_width)
: max_width_(max_width) {
SetLayoutManager(std::make_unique<views::FillLayout>());
AddChildView(child);
}
| 0 |
thrift | 2007783e874d524a46b818598a45078448ecc53e | NOT_APPLICABLE | NOT_APPLICABLE | void t_go_generator::generate_service_client(t_service* tservice) {
string extends = "";
string extends_field = "";
string extends_client = "";
string extends_client_new = "";
string serviceName(publicize(tservice->get_name()));
if (tservice->get_extends() != NULL) {
extends = type_name(tservice->get_extends());
size_t index = extends.rfind(".");
if (index != string::npos) {
extends_client = extends.substr(0, index + 1) + publicize(extends.substr(index + 1))
+ "Client";
extends_client_new = extends.substr(0, index + 1) + "New"
+ publicize(extends.substr(index + 1)) + "Client";
} else {
extends_client = publicize(extends) + "Client";
extends_client_new = "New" + extends_client;
}
}
extends_field = extends_client.substr(extends_client.find(".") + 1);
generate_go_docstring(f_types_, tservice);
f_types_ << indent() << "type " << serviceName << "Client struct {" << endl;
indent_up();
if (!extends_client.empty()) {
f_types_ << indent() << "*" << extends_client << endl;
} else {
f_types_ << indent() << "Transport thrift.TTransport" << endl;
f_types_ << indent() << "ProtocolFactory thrift.TProtocolFactory" << endl;
f_types_ << indent() << "InputProtocol thrift.TProtocol" << endl;
f_types_ << indent() << "OutputProtocol thrift.TProtocol" << endl;
f_types_ << indent() << "SeqId int32" << endl;
/*f_types_ << indent() << "reqs map[int32]Deferred" << endl*/;
}
indent_down();
f_types_ << indent() << "}" << endl << endl;
// Constructor function
f_types_ << indent() << "func New" << serviceName
<< "ClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *" << serviceName
<< "Client {" << endl;
indent_up();
f_types_ << indent() << "return &" << serviceName << "Client";
if (!extends.empty()) {
f_types_ << "{" << extends_field << ": " << extends_client_new << "Factory(t, f)}";
} else {
indent_up();
f_types_ << "{Transport: t," << endl;
f_types_ << indent() << "ProtocolFactory: f," << endl;
f_types_ << indent() << "InputProtocol: f.GetProtocol(t)," << endl;
f_types_ << indent() << "OutputProtocol: f.GetProtocol(t)," << endl;
f_types_ << indent() << "SeqId: 0," << endl;
/*f_types_ << indent() << "Reqs: make(map[int32]Deferred)" << endl*/;
indent_down();
f_types_ << indent() << "}" << endl;
}
indent_down();
f_types_ << indent() << "}" << endl << endl;
// Constructor function
f_types_
<< indent() << "func New" << serviceName
<< "ClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *"
<< serviceName << "Client {" << endl;
indent_up();
f_types_ << indent() << "return &" << serviceName << "Client";
if (!extends.empty()) {
f_types_ << "{" << extends_field << ": " << extends_client_new << "Protocol(t, iprot, oprot)}"
<< endl;
} else {
indent_up();
f_types_ << "{Transport: t," << endl;
f_types_ << indent() << "ProtocolFactory: nil," << endl;
f_types_ << indent() << "InputProtocol: iprot," << endl;
f_types_ << indent() << "OutputProtocol: oprot," << endl;
f_types_ << indent() << "SeqId: 0," << endl;
/*f_types_ << indent() << "Reqs: make(map[int32]interface{})" << endl*/;
indent_down();
f_types_ << indent() << "}" << endl;
}
indent_down();
f_types_ << indent() << "}" << endl << endl;
// Generate client method implementations
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::const_iterator f_iter;
for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
t_struct* arg_struct = (*f_iter)->get_arglist();
const vector<t_field*>& fields = arg_struct->get_members();
vector<t_field*>::const_iterator fld_iter;
string funname = publicize((*f_iter)->get_name());
// Open function
generate_go_docstring(f_types_, (*f_iter));
f_types_ << indent() << "func (p *" << serviceName << "Client) "
<< function_signature_if(*f_iter, "", true) << " {" << endl;
indent_up();
/*
f_types_ <<
indent() << "p.SeqId += 1" << endl;
if (!(*f_iter)->is_oneway()) {
f_types_ <<
indent() << "d := defer.Deferred()" << endl <<
indent() << "p.Reqs[p.SeqId] = d" << endl;
}
*/
f_types_ << indent() << "if err = p.send" << funname << "(";
bool first = true;
for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
if (first) {
first = false;
} else {
f_types_ << ", ";
}
f_types_ << variable_name_to_go_name((*fld_iter)->get_name());
}
f_types_ << "); err != nil { return }" << endl;
if (!(*f_iter)->is_oneway()) {
f_types_ << indent() << "return p.recv" << funname << "()" << endl;
} else {
f_types_ << indent() << "return" << endl;
}
indent_down();
f_types_ << indent() << "}" << endl << endl;
f_types_ << indent() << "func (p *" << serviceName << "Client) send"
<< function_signature(*f_iter) << "(err error) {" << endl;
indent_up();
std::string argsname = publicize((*f_iter)->get_name() + "_args", true);
// Serialize the request header
f_types_ << indent() << "oprot := p.OutputProtocol" << endl;
f_types_ << indent() << "if oprot == nil {" << endl;
f_types_ << indent() << " oprot = p.ProtocolFactory.GetProtocol(p.Transport)" << endl;
f_types_ << indent() << " p.OutputProtocol = oprot" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "p.SeqId++" << endl;
f_types_ << indent() << "if err = oprot.WriteMessageBegin(\"" << (*f_iter)->get_name()
<< "\", " << ((*f_iter)->is_oneway() ? "thrift.ONEWAY" : "thrift.CALL")
<< ", p.SeqId); err != nil {" << endl;
indent_up();
f_types_ << indent() << " return" << endl;
indent_down();
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "args := " << argsname << "{" << endl;
for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
f_types_ << indent() << publicize((*fld_iter)->get_name()) << " : "
<< variable_name_to_go_name((*fld_iter)->get_name()) << "," << endl;
}
f_types_ << indent() << "}" << endl;
// Write to the stream
f_types_ << indent() << "if err = args." << write_method_name_ << "(oprot); err != nil {" << endl;
indent_up();
f_types_ << indent() << " return" << endl;
indent_down();
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if err = oprot.WriteMessageEnd(); err != nil {" << endl;
indent_up();
f_types_ << indent() << " return" << endl;
indent_down();
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "return oprot.Flush()" << endl;
indent_down();
f_types_ << indent() << "}" << endl << endl;
if (!(*f_iter)->is_oneway()) {
std::string resultname = publicize((*f_iter)->get_name() + "_result", true);
// Open function
f_types_ << endl << indent() << "func (p *" << serviceName << "Client) recv"
<< publicize((*f_iter)->get_name()) << "() (";
if (!(*f_iter)->get_returntype()->is_void()) {
f_types_ << "value " << type_to_go_type((*f_iter)->get_returntype()) << ", ";
}
f_types_ << "err error) {" << endl;
indent_up();
// TODO(mcslee): Validate message reply here, seq ids etc.
string error(tmp("error"));
string error2(tmp("error"));
f_types_ << indent() << "iprot := p.InputProtocol" << endl;
f_types_ << indent() << "if iprot == nil {" << endl;
f_types_ << indent() << " iprot = p.ProtocolFactory.GetProtocol(p.Transport)" << endl;
f_types_ << indent() << " p.InputProtocol = iprot" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "method, mTypeId, seqId, err := iprot.ReadMessageBegin()" << endl;
f_types_ << indent() << "if err != nil {" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if method != \"" << (*f_iter)->get_name() << "\" {" << endl;
f_types_ << indent() << " err = thrift.NewTApplicationException("
<< "thrift.WRONG_METHOD_NAME, \"" << (*f_iter)->get_name()
<< " failed: wrong method name\")" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if p.SeqId != seqId {" << endl;
f_types_ << indent() << " err = thrift.NewTApplicationException("
<< "thrift.BAD_SEQUENCE_ID, \"" << (*f_iter)->get_name()
<< " failed: out of sequence response\")" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if mTypeId == thrift.EXCEPTION {" << endl;
f_types_ << indent() << " " << error
<< " := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "
"\"Unknown Exception\")" << endl;
f_types_ << indent() << " var " << error2 << " error" << endl;
f_types_ << indent() << " " << error2 << ", err = " << error << ".Read(iprot)" << endl;
f_types_ << indent() << " if err != nil {" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << " }" << endl;
f_types_ << indent() << " if err = iprot.ReadMessageEnd(); err != nil {" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << " }" << endl;
f_types_ << indent() << " err = " << error2 << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if mTypeId != thrift.REPLY {" << endl;
f_types_ << indent() << " err = thrift.NewTApplicationException("
<< "thrift.INVALID_MESSAGE_TYPE_EXCEPTION, \"" << (*f_iter)->get_name()
<< " failed: invalid message type\")" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "result := " << resultname << "{}" << endl;
f_types_ << indent() << "if err = result." << read_method_name_ << "(iprot); err != nil {" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
f_types_ << indent() << "if err = iprot.ReadMessageEnd(); err != nil {" << endl;
f_types_ << indent() << " return" << endl;
f_types_ << indent() << "}" << endl;
t_struct* xs = (*f_iter)->get_xceptions();
const std::vector<t_field*>& xceptions = xs->get_members();
vector<t_field*>::const_iterator x_iter;
for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
const std::string pubname = publicize((*x_iter)->get_name());
f_types_ << indent() << "if result." << pubname << " != nil {" << endl;
f_types_ << indent() << " err = result." << pubname << endl;
f_types_ << indent() << " return " << endl;
f_types_ << indent() << "}";
if ((x_iter + 1) != xceptions.end()) {
f_types_ << " else ";
} else {
f_types_ << endl;
}
}
// Careful, only return _result if not a void function
if (!(*f_iter)->get_returntype()->is_void()) {
f_types_ << indent() << "value = result.GetSuccess()" << endl;
}
f_types_ << indent() << "return" << endl;
// Close function
indent_down();
f_types_ << indent() << "}" << endl << endl;
}
}
// indent_down();
f_types_ << endl;
} | 0 |
linux | 6265539776a0810b7ce6398c27866ddb9c6bd154 | CVE-2017-12146 | CWE-362 | static ssize_t driver_override_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
char *driver_override, *old = pdev->driver_override, *cp;
if (count > PATH_MAX)
return -EINVAL;
driver_override = kstrndup(buf, count, GFP_KERNEL);
if (!driver_override)
return -ENOMEM;
cp = strchr(driver_override, '\n');
if (cp)
*cp = '\0';
if (strlen(driver_override)) {
pdev->driver_override = driver_override;
} else {
kfree(driver_override);
pdev->driver_override = NULL;
}
kfree(old);
return count;
}
| 1 |
systemd | 5ebff5337594d690b322078c512eb222d34aaa82 | NOT_APPLICABLE | NOT_APPLICABLE | int dir_is_empty(const char *path) {
DIR *d;
int r;
struct dirent buf, *de;
if (!(d = opendir(path)))
return -errno;
for (;;) {
if ((r = readdir_r(d, &buf, &de)) > 0) {
r = -r;
break;
}
if (!de) {
r = 1;
break;
}
if (!ignore_file(de->d_name)) {
r = 0;
break;
}
}
closedir(d);
return r;
}
| 0 |
Chrome | b755ebba29dd405d6f1e4cf70f5bc81ffd33b0f6 | NOT_APPLICABLE | NOT_APPLICABLE | bool IsPrintPreviewEnabled() {
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kRendererPrintPreview);
}
| 0 |
linux | 550fd08c2cebad61c548def135f67aba284c6162 | NOT_APPLICABLE | NOT_APPLICABLE | static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device *rcv = NULL;
struct veth_priv *priv, *rcv_priv;
struct veth_net_stats *stats, *rcv_stats;
int length;
priv = netdev_priv(dev);
rcv = priv->peer;
rcv_priv = netdev_priv(rcv);
stats = this_cpu_ptr(priv->stats);
rcv_stats = this_cpu_ptr(rcv_priv->stats);
/* don't change ip_summed == CHECKSUM_PARTIAL, as that
will cause bad checksum on forwarded packets */
if (skb->ip_summed == CHECKSUM_NONE &&
rcv->features & NETIF_F_RXCSUM)
skb->ip_summed = CHECKSUM_UNNECESSARY;
length = skb->len;
if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS)
goto rx_drop;
u64_stats_update_begin(&stats->syncp);
stats->tx_bytes += length;
stats->tx_packets++;
u64_stats_update_end(&stats->syncp);
u64_stats_update_begin(&rcv_stats->syncp);
rcv_stats->rx_bytes += length;
rcv_stats->rx_packets++;
u64_stats_update_end(&rcv_stats->syncp);
return NETDEV_TX_OK;
rx_drop:
u64_stats_update_begin(&rcv_stats->syncp);
rcv_stats->rx_dropped++;
u64_stats_update_end(&rcv_stats->syncp);
return NETDEV_TX_OK;
}
| 0 |
ghostpdl | c9b362ba908ca4b1d7c72663a33229588012d7d9 | NOT_APPLICABLE | NOT_APPLICABLE | int epo_fill_trapezoid(gx_device *dev, const gs_fixed_edge *left, const gs_fixed_edge *right,
fixed ybot, fixed ytop, bool swap_axes,
const gx_drawing_color *pdcolor, gs_logical_operation_t lop)
{
int code = epo_handle_erase_page(dev);
if (code != 0)
return code;
return dev_proc(dev, fill_trapezoid)(dev, left, right, ybot, ytop, swap_axes, pdcolor, lop);
} | 0 |
php-src | 336d2086a9189006909ae06c7e95902d7d5ff77e | NOT_APPLICABLE | NOT_APPLICABLE |
PHP_IMAP_EXPORT void mm_status(MAILSTREAM *stream, char *mailbox, MAILSTATUS *status)
{
IMAPG(status_flags)=status->flags;
if (IMAPG(status_flags) & SA_MESSAGES) {
IMAPG(status_messages)=status->messages;
}
if (IMAPG(status_flags) & SA_RECENT) {
IMAPG(status_recent)=status->recent;
}
if (IMAPG(status_flags) & SA_UNSEEN) {
IMAPG(status_unseen)=status->unseen;
}
if (IMAPG(status_flags) & SA_UIDNEXT) {
IMAPG(status_uidnext)=status->uidnext;
}
if (IMAPG(status_flags) & SA_UIDVALIDITY) {
IMAPG(status_uidvalidity)=status->uidvalidity;
} | 0 |
Android | 42a25c46b844518ff0d0b920c20c519e1417be69 | NOT_APPLICABLE | NOT_APPLICABLE | MediaRecorder::~MediaRecorder()
{
ALOGV("destructor");
if (mMediaRecorder != NULL) {
mMediaRecorder.clear();
}
if (mSurfaceMediaSource != NULL) {
mSurfaceMediaSource.clear();
}
}
| 0 |
php | 88412772d295ebf7dd34409534507dc9bcac726e | NOT_APPLICABLE | NOT_APPLICABLE | int XMLRPC_ServerRegisterMethod(XMLRPC_SERVER server, const char *name, XMLRPC_Callback cb) {
if(server && name && cb) {
server_method* sm = malloc(sizeof(server_method));
if(sm) {
sm->name = strdup(name);
sm->method = cb;
sm->desc = NULL;
return Q_PushTail(&server->methodlist, sm);
}
}
return 0;
}
| 0 |
ceph | ba0790a01ba5252db1ebc299db6e12cd758d0ff9 | NOT_APPLICABLE | NOT_APPLICABLE | void RGWListBuckets_ObjStore_S3::send_response_data(RGWUserBuckets& buckets)
{
if (!sent_data)
return;
map<string, RGWBucketEnt>& m = buckets.get_buckets();
map<string, RGWBucketEnt>::iterator iter;
for (iter = m.begin(); iter != m.end(); ++iter) {
RGWBucketEnt obj = iter->second;
dump_bucket(s, obj);
}
rgw_flush_formatter(s, s->formatter);
} | 0 |
samba | c300a85848350635e7ddd8129b31c4d439dc0f8a | NOT_APPLICABLE | NOT_APPLICABLE | static int compare_notify_change_events(const void *p1, const void *p2)
{
const struct notify_change_event *e1 = p1;
const struct notify_change_event *e2 = p2;
return timespec_compare(&e1->when, &e2->when);
} | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.