instruction stringclasses 1 value | input stringlengths 56 241k | output int64 0 1 | __index_level_0__ int64 0 175k |
|---|---|---|---|
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void BluetoothAdapterChromeOS::StartDiscovering(
const base::Closure& callback,
const ErrorCallback& error_callback) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->
StartDiscovery(
object_path_,
base::Bind(&BluetoothAdapterChromeOS::OnStartDiscovery,
weak_ptr_factory_.GetWeakPtr(),
callback),
base::Bind(&BluetoothAdapterChromeOS::OnStartDiscoveryError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | 0 | 112,538 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void ResourceDispatcherHostImpl::OnShutdown() {
DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
is_shutdown_ = true;
weak_factory_on_io_.InvalidateWeakPtrs();
pending_loaders_.clear();
update_load_info_timer_.reset();
std::set<GlobalFrameRoutingId> ids;
for (const auto& blocked_loaders : blocked_loaders_map_) {
std::pair<std::set<GlobalFrameRoutingId>::iterator, bool> result =
ids.insert(blocked_loaders.first);
DCHECK(result.second);
}
for (const auto& routing_id : ids) {
CancelBlockedRequestsForRoute(routing_id);
}
scheduler_.reset();
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <japhet@chromium.org>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <clamy@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | 0 | 152,033 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
int32_t *out, APERice *rice, int blockstodecode)
{
int i;
int ksummax, ksummin;
rice->ksum = 0;
for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
out[i] = get_rice_ook(&ctx->gb, 10);
rice->ksum += out[i];
}
rice->k = av_log2(rice->ksum / 10) + 1;
if (rice->k >= 24)
return;
for (; i < FFMIN(blockstodecode, 64); i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i];
rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
if (rice->k >= 24)
return;
}
ksummax = 1 << rice->k + 7;
ksummin = rice->k ? (1 << rice->k + 6) : 0;
for (; i < blockstodecode; i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i] - out[i - 64];
while (rice->ksum < ksummin) {
rice->k--;
ksummin = rice->k ? ksummin >> 1 : 0;
ksummax >>= 1;
}
while (rice->ksum >= ksummax) {
rice->k++;
if (rice->k > 24)
return;
ksummax <<= 1;
ksummin = ksummin ? ksummin << 1 : 128;
}
}
for (i = 0; i < blockstodecode; i++)
out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
}
Commit Message: avcodec/apedec: Fix integer overflow
Fixes: out of array access
Fixes: PoC.ape and others
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-125 | 0 | 63,400 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void V8TestObject::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
static constexpr V8DOMConfiguration::AccessorConfiguration
kAccessorConfigurations[] = {
{ "runtimeEnabledLongAttribute", V8TestObject::RuntimeEnabledLongAttributeAttributeGetterCallback, V8TestObject::RuntimeEnabledLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
{ "unscopableRuntimeEnabledLongAttribute", V8TestObject::UnscopableRuntimeEnabledLongAttributeAttributeGetterCallback, V8TestObject::UnscopableRuntimeEnabledLongAttributeAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
};
V8DOMConfiguration::InstallAccessors(
isolate, world, instance_template, prototype_template, interface_template,
signature, kAccessorConfigurations,
base::size(kAccessorConfigurations));
}
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
{
constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
{"unscopableRuntimeEnabledVoidMethod", V8TestObject::UnscopableRuntimeEnabledVoidMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}
};
for (const auto& config : kConfigurations) {
V8DOMConfiguration::InstallMethod(
isolate, world, instance_template, prototype_template,
interface_template, signature, config);
}
}
}
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
{
constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
{"runtimeEnabledVoidMethod", V8TestObject::RuntimeEnabledVoidMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}
};
for (const auto& config : kConfigurations) {
V8DOMConfiguration::InstallMethod(
isolate, world, instance_template, prototype_template,
interface_template, signature, config);
}
}
}
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
{
constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
{"perWorldBindingsRuntimeEnabledVoidMethod", V8TestObject::PerWorldBindingsRuntimeEnabledVoidMethodMethodCallbackForMainWorld, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kMainWorld},
{"perWorldBindingsRuntimeEnabledVoidMethod", V8TestObject::PerWorldBindingsRuntimeEnabledVoidMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kNonMainWorlds}
};
for (const auto& config : kConfigurations) {
V8DOMConfiguration::InstallMethod(
isolate, world, instance_template, prototype_template,
interface_template, signature, config);
}
}
}
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
{
constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
{"runtimeEnabledOverloadedVoidMethod", V8TestObject::RuntimeEnabledOverloadedVoidMethodMethodCallback, 1, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}
};
for (const auto& config : kConfigurations) {
V8DOMConfiguration::InstallMethod(
isolate, world, instance_template, prototype_template,
interface_template, signature, config);
}
}
}
if (RuntimeEnabledFeatures::RuntimeFeatureEnabled()) {
{
constexpr V8DOMConfiguration::MethodConfiguration kConfigurations[] = {
{"clear", V8TestObject::ClearMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}
};
for (const auto& config : kConfigurations) {
V8DOMConfiguration::InstallMethod(
isolate, world, instance_template, prototype_template,
interface_template, signature, config);
}
}
}
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <peria@chromium.org>
Commit-Queue: Yuki Shiino <yukishiino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID: | 0 | 134,778 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: MYSQLND_METHOD(mysqlnd_conn_data, end_psession)(MYSQLND_CONN_DATA * conn TSRMLS_DC)
{
DBG_ENTER("mysqlnd_conn_data::end_psession");
DBG_RETURN(PASS);
}
Commit Message:
CWE ID: CWE-284 | 0 | 14,271 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: bool NormalPage::IsEmpty() {
HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(Payload());
return header->IsFree() && header->size() == PayloadSize();
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <mlippautz@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362 | 0 | 153,715 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: virDomainMigratePerform(virDomainPtr domain,
const char *cookie,
int cookielen,
const char *uri,
unsigned long flags,
const char *dname,
unsigned long bandwidth)
{
virConnectPtr conn;
VIR_DOMAIN_DEBUG(domain, "cookie=%p, cookielen=%d, uri=%s, flags=%lx, "
"dname=%s, bandwidth=%lu", cookie, cookielen, uri, flags,
NULLSTR(dname), bandwidth);
virResetLastError();
virCheckDomainReturn(domain, -1);
conn = domain->conn;
virCheckReadOnlyGoto(conn->flags, error);
if (conn->driver->domainMigratePerform) {
int ret;
ret = conn->driver->domainMigratePerform(domain, cookie, cookielen,
uri,
flags, dname, bandwidth);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(domain->conn);
return -1;
}
Commit Message: virDomainGetTime: Deny on RO connections
We have a policy that if API may end up talking to a guest agent
it should require RW connection. We don't obey the rule in
virDomainGetTime().
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
CWE ID: CWE-254 | 0 | 93,862 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: base::CommandLine::StringType GetSwitchString(const std::string& flag) {
base::CommandLine cmd_line(base::CommandLine::NO_PROGRAM);
cmd_line.AppendSwitch(flag);
DCHECK_EQ(2U, cmd_line.argv().size());
return cmd_line.argv()[1];
}
Commit Message: Move smart deploy to tristate.
BUG=
Review URL: https://codereview.chromium.org/1149383006
Cr-Commit-Position: refs/heads/master@{#333058}
CWE ID: CWE-399 | 0 | 123,315 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void filter_free_subsystem_filters(struct trace_subsystem_dir *dir,
struct trace_array *tr)
{
struct trace_event_file *file;
list_for_each_entry(file, &tr->events, list) {
if (file->system != dir)
continue;
__free_subsystem_filter(file);
}
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787 | 0 | 81,570 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: AutofillMetrics::CardNumberStatus AutofillManager::GetCardNumberStatus(
CreditCard& credit_card) {
base::string16 number = credit_card.number();
if (number.empty())
return AutofillMetrics::EMPTY_CARD;
else if (!HasCorrectLength(number))
return AutofillMetrics::WRONG_SIZE_CARD;
else if (!PassesLuhnCheck(number))
return AutofillMetrics::FAIL_LUHN_CHECK_CARD;
else if (personal_data_->IsKnownCard(credit_card))
return AutofillMetrics::KNOWN_CARD;
else
return AutofillMetrics::UNKNOWN_CARD;
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <rogerm@chromium.org>
Commit-Queue: Sebastien Seguin-Gagnon <sebsg@chromium.org>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID: | 0 | 154,953 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: NavigateParams::NavigateParams(
Browser* a_browser,
const GURL& a_url,
content::PageTransition a_transition)
: url(a_url),
target_contents(NULL),
source_contents(NULL),
disposition(CURRENT_TAB),
transition(a_transition),
tabstrip_index(-1),
tabstrip_add_types(TabStripModel::ADD_ACTIVE),
window_action(NO_ACTION),
user_gesture(true),
path_behavior(RESPECT),
ref_behavior(IGNORE_REF),
browser(a_browser),
profile(NULL) {
}
Commit Message: Fix memory error in previous CL.
BUG=100315
BUG=99016
TEST=Memory bots go green
Review URL: http://codereview.chromium.org/8302001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | 1 | 170,249 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void __d_instantiate(struct dentry *dentry, struct inode *inode)
{
unsigned add_flags = d_flags_for_inode(inode);
WARN_ON(d_in_lookup(dentry));
spin_lock(&dentry->d_lock);
hlist_add_head(&dentry->d_u.d_alias, &inode->i_dentry);
raw_write_seqcount_begin(&dentry->d_seq);
__d_set_inode_and_type(dentry, inode, add_flags);
raw_write_seqcount_end(&dentry->d_seq);
fsnotify_update_flags(dentry);
spin_unlock(&dentry->d_lock);
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-362 | 0 | 67,270 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int ip6mr_mfc_delete(struct mr6_table *mrt, struct mf6cctl *mfc,
int parent)
{
int line;
struct mfc6_cache *c, *next;
line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr);
list_for_each_entry_safe(c, next, &mrt->mfc6_cache_array[line], list) {
if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) &&
ipv6_addr_equal(&c->mf6c_mcastgrp,
&mfc->mf6cc_mcastgrp.sin6_addr) &&
(parent == -1 || parent == c->mf6c_parent)) {
write_lock_bh(&mrt_lock);
list_del(&c->list);
write_unlock_bh(&mrt_lock);
mr6_netlink_event(mrt, c, RTM_DELROUTE);
ip6mr_cache_free(c);
return 0;
}
}
return -ENOENT;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <lucien.xin@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20 | 0 | 93,536 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void CL_UpdateInfoPacket( netadr_t from ) {
if ( cls.autoupdateServer.type == NA_BAD ) {
Com_DPrintf( "CL_UpdateInfoPacket: Auto-Updater has bad address\n" );
return;
}
Com_DPrintf( "Auto-Updater resolved to %i.%i.%i.%i:%i\n",
cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1],
cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3],
BigShort( cls.autoupdateServer.port ) );
if ( !NET_CompareAdr( from, cls.autoupdateServer ) ) {
Com_DPrintf( "CL_UpdateInfoPacket: Received packet from %i.%i.%i.%i:%i\n",
from.ip[0], from.ip[1], from.ip[2], from.ip[3],
BigShort( from.port ) );
return;
}
Cvar_Set( "cl_updateavailable", Cmd_Argv( 1 ) );
if ( !Q_stricmp( cl_updateavailable->string, "1" ) ) {
Cvar_Set( "cl_updatefiles", Cmd_Argv( 2 ) );
VM_Call( uivm, UI_SET_ACTIVE_MENU, UIMENU_WM_AUTOUPDATE );
}
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269 | 0 | 95,738 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: int yr_scan_verify_match(
YR_SCAN_CONTEXT* context,
YR_AC_MATCH* ac_match,
uint8_t* data,
size_t data_size,
size_t data_base,
size_t offset)
{
YR_STRING* string = ac_match->string;
#ifdef PROFILING_ENABLED
clock_t start = clock();
#endif
if (data_size - offset <= 0)
return ERROR_SUCCESS;
if (context->flags & SCAN_FLAGS_FAST_MODE &&
STRING_IS_SINGLE_MATCH(string) &&
string->matches[context->tidx].head != NULL)
return ERROR_SUCCESS;
if (STRING_IS_FIXED_OFFSET(string) &&
string->fixed_offset != data_base + offset)
return ERROR_SUCCESS;
if (STRING_IS_LITERAL(string))
{
FAIL_ON_ERROR(_yr_scan_verify_literal_match(
context, ac_match, data, data_size, data_base, offset));
}
else
{
FAIL_ON_ERROR(_yr_scan_verify_re_match(
context, ac_match, data, data_size, data_base, offset));
}
#ifdef PROFILING_ENABLED
string->clock_ticks += clock() - start;
#endif
return ERROR_SUCCESS;
}
Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
CWE ID: CWE-125 | 0 | 64,594 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt)
{
FILE *fp;
size_t n;
JAS_DBGLOG(100, ("sfile_write(%p, %p, %d)\n", obj, buf, cnt));
fp = JAS_CAST(FILE *, obj);
n = fwrite(buf, 1, cnt, fp);
return (n != JAS_CAST(size_t, cnt)) ? (-1) : cnt;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | 0 | 67,944 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void ff_amf_write_string2(uint8_t **dst, const char *str1, const char *str2)
{
int len1 = 0, len2 = 0;
if (str1)
len1 = strlen(str1);
if (str2)
len2 = strlen(str2);
bytestream_put_byte(dst, AMF_DATA_TYPE_STRING);
bytestream_put_be16(dst, len1 + len2);
bytestream_put_buffer(dst, str1, len1);
bytestream_put_buffer(dst, str2, len2);
}
Commit Message: avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2
Fixes: out of array accesses
Found-by: JunDong Xie of Ant-financial Light-Year Security Lab
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-20 | 0 | 63,208 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: tt_cmap12_char_next( TT_CMap cmap,
FT_UInt32 *pchar_code )
{
TT_CMap12 cmap12 = (TT_CMap12)cmap;
FT_UInt gindex;
/* no need to search */
if ( cmap12->valid && cmap12->cur_charcode == *pchar_code )
{
tt_cmap12_next( cmap12 );
if ( cmap12->valid )
{
gindex = cmap12->cur_gindex;
*pchar_code = (FT_UInt32)cmap12->cur_charcode;
}
else
gindex = 0;
}
else
gindex = tt_cmap12_char_map_binary( cmap, pchar_code, 1 );
return gindex;
}
Commit Message:
CWE ID: CWE-125 | 0 | 17,263 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int tracing_buffers_release(struct inode *inode, struct file *file)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
mutex_lock(&trace_types_lock);
iter->tr->current_trace->ref--;
__trace_array_put(iter->tr);
if (info->spare)
ring_buffer_free_read_page(iter->trace_buffer->buffer,
info->spare_cpu, info->spare);
kfree(info);
mutex_unlock(&trace_types_lock);
return 0;
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787 | 0 | 81,457 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: QQuickWebPage* QQuickWebViewExperimental::page()
{
return q_ptr->page();
}
Commit Message: [Qt][WK2] Allow transparent WebViews
https://bugs.webkit.org/show_bug.cgi?id=80608
Reviewed by Tor Arne Vestbø.
Added support for transparentBackground in QQuickWebViewExperimental.
This uses the existing drawsTransparentBackground property in WebKit2.
Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes,
otherwise the change doesn't take effect.
A new API test was added.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::setTransparentBackground):
(QQuickWebViewPrivate::transparentBackground):
(QQuickWebViewExperimental::transparentBackground):
(QQuickWebViewExperimental::setTransparentBackground):
* UIProcess/API/qt/qquickwebview_p.h:
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
* UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp:
(tst_QQuickWebView):
(tst_QQuickWebView::transparentWebViews):
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::LayerTreeHostQt::LayerTreeHostQt):
(WebKit::LayerTreeHostQt::setRootCompositingLayer):
git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-189 | 0 | 101,747 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void DownloadItemImpl::SetExternalData(
const void* key, DownloadItem::ExternalData* data) {
std::map<const void*, ExternalData*>::iterator it =
external_data_map_.find(key);
if (it == external_data_map_.end()) {
external_data_map_[key] = data;
} else if (it->second != data) {
delete it->second;
it->second = data;
}
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
R=asanka@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | 0 | 106,150 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: rad_create_request(struct rad_handle *h, int code)
{
int i;
h->request[POS_CODE] = code;
h->request[POS_IDENT] = ++h->ident;
/* Create a random authenticator */
for (i = 0; i < LEN_AUTH; i += 2) {
long r;
TSRMLS_FETCH();
r = php_rand(TSRMLS_C);
h->request[POS_AUTH+i] = (unsigned char) r;
h->request[POS_AUTH+i+1] = (unsigned char) (r >> 8);
}
h->req_len = POS_ATTRS;
h->request_created = 1;
clear_password(h);
return 0;
}
Commit Message: Fix a security issue in radius_get_vendor_attr().
The underlying rad_get_vendor_attr() function assumed that it would always be
given valid VSA data. Indeed, the buffer length wasn't even passed in; the
assumption was that the length field within the VSA structure would be valid.
This could result in denial of service by providing a length that would be
beyond the memory limit, or potential arbitrary memory access by providing a
length greater than the actual data given.
rad_get_vendor_attr() has been changed to require the raw data length be
provided, and this is then used to check that the VSA is valid.
Conflicts:
radlib_vs.h
CWE ID: CWE-119 | 0 | 31,532 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static ssize_t write_file_dummy(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return -EINVAL;
}
Commit Message: libertas: potential oops in debugfs
If we do a zero size allocation then it will oops. Also we can't be
sure the user passes us a NUL terminated string so I've added a
terminator.
This code can only be triggered by root.
Reported-by: Nico Golde <nico@ngolde.de>
Reported-by: Fabian Yamaguchi <fabs@goesec.de>
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Acked-by: Dan Williams <dcbw@redhat.com>
Signed-off-by: John W. Linville <linville@tuxdriver.com>
CWE ID: CWE-189 | 0 | 28,706 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static CURLcode nss_cache_crl(SECItem *crl_der)
{
CERTCertDBHandle *db = CERT_GetDefaultCertDB();
CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
if(crl) {
/* CRL already cached */
SEC_DestroyCrl(crl);
SECITEM_FreeItem(crl_der, PR_TRUE);
return CURLE_OK;
}
/* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
PR_Lock(nss_crllock);
/* store the CRL item so that we can free it in Curl_nss_cleanup() */
if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
SECITEM_FreeItem(crl_der, PR_TRUE);
PR_Unlock(nss_crllock);
return CURLE_OUT_OF_MEMORY;
}
if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
/* unable to cache CRL */
PR_Unlock(nss_crllock);
return CURLE_SSL_CRL_BADFILE;
}
/* we need to clear session cache, so that the CRL could take effect */
SSL_ClearSessionCache();
PR_Unlock(nss_crllock);
return CURLE_OK;
}
Commit Message: nss: refuse previously loaded certificate from file
... when we are not asked to use a certificate from file
CWE ID: CWE-287 | 0 | 50,097 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void rpcap_frame_end (void)
{
info_added = FALSE;
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <guy@alum.mit.edu>
CWE ID: CWE-20 | 0 | 51,764 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
{
return sprintf(page, "%llu\n",
(unsigned long long)rdev->new_data_offset);
}
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr>
Signed-off-by: NeilBrown <neilb@suse.com>
CWE ID: CWE-200 | 0 | 42,502 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: MessageLoop* RenderThreadImpl::GetMessageLoop() {
return message_loop();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | 0 | 107,083 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: brcmf_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif = ifp->vif;
s32 infra = 0;
s32 ap = 0;
s32 err = 0;
brcmf_dbg(TRACE, "Enter, bsscfgidx=%d, type=%d\n", ifp->bsscfgidx,
type);
/* WAR: There are a number of p2p interface related problems which
* need to be handled initially (before doing the validate).
* wpa_supplicant tends to do iface changes on p2p device/client/go
* which are not always possible/allowed. However we need to return
* OK otherwise the wpa_supplicant wont start. The situation differs
* on configuration and setup (p2pon=1 module param). The first check
* is to see if the request is a change to station for p2p iface.
*/
if ((type == NL80211_IFTYPE_STATION) &&
((vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_GO) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_DEVICE))) {
brcmf_dbg(TRACE, "Ignoring cmd for p2p if\n");
/* Now depending on whether module param p2pon=1 was used the
* response needs to be either 0 or EOPNOTSUPP. The reason is
* that if p2pon=1 is used, but a newer supplicant is used then
* we should return an error, as this combination wont work.
* In other situations 0 is returned and supplicant will start
* normally. It will give a trace in cfg80211, but it is the
* only way to get it working. Unfortunately this will result
* in situation where we wont support new supplicant in
* combination with module param p2pon=1, but that is the way
* it is. If the user tries this then unloading of driver might
* fail/lock.
*/
if (cfg->p2p.p2pdev_dynamically)
return -EOPNOTSUPP;
else
return 0;
}
err = brcmf_vif_change_validate(wiphy_to_cfg(wiphy), vif, type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return err;
}
switch (type) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_WDS:
brcmf_err("type (%d) : currently we do not support this type\n",
type);
return -EOPNOTSUPP;
case NL80211_IFTYPE_ADHOC:
infra = 0;
break;
case NL80211_IFTYPE_STATION:
infra = 1;
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
ap = 1;
break;
default:
err = -EINVAL;
goto done;
}
if (ap) {
if (type == NL80211_IFTYPE_P2P_GO) {
brcmf_dbg(INFO, "IF Type = P2P GO\n");
err = brcmf_p2p_ifchange(cfg, BRCMF_FIL_P2P_IF_GO);
}
if (!err) {
brcmf_dbg(INFO, "IF Type = AP\n");
}
} else {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, infra);
if (err) {
brcmf_err("WLC_SET_INFRA error (%d)\n", err);
err = -EAGAIN;
goto done;
}
brcmf_dbg(INFO, "IF Type = %s\n", brcmf_is_ibssmode(vif) ?
"Adhoc" : "Infra");
}
ndev->ieee80211_ptr->iftype = type;
brcmf_cfg80211_update_proto_addr_mode(&vif->wdev);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
Commit Message: brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx()
The lower level nl80211 code in cfg80211 ensures that "len" is between
25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from
"len" so thats's max of 2280. However, the action_frame->data[] buffer is
only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can
overflow.
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
Cc: stable@vger.kernel.org # 3.9.x
Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.")
Reported-by: "freenerguo(郭大兴)" <freenerguo@tencent.com>
Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-119 | 0 | 67,220 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
const struct tcphdr *th)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_fastopen_cookie foc = { .len = -1 };
int saved_clamp = tp->rx_opt.mss_clamp;
tcp_parse_options(skb, &tp->rx_opt, 0, &foc);
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
tp->rx_opt.rcv_tsecr -= tp->tsoffset;
if (th->ack) {
/* rfc793:
* "If the state is SYN-SENT then
* first check the ACK bit
* If the ACK bit is set
* If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
* a reset (unless the RST bit is set, if so drop
* the segment and return)"
*/
if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt))
goto reset_and_undo;
if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
!between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
tcp_time_stamp)) {
NET_INC_STATS(sock_net(sk),
LINUX_MIB_PAWSACTIVEREJECTED);
goto reset_and_undo;
}
/* Now ACK is acceptable.
*
* "If the RST bit is set
* If the ACK was acceptable then signal the user "error:
* connection reset", drop the segment, enter CLOSED state,
* delete TCB, and return."
*/
if (th->rst) {
tcp_reset(sk);
goto discard;
}
/* rfc793:
* "fifth, if neither of the SYN or RST bits is set then
* drop the segment and return."
*
* See note below!
* --ANK(990513)
*/
if (!th->syn)
goto discard_and_undo;
/* rfc793:
* "If the SYN bit is on ...
* are acceptable then ...
* (our SYN has been ACKed), change the connection
* state to ESTABLISHED..."
*/
tcp_ecn_rcv_synack(tp, th);
tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
tcp_ack(sk, skb, FLAG_SLOWPATH);
/* Ok.. it's good. Set up sequence numbers and
* move to established.
*/
tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
/* RFC1323: The window in SYN & SYN/ACK segments is
* never scaled.
*/
tp->snd_wnd = ntohs(th->window);
if (!tp->rx_opt.wscale_ok) {
tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
tp->window_clamp = min(tp->window_clamp, 65535U);
}
if (tp->rx_opt.saw_tstamp) {
tp->rx_opt.tstamp_ok = 1;
tp->tcp_header_len =
sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
tcp_store_ts_recent(tp);
} else {
tp->tcp_header_len = sizeof(struct tcphdr);
}
if (tcp_is_sack(tp) && sysctl_tcp_fack)
tcp_enable_fack(tp);
tcp_mtup_init(sk);
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
tcp_initialize_rcv_mss(sk);
/* Remember, tcp_poll() does not lock socket!
* Change state from SYN-SENT only after copied_seq
* is initialized. */
tp->copied_seq = tp->rcv_nxt;
smp_mb();
tcp_finish_connect(sk, skb);
if ((tp->syn_fastopen || tp->syn_data) &&
tcp_rcv_fastopen_synack(sk, skb, &foc))
return -1;
if (sk->sk_write_pending ||
icsk->icsk_accept_queue.rskq_defer_accept ||
icsk->icsk_ack.pingpong) {
/* Save one ACK. Data will be ready after
* several ticks, if write_pending is set.
*
* It may be deleted, but with this feature tcpdumps
* look so _wonderfully_ clever, that I was not able
* to stand against the temptation 8) --ANK
*/
inet_csk_schedule_ack(sk);
icsk->icsk_ack.lrcvtime = tcp_time_stamp;
tcp_enter_quickack_mode(sk);
inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
TCP_DELACK_MAX, TCP_RTO_MAX);
discard:
tcp_drop(sk, skb);
return 0;
} else {
tcp_send_ack(sk);
}
return -1;
}
/* No ACK in the segment */
if (th->rst) {
/* rfc793:
* "If the RST bit is set
*
* Otherwise (no ACK) drop the segment and return."
*/
goto discard_and_undo;
}
/* PAWS check. */
if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
tcp_paws_reject(&tp->rx_opt, 0))
goto discard_and_undo;
if (th->syn) {
/* We see SYN without ACK. It is attempt of
* simultaneous connect with crossed SYNs.
* Particularly, it can be connect to self.
*/
tcp_set_state(sk, TCP_SYN_RECV);
if (tp->rx_opt.saw_tstamp) {
tp->rx_opt.tstamp_ok = 1;
tcp_store_ts_recent(tp);
tp->tcp_header_len =
sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
} else {
tp->tcp_header_len = sizeof(struct tcphdr);
}
tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
tp->copied_seq = tp->rcv_nxt;
tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
/* RFC1323: The window in SYN & SYN/ACK segments is
* never scaled.
*/
tp->snd_wnd = ntohs(th->window);
tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
tp->max_window = tp->snd_wnd;
tcp_ecn_rcv_syn(tp, th);
tcp_mtup_init(sk);
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
tcp_initialize_rcv_mss(sk);
tcp_send_synack(sk);
#if 0
/* Note, we could accept data and URG from this segment.
* There are no obstacles to make this (except that we must
* either change tcp_recvmsg() to prevent it from returning data
* before 3WHS completes per RFC793, or employ TCP Fast Open).
*
* However, if we ignore data in ACKless segments sometimes,
* we have no reasons to accept it sometimes.
* Also, seems the code doing it in step6 of tcp_rcv_state_process
* is not flawless. So, discard packet for sanity.
* Uncomment this return to process the data.
*/
return -1;
#else
goto discard;
#endif
}
/* "fifth, if neither of the SYN or RST bits is set then
* drop the segment and return."
*/
discard_and_undo:
tcp_clear_options(&tp->rx_opt);
tp->rx_opt.mss_clamp = saved_clamp;
goto discard;
reset_and_undo:
tcp_clear_options(&tp->rx_opt);
tp->rx_opt.mss_clamp = saved_clamp;
return 1;
}
Commit Message: tcp: make challenge acks less predictable
Yue Cao claims that current host rate limiting of challenge ACKS
(RFC 5961) could leak enough information to allow a patient attacker
to hijack TCP sessions. He will soon provide details in an academic
paper.
This patch increases the default limit from 100 to 1000, and adds
some randomization so that the attacker can no longer hijack
sessions without spending a considerable amount of probes.
Based on initial analysis and patch from Linus.
Note that we also have per socket rate limiting, so it is tempting
to remove the host limit in the future.
v2: randomize the count of challenge acks per second, not the period.
Fixes: 282f23c6ee34 ("tcp: implement RFC 5961 3.2")
Reported-by: Yue Cao <ycao009@ucr.edu>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Yuchung Cheng <ycheng@google.com>
Cc: Neal Cardwell <ncardwell@google.com>
Acked-by: Neal Cardwell <ncardwell@google.com>
Acked-by: Yuchung Cheng <ycheng@google.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | 0 | 51,595 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
sp<Camera3Device> parent = mParent.promote();
if (parent != NULL) {
va_list args;
va_start(args, fmt);
parent->setErrorStateV(fmt, args);
va_end(args);
}
}
Commit Message: Camera3Device: Validate template ID
Validate template ID before creating a default request.
Bug: 26866110
Bug: 27568958
Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d
CWE ID: CWE-264 | 0 | 161,092 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static ssize_t snd_disconnect_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
return -ENODEV;
}
Commit Message: ALSA: control: Protect user controls against concurrent access
The user-control put and get handlers as well as the tlv do not protect against
concurrent access from multiple threads. Since the state of the control is not
updated atomically it is possible that either two write operations or a write
and a read operation race against each other. Both can lead to arbitrary memory
disclosure. This patch introduces a new lock that protects user-controls from
concurrent access. Since applications typically access controls sequentially
than in parallel a single lock per card should be fine.
Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
Acked-by: Jaroslav Kysela <perex@perex.cz>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID: CWE-362 | 0 | 36,537 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void gf_fm_request_set_callback(void *cbk_obj, fm_callback_func cbk_func) {
fm_cbk = cbk_func;
fm_cbk_obj = cbk_obj;
}
Commit Message: fix buffer overrun in gf_bin128_parse
closes #1204
closes #1205
CWE ID: CWE-119 | 0 | 90,806 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: bool isEmpty()
{
return m_layers.isEmpty();
}
Commit Message: Disable some more query compositingState asserts.
This gets the tests passing again on Mac. See the bug for the stacktrace.
A future patch will need to actually fix the incorrect reading of
compositingState.
BUG=343179
Review URL: https://codereview.chromium.org/162153002
git-svn-id: svn://svn.chromium.org/blink/trunk@167069 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | 0 | 113,807 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: bool WebContentsImpl::CreateRenderViewForRenderManager(
RenderViewHost* render_view_host,
int opener_frame_routing_id,
int proxy_routing_id,
const FrameReplicationState& replicated_frame_state) {
TRACE_EVENT0("browser,navigation",
"WebContentsImpl::CreateRenderViewForRenderManager");
if (proxy_routing_id == MSG_ROUTING_NONE)
CreateRenderWidgetHostViewForRenderManager(render_view_host);
UpdateMaxPageIDIfNecessary(render_view_host);
int32_t max_page_id =
GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
if (!static_cast<RenderViewHostImpl*>(render_view_host)
->CreateRenderView(opener_frame_routing_id, proxy_routing_id,
max_page_id, replicated_frame_state,
created_with_opener_)) {
return false;
}
SetHistoryOffsetAndLengthForView(render_view_host,
controller_.GetLastCommittedEntryIndex(),
controller_.GetEntryCount());
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
if (rwh_view) {
if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
render_widget_host->WasResized();
}
#endif
return true;
}
Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted
BUG=583718
Review URL: https://codereview.chromium.org/1685343004
Cr-Commit-Position: refs/heads/master@{#375700}
CWE ID: | 0 | 131,780 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0;
int64_t total_samples = 0, infilesize;
RiffChunkHeader riff_chunk_header;
ChunkHeader chunk_header;
WaveHeader WaveHeader;
DS64Chunk ds64_chunk;
uint32_t bcount;
CLEAR (WaveHeader);
CLEAR (ds64_chunk);
infilesize = DoGetFileSize (infile);
if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {
error_line ("can't handle .WAV files larger than 4 GB (non-standard)!");
return WAVPACK_SOFT_ERROR;
}
memcpy (&riff_chunk_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||
bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||
bcount != sizeof (ChunkHeader)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);
if (!strncmp (chunk_header.ckID, "ds64", 4)) {
if (chunk_header.ckSize < sizeof (DS64Chunk) ||
!DoReadFile (infile, &ds64_chunk, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &ds64_chunk, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
got_ds64 = 1;
WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);
if (debug_logging_mode)
error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d",
(long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,
(long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);
if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
while (ds64_chunk.tableLength--) {
CS64Chunk cs64_chunk;
if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||
bcount != sizeof (CS64Chunk) ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
}
}
else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and
int supported = TRUE, format; // make sure it's a .wav file we can handle
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .WAV format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this WAV file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else if (config->float_norm_exp)
error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)",
config->float_norm_exp - 126, 150 - config->float_norm_exp);
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop
int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?
ds64_chunk.dataSize64 : chunk_header.ckSize;
if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required)
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {
error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (config->qmode & QMODE_IGNORE_LENGTH) {
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
total_samples = data_chunk_size / WaveHeader.BlockAlign;
if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (!total_samples) {
error_line ("this .WAV file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
Commit Message: issue #27, do not overwrite stack on corrupt RF64 file
CWE ID: CWE-119 | 1 | 169,334 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static struct sit_entry_set *grab_sit_entry_set(void)
{
struct sit_entry_set *ses =
f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
ses->entry_cnt = 0;
INIT_LIST_HEAD(&ses->set_list);
return ses;
}
Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control
Mount fs with option noflush_merge, boot failed for illegal address
fcc in function f2fs_issue_flush:
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush); -> Here, fcc illegal
return ret;
}
Signed-off-by: Yunlei He <heyunlei@huawei.com>
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
CWE ID: CWE-476 | 0 | 85,400 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static bool IsTerminatingCharacter(UChar c) {
return (c == '&' || c == '/' || c == '"' || c == '\'' || c == '<' ||
c == '>' || c == ',');
}
Commit Message: Restrict the xss audit report URL to same origin
BUG=441275
R=tsepez@chromium.org,mkwst@chromium.org
Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d
Reviewed-on: https://chromium-review.googlesource.com/768367
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Jochen Eisinger <jochen@chromium.org>
Cr-Commit-Position: refs/heads/master@{#516666}
CWE ID: CWE-79 | 0 | 147,014 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: const MidiPortInfoList& output_ports() { return client_->output_ports_; }
Commit Message: MidiManagerUsb should not trust indices provided by renderer.
MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is
provided by a renderer possibly under the control of an attacker, we must
validate the given index before using it.
BUG=456516
Review URL: https://codereview.chromium.org/907793002
Cr-Commit-Position: refs/heads/master@{#315303}
CWE ID: CWE-119 | 0 | 128,717 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void show_help_default(const char *opt, const char *arg)
{
printf("usage: ffserver [options]\n"
"Hyper fast multi format Audio/Video streaming server\n");
printf("\n");
show_help_options(options, "Main options:", 0, 0, 0);
}
Commit Message: ffserver: Check chunk size
Fixes out of array access
Fixes: poc_ffserver.py
Found-by: Paul Cher <paulcher@icloud.com>
Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
CWE ID: CWE-119 | 0 | 70,833 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, RenderFlowThread* flowThread)
{
LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
LayoutUnit logicalOffset = min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
LayoutUnit logicalBottom = max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
LayoutUnit lineHeight = logicalBottom - logicalOffset;
updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(style(), lineBox, logicalOffset, logicalBottom));
logicalOffset += delta;
lineBox->setPaginationStrut(0);
lineBox->setIsFirstAfterPageBreak(false);
LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight))
return;
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
int lineIndex = lineCount(lineBox);
if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
if (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex) {
clearShouldBreakAtLineToAvoidWidow();
setDidBreakAtLineToAvoidWidow();
}
if (lineHeight > pageLogicalHeight) {
remainingLogicalHeight -= min(lineHeight - pageLogicalHeight, max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
}
LayoutUnit totalLogicalHeight = lineHeight + max<LayoutUnit>(0, logicalOffset);
LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style()->hasAutoOrphans() && style()->orphans() >= lineIndex))
&& !isOutOfFlowPositioned() && !isTableCell())
setPaginationStrut(remainingLogicalHeight + max<LayoutUnit>(0, logicalOffset));
else {
delta += remainingLogicalHeight;
lineBox->setPaginationStrut(remainingLogicalHeight);
lineBox->setIsFirstAfterPageBreak(true);
}
} else if (remainingLogicalHeight == pageLogicalHeight) {
if (lineBox != firstRootBox())
lineBox->setIsFirstAfterPageBreak(true);
if (lineBox != firstRootBox() || offsetFromLogicalTopOfFirstPage())
setPageBreak(logicalOffset, lineHeight);
}
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
R=eseidel@chromium.org, esprehn@chromium.org, jchaffraix@chromium.org
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | 0 | 116,142 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void ctr64_inc(unsigned char *counter)
{
int n = 8;
unsigned char c;
do {
--n;
c = counter[n];
++c;
counter[n] = c;
if (c)
return;
} while (n);
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <rsalz@openssl.org>
CWE ID: CWE-125 | 0 | 69,349 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: isdn_net_ciscohdlck_slarp_send_keepalive(unsigned long data)
{
isdn_net_local *lp = (isdn_net_local *) data;
struct sk_buff *skb;
unsigned char *p;
unsigned long last_cisco_myseq = lp->cisco_myseq;
int myseq_diff = 0;
if (!(lp->flags & ISDN_NET_CONNECTED) || lp->dialstate) {
printk("isdn BUG at %s:%d!\n", __FILE__, __LINE__);
return;
}
lp->cisco_myseq++;
myseq_diff = (lp->cisco_myseq - lp->cisco_mineseen);
if ((lp->cisco_line_state) && ((myseq_diff >= 3)||(myseq_diff <= -3))) {
/* line up -> down */
lp->cisco_line_state = 0;
printk (KERN_WARNING
"UPDOWN: Line protocol on Interface %s,"
" changed state to down\n", lp->netdev->dev->name);
/* should stop routing higher-level data across */
} else if ((!lp->cisco_line_state) &&
(myseq_diff >= 0) && (myseq_diff <= 2)) {
/* line down -> up */
lp->cisco_line_state = 1;
printk (KERN_WARNING
"UPDOWN: Line protocol on Interface %s,"
" changed state to up\n", lp->netdev->dev->name);
/* restart routing higher-level data across */
}
if (lp->cisco_debserint)
printk (KERN_DEBUG "%s: HDLC "
"myseq %lu, mineseen %lu%c, yourseen %lu, %s\n",
lp->netdev->dev->name, last_cisco_myseq, lp->cisco_mineseen,
((last_cisco_myseq == lp->cisco_mineseen) ? '*' : 040),
lp->cisco_yourseq,
((lp->cisco_line_state) ? "line up" : "line down"));
skb = isdn_net_ciscohdlck_alloc_skb(lp, 4 + 14);
if (!skb)
return;
p = skb_put(skb, 4 + 14);
/* cisco header */
*(u8 *)(p + 0) = CISCO_ADDR_UNICAST;
*(u8 *)(p + 1) = CISCO_CTRL;
*(__be16 *)(p + 2) = cpu_to_be16(CISCO_TYPE_SLARP);
/* slarp keepalive */
*(__be32 *)(p + 4) = cpu_to_be32(CISCO_SLARP_KEEPALIVE);
*(__be32 *)(p + 8) = cpu_to_be32(lp->cisco_myseq);
*(__be32 *)(p + 12) = cpu_to_be32(lp->cisco_yourseq);
*(__be16 *)(p + 16) = cpu_to_be16(0xffff); // reliability, always 0xffff
p += 18;
isdn_net_write_super(lp, skb);
lp->cisco_timer.expires = jiffies + lp->cisco_keepalive_period * HZ;
add_timer(&lp->cisco_timer);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-264 | 0 | 23,627 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void ion_pages_sync_for_device(struct device *dev, struct page *page,
size_t size, enum dma_data_direction dir)
{
struct scatterlist sg;
sg_init_table(&sg, 1);
sg_set_page(&sg, page, size, 0);
/*
* This is not correct - sg_dma_address needs a dma_addr_t that is valid
* for the targeted device, but this works on the currently targeted
* hardware.
*/
sg_dma_address(&sg) = page_to_phys(page);
dma_sync_sg_for_device(dev, &sg, 1, dir);
}
Commit Message: staging/android/ion : fix a race condition in the ion driver
There is a use-after-free problem in the ion driver.
This is caused by a race condition in the ion_ioctl()
function.
A handle has ref count of 1 and two tasks on different
cpus calls ION_IOC_FREE simultaneously.
cpu 0 cpu 1
-------------------------------------------------------
ion_handle_get_by_id()
(ref == 2)
ion_handle_get_by_id()
(ref == 3)
ion_free()
(ref == 2)
ion_handle_put()
(ref == 1)
ion_free()
(ref == 0 so ion_handle_destroy() is
called
and the handle is freed.)
ion_handle_put() is called and it
decreases the slub's next free pointer
The problem is detected as an unaligned access in the
spin lock functions since it uses load exclusive
instruction. In some cases it corrupts the slub's
free pointer which causes a mis-aligned access to the
next free pointer.(kmalloc returns a pointer like
ffffc0745b4580aa). And it causes lots of other
hard-to-debug problems.
This symptom is caused since the first member in the
ion_handle structure is the reference count and the
ion driver decrements the reference after it has been
freed.
To fix this problem client->lock mutex is extended
to protect all the codes that uses the handle.
Signed-off-by: Eun Taik Lee <eun.taik.lee@samsung.com>
Reviewed-by: Laura Abbott <labbott@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-416 | 0 | 48,564 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void ContainerNode::insertBeforeCommon(Node* nextChild, Node* newChild)
{
NoEventDispatchAssertion assertNoEventDispatch;
ASSERT(newChild);
ASSERT(!newChild->parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
ASSERT(!newChild->nextSibling());
ASSERT(!newChild->previousSibling());
ASSERT(!newChild->isShadowRoot());
Node* prev = nextChild->previousSibling();
ASSERT(m_lastChild != prev);
nextChild->setPreviousSibling(newChild);
if (prev) {
ASSERT(m_firstChild != nextChild);
ASSERT(prev->nextSibling() == nextChild);
prev->setNextSibling(newChild);
} else {
ASSERT(m_firstChild == nextChild);
m_firstChild = newChild;
}
newChild->setParentOrShadowHostNode(this);
newChild->setPreviousSibling(prev);
newChild->setNextSibling(nextChild);
}
Commit Message: Notify nodes removal to Range/Selection after dispatching blur and mutation event
This patch changes notifying nodes removal to Range/Selection after dispatching blur and mutation event. In willRemoveChildren(), like willRemoveChild(); r115686 did same change, although it didn't change willRemoveChildren().
The issue 295010, use-after-free, is caused by setting removed node to Selection in mutation event handler.
BUG=295010
TEST=LayoutTests/fast/dom/Range/range-created-during-remove-children.html, LayoutTests/editing/selection/selection-change-in-mutation-event-by-remove-children.html, LayoutTests/editing/selection/selection-change-in-blur-event-by-remove-children.html
R=tkent@chromium.org
Review URL: https://codereview.chromium.org/25389004
git-svn-id: svn://svn.chromium.org/blink/trunk@159007 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | 0 | 110,511 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
size_t size)
{
unsigned char *buffer_compressed;
size_t bytes_compressed;
size_t bytes_used;
int ret;
ret = hfs_reset_compressor(a);
if (ret != ARCHIVE_OK)
return (ret);
if (a->compressed_buffer == NULL) {
size_t block_size;
block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
+ compressBound(MAX_DECMPFS_BLOCK_SIZE);
a->compressed_buffer = malloc(block_size);
if (a->compressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Resource Fork");
return (ARCHIVE_FATAL);
}
a->compressed_buffer_size = block_size;
a->compressed_buffer_remaining = block_size;
}
buffer_compressed = a->compressed_buffer +
a->compressed_buffer_size - a->compressed_buffer_remaining;
a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
a->stream.avail_in = size;
a->stream.next_out = buffer_compressed;
a->stream.avail_out = a->compressed_buffer_remaining;
do {
ret = deflate(&a->stream, Z_FINISH);
switch (ret) {
case Z_OK:
case Z_STREAM_END:
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to compress data");
return (ARCHIVE_FAILED);
}
} while (ret == Z_OK);
bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
/*
* If the compressed size is larger than the original size,
* throw away compressed data, use uncompressed data instead.
*/
if (bytes_compressed > size) {
buffer_compressed[0] = 0xFF;/* uncompressed marker. */
memcpy(buffer_compressed + 1, buff, size);
bytes_compressed = size + 1;
}
a->compressed_buffer_remaining -= bytes_compressed;
/*
* If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
* and the block count in the file is only one, store compressed
* data to decmpfs xattr instead of the resource fork.
*/
if (a->decmpfs_block_count == 1 &&
(a->decmpfs_attr_size + bytes_compressed)
<= MAX_DECMPFS_XATTR_SIZE) {
archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
CMP_XATTR);
memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
buffer_compressed, bytes_compressed);
a->decmpfs_attr_size += bytes_compressed;
a->compressed_buffer_remaining = a->compressed_buffer_size;
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
return (ret);
}
/* Update block info. */
archive_le32enc(a->decmpfs_block_info++,
a->compressed_rsrc_position_v - RSRC_H_SIZE);
archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
a->compressed_rsrc_position_v += bytes_compressed;
/*
* Write the compressed data to the resource fork.
*/
bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
while (bytes_used >= COMPRESSED_W_SIZE) {
ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
if (ret != ARCHIVE_OK)
return (ret);
bytes_used -= COMPRESSED_W_SIZE;
if (bytes_used > COMPRESSED_W_SIZE)
memmove(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
else
memcpy(a->compressed_buffer,
a->compressed_buffer + COMPRESSED_W_SIZE,
bytes_used);
}
a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
/*
* If the current block is the last block, write the remaining
* compressed data and the resource fork footer.
*/
if (a->file_remaining_bytes == 0) {
size_t rsrc_size;
int64_t bk;
/* Append the resource footer. */
rsrc_size = hfs_set_resource_fork_footer(
a->compressed_buffer + bytes_used,
a->compressed_buffer_remaining);
ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
a->compressed_buffer_remaining = a->compressed_buffer_size;
/* If the compressed size is not enouph smaller than
* the uncompressed size. cancel HFS+ compression.
* TODO: study a behavior of ditto utility and improve
* the condition to fall back into no HFS+ compression. */
bk = HFS_BLOCKS(a->compressed_rsrc_position);
bk += bk >> 7;
if (bk > HFS_BLOCKS(a->filesize))
return hfs_decompress(a);
/*
* Write the resourcefork header.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_resource_fork_header(a);
/*
* Finish HFS+ Compression.
* - Write the decmpfs xattr.
* - Set the UF_COMPRESSED file flag.
*/
if (ret == ARCHIVE_OK)
ret = hfs_write_decmpfs(a);
if (ret == ARCHIVE_OK)
ret = hfs_set_compressed_fflag(a);
}
return (ret);
}
Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option
This fixes a directory traversal in the cpio tool.
CWE ID: CWE-22 | 0 | 43,913 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int java_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalBlock *bb;
RAnalBlock *current_head;
if (!anal || !state || !state->current_bb || state->current_bb_head)
return 0;
bb = state->current_bb;
current_head = state->current_bb_head;
if (current_head && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) {
r_anal_ex_update_bb_cfg_head_tail (current_head, current_head, state->current_bb);
}
if (bb->type2 & R_ANAL_EX_CODE_OP) handle_bb_cf_recursive_descent (anal, state);
return 0;
}
Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op()
CWE ID: CWE-125 | 0 | 82,023 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index)
{
if (index >= src_len) {
return -1;
}
size_t dummy_index;
if (next_index == NULL) {
next_index = &dummy_index;
}
size_t num_read;
int32_t ret = utf32_at_internal(src + index, &num_read);
if (ret >= 0) {
*next_index = index + num_read;
}
return ret;
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119 | 0 | 158,437 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: GLManager::GLManager() {
SetupBaseContext();
}
Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data.
In linux and android, we are seeing an issue where texture data from one
tab overwrites the texture data of another tab. This is happening for apps
which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D.
Due to a bug in virtual context save/restore code for above texture formats,
the texture data is not properly restored while switching tabs. Hence
texture data from one tab overwrites other.
This CL has fix for that issue, an update for existing test expectations
and a new unit test for this bug.
Bug: 788448
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28
Reviewed-on: https://chromium-review.googlesource.com/930327
Reviewed-by: Zhenyao Mo <zmo@chromium.org>
Commit-Queue: vikas soni <vikassoni@chromium.org>
Cr-Commit-Position: refs/heads/master@{#539111}
CWE ID: CWE-200 | 0 | 150,042 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: int __init ipv6_exthdrs_init(void)
{
int ret;
ret = inet6_add_protocol(&rthdr_protocol, IPPROTO_ROUTING);
if (ret)
goto out;
ret = inet6_add_protocol(&destopt_protocol, IPPROTO_DSTOPTS);
if (ret)
goto out_rthdr;
ret = inet6_add_protocol(&nodata_protocol, IPPROTO_NONE);
if (ret)
goto out_destopt;
out:
return ret;
out_destopt:
inet6_del_protocol(&destopt_protocol, IPPROTO_DSTOPTS);
out_rthdr:
inet6_del_protocol(&rthdr_protocol, IPPROTO_ROUTING);
goto out;
};
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <dvyukov@google.com>
Signed-off-by: Eric Dumazet <edumazet@google.com>
Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-416 | 0 | 53,678 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static inline ResourceRequestCachePolicy toWebCoreCachePolicy(Platform::NetworkRequest::CachePolicy policy)
{
switch (policy) {
case Platform::NetworkRequest::UseProtocolCachePolicy:
return UseProtocolCachePolicy;
case Platform::NetworkRequest::ReloadIgnoringCacheData:
return ReloadIgnoringCacheData;
case Platform::NetworkRequest::ReturnCacheDataElseLoad:
return ReturnCacheDataElseLoad;
case Platform::NetworkRequest::ReturnCacheDataDontLoad:
return ReturnCacheDataDontLoad;
default:
ASSERT_NOT_REACHED();
return UseProtocolCachePolicy;
}
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | 0 | 104,454 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: status_t OMXNodeInstance::setParameter(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_SetParameter(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200 | 0 | 157,743 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)
{
int depth;
BUG_ON(path == NULL);
depth = path->p_depth;
/* zero-tree has no leaf blocks at all */
if (depth == 0)
return EXT_MAX_BLOCKS;
/* go to index block */
depth--;
while (depth >= 0) {
if (path[depth].p_idx !=
EXT_LAST_INDEX(path[depth].p_hdr))
return (ext4_lblk_t)
le32_to_cpu(path[depth].p_idx[1].ei_block);
depth--;
}
return EXT_MAX_BLOCKS;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <dmonakhov@openvz.org>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Cc: stable@vger.kernel.org
CWE ID: CWE-362 | 0 | 18,567 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int _converse(pam_handle_t *pamh, int nargs,
const struct pam_message **message,
struct pam_response **response) {
struct pam_conv *conv;
int retval;
retval = pam_get_item(pamh, PAM_CONV, (void *)&conv);
if (retval != PAM_SUCCESS) {
return retval;
}
return conv->conv(nargs, message, response, conv->appdata_ptr);
}
Commit Message: Do not leak file descriptor when doing exec
When opening a custom debug file, the descriptor would stay
open when calling exec and leak to the child process.
Make sure all files are opened with close-on-exec.
This fixes CVE-2019-12210.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.
CWE ID: CWE-200 | 0 | 89,793 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: std::unique_ptr<SymmetricKey> CopyDefaultPaddingKey() {
return SymmetricKey::Import(kPaddingKeyAlgorithm, (*GetPaddingKey())->key());
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <staphany@chromium.org>
> Reviewed-by: Victor Costan <pwnall@chromium.org>
> Reviewed-by: Marijn Kruisselbrink <mek@chromium.org>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <pwnall@chromium.org>
Commit-Queue: Staphany Park <staphany@chromium.org>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | 1 | 172,999 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: struct MACH0_(obj_t)* MACH0_(new_buf_steal)(RBuffer *buf, bool verbose) {
struct MACH0_(obj_t) *bin = R_NEW0 (struct MACH0_(obj_t));
if (!bin) {
return NULL;
}
bin->kv = sdb_new (NULL, "bin.mach0", 0);
bin->size = r_buf_size (buf);
bin->verbose = verbose;
bin->b = buf;
if (!init (bin)) {
return MACH0_(mach0_free)(bin);
}
return bin;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125 | 0 | 82,825 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: error::Error GLES2DecoderPassthroughImpl::DoUniformMatrix2x3fv(
GLint location,
GLsizei count,
GLboolean transpose,
const volatile GLfloat* value) {
api()->glUniformMatrix2x3fvFn(location, count, transpose,
const_cast<const GLfloat*>(value));
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | 0 | 142,163 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
{
BDRVQcowState *s = bs->opaque;
int flags = s->flags;
AES_KEY aes_encrypt_key;
AES_KEY aes_decrypt_key;
uint32_t crypt_method = 0;
QDict *options;
Error *local_err = NULL;
int ret;
/*
* Backing files are read-only which makes all of their metadata immutable,
* that means we don't have to worry about reopening them here.
*/
if (s->crypt_method) {
crypt_method = s->crypt_method;
memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
}
qcow2_close(bs);
bdrv_invalidate_cache(bs->file, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
memset(s, 0, sizeof(BDRVQcowState));
options = qdict_clone_shallow(bs->options);
ret = qcow2_open(bs, options, flags, &local_err);
if (local_err) {
error_setg(errp, "Could not reopen qcow2 layer: %s",
error_get_pretty(local_err));
error_free(local_err);
return;
} else if (ret < 0) {
error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
return;
}
QDECREF(options);
if (crypt_method) {
s->crypt_method = crypt_method;
memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
}
}
Commit Message:
CWE ID: CWE-476 | 0 | 16,773 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext3_incompat_features(sb))
return 0;
if (!ext4_has_feature_journal(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext3_ro_compat_features(sb))
return 0;
return 1;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <jack@suse.com>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-362 | 0 | 56,646 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
Commit Message: Fix issue #674 for hex strings.
CWE ID: CWE-674 | 0 | 64,599 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: invoke_NPN_InvalidateRect(PluginInstance *plugin, NPRect *invalidRect)
{
npw_return_if_fail(rpc_method_invoke_possible(g_rpc_connection));
int error = rpc_method_invoke(g_rpc_connection,
RPC_METHOD_NPN_INVALIDATE_RECT,
RPC_TYPE_NPW_PLUGIN_INSTANCE, plugin,
RPC_TYPE_NP_RECT, invalidRect,
RPC_TYPE_INVALID);
if (error != RPC_ERROR_NO_ERROR) {
npw_perror("NPN_InvalidateRect() invoke", error);
return;
}
error = rpc_method_wait_for_reply(g_rpc_connection, RPC_TYPE_INVALID);
if (error != RPC_ERROR_NO_ERROR) {
npw_perror("NPN_InvalidateRect() wait for reply", error);
return;
}
}
Commit Message: Support all the new variables added
CWE ID: CWE-264 | 0 | 27,127 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void SyncTest::TriggerCreateSyncedBookmarks() {
ASSERT_TRUE(ServerSupportsErrorTriggering());
std::string path = "chromiumsync/createsyncedbookmarks";
ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path));
ASSERT_EQ("Synced Bookmarks",
UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle()));
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | 0 | 105,071 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static const char *req_document_root(request_rec *r)
{
return ap_document_root(r);
}
Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org)
mod_lua: A maliciously crafted websockets PING after a script
calls r:wsupgrade() can cause a child process crash.
[Edward Lu <Chaosed0 gmail.com>]
Discovered by Guido Vranken <guidovranken gmail.com>
Submitted by: Edward Lu
Committed by: covener
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20 | 0 | 45,129 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: WORD32 ih264d_get_version(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
char version_string[MAXVERSION_STRLEN + 1];
UWORD32 version_string_len;
ivd_ctl_getversioninfo_ip_t *ps_ip;
ivd_ctl_getversioninfo_op_t *ps_op;
ps_ip = (ivd_ctl_getversioninfo_ip_t *)pv_api_ip;
ps_op = (ivd_ctl_getversioninfo_op_t *)pv_api_op;
UNUSED(dec_hdl);
ps_op->u4_error_code = IV_SUCCESS;
VERSION(version_string, CODEC_NAME, CODEC_RELEASE_TYPE, CODEC_RELEASE_VER,
CODEC_VENDOR);
if((WORD32)ps_ip->u4_version_buffer_size <= 0)
{
ps_op->u4_error_code = IH264D_VERS_BUF_INSUFFICIENT;
return (IV_FAIL);
}
version_string_len = strnlen(version_string, MAXVERSION_STRLEN) + 1;
if(ps_ip->u4_version_buffer_size >= version_string_len) //(WORD32)sizeof(sizeof(version_string)))
{
memcpy(ps_ip->pv_version_buffer, version_string, version_string_len);
ps_op->u4_error_code = IV_SUCCESS;
}
else
{
ps_op->u4_error_code = IH264D_VERS_BUF_INSUFFICIENT;
return IV_FAIL;
}
return (IV_SUCCESS);
}
Commit Message: Fixed error concealment when no MBs are decoded in the current pic
Bug: 29493002
Change-Id: I3fae547ddb0616b4e6579580985232bd3d65881e
CWE ID: CWE-284 | 0 | 158,317 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: GF_Err saio_Size(GF_Box *s)
{
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*)s;
if (ptr->aux_info_type || ptr->aux_info_type_parameter) {
ptr->flags |= 1;
}
if (ptr->offsets_large) {
ptr->version = 1;
}
if (ptr->flags & 1) ptr->size += 8;
ptr->size += 4;
switch (ptr->aux_info_type) {
case GF_ISOM_CENC_SCHEME:
case GF_ISOM_CBC_SCHEME:
case GF_ISOM_CENS_SCHEME:
case GF_ISOM_CBCS_SCHEME:
if (ptr->offsets_large) gf_free(ptr->offsets_large);
if (ptr->offsets) gf_free(ptr->offsets);
ptr->offsets_large = NULL;
ptr->offsets = NULL;
ptr->entry_count = 1;
break;
}
ptr->size += ((ptr->version==1) ? 8 : 4) * ptr->entry_count;
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | 0 | 80,374 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: char *stripoff_last_component(char *path)
{
char *p = path ? strrchr(path, '/') : NULL;
if (!p)
return NULL;
*p = '\0';
return p + 1;
}
Commit Message: chsh, chfn, vipw: fix filenames collision
The utils when compiled WITHOUT libuser then mkostemp()ing
"/etc/%s.XXXXXX" where the filename prefix is argv[0] basename.
An attacker could repeatedly execute the util with modified argv[0]
and after many many attempts mkostemp() may generate suffix which
makes sense. The result maybe temporary file with name like rc.status
ld.so.preload or krb5.keytab, etc.
Note that distros usually use libuser based ch{sh,fn} or stuff from
shadow-utils.
It's probably very minor security bug.
Addresses: CVE-2015-5224
Signed-off-by: Karel Zak <kzak@redhat.com>
CWE ID: CWE-264 | 0 | 74,114 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static inline char *get_default_content_type(uint prefix_len, uint *len TSRMLS_DC)
{
char *mimetype, *charset, *content_type;
uint mimetype_len, charset_len;
if (SG(default_mimetype)) {
mimetype = SG(default_mimetype);
mimetype_len = strlen(SG(default_mimetype));
} else {
mimetype = SAPI_DEFAULT_MIMETYPE;
mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1;
}
if (SG(default_charset)) {
charset = SG(default_charset);
charset_len = strlen(SG(default_charset));
} else {
charset = SAPI_DEFAULT_CHARSET;
charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1;
}
if (*charset && strncasecmp(mimetype, "text/", 5) == 0) {
char *p;
*len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len;
content_type = (char*)emalloc(*len + 1);
p = content_type + prefix_len;
memcpy(p, mimetype, mimetype_len);
p += mimetype_len;
memcpy(p, "; charset=", sizeof("; charset=") - 1);
p += sizeof("; charset=") - 1;
memcpy(p, charset, charset_len + 1);
} else {
*len = prefix_len + mimetype_len;
content_type = (char*)emalloc(*len + 1);
memcpy(content_type + prefix_len, mimetype, mimetype_len + 1);
}
return content_type;
}
Commit Message: Update header handling to RFC 7230
CWE ID: CWE-79 | 0 | 56,262 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_Int i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_Int bit_width = pitch * 8;
FT_Int bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_Int shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_Int count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
Commit Message:
CWE ID: CWE-119 | 1 | 164,850 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: ResourcePtr<ScriptResource> ResourceFetcher::fetchScript(FetchRequest& request)
{
return toScriptResource(requestResource(Resource::Script, request));
}
Commit Message: Enforce SVG image security rules
SVG images have unique security rules that prevent them from loading
any external resources. This patch enforces these rules in
ResourceFetcher::canRequest for all non-data-uri resources. This locks
down our SVG resource handling and fixes two security bugs.
In the case of SVG images that reference other images, we had a bug
where a cached subresource would be used directly from the cache.
This has been fixed because the canRequest check occurs before we use
cached resources.
In the case of SVG images that use CSS imports, we had a bug where
imports were blindly requested. This has been fixed by stopping all
non-data-uri requests in SVG images.
With this patch we now match Gecko's behavior on both testcases.
BUG=380885, 382296
Review URL: https://codereview.chromium.org/320763002
git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | 0 | 121,244 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: sg_add_device(struct device *cl_dev, struct class_interface *cl_intf)
{
struct scsi_device *scsidp = to_scsi_device(cl_dev->parent);
struct gendisk *disk;
Sg_device *sdp = NULL;
struct cdev * cdev = NULL;
int error;
unsigned long iflags;
disk = alloc_disk(1);
if (!disk) {
pr_warn("%s: alloc_disk failed\n", __func__);
return -ENOMEM;
}
disk->major = SCSI_GENERIC_MAJOR;
error = -ENOMEM;
cdev = cdev_alloc();
if (!cdev) {
pr_warn("%s: cdev_alloc failed\n", __func__);
goto out;
}
cdev->owner = THIS_MODULE;
cdev->ops = &sg_fops;
sdp = sg_alloc(disk, scsidp);
if (IS_ERR(sdp)) {
pr_warn("%s: sg_alloc failed\n", __func__);
error = PTR_ERR(sdp);
goto out;
}
error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1);
if (error)
goto cdev_add_err;
sdp->cdev = cdev;
if (sg_sysfs_valid) {
struct device *sg_class_member;
sg_class_member = device_create(sg_sysfs_class, cl_dev->parent,
MKDEV(SCSI_GENERIC_MAJOR,
sdp->index),
sdp, "%s", disk->disk_name);
if (IS_ERR(sg_class_member)) {
pr_err("%s: device_create failed\n", __func__);
error = PTR_ERR(sg_class_member);
goto cdev_add_err;
}
error = sysfs_create_link(&scsidp->sdev_gendev.kobj,
&sg_class_member->kobj, "generic");
if (error)
pr_err("%s: unable to make symlink 'generic' back "
"to sg%d\n", __func__, sdp->index);
} else
pr_warn("%s: sg_sys Invalid\n", __func__);
sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d "
"type %d\n", sdp->index, scsidp->type);
dev_set_drvdata(cl_dev, sdp);
return 0;
cdev_add_err:
write_lock_irqsave(&sg_index_lock, iflags);
idr_remove(&sg_index_idr, sdp->index);
write_unlock_irqrestore(&sg_index_lock, iflags);
kfree(sdp);
out:
put_disk(disk);
if (cdev)
cdev_del(cdev);
return error;
}
Commit Message: sg_start_req(): make sure that there's not too many elements in iovec
unfortunately, allowing an arbitrary 16bit value means a possibility of
overflow in the calculation of total number of pages in bio_map_user_iov() -
we rely on there being no more than PAGE_SIZE members of sum in the
first loop there. If that sum wraps around, we end up allocating
too small array of pointers to pages and it's easy to overflow it in
the second loop.
X-Coverup: TINC (and there's no lumber cartel either)
Cc: stable@vger.kernel.org # way, way back
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-189 | 0 | 42,256 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: SimpleSwapPromiseMonitor(LayerTreeHost* layer_tree_host,
LayerTreeHostImpl* layer_tree_host_impl,
int* set_needs_commit_count,
int* set_needs_redraw_count)
: SwapPromiseMonitor(
(layer_tree_host ? layer_tree_host->GetSwapPromiseManager()
: nullptr),
layer_tree_host_impl),
set_needs_commit_count_(set_needs_commit_count) {}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
TBR=danakj@chromium.org, creis@chromium.org
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362 | 0 | 137,468 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void bta_av_rc_remote_cmd(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) {
tBTA_AV_RCB* p_rcb;
if (p_cb->features & BTA_AV_FEAT_RCCT) {
if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) {
p_rcb = &p_cb->rcb[p_data->hdr.layer_specific];
if (p_rcb->status & BTA_AV_RC_CONN_MASK) {
AVRC_PassCmd(p_rcb->handle, p_data->api_remote_cmd.label,
&p_data->api_remote_cmd.msg);
}
}
}
}
Commit Message: Check packet length in bta_av_proc_meta_cmd
Bug: 111893951
Test: manual - connect A2DP
Change-Id: Ibbf347863dfd29ea3385312e9dde1082bc90d2f3
(cherry picked from commit ed51887f921263219bcd2fbf6650ead5ec8d334e)
CWE ID: CWE-125 | 0 | 162,864 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void Browser::OpenURLOffTheRecord(Profile* profile, const GURL& url) {
Browser* browser = GetOrCreateTabbedBrowser(
profile->GetOffTheRecordProfile());
browser->AddSelectedTabWithURL(url, PageTransition::LINK);
browser->window()->Show();
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | 0 | 97,324 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static bool HasPort(const std::string& original_text,
const url_parse::Component& scheme_component) {
size_t port_start = scheme_component.end() + 1;
size_t port_end = port_start;
while ((port_end < original_text.length()) &&
!url_parse::IsAuthorityTerminator(original_text[port_end]))
++port_end;
if (port_end == port_start)
return false;
for (size_t i = port_start; i < port_end; ++i) {
if (!IsAsciiDigit(original_text[i]))
return false;
}
return true;
}
Commit Message: Be a little more careful whether something is an URL or a file path.
BUG=72492
Review URL: http://codereview.chromium.org/7572046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | 0 | 99,443 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void js_pushglobal(js_State *J)
{
js_pushobject(J, J->G);
}
Commit Message:
CWE ID: CWE-119 | 0 | 13,459 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: ar6000_stop_endpoint(struct net_device *dev, bool keepprofile, bool getdbglogs)
{
struct ar6_softc *ar = (struct ar6_softc *)ar6k_priv(dev);
/* Stop the transmit queues */
netif_stop_queue(dev);
/* Disable the target and the interrupts associated with it */
if (ar->arWmiReady == true)
{
if (!bypasswmi)
{
bool disconnectIssued;
disconnectIssued = (ar->arConnected) || (ar->arConnectPending);
ar6000_disconnect(ar);
if (!keepprofile) {
ar6000_init_profile_info(ar);
}
A_UNTIMEOUT(&ar->disconnect_timer);
if (getdbglogs) {
ar6000_dbglog_get_debug_logs(ar);
}
ar->arWmiReady = false;
wmi_shutdown(ar->arWmi);
ar->arWmiEnabled = false;
ar->arWmi = NULL;
/*
* After wmi_shudown all WMI events will be dropped.
* We need to cleanup the buffers allocated in AP mode
* and give disconnect notification to stack, which usually
* happens in the disconnect_event.
* Simulate the disconnect_event by calling the function directly.
* Sometimes disconnect_event will be received when the debug logs
* are collected.
*/
if (disconnectIssued) {
if(ar->arNetworkType & AP_NETWORK) {
ar6000_disconnect_event(ar, DISCONNECT_CMD, bcast_mac, 0, NULL, 0);
} else {
ar6000_disconnect_event(ar, DISCONNECT_CMD, ar->arBssid, 0, NULL, 0);
}
}
ar->user_savedkeys_stat = USER_SAVEDKEYS_STAT_INIT;
ar->user_key_ctrl = 0;
}
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): WMI stopped\n", __func__));
}
else
{
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): WMI not ready 0x%lx 0x%lx\n",
__func__, (unsigned long) ar, (unsigned long) ar->arWmi));
/* Shut down WMI if we have started it */
if(ar->arWmiEnabled == true)
{
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("%s(): Shut down WMI\n", __func__));
wmi_shutdown(ar->arWmi);
ar->arWmiEnabled = false;
ar->arWmi = NULL;
}
}
if (ar->arHtcTarget != NULL) {
#ifdef EXPORT_HCI_BRIDGE_INTERFACE
if (NULL != ar6kHciTransCallbacks.cleanupTransport) {
ar6kHciTransCallbacks.cleanupTransport(NULL);
}
#else
if (NULL != ar->exitCallback) {
struct ar3k_config_info ar3kconfig;
int status;
A_MEMZERO(&ar3kconfig,sizeof(ar3kconfig));
ar6000_set_default_ar3kconfig(ar, (void *)&ar3kconfig);
status = ar->exitCallback(&ar3kconfig);
if (0 != status) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("Failed to reset AR3K baud rate! \n"));
}
}
if (setuphci)
ar6000_cleanup_hci(ar);
#endif
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Shutting down HTC .... \n"));
/* stop HTC */
HTCStop(ar->arHtcTarget);
}
if (resetok) {
/* try to reset the device if we can
* The driver may have been configure NOT to reset the target during
* a debug session */
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Attempting to reset target on instance destroy.... \n"));
if (ar->arHifDevice != NULL) {
bool coldReset = (ar->arTargetType == TARGET_TYPE_AR6003) ? true: false;
ar6000_reset_device(ar->arHifDevice, ar->arTargetType, true, coldReset);
}
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,(" Host does not want target reset. \n"));
}
/* Done with cookies */
ar6000_cookie_cleanup(ar);
/* cleanup any allocated AMSDU buffers */
ar6000_cleanup_amsdu_rxbufs(ar);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <nhorman@tuxdriver.com>
CC: Karsten Keil <isdn@linux-pingi.de>
CC: "David S. Miller" <davem@davemloft.net>
CC: Jay Vosburgh <fubar@us.ibm.com>
CC: Andy Gospodarek <andy@greyhouse.net>
CC: Patrick McHardy <kaber@trash.net>
CC: Krzysztof Halasa <khc@pm.waw.pl>
CC: "John W. Linville" <linville@tuxdriver.com>
CC: Greg Kroah-Hartman <gregkh@suse.de>
CC: Marcel Holtmann <marcel@holtmann.org>
CC: Johannes Berg <johannes@sipsolutions.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-264 | 0 | 24,225 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int nfs4_lookup_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fsinfo *info, rpc_authflavor_t flavor)
{
struct rpc_auth_create_args auth_args = {
.pseudoflavor = flavor,
};
struct rpc_auth *auth;
int ret;
auth = rpcauth_create(&auth_args, server->client);
if (IS_ERR(auth)) {
ret = -EACCES;
goto out;
}
ret = nfs4_lookup_root(server, fhandle, info);
out:
return ret;
}
Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client
---Steps to Reproduce--
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
<nfs-client>
# mount -t nfs nfs-server:/nfs/ /mnt/
# ll /mnt/*/
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
# service nfs restart
<nfs-client>
# ll /mnt/*/ --->>>>> oops here
[ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null)
[ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0
[ 5123.104131] Oops: 0000 [#1]
[ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd]
[ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214
[ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014
[ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000
[ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246
[ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240
[ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908
[ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000
[ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800
[ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240
[ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000
[ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0
[ 5123.112888] Stack:
[ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000
[ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6
[ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800
[ 5123.115264] Call Trace:
[ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4]
[ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4]
[ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4]
[ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0
[ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70
[ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33
[ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.122308] RSP <ffff88005877fdb8>
[ 5123.122942] CR2: 0000000000000000
Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops")
Cc: stable@vger.kernel.org # v3.13+
Signed-off-by: Kinglong Mee <kinglongmee@gmail.com>
Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com>
CWE ID: | 0 | 57,163 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: byte(const u32 x, const unsigned n)
{
return x >> (n << 3);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
CWE ID: CWE-264 | 0 | 47,333 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void sapi_send_headers_free(TSRMLS_D)
{
if (SG(sapi_headers).http_status_line) {
efree(SG(sapi_headers).http_status_line);
SG(sapi_headers).http_status_line = NULL;
}
}
Commit Message: Update header handling to RFC 7230
CWE ID: CWE-79 | 0 | 56,294 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
unsigned int flags)
{
struct fuse_file *ff = file->private_data;
struct fuse_conn *fc = ff->fc;
struct fuse_ioctl_in inarg = {
.fh = ff->fh,
.cmd = cmd,
.arg = arg,
.flags = flags
};
struct fuse_ioctl_out outarg;
struct fuse_req *req = NULL;
struct page **pages = NULL;
struct page *iov_page = NULL;
struct iovec *in_iov = NULL, *out_iov = NULL;
unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
size_t in_size, out_size, transferred;
int err;
/* assume all the iovs returned by client always fits in a page */
BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
err = -ENOMEM;
pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
iov_page = alloc_page(GFP_KERNEL);
if (!pages || !iov_page)
goto out;
/*
* If restricted, initialize IO parameters as encoded in @cmd.
* RETRY from server is not allowed.
*/
if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
struct iovec *iov = page_address(iov_page);
iov->iov_base = (void __user *)arg;
iov->iov_len = _IOC_SIZE(cmd);
if (_IOC_DIR(cmd) & _IOC_WRITE) {
in_iov = iov;
in_iovs = 1;
}
if (_IOC_DIR(cmd) & _IOC_READ) {
out_iov = iov;
out_iovs = 1;
}
}
retry:
inarg.in_size = in_size = iov_length(in_iov, in_iovs);
inarg.out_size = out_size = iov_length(out_iov, out_iovs);
/*
* Out data can be used either for actual out data or iovs,
* make sure there always is at least one page.
*/
out_size = max_t(size_t, out_size, PAGE_SIZE);
max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
/* make sure there are enough buffer pages and init request with them */
err = -ENOMEM;
if (max_pages > FUSE_MAX_PAGES_PER_REQ)
goto out;
while (num_pages < max_pages) {
pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[num_pages])
goto out;
num_pages++;
}
req = fuse_get_req(fc);
if (IS_ERR(req)) {
err = PTR_ERR(req);
req = NULL;
goto out;
}
memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
req->num_pages = num_pages;
/* okay, let's send it to the client */
req->in.h.opcode = FUSE_IOCTL;
req->in.h.nodeid = ff->nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
if (in_size) {
req->in.numargs++;
req->in.args[1].size = in_size;
req->in.argpages = 1;
err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
false);
if (err)
goto out;
}
req->out.numargs = 2;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
req->out.args[1].size = out_size;
req->out.argpages = 1;
req->out.argvar = 1;
fuse_request_send(fc, req);
err = req->out.h.error;
transferred = req->out.args[1].size;
fuse_put_request(fc, req);
req = NULL;
if (err)
goto out;
/* did it ask for retry? */
if (outarg.flags & FUSE_IOCTL_RETRY) {
char *vaddr;
/* no retry if in restricted mode */
err = -EIO;
if (!(flags & FUSE_IOCTL_UNRESTRICTED))
goto out;
in_iovs = outarg.in_iovs;
out_iovs = outarg.out_iovs;
/*
* Make sure things are in boundary, separate checks
* are to protect against overflow.
*/
err = -ENOMEM;
if (in_iovs > FUSE_IOCTL_MAX_IOV ||
out_iovs > FUSE_IOCTL_MAX_IOV ||
in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
goto out;
vaddr = kmap_atomic(pages[0], KM_USER0);
err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr,
transferred, in_iovs + out_iovs,
(flags & FUSE_IOCTL_COMPAT) != 0);
kunmap_atomic(vaddr, KM_USER0);
if (err)
goto out;
in_iov = page_address(iov_page);
out_iov = in_iov + in_iovs;
goto retry;
}
err = -EIO;
if (transferred > inarg.out_size)
goto out;
err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
out:
if (req)
fuse_put_request(fc, req);
if (iov_page)
__free_page(iov_page);
while (num_pages)
__free_page(pages[--num_pages]);
kfree(pages);
return err ? err : outarg.result;
}
Commit Message: fuse: verify ioctl retries
Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY
doesn't overflow iov_length().
Signed-off-by: Miklos Szeredi <mszeredi@suse.cz>
CC: Tejun Heo <tj@kernel.org>
CC: <stable@kernel.org> [2.6.31+]
CWE ID: CWE-119 | 1 | 165,906 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: ServiceWorkerLazyBackgroundTest()
: ServiceWorkerTest(
version_info::Channel::UNKNOWN) {}
Commit Message: Skip Service workers in requests for mime handler plugins
BUG=808838
TEST=./browser_tests --gtest_filter=*/ServiceWorkerTest.MimeHandlerView*
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: I82e75c200091babbab648a04232db47e2938d914
Reviewed-on: https://chromium-review.googlesource.com/914150
Commit-Queue: Rob Wu <rob@robwu.nl>
Reviewed-by: Istiaque Ahmed <lazyboy@chromium.org>
Reviewed-by: Matt Falkenhagen <falken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#537386}
CWE ID: CWE-20 | 0 | 147,446 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
struct xfrm_algo_desc *(*get_byname)(const char *, int),
struct nlattr *rta)
{
struct xfrm_algo *p, *ualg;
struct xfrm_algo_desc *algo;
if (!rta)
return 0;
ualg = nla_data(rta);
algo = get_byname(ualg->alg_name, 1);
if (!algo)
return -ENOSYS;
*props = algo->desc.sadb_alg_id;
p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
if (!p)
return -ENOMEM;
strcpy(p->alg_name, algo->name);
*algpp = p;
return 0;
}
Commit Message: xfrm_user: return error pointer instead of NULL
When dump_one_state() returns an error, e.g. because of a too small
buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL
instead of an error pointer. But its callers expect an error pointer
and therefore continue to operate on a NULL skbuff.
This could lead to a privilege escalation (execution of user code in
kernel context) if the attacker has CAP_NET_ADMIN and is able to map
address 0.
Signed-off-by: Mathias Krause <minipli@googlemail.com>
Acked-by: Steffen Klassert <steffen.klassert@secunet.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: | 0 | 33,086 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
u64 nr, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
struct perf_event *event;
struct hlist_node *node;
struct hlist_head *head;
rcu_read_lock();
head = find_swevent_head_rcu(swhash, type, event_id);
if (!head)
goto end;
hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
if (perf_swevent_match(event, type, event_id, data, regs))
perf_swevent_event(event, nr, nmi, data, regs);
}
end:
rcu_read_unlock();
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: CWE-399 | 1 | 165,828 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int packet_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &packet_seq_ops,
sizeof(struct seq_net_private));
}
Commit Message: af_packet: prevent information leak
In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)
added a small information leak.
Add padding field and make sure its zeroed before copy to user.
Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com>
CC: Patrick McHardy <kaber@trash.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-264 | 0 | 26,573 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: decode_sattr3(__be32 *p, struct iattr *iap)
{
u32 tmp;
iap->ia_valid = 0;
if (*p++) {
iap->ia_valid |= ATTR_MODE;
iap->ia_mode = ntohl(*p++);
}
if (*p++) {
iap->ia_uid = make_kuid(&init_user_ns, ntohl(*p++));
if (uid_valid(iap->ia_uid))
iap->ia_valid |= ATTR_UID;
}
if (*p++) {
iap->ia_gid = make_kgid(&init_user_ns, ntohl(*p++));
if (gid_valid(iap->ia_gid))
iap->ia_valid |= ATTR_GID;
}
if (*p++) {
u64 newsize;
iap->ia_valid |= ATTR_SIZE;
p = xdr_decode_hyper(p, &newsize);
iap->ia_size = min_t(u64, newsize, NFS_OFFSET_MAX);
}
if ((tmp = ntohl(*p++)) == 1) { /* set to server time */
iap->ia_valid |= ATTR_ATIME;
} else if (tmp == 2) { /* set to client time */
iap->ia_valid |= ATTR_ATIME | ATTR_ATIME_SET;
iap->ia_atime.tv_sec = ntohl(*p++);
iap->ia_atime.tv_nsec = ntohl(*p++);
}
if ((tmp = ntohl(*p++)) == 1) { /* set to server time */
iap->ia_valid |= ATTR_MTIME;
} else if (tmp == 2) { /* set to client time */
iap->ia_valid |= ATTR_MTIME | ATTR_MTIME_SET;
iap->ia_mtime.tv_sec = ntohl(*p++);
iap->ia_mtime.tv_nsec = ntohl(*p++);
}
return p;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | 0 | 65,252 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent_header *eh;
int depth = ext_depth(inode);
struct ext4_extent *ex;
__le32 border;
int k, err = 0;
eh = path[depth].p_hdr;
ex = path[depth].p_ext;
if (unlikely(ex == NULL || eh == NULL)) {
EXT4_ERROR_INODE(inode,
"ex %p == NULL or eh %p == NULL", ex, eh);
return -EIO;
}
if (depth == 0) {
/* there is no tree at all */
return 0;
}
if (ex != EXT_FIRST_EXTENT(eh)) {
/* we correct tree if first leaf got modified only */
return 0;
}
/*
* TODO: we need correction if border is smaller than current one
*/
k = depth - 1;
border = path[depth].p_ext->ee_block;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
return err;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
return err;
while (k--) {
/* change all left-side indexes */
if (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))
break;
err = ext4_ext_get_access(handle, inode, path + k);
if (err)
break;
path[k].p_idx->ei_block = border;
err = ext4_ext_dirty(handle, inode, path + k);
if (err)
break;
}
return err;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <dmonakhov@openvz.org>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
Cc: stable@vger.kernel.org
CWE ID: CWE-362 | 0 | 18,550 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static struct nl_mmap_hdr *netlink_mmap_hdr(struct sk_buff *skb)
{
return (struct nl_mmap_hdr *)(skb->head - NL_MMAP_HDRLEN);
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <davem@davemloft.net>
Suggested-by: Eric Dumazet <eric.dumazet@gmail.com>
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20 | 0 | 40,541 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int has_buffered_data(request_rec *r)
{
apr_bucket_brigade *bb;
apr_off_t len;
apr_status_t rv;
int result;
bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
rv = ap_get_brigade(r->connection->input_filters, bb, AP_MODE_SPECULATIVE,
APR_NONBLOCK_READ, 1);
result = rv == APR_SUCCESS
&& apr_brigade_length(bb, 1, &len) == APR_SUCCESS
&& len > 0;
apr_brigade_destroy(bb);
return result;
}
Commit Message: modssl: reset client-verify state when renegotiation is aborted
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1750779 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-284 | 0 | 52,454 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void pdf_xref_store_unsaved_signature(fz_context *ctx, pdf_document *doc, pdf_obj *field, pdf_signer *signer)
{
pdf_xref *xref = &doc->xref_sections[0];
pdf_unsaved_sig *unsaved_sig;
/* Record details within the document structure so that contents
* and byte_range can be updated with their correct values at
* saving time */
unsaved_sig = fz_malloc_struct(ctx, pdf_unsaved_sig);
unsaved_sig->field = pdf_keep_obj(ctx, field);
unsaved_sig->signer = pdf_keep_signer(ctx, signer);
unsaved_sig->next = NULL;
if (xref->unsaved_sigs_end == NULL)
xref->unsaved_sigs_end = &xref->unsaved_sigs;
*xref->unsaved_sigs_end = unsaved_sig;
xref->unsaved_sigs_end = &unsaved_sig->next;
}
Commit Message:
CWE ID: CWE-119 | 0 | 16,732 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
PGconn *pgsql;
smart_str str = {0};
zval *args;
uint32_t i;
int connect_type = 0;
PGresult *pg_result;
args = (zval *)safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval), 0);
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
|| zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
efree(args);
WRONG_PARAM_COUNT;
}
smart_str_appends(&str, "pgsql");
for (i = 0; i < ZEND_NUM_ARGS(); i++) {
/* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections
* can re-use this connection. Bug #39979
*/
if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE(args[i]) == IS_LONG) {
if (Z_LVAL(args[1]) == PGSQL_CONNECT_FORCE_NEW) {
continue;
} else if (Z_LVAL(args[1]) & PGSQL_CONNECT_FORCE_NEW) {
smart_str_append_long(&str, Z_LVAL(args[1]) ^ PGSQL_CONNECT_FORCE_NEW);
}
}
convert_to_string_ex(&args[i]);
smart_str_appendc(&str, '_');
smart_str_appendl(&str, Z_STRVAL(args[i]), Z_STRLEN(args[i]));
}
smart_str_0(&str);
if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
connstring = Z_STRVAL(args[0]);
} else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
connstring = Z_STRVAL(args[0]);
convert_to_long_ex(&args[1]);
connect_type = (int)Z_LVAL(args[1]);
} else {
host = Z_STRVAL(args[0]);
port = Z_STRVAL(args[1]);
dbname = Z_STRVAL(args[ZEND_NUM_ARGS()-1]);
switch (ZEND_NUM_ARGS()) {
case 5:
tty = Z_STRVAL(args[3]);
/* fall through */
case 4:
options = Z_STRVAL(args[2]);
break;
}
}
efree(args);
if (persistent && PGG(allow_persistent)) {
zend_resource *le;
/* try to find if we already have this link in our persistent list */
if ((le = zend_hash_find_ptr(&EG(persistent_list), str.s)) == NULL) { /* we don't */
zend_resource new_le;
if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) {
php_error_docref(NULL, E_WARNING,
"Cannot create new link. Too many open links (%pd)", PGG(num_links));
goto err;
}
if (PGG(max_persistent) != -1 && PGG(num_persistent) >= PGG(max_persistent)) {
php_error_docref(NULL, E_WARNING,
"Cannot create new link. Too many open persistent links (%pd)", PGG(num_persistent));
goto err;
}
/* create the link */
if (connstring) {
pgsql = PQconnectdb(connstring);
} else {
pgsql = PQsetdb(host, port, options, tty, dbname);
}
if (pgsql == NULL || PQstatus(pgsql) == CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
/* hash it up */
new_le.type = le_plink;
new_le.ptr = pgsql;
if (zend_hash_str_update_mem(&EG(persistent_list), str.s->val, str.s->len, &new_le, sizeof(zend_resource)) == NULL) {
goto err;
}
PGG(num_links)++;
PGG(num_persistent)++;
} else { /* we do */
if (le->type != le_plink) {
RETURN_FALSE;
}
/* ensure that the link did not die */
if (PGG(auto_reset_persistent) & 1) {
/* need to send & get something from backend to
make sure we catch CONNECTION_BAD every time */
PGresult *pg_result;
pg_result = PQexec(le->ptr, "select 1");
PQclear(pg_result);
}
if (PQstatus(le->ptr) == CONNECTION_BAD) { /* the link died */
if (le->ptr == NULL) {
if (connstring) {
le->ptr = PQconnectdb(connstring);
} else {
le->ptr = PQsetdb(host,port,options,tty,dbname);
}
}
else {
PQreset(le->ptr);
}
if (le->ptr == NULL || PQstatus(le->ptr) == CONNECTION_BAD) {
php_error_docref(NULL, E_WARNING,"PostgreSQL link lost, unable to reconnect");
zend_hash_del(&EG(persistent_list), str.s);
goto err;
}
}
pgsql = (PGconn *) le->ptr;
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
#else
if (atof(PG_VERSION) >= 7.2) {
#endif
pg_result = PQexec(pgsql, "RESET ALL;");
PQclear(pg_result);
}
}
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
} else { /* Non persistent connection */
zend_resource *index_ptr, new_index_ptr;
/* first we check the hash for the hashed_details key. if it exists,
* it should point us to the right offset where the actual pgsql link sits.
* if it doesn't, open a new pgsql link, add it to the resource list,
* and add a pointer to it with hashed_details as the key.
*/
if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
&& (index_ptr = zend_hash_find_ptr(&EG(regular_list), str.s)) != NULL) {
zend_resource *link;
if (index_ptr->type != le_index_ptr) {
RETURN_FALSE;
}
link = (zend_resource *)index_ptr->ptr;
if (link->ptr && (link->type == le_link || link->type == le_plink)) {
php_pgsql_set_default_link(link);
GC_REFCOUNT(link)++;
RETVAL_RES(link);
goto cleanup;
} else {
zend_hash_del(&EG(regular_list), str.s);
}
}
if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) {
php_error_docref(NULL, E_WARNING, "Cannot create new link. Too many open links (%pd)", PGG(num_links));
goto err;
}
/* Non-blocking connect */
if (connect_type & PGSQL_CONNECT_ASYNC) {
if (connstring) {
pgsql = PQconnectStart(connstring);
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
} else {
php_error_docref(NULL, E_WARNING, "Connection string required for async connections");
goto err;
}
} else {
if (connstring) {
pgsql = PQconnectdb(connstring);
} else {
pgsql = PQsetdb(host,port,options,tty,dbname);
}
if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
if (pgsql) {
PQfinish(pgsql);
}
goto err;
}
}
/* add it to the list */
ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
/* add it to the hash */
new_index_ptr.ptr = (void *) Z_RES_P(return_value);
new_index_ptr.type = le_index_ptr;
if (zend_hash_update_mem(&EG(regular_list), str.s, (void *) &new_index_ptr, sizeof(zend_resource)) == NULL) {
goto err;
}
PGG(num_links)++;
}
/* set notice processor */
if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RES_HANDLE_P(return_value));
}
php_pgsql_set_default_link(Z_RES_P(return_value));
cleanup:
smart_str_free(&str);
return;
err:
smart_str_free(&str);
RETURN_FALSE;
}
/* }}} */
#if 0
/* {{{ php_pgsql_get_default_link
*/
static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
{
if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
ht = 0;
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
return PGG(default_link);
}
/* }}} */
#endif
/* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
Open a PostgreSQL connection */
PHP_FUNCTION(pg_connect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
}
/* }}} */
/* {{{ proto resource pg_connect_poll(resource connection)
Poll the status of an in-progress async PostgreSQL connection attempt*/
PHP_FUNCTION(pg_connect_poll)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) {
return;
}
if (pgsql_link == NULL) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
ret = PQconnectPoll(pgsql);
RETURN_LONG(ret);
}
/* }}} */
/* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
Open a persistent PostgreSQL connection */
PHP_FUNCTION(pg_pconnect)
{
php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
}
/* }}} */
/* {{{ proto bool pg_close([resource connection])
Close a PostgreSQL connection */
PHP_FUNCTION(pg_close)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (id==-1) { /* explicit resource number */
zend_list_close(Z_RES_P(pgsql_link));
}
if (id!=-1
|| (pgsql_link && Z_RES_P(pgsql_link) == PGG(default_link))) {
zend_list_close(PGG(default_link));
PGG(default_link) = NULL;
}
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DBNAME 1
#define PHP_PG_ERROR_MESSAGE 2
#define PHP_PG_OPTIONS 3
#define PHP_PG_PORT 4
#define PHP_PG_TTY 5
#define PHP_PG_HOST 6
#define PHP_PG_VERSION 7
/* {{{ php_pgsql_get_link_info
*/
static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
char *msgbuf;
char *result;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
switch(entry_type) {
case PHP_PG_DBNAME:
result = PQdb(pgsql);
break;
case PHP_PG_ERROR_MESSAGE:
result = PQErrorMessageTrim(pgsql, &msgbuf);
RETVAL_STRING(result);
efree(result);
return;
case PHP_PG_OPTIONS:
result = PQoptions(pgsql);
break;
case PHP_PG_PORT:
result = PQport(pgsql);
break;
case PHP_PG_TTY:
result = PQtty(pgsql);
break;
case PHP_PG_HOST:
result = PQhost(pgsql);
break;
case PHP_PG_VERSION:
array_init(return_value);
add_assoc_string(return_value, "client", PG_VERSION);
#if HAVE_PQPROTOCOLVERSION
add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
#if HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3) {
/* 8.0 or grater supports protorol version 3 */
char *tmp;
add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"));
tmp = (char*)PQparameterStatus(pgsql, "server_encoding");
add_assoc_string(return_value, "server_encoding", tmp);
tmp = (char*)PQparameterStatus(pgsql, "client_encoding");
add_assoc_string(return_value, "client_encoding", tmp);
tmp = (char*)PQparameterStatus(pgsql, "is_superuser");
add_assoc_string(return_value, "is_superuser", tmp);
tmp = (char*)PQparameterStatus(pgsql, "session_authorization");
add_assoc_string(return_value, "session_authorization", tmp);
tmp = (char*)PQparameterStatus(pgsql, "DateStyle");
add_assoc_string(return_value, "DateStyle", tmp);
tmp = (char*)PQparameterStatus(pgsql, "IntervalStyle");
add_assoc_string(return_value, "IntervalStyle", tmp ? tmp : "");
tmp = (char*)PQparameterStatus(pgsql, "TimeZone");
add_assoc_string(return_value, "TimeZone", tmp ? tmp : "");
tmp = (char*)PQparameterStatus(pgsql, "integer_datetimes");
add_assoc_string(return_value, "integer_datetimes", tmp ? tmp : "");
tmp = (char*)PQparameterStatus(pgsql, "standard_conforming_strings");
add_assoc_string(return_value, "standard_conforming_strings", tmp ? tmp : "");
tmp = (char*)PQparameterStatus(pgsql, "application_name");
add_assoc_string(return_value, "application_name", tmp ? tmp : "");
}
#endif
#endif
return;
default:
RETURN_FALSE;
}
if (result) {
RETURN_STRING(result);
} else {
RETURN_EMPTY_STRING();
}
}
/* }}} */
/* {{{ proto string pg_dbname([resource connection])
Get the database name */
PHP_FUNCTION(pg_dbname)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
}
/* }}} */
/* {{{ proto string pg_last_error([resource connection])
Get the error message string */
PHP_FUNCTION(pg_last_error)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
}
/* }}} */
/* {{{ proto string pg_options([resource connection])
Get the options associated with the connection */
PHP_FUNCTION(pg_options)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
}
/* }}} */
/* {{{ proto int pg_port([resource connection])
Return the port number associated with the connection */
PHP_FUNCTION(pg_port)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
}
/* }}} */
/* {{{ proto string pg_tty([resource connection])
Return the tty name associated with the connection */
PHP_FUNCTION(pg_tty)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
}
/* }}} */
/* {{{ proto string pg_host([resource connection])
Returns the host name associated with the connection */
PHP_FUNCTION(pg_host)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
}
/* }}} */
/* {{{ proto array pg_version([resource connection])
Returns an array with client, protocol and server version (when available) */
PHP_FUNCTION(pg_version)
{
php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
}
/* }}} */
#if HAVE_PQPARAMETERSTATUS
/* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
Returns the value of a server parameter */
PHP_FUNCTION(pg_parameter_status)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
char *param;
size_t len;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "rs", &pgsql_link, ¶m, &len) == SUCCESS) {
id = -1;
} else if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", ¶m, &len) == SUCCESS) {
pgsql_link = NULL;
id = FETCH_DEFAULT_LINK();
} else {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
param = (char*)PQparameterStatus(pgsql, param);
if (param) {
RETURN_STRING(param);
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
/* {{{ proto bool pg_ping([resource connection])
Ping database. If connection is bad, try to reconnect. */
PHP_FUNCTION(pg_ping)
{
zval *pgsql_link;
int id;
PGconn *pgsql;
PGresult *res;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == SUCCESS) {
id = -1;
} else {
pgsql_link = NULL;
id = FETCH_DEFAULT_LINK();
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* ping connection */
res = PQexec(pgsql, "SELECT 1;");
PQclear(res);
/* check status. */
if (PQstatus(pgsql) == CONNECTION_OK)
RETURN_TRUE;
/* reset connection if it's broken */
PQreset(pgsql);
if (PQstatus(pgsql) == CONNECTION_OK) {
RETURN_TRUE;
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto resource pg_query([resource connection,] string query)
Execute a query */
PHP_FUNCTION(pg_query)
{
zval *pgsql_link = NULL;
char *query;
int id = -1, argc = ZEND_NUM_ARGS();
size_t query_len;
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &query, &query_len) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQexec(pgsql, query);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexec(pgsql, query);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
/* {{{ _php_pgsql_free_params */
static void _php_pgsql_free_params(char **params, int num_params)
{
if (num_params > 0) {
int i;
for (i = 0; i < num_params; i++) {
if (params[i]) {
efree(params[i]);
}
}
efree(params);
}
}
/* }}} */
#endif
#if HAVE_PQEXECPARAMS
/* {{{ proto resource pg_query_params([resource connection,] string query, array params)
Execute a query */
PHP_FUNCTION(pg_query_params)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, *tmp;
char *query;
size_t query_len;
int id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc, "sa", &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) {
if (Z_TYPE_P(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val;
ZVAL_COPY(&tmp_val, tmp);
convert_to_cstring(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL, E_WARNING,"Error converting parameter");
zval_ptr_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_ptr_dtor(&tmp_val);
}
i++;
} ZEND_HASH_FOREACH_END();
}
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecParams(pgsql, query, num_params,
NULL, (const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQPREPARE
/* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
Prepare a query for future execution */
PHP_FUNCTION(pg_prepare)
{
zval *pgsql_link = NULL;
char *query, *stmtname;
size_t query_len, stmtname_len;
int id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#if HAVE_PQEXECPREPARED
/* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
Execute a prepared query */
PHP_FUNCTION(pg_execute)
{
zval *pgsql_link = NULL;
zval *pv_param_arr, *tmp;
char *stmtname;
size_t stmtname_len;
int id = -1, argc = ZEND_NUM_ARGS();
int leftover = 0;
int num_params = 0;
char **params = NULL;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
pgsql_result_handle *pg_result;
if (argc == 2) {
if (zend_parse_parameters(argc, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode");
RETURN_FALSE;
}
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
leftover = 1;
}
if (leftover) {
php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
}
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) {
if (Z_TYPE_P(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val;
ZVAL_COPY(&tmp_val, tmp);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL, E_WARNING,"Error converting parameter");
zval_ptr_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_ptr_dtor(&tmp_val);
}
i++;
} ZEND_HASH_FOREACH_END();
}
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQclear(pgsql_result);
PQreset(pgsql);
pgsql_result = PQexecPrepared(pgsql, stmtname, num_params,
(const char * const *)params, NULL, NULL, 0);
}
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
_php_pgsql_free_params(params, num_params);
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pgsql);
PQclear(pgsql_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pgsql_result) {
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
}
}
/* }}} */
#endif
#define PHP_PG_NUM_ROWS 1
#define PHP_PG_NUM_FIELDS 2
#define PHP_PG_CMD_TUPLES 3
/* {{{ php_pgsql_get_result_info
*/
static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
switch (entry_type) {
case PHP_PG_NUM_ROWS:
RETVAL_LONG(PQntuples(pgsql_result));
break;
case PHP_PG_NUM_FIELDS:
RETVAL_LONG(PQnfields(pgsql_result));
break;
case PHP_PG_CMD_TUPLES:
#if HAVE_PQCMDTUPLES
RETVAL_LONG(atoi(PQcmdTuples(pgsql_result)));
#else
php_error_docref(NULL, E_WARNING, "Not supported under this build");
RETVAL_LONG(0);
#endif
break;
default:
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int pg_num_rows(resource result)
Return the number of rows in the result */
PHP_FUNCTION(pg_num_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
}
/* }}} */
/* {{{ proto int pg_num_fields(resource result)
Return the number of fields in the result */
PHP_FUNCTION(pg_num_fields)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
}
/* }}} */
#if HAVE_PQCMDTUPLES
/* {{{ proto int pg_affected_rows(resource result)
Returns the number of affected tuples */
PHP_FUNCTION(pg_affected_rows)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
}
/* }}} */
#endif
/* {{{ proto string pg_last_notice(resource connection)
Returns the last notice set by the backend */
PHP_FUNCTION(pg_last_notice)
{
zval *pgsql_link = NULL;
PGconn *pg_link;
int id = -1;
php_pgsql_notice *notice;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) {
return;
}
if (pgsql_link == NULL) {
RETURN_FALSE;
}
/* Just to check if user passed valid resoruce */
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if ((notice = zend_hash_index_find_ptr(&PGG(notices), (zend_ulong)Z_RES_HANDLE_P(pgsql_link))) == NULL) {
RETURN_FALSE;
}
RETURN_STRINGL(notice->message, notice->len);
}
/* }}} */
/* {{{ get_field_name
*/
static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list)
{
PGresult *result;
smart_str str = {0};
zend_resource *field_type;
char *ret=NULL;
/* try to lookup the type in the resource list */
smart_str_appends(&str, "pgsql_oid_");
smart_str_append_unsigned(&str, oid);
smart_str_0(&str);
if ((field_type = zend_hash_find_ptr(list, str.s)) != NULL) {
ret = estrdup((char *)field_type->ptr);
} else { /* hash all oid's */
int i, num_rows;
int oid_offset,name_offset;
char *tmp_oid, *end_ptr, *tmp_name;
zend_resource new_oid_entry;
if ((result = PQexec(pgsql, "select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
if (result) {
PQclear(result);
}
smart_str_free(&str);
return estrndup("", sizeof("") - 1);
}
num_rows = PQntuples(result);
oid_offset = PQfnumber(result,"oid");
name_offset = PQfnumber(result,"typname");
for (i=0; i<num_rows; i++) {
if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
continue;
}
str.s->len = 0;
smart_str_appends(&str, "pgsql_oid_");
smart_str_appends(&str, tmp_oid);
smart_str_0(&str);
if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
continue;
}
new_oid_entry.type = le_string;
new_oid_entry.ptr = estrdup(tmp_name);
zend_hash_update_mem(list, str.s, (void *) &new_oid_entry, sizeof(zend_resource));
if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
ret = estrdup(tmp_name);
}
}
PQclear(result);
}
smart_str_free(&str);
return ret;
}
/* }}} */
#ifdef HAVE_PQFTABLE
/* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only])
Returns the name of the table field belongs to, or table's oid if oid_only is true */
PHP_FUNCTION(pg_field_table)
{
zval *result;
pgsql_result_handle *pg_result;
zend_long fnum = -1;
zend_bool return_oid = 0;
Oid oid;
smart_str hash_key = {0};
char *table_name;
zend_resource *field_table;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|b", &result, &fnum, &return_oid) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
if (fnum < 0 || fnum >= PQnfields(pg_result->result)) {
php_error_docref(NULL, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
oid = PQftable(pg_result->result, (int)fnum);
if (InvalidOid == oid) {
RETURN_FALSE;
}
if (return_oid) {
#if UINT_MAX > ZEND_LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */
if (oid > ZEND_LONG_MAX) {
smart_str oidstr = {0};
smart_str_append_unsigned(&oidstr, oid);
smart_str_0(&oidstr);
RETURN_STR(oidstr.s);
} else
#endif
RETURN_LONG((zend_long)oid);
}
/* try to lookup the table name in the resource list */
smart_str_appends(&hash_key, "pgsql_table_oid_");
smart_str_append_unsigned(&hash_key, oid);
smart_str_0(&hash_key);
if ((field_table = zend_hash_find_ptr(&EG(regular_list), hash_key.s)) != NULL) {
smart_str_free(&hash_key);
RETURN_STRING((char *)field_table->ptr);
} else { /* Not found, lookup by querying PostgreSQL system tables */
PGresult *tmp_res;
smart_str querystr = {0};
zend_resource new_field_table;
smart_str_appends(&querystr, "select relname from pg_class where oid=");
smart_str_append_unsigned(&querystr, oid);
smart_str_0(&querystr);
if ((tmp_res = PQexec(pg_result->conn, querystr.s->val)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) {
if (tmp_res) {
PQclear(tmp_res);
}
smart_str_free(&querystr);
smart_str_free(&hash_key);
RETURN_FALSE;
}
smart_str_free(&querystr);
if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) {
PQclear(tmp_res);
smart_str_free(&hash_key);
RETURN_FALSE;
}
new_field_table.type = le_string;
new_field_table.ptr = estrdup(table_name);
zend_hash_update_mem(&EG(regular_list), hash_key.s, (void *)&new_field_table, sizeof(zend_resource));
smart_str_free(&hash_key);
PQclear(tmp_res);
RETURN_STRING(table_name);
}
}
/* }}} */
#endif
#define PHP_PG_FIELD_NAME 1
#define PHP_PG_FIELD_SIZE 2
#define PHP_PG_FIELD_TYPE 3
#define PHP_PG_FIELD_TYPE_OID 4
/* {{{ php_pgsql_get_field_info
*/
static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result;
zend_long field;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
Oid oid;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &result, &field) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (field < 0 || field >= PQnfields(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Bad field offset specified");
RETURN_FALSE;
}
switch (entry_type) {
case PHP_PG_FIELD_NAME:
RETURN_STRING(PQfname(pgsql_result, (int)field));
break;
case PHP_PG_FIELD_SIZE:
RETURN_LONG(PQfsize(pgsql_result, (int)field));
break;
case PHP_PG_FIELD_TYPE: {
char *name = get_field_name(pg_result->conn, PQftype(pgsql_result, (int)field), &EG(regular_list));
RETVAL_STRING(name);
efree(name);
}
break;
case PHP_PG_FIELD_TYPE_OID:
oid = PQftype(pgsql_result, (int)field);
#if UINT_MAX > ZEND_LONG_MAX
if (oid > ZEND_LONG_MAX) {
smart_str s = {0};
smart_str_append_unsigned(&s, oid);
smart_str_0(&s);
RETURN_STR(s.s);
} else
#endif
{
RETURN_LONG((zend_long)oid);
}
break;
default:
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string pg_field_name(resource result, int field_number)
Returns the name of the field */
PHP_FUNCTION(pg_field_name)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
}
/* }}} */
/* {{{ proto int pg_field_size(resource result, int field_number)
Returns the internal size of the field */
PHP_FUNCTION(pg_field_size)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
}
/* }}} */
/* {{{ proto string pg_field_type(resource result, int field_number)
Returns the type name for the given field */
PHP_FUNCTION(pg_field_type)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
}
/* }}} */
/* {{{ proto string pg_field_type_oid(resource result, int field_number)
Returns the type oid for the given field */
PHP_FUNCTION(pg_field_type_oid)
{
php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
}
/* }}} */
/* {{{ proto int pg_field_num(resource result, string field_name)
Returns the field number of the named field */
PHP_FUNCTION(pg_field_num)
{
zval *result;
char *field;
size_t field_len;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &result, &field, &field_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
RETURN_LONG(PQfnumber(pgsql_result, field));
}
/* }}} */
/* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
Returns values from a result identifier */
PHP_FUNCTION(pg_fetch_result)
{
zval *result, *field=NULL;
zend_long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc, "rz", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc, "rlz", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
if (row < 0 || row >= PQntuples(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Unable to jump to row %pd on PostgreSQL result index %pd",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
pgsql_row = (int)row;
}
switch (Z_TYPE_P(field)) {
case IS_STRING:
field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field));
if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
break;
default:
convert_to_long_ex(field);
if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
field_offset = (int)Z_LVAL_P(field);
break;
}
if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
RETVAL_NULL();
} else {
RETVAL_STRINGL(PQgetvalue(pgsql_result, pgsql_row, field_offset),
PQgetlength(pgsql_result, pgsql_row, field_offset));
}
}
/* }}} */
/* {{{ void php_pgsql_fetch_hash */
static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, zend_long result_type, int into_object)
{
zval *result, *zrow = NULL;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int i, num_fields, pgsql_row, use_row;
zend_long row = -1;
char *field_name;
zval *ctor_params = NULL;
zend_class_entry *ce = NULL;
if (into_object) {
zend_string *class_name = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|z!Sz", &result, &zrow, &class_name, &ctor_params) == FAILURE) {
return;
}
if (!class_name) {
ce = zend_standard_class_def;
} else {
ce = zend_fetch_class(class_name, ZEND_FETCH_CLASS_AUTO);
}
if (!ce) {
php_error_docref(NULL, E_WARNING, "Could not find class '%s'", class_name->val);
return;
}
result_type = PGSQL_ASSOC;
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|z!l", &result, &zrow, &result_type) == FAILURE) {
return;
}
}
if (zrow == NULL) {
row = -1;
} else {
convert_to_long(zrow);
row = Z_LVAL_P(zrow);
if (row < 0) {
php_error_docref(NULL, E_WARNING, "The row parameter must be greater or equal to zero");
RETURN_FALSE;
}
}
use_row = ZEND_NUM_ARGS() > 1 && row != -1;
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (use_row) {
if (row < 0 || row >= PQntuples(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Unable to jump to row %pd on PostgreSQL result index %pd",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
pgsql_row = (int)row;
pg_result->row = pgsql_row;
} else {
/* If 2nd param is NULL, use internal row counter to access next row */
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
pg_result->row++;
}
array_init(return_value);
for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
if (PQgetisnull(pgsql_result, pgsql_row, i)) {
if (result_type & PGSQL_NUM) {
add_index_null(return_value, i);
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_null(return_value, field_name);
}
} else {
char *element = PQgetvalue(pgsql_result, pgsql_row, i);
if (element) {
const size_t element_len = strlen(element);
if (result_type & PGSQL_NUM) {
add_index_stringl(return_value, i, element, element_len);
}
if (result_type & PGSQL_ASSOC) {
field_name = PQfname(pgsql_result, i);
add_assoc_stringl(return_value, field_name, element, element_len);
}
}
}
}
if (into_object) {
zval dataset;
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval retval;
ZVAL_COPY_VALUE(&dataset, return_value);
object_and_properties_init(return_value, ce, NULL);
if (!ce->default_properties_count && !ce->__set) {
ALLOC_HASHTABLE(Z_OBJ_P(return_value)->properties);
*Z_OBJ_P(return_value)->properties = *Z_ARRVAL(dataset);
efree(Z_ARR(dataset));
} else {
zend_merge_properties(return_value, Z_ARRVAL(dataset));
zval_ptr_dtor(&dataset);
}
if (ce->constructor) {
fci.size = sizeof(fci);
fci.function_table = &ce->function_table;
ZVAL_UNDEF(&fci.function_name);
fci.symbol_table = NULL;
fci.object = Z_OBJ_P(return_value);
fci.retval = &retval;
fci.params = NULL;
fci.param_count = 0;
fci.no_separation = 1;
if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
if (zend_fcall_info_args(&fci, ctor_params) == FAILURE) {
/* Two problems why we throw exceptions here: PHP is typeless
* and hence passing one argument that's not an array could be
* by mistake and the other way round is possible, too. The
* single value is an array. Also we'd have to make that one
* argument passed by reference.
*/
zend_throw_exception(zend_exception_get_default(), "Parameter ctor_params must be an array", 0);
return;
}
}
fcc.initialized = 1;
fcc.function_handler = ce->constructor;
fcc.calling_scope = EG(scope);
fcc.called_scope = Z_OBJCE_P(return_value);
fcc.object = Z_OBJ_P(return_value);
if (zend_call_function(&fci, &fcc) == FAILURE) {
zend_throw_exception_ex(zend_exception_get_default(), 0, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
} else {
zval_ptr_dtor(&retval);
}
if (fci.params) {
efree(fci.params);
}
} else if (ctor_params) {
zend_throw_exception_ex(zend_exception_get_default(), 0, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
}
}
}
/* }}} */
/* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
Get a row as an enumerated array */
PHP_FUNCTION(pg_fetch_row)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_assoc(resource result [, int row])
Fetch a row as an assoc array */
PHP_FUNCTION(pg_fetch_assoc)
{
/* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
there is 3rd parameter */
if (ZEND_NUM_ARGS() > 2)
WRONG_PARAM_COUNT;
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
}
/* }}} */
/* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
Fetch a row as an array */
PHP_FUNCTION(pg_fetch_array)
{
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
}
/* }}} */
/* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
Fetch a row as an object */
PHP_FUNCTION(pg_fetch_object)
{
/* pg_fetch_object() allowed result_type used to be. 3rd parameter
must be allowed for compatibility */
php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
}
/* }}} */
/* {{{ proto array pg_fetch_all(resource result)
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
array_init(return_value);
if (php_pgsql_result2array(pgsql_result, return_value) == FAILURE) {
zval_dtor(return_value);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
Fetch all rows into array */
PHP_FUNCTION(pg_fetch_all_columns)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
zend_long colno=0;
int pg_numrows, pg_row;
size_t num_fields;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &result, &colno) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
num_fields = PQnfields(pgsql_result);
if (colno >= (zend_long)num_fields || colno < 0) {
php_error_docref(NULL, E_WARNING, "Invalid column number '%pd'", colno);
RETURN_FALSE;
}
array_init(return_value);
if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
return;
}
for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
if (PQgetisnull(pgsql_result, pg_row, (int)colno)) {
add_next_index_null(return_value);
} else {
add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno));
}
}
}
/* }}} */
/* {{{ proto bool pg_result_seek(resource result, int offset)
Set internal row offset */
PHP_FUNCTION(pg_result_seek)
{
zval *result;
zend_long row;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &result, &row) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
if (row < 0 || row >= PQntuples(pg_result->result)) {
RETURN_FALSE;
}
/* seek to offset */
pg_result->row = (int)row;
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_DATA_LENGTH 1
#define PHP_PG_DATA_ISNULL 2
/* {{{ php_pgsql_data_info
*/
static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *result, *field;
zend_long row;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
int field_offset, pgsql_row, argc = ZEND_NUM_ARGS();
if (argc == 2) {
if (zend_parse_parameters(argc, "rz", &result, &field) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(argc, "rlz", &result, &row, &field) == FAILURE) {
return;
}
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (argc == 2) {
if (pg_result->row < 0) {
pg_result->row = 0;
}
pgsql_row = pg_result->row;
if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
RETURN_FALSE;
}
} else {
if (row < 0 || row >= PQntuples(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Unable to jump to row %pd on PostgreSQL result index %pd",
row, Z_LVAL_P(result));
RETURN_FALSE;
}
pgsql_row = (int)row;
}
switch (Z_TYPE_P(field)) {
case IS_STRING:
convert_to_string_ex(field);
field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field));
if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
break;
default:
convert_to_long_ex(field);
if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) {
php_error_docref(NULL, E_WARNING, "Bad column offset specified");
RETURN_FALSE;
}
field_offset = (int)Z_LVAL_P(field);
break;
}
switch (entry_type) {
case PHP_PG_DATA_LENGTH:
RETVAL_LONG(PQgetlength(pgsql_result, pgsql_row, field_offset));
break;
case PHP_PG_DATA_ISNULL:
RETVAL_LONG(PQgetisnull(pgsql_result, pgsql_row, field_offset))
break;
}
}
/* }}} */
/* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
Returns the printed length */
PHP_FUNCTION(pg_field_prtlen)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
}
/* }}} */
/* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
Test if a field is NULL */
PHP_FUNCTION(pg_field_is_null)
{
php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
}
/* }}} */
/* {{{ proto bool pg_free_result(resource result)
Free result memory */
PHP_FUNCTION(pg_free_result)
{
zval *result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
if (Z_RES_P(result) == NULL) {
RETURN_FALSE;
}
zend_list_close(Z_RES_P(result));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string pg_last_oid(resource result)
Returns the last object identifier */
PHP_FUNCTION(pg_last_oid)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
#ifdef HAVE_PQOIDVALUE
Oid oid;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
#ifdef HAVE_PQOIDVALUE
oid = PQoidValue(pgsql_result);
if (oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(oid);
#else
Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
if (Z_STRVAL_P(return_value)) {
RETURN_STRING(Z_STRVAL_P(return_value));
}
RETURN_EMPTY_STRING();
#endif
}
/* }}} */
/* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
Enable tracing a PostgreSQL connection */
PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
size_t z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = FETCH_DEFAULT_LINK();
if (zend_parse_parameters(argc, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_untrace([resource connection])
Disable tracing of a PostgreSQL connection */
PHP_FUNCTION(pg_untrace)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQuntrace(pgsql);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid])
Create a large object */
PHP_FUNCTION(pg_lo_create)
{
zval *pgsql_link = NULL, *oid = NULL;
PGconn *pgsql;
Oid pgsql_oid, wanted_oid = InvalidOid;
int id = -1, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "|zz", &pgsql_link, &oid) == FAILURE) {
return;
}
if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) {
oid = pgsql_link;
pgsql_link = NULL;
}
if (pgsql_link == NULL) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
if (id == -1) {
RETURN_FALSE;
}
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_CREATE
php_error_docref(NULL, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL");
#else
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (zend_long)InvalidOid) {
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) {
php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
#endif
}
if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
}
PGSQL_RETURN_OID(pgsql_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
Delete a large object */
PHP_FUNCTION(pg_lo_unlink)
{
zval *pgsql_link = NULL;
zend_long oid_long;
char *oid_string, *end_ptr;
size_t oid_strlen;
PGconn *pgsql;
Oid oid;
int id = -1;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid type is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rl", &pgsql_link, &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"s", &oid_string, &oid_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"l", &oid_long) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID is specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_unlink(pgsql, oid) == -1) {
php_error_docref(NULL, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
Open a large object and return fd */
PHP_FUNCTION(pg_lo_open)
{
zval *pgsql_link = NULL;
zend_long oid_long;
char *oid_string, *end_ptr, *mode_string;
size_t oid_strlen, mode_strlen;
PGconn *pgsql;
Oid oid;
int id = -1, pgsql_mode=0, pgsql_lofd;
int create = 0;
pgLofp *pgsql_lofp;
int argc = ZEND_NUM_ARGS();
/* accept string type since Oid is unsigned int */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else {
php_error_docref(NULL, E_WARNING, "Requires 1 or 2 arguments");
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
faster to type. Unfortunately, doesn't behave the same way as fopen()...
(Jouni)
*/
if (strchr(mode_string, 'r') == mode_string) {
pgsql_mode |= INV_READ;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_WRITE;
}
}
if (strchr(mode_string, 'w') == mode_string) {
pgsql_mode |= INV_WRITE;
create = 1;
if (strchr(mode_string, '+') == mode_string+1) {
pgsql_mode |= INV_READ;
}
}
pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (create) {
if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
efree(pgsql_lofp);
php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object");
RETURN_FALSE;
} else {
if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
if (lo_unlink(pgsql, oid) == -1) {
efree(pgsql_lofp);
php_error_docref(NULL, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
RETURN_FALSE;
}
efree(pgsql_lofp);
php_error_docref(NULL, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
}
}
} else {
efree(pgsql_lofp);
php_error_docref(NULL, E_WARNING, "Unable to open PostgreSQL large object");
RETURN_FALSE;
}
} else {
pgsql_lofp->conn = pgsql;
pgsql_lofp->lofd = pgsql_lofd;
ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
}
}
/* }}} */
/* {{{ proto bool pg_lo_close(resource large_object)
Close a large object */
PHP_FUNCTION(pg_lo_close)
{
zval *pgsql_lofp;
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_lofp) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
php_error_docref(NULL, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
zend_list_close(Z_RES_P(pgsql_lofp));
return;
}
/* }}} */
#define PGSQL_LO_READ_BUF_SIZE 8192
/* {{{ proto string pg_lo_read(resource large_object [, int len])
Read a large object */
PHP_FUNCTION(pg_lo_read)
{
zval *pgsql_id;
zend_long len;
size_t buf_len = PGSQL_LO_READ_BUF_SIZE;
int nbytes, argc = ZEND_NUM_ARGS();
zend_string *buf;
pgLofp *pgsql;
if (zend_parse_parameters(argc, "r|l", &pgsql_id, &len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
if (argc > 1) {
buf_len = len < 0 ? 0 : len;
}
buf = zend_string_alloc(buf_len, 0);
if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf->val, buf->len))<0) {
zend_string_free(buf);
RETURN_FALSE;
}
buf->len = nbytes;
buf->val[buf->len] = '\0';
RETURN_STR(buf);
}
/* }}} */
/* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
Write a large object */
PHP_FUNCTION(pg_lo_write)
{
zval *pgsql_id;
char *str;
zend_long z_len;
size_t str_len, nbytes;
size_t len;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) {
return;
}
if (argc > 2) {
if (z_len > (zend_long)str_len) {
php_error_docref(NULL, E_WARNING, "Cannot write more than buffer size %d. Tried to write %pd", str_len, z_len);
RETURN_FALSE;
}
if (z_len < 0) {
php_error_docref(NULL, E_WARNING, "Buffer size must be larger than 0, but %pd was specified", z_len);
RETURN_FALSE;
}
len = z_len;
}
else {
len = str_len;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) {
RETURN_FALSE;
}
RETURN_LONG(nbytes);
}
/* }}} */
/* {{{ proto int pg_lo_read_all(resource large_object)
Read a large object and send straight to browser */
PHP_FUNCTION(pg_lo_read_all)
{
zval *pgsql_id;
int tbytes;
volatile int nbytes;
char buf[PGSQL_LO_READ_BUF_SIZE];
pgLofp *pgsql;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
tbytes = 0;
while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
PHPWRITE(buf, nbytes);
tbytes += nbytes;
}
RETURN_LONG(tbytes);
}
/* }}} */
/* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid])
Import large object direct from filesystem */
PHP_FUNCTION(pg_lo_import)
{
zval *pgsql_link = NULL, *oid = NULL;
char *file_in;
int id = -1;
size_t name_len;
int argc = ZEND_NUM_ARGS();
PGconn *pgsql;
Oid returned_oid;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) {
;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"p|z", &file_in, &name_len, &oid) == SUCCESS) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
/* old calling convention, deprecated since PHP 4.2 */
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
php_error_docref(NULL, E_NOTICE, "Old API is used");
}
else {
WRONG_PARAM_COUNT;
}
if (php_check_open_basedir(file_in)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (oid) {
#ifndef HAVE_PG_LO_IMPORT_WITH_OID
php_error_docref(NULL, E_NOTICE, "OID value passing not supported");
#else
Oid wanted_oid;
switch (Z_TYPE_P(oid)) {
case IS_STRING:
{
char *end_ptr;
wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10);
if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
}
break;
case IS_LONG:
if (Z_LVAL_P(oid) < (zend_long)InvalidOid) {
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
wanted_oid = (Oid)Z_LVAL_P(oid);
break;
default:
php_error_docref(NULL, E_NOTICE, "invalid OID value passed");
RETURN_FALSE;
}
returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
#endif
}
returned_oid = lo_import(pgsql, file_in);
if (returned_oid == InvalidOid) {
RETURN_FALSE;
}
PGSQL_RETURN_OID(returned_oid);
}
/* }}} */
/* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
Export large object direct to filesystem */
PHP_FUNCTION(pg_lo_export)
{
zval *pgsql_link = NULL;
char *file_out, *oid_string, *end_ptr;
size_t oid_strlen;
int id = -1;
size_t name_len;
zend_long oid_long;
Oid oid;
PGconn *pgsql;
int argc = ZEND_NUM_ARGS();
/* allow string to handle large OID value correctly */
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"lp", &oid_long, &file_out, &name_len) == SUCCESS) {
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
oid = (Oid)strtoul(oid_string, &end_ptr, 10);
if ((oid_string+oid_strlen) != end_ptr) {
/* wrong integer format */
php_error_docref(NULL, E_NOTICE, "Wrong OID value passed");
RETURN_FALSE;
}
}
else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc,
"lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
php_error_docref(NULL, E_NOTICE, "Old API is used");
if (oid_long <= InvalidOid) {
php_error_docref(NULL, E_NOTICE, "Invalid OID specified");
RETURN_FALSE;
}
oid = (Oid)oid_long;
}
else {
php_error_docref(NULL, E_WARNING, "Requires 2 or 3 arguments");
RETURN_FALSE;
}
if (php_check_open_basedir(file_out)) {
RETURN_FALSE;
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (lo_export(pgsql, oid, file_out) == -1) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
Seeks position of large object */
PHP_FUNCTION(pg_lo_seek)
{
zval *pgsql_id = NULL;
zend_long result, offset = 0, whence = SEEK_CUR;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
return;
}
if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
php_error_docref(NULL, E_WARNING, "Invalid whence parameter");
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
#if HAVE_PG_LO64
if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
result = lo_lseek64((PGconn *)pgsql->conn, pgsql->lofd, offset, (int)whence);
} else {
result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, (int)offset, (int)whence);
}
#else
result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence);
#endif
if (result > -1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int pg_lo_tell(resource large_object)
Returns current position of large object */
PHP_FUNCTION(pg_lo_tell)
{
zval *pgsql_id = NULL;
zend_long offset = 0;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "r", &pgsql_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
#if HAVE_PG_LO64
if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
offset = lo_tell64((PGconn *)pgsql->conn, pgsql->lofd);
} else {
offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
}
#else
offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
#endif
RETURN_LONG(offset);
}
/* }}} */
#if HAVE_PG_LO_TRUNCATE
/* {{{ proto bool pg_lo_truncate(resource large_object, int size)
Truncate large object to size */
PHP_FUNCTION(pg_lo_truncate)
{
zval *pgsql_id = NULL;
size_t size;
pgLofp *pgsql;
int argc = ZEND_NUM_ARGS();
int result;
if (zend_parse_parameters(argc, "rl", &pgsql_id, &size) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
#if HAVE_PG_LO64
if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) {
result = lo_truncate64((PGconn *)pgsql->conn, pgsql->lofd, size);
} else {
result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size);
}
#else
result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size);
#endif
if (!result) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#if HAVE_PQSETERRORVERBOSITY
/* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
Set error verbosity */
PHP_FUNCTION(pg_set_error_verbosity)
{
zval *pgsql_link = NULL;
zend_long verbosity;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc, "l", &verbosity) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rl", &pgsql_link, &verbosity) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
RETURN_LONG(PQsetErrorVerbosity(pgsql, verbosity));
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#ifdef HAVE_PQCLIENTENCODING
/* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
Set client encoding */
PHP_FUNCTION(pg_set_client_encoding)
{
char *encoding;
size_t encoding_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (argc == 1) {
if (zend_parse_parameters(argc, "s", &encoding, &encoding_len) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
RETURN_LONG(PQsetClientEncoding(pgsql, encoding));
}
/* }}} */
/* {{{ proto string pg_client_encoding([resource connection])
Get the current client encoding */
PHP_FUNCTION(pg_client_encoding)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
/* Just do the same as found in PostgreSQL sources... */
RETURN_STRING((char *) pg_encoding_to_char(PQclientEncoding(pgsql)));
}
/* }}} */
#endif
#if !HAVE_PQGETCOPYDATA
#define COPYBUFSIZ 8192
#endif
/* {{{ proto bool pg_end_copy([resource connection])
Sync with backend. Completes the Copy command */
PHP_FUNCTION(pg_end_copy)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
int result = 0;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQendcopy(pgsql);
if (result!=0) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool pg_put_line([resource connection,] string query)
Send null-terminated string to backend server*/
PHP_FUNCTION(pg_put_line)
{
char *query;
zval *pgsql_link = NULL;
size_t query_len;
int id = -1;
PGconn *pgsql;
int result = 0, argc = ZEND_NUM_ARGS();
if (argc == 1) {
if (zend_parse_parameters(argc, "s", &query, &query_len) == FAILURE) {
return;
}
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
} else {
if (zend_parse_parameters(argc, "rs", &pgsql_link, &query, &query_len) == FAILURE) {
return;
}
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
result = PQputline(pgsql, query);
if (result==EOF) {
PHP_PQ_ERROR("Query failed: %s", pgsql);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
Copy table to array */
PHP_FUNCTION(pg_copy_to)
{
zval *pgsql_link;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
size_t table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0;
char *query;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int copydone = 0;
#if !HAVE_PQGETCOPYDATA
char copybuf[COPYBUFSIZ];
#endif
char *csv = (char *)NULL;
int ret;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "rs|ss",
&pgsql_link, &table_name, &table_name_len,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!pg_null_as) {
pg_null_as = estrdup("\\\\N");
free_pg_null = 1;
}
spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (free_pg_null) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_OUT:
if (pgsql_result) {
PQclear(pgsql_result);
array_init(return_value);
#if HAVE_PQGETCOPYDATA
while (!copydone)
{
ret = PQgetCopyData(pgsql, &csv, 0);
switch (ret) {
case -1:
copydone = 1;
break;
case 0:
case -2:
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
break;
default:
add_next_index_string(return_value, csv);
PQfreemem(csv);
break;
}
}
#else
while (!copydone)
{
if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
PHP_PQ_ERROR("getline failed: %s", pgsql);
RETURN_FALSE;
}
if (copybuf[0] == '\\' &&
copybuf[1] == '.' &&
copybuf[2] == '\0')
{
copydone = 1;
}
else
{
if (csv == (char *)NULL) {
csv = estrdup(copybuf);
} else {
csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
strcat(csv, copybuf);
}
switch (ret)
{
case EOF:
copydone = 1;
case 0:
add_next_index_string(return_value, csv);
efree(csv);
csv = (char *)NULL;
break;
case 1:
break;
}
}
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
Copy table from array */
PHP_FUNCTION(pg_copy_from)
{
zval *pgsql_link = NULL, *pg_rows;
zval *tmp;
char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
size_t table_name_len, pg_delim_len, pg_null_as_len;
int pg_null_as_free = 0;
char *query;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
ExecStatusType status;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "rsa|ss",
&pgsql_link, &table_name, &table_name_len, &pg_rows,
&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
return;
}
if (!pg_delim) {
pg_delim = "\t";
}
if (!pg_null_as) {
pg_null_as = estrdup("\\\\N");
pg_null_as_free = 1;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as);
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
pgsql_result = PQexec(pgsql, query);
if (pg_null_as_free) {
efree(pg_null_as);
}
efree(query);
if (pgsql_result) {
status = PQresultStatus(pgsql_result);
} else {
status = (ExecStatusType) PQstatus(pgsql);
}
switch (status) {
case PGRES_COPY_IN:
if (pgsql_result) {
int command_failed = 0;
PQclear(pgsql_result);
#if HAVE_PQPUTCOPYDATA
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_P(tmp) + 2);
strlcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp) + 2);
if(Z_STRLEN_P(tmp) > 0 && *(query + Z_STRLEN_P(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_P(tmp) + 2);
}
if (PQputCopyData(pgsql, query, (int)strlen(query)) != 1) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
} ZEND_HASH_FOREACH_END();
if (PQputCopyEnd(pgsql, NULL) != 1) {
PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
RETURN_FALSE;
}
#else
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) {
convert_to_string_ex(tmp);
query = (char *)emalloc(Z_STRLEN_P(tmp) + 2);
strlcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp) + 2);
if(Z_STRLEN_P(tmp) > 0 && *(query + Z_STRLEN_P(tmp) - 1) != '\n') {
strlcat(query, "\n", Z_STRLEN_P(tmp) + 2);
}
if (PQputline(pgsql, query)==EOF) {
efree(query);
PHP_PQ_ERROR("copy failed: %s", pgsql);
RETURN_FALSE;
}
efree(query);
} ZEND_HASH_FOREACH_END();
if (PQputline(pgsql, "\\.\n") == EOF) {
PHP_PQ_ERROR("putline failed: %s", pgsql);
RETURN_FALSE;
}
if (PQendcopy(pgsql)) {
PHP_PQ_ERROR("endcopy failed: %s", pgsql);
RETURN_FALSE;
}
#endif
while ((pgsql_result = PQgetResult(pgsql))) {
if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
command_failed = 1;
}
PQclear(pgsql_result);
}
if (command_failed) {
RETURN_FALSE;
}
} else {
PQclear(pgsql_result);
RETURN_FALSE;
}
RETURN_TRUE;
break;
default:
PQclear(pgsql_result);
PHP_PQ_ERROR("Copy command failed: %s", pgsql);
RETURN_FALSE;
break;
}
}
/* }}} */
#ifdef HAVE_PQESCAPE
/* {{{ proto string pg_escape_string([resource connection,] string data)
Escape string for text/char type */
PHP_FUNCTION(pg_escape_string)
{
zend_string *from = NULL, *to = NULL;
zval *pgsql_link;
#ifdef HAVE_PQESCAPE_CONN
PGconn *pgsql;
#endif
int id = -1;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &from) == FAILURE) {
return;
}
pgsql_link = NULL;
id = FETCH_DEFAULT_LINK();
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rS", &pgsql_link, &from) == FAILURE) {
return;
}
break;
}
to = zend_string_alloc(from->len * 2, 0);
#ifdef HAVE_PQESCAPE_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to->len = PQescapeStringConn(pgsql, to->val, from->val, from->len, NULL);
} else
#endif
{
to->len = PQescapeString(to->val, from->val, from->len);
}
to = zend_string_realloc(to, to->len, 0);
RETURN_STR(to);
}
/* }}} */
/* {{{ proto string pg_escape_bytea([resource connection,] string data)
Escape binary for bytea type */
PHP_FUNCTION(pg_escape_bytea)
{
char *from = NULL, *to = NULL;
size_t to_len;
size_t from_len;
int id = -1;
#ifdef HAVE_PQESCAPE_BYTEA_CONN
PGconn *pgsql;
#endif
zval *pgsql_link;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = FETCH_DEFAULT_LINK();
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
#ifdef HAVE_PQESCAPE_BYTEA_CONN
if (pgsql_link != NULL || id != -1) {
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len);
} else
#endif
to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
RETVAL_STRINGL(to, to_len-1); /* to_len includes additional '\0' */
}
/* }}} */
#if !HAVE_PQUNESCAPEBYTEA
/* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
Renamed to php_pgsql_unescape_bytea() */
/*
* PQunescapeBytea - converts the null terminated string representation
* of a bytea, strtext, into binary, filling a buffer. It returns a
* pointer to the buffer which is NULL on error, and the size of the
* buffer in retbuflen. The pointer may subsequently be used as an
* argument to the function free(3). It is the reverse of PQescapeBytea.
*
* The following transformations are reversed:
* '\0' == ASCII 0 == \000
* '\'' == ASCII 39 == \'
* '\\' == ASCII 92 == \\
*
* States:
* 0 normal 0->1->2->3->4
* 1 \ 1->5
* 2 \0 1->6
* 3 \00
* 4 \000
* 5 \'
* 6 \\
*/
static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen) /* {{{ */
{
size_t buflen;
unsigned char *buffer,
*sp,
*bp;
unsigned int state = 0;
if (strtext == NULL)
return NULL;
buflen = strlen(strtext); /* will shrink, also we discover if
* strtext */
buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */
for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
{
switch (state)
{
case 0:
if (*sp == '\\')
state = 1;
*bp = *sp;
break;
case 1:
if (*sp == '\'') /* state=5 */
{ /* replace \' with 39 */
bp--;
*bp = '\'';
buflen--;
state = 0;
}
else if (*sp == '\\') /* state=6 */
{ /* replace \\ with 92 */
bp--;
*bp = '\\';
buflen--;
state = 0;
}
else
{
if (isdigit(*sp))
state = 2;
else
state = 0;
*bp = *sp;
}
break;
case 2:
if (isdigit(*sp))
state = 3;
else
state = 0;
*bp = *sp;
break;
case 3:
if (isdigit(*sp)) /* state=4 */
{
unsigned char *start, *end, buf[4]; /* 000 + '\0' */
bp -= 3;
memcpy(buf, sp-2, 3);
buf[3] = '\0';
start = buf;
*bp = (unsigned char)strtoul(start, (char **)&end, 8);
buflen -= 3;
state = 0;
}
else
{
*bp = *sp;
state = 0;
}
break;
}
}
buffer = erealloc(buffer, buflen+1);
buffer[buflen] = '\0';
*retbuflen = buflen;
return buffer;
}
/* }}} */
#endif
/* {{{ proto string pg_unescape_bytea(string data)
Unescape binary for bytea type */
PHP_FUNCTION(pg_unescape_bytea)
{
char *from = NULL, *to = NULL, *tmp = NULL;
size_t to_len;
size_t from_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s",
&from, &from_len) == FAILURE) {
return;
}
#if HAVE_PQUNESCAPEBYTEA
tmp = (char *)PQunescapeBytea((unsigned char*)from, &to_len);
to = estrndup(tmp, to_len);
PQfreemem(tmp);
#else
to = (char *)php_pgsql_unescape_bytea((unsigned char*)from, &to_len);
#endif
if (!to) {
php_error_docref(NULL, E_WARNING,"Invalid parameter");
RETURN_FALSE;
}
RETVAL_STRINGL(to, to_len);
efree(to);
}
/* }}} */
#endif
#ifdef HAVE_PQESCAPE
static void php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAMETERS, int escape_literal) /* {{{ */ {
char *from = NULL;
zval *pgsql_link = NULL;
PGconn *pgsql;
size_t from_len;
int id = -1;
char *tmp;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &from, &from_len) == FAILURE) {
return;
}
pgsql_link = NULL;
id = FETCH_DEFAULT_LINK();
break;
default:
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &from, &from_len) == FAILURE) {
return;
}
break;
}
if (pgsql_link == NULL && id == -1) {
php_error_docref(NULL, E_WARNING,"Cannot get default pgsql link");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (pgsql == NULL) {
php_error_docref(NULL, E_WARNING,"Cannot get pgsql link");
RETURN_FALSE;
}
if (escape_literal) {
tmp = PGSQLescapeLiteral(pgsql, from, (size_t)from_len);
} else {
tmp = PGSQLescapeIdentifier(pgsql, from, (size_t)from_len);
}
if (!tmp) {
php_error_docref(NULL, E_WARNING,"Failed to escape");
RETURN_FALSE;
}
RETVAL_STRING(tmp);
PGSQLfree(tmp);
}
/* }}} */
/* {{{ proto string pg_escape_literal([resource connection,] string data)
Escape parameter as string literal (i.e. parameter) */
PHP_FUNCTION(pg_escape_literal)
{
php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto string pg_escape_identifier([resource connection,] string data)
Escape identifier (i.e. table name, field name) */
PHP_FUNCTION(pg_escape_identifier)
{
php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
#endif
/* {{{ proto string pg_result_error(resource result)
Get error message associated with result */
PHP_FUNCTION(pg_result_error)
{
zval *result;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
char *err = NULL;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r",
&result) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (!pgsql_result) {
RETURN_FALSE;
}
err = (char *)PQresultErrorMessage(pgsql_result);
RETURN_STRING(err);
}
/* }}} */
#if HAVE_PQRESULTERRORFIELD
/* {{{ proto string pg_result_error_field(resource result, int fieldcode)
Get error message field associated with result */
PHP_FUNCTION(pg_result_error_field)
{
zval *result;
zend_long fieldcode;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
char *field = NULL;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "rl",
&result, &fieldcode) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (!pgsql_result) {
RETURN_FALSE;
}
if (fieldcode & (PG_DIAG_SEVERITY|PG_DIAG_SQLSTATE|PG_DIAG_MESSAGE_PRIMARY|PG_DIAG_MESSAGE_DETAIL
|PG_DIAG_MESSAGE_HINT|PG_DIAG_STATEMENT_POSITION
#if PG_DIAG_INTERNAL_POSITION
|PG_DIAG_INTERNAL_POSITION
#endif
#if PG_DIAG_INTERNAL_QUERY
|PG_DIAG_INTERNAL_QUERY
#endif
|PG_DIAG_CONTEXT|PG_DIAG_SOURCE_FILE|PG_DIAG_SOURCE_LINE
|PG_DIAG_SOURCE_FUNCTION)) {
field = (char *)PQresultErrorField(pgsql_result, (int)fieldcode);
if (field == NULL) {
RETURN_NULL();
} else {
RETURN_STRING(field);
}
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
/* {{{ proto int pg_connection_status(resource connection)
Get connection status */
PHP_FUNCTION(pg_connection_status)
{
zval *pgsql_link = NULL;
int id = -1;
PGconn *pgsql;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
RETURN_LONG(PQstatus(pgsql));
}
/* }}} */
#if HAVE_PGTRANSACTIONSTATUS
/* {{{ proto int pg_transaction_status(resource connection)
Get transaction status */
PHP_FUNCTION(pg_transaction_status)
{
zval *pgsql_link = NULL;
int id = -1;
PGconn *pgsql;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
RETURN_LONG(PQtransactionStatus(pgsql));
}
#endif
/* }}} */
/* {{{ proto bool pg_connection_reset(resource connection)
Reset connection (reconnect) */
PHP_FUNCTION(pg_connection_reset)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQreset(pgsql);
if (PQstatus(pgsql) == CONNECTION_BAD) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#define PHP_PG_ASYNC_IS_BUSY 1
#define PHP_PG_ASYNC_REQUEST_CANCEL 2
/* {{{ php_pgsql_flush_query
*/
static int php_pgsql_flush_query(PGconn *pgsql)
{
PGresult *res;
int leftover = 0;
if (PQ_SETNONBLOCKING(pgsql, 1)) {
php_error_docref(NULL, E_NOTICE,"Cannot set connection to nonblocking mode");
return -1;
}
while ((res = PQgetResult(pgsql))) {
PQclear(res);
leftover++;
}
PQ_SETNONBLOCKING(pgsql, 0);
return leftover;
}
/* }}} */
/* {{{ php_pgsql_do_async
*/
static void php_pgsql_do_async(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (PQ_SETNONBLOCKING(pgsql, 1)) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
switch(entry_type) {
case PHP_PG_ASYNC_IS_BUSY:
PQconsumeInput(pgsql);
RETVAL_LONG(PQisBusy(pgsql));
break;
case PHP_PG_ASYNC_REQUEST_CANCEL:
RETVAL_LONG(PQrequestCancel(pgsql));
while ((pgsql_result = PQgetResult(pgsql))) {
PQclear(pgsql_result);
}
break;
default:
php_error_docref(NULL, E_ERROR, "PostgreSQL module error, please report this error");
break;
}
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode");
}
convert_to_boolean_ex(return_value);
}
/* }}} */
/* {{{ proto bool pg_cancel_query(resource connection)
Cancel request */
PHP_FUNCTION(pg_cancel_query)
{
php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_REQUEST_CANCEL);
}
/* }}} */
/* {{{ proto bool pg_connection_busy(resource connection)
Get connection is busy or not */
PHP_FUNCTION(pg_connection_busy)
{
php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY);
}
/* }}} */
static int _php_pgsql_link_has_results(PGconn *pgsql) /* {{{ */
{
PGresult *result;
while ((result = PQgetResult(pgsql))) {
PQclear(result);
return 1;
}
return 0;
}
/* }}} */
/* {{{ proto bool pg_send_query(resource connection, string query)
Send asynchronous query */
PHP_FUNCTION(pg_send_query)
{
zval *pgsql_link;
char *query;
size_t len;
int id = -1;
PGconn *pgsql;
int is_non_blocking;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &query, &len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
is_non_blocking = PQisnonblocking(pgsql);
if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
if (_php_pgsql_link_has_results(pgsql)) {
php_error_docref(NULL, E_NOTICE,
"There are results on this connection. Call pg_get_result() until it returns FALSE");
}
if (is_non_blocking) {
if (!PQsendQuery(pgsql, query)) {
RETURN_FALSE;
}
ret = PQflush(pgsql);
} else {
if (!PQsendQuery(pgsql, query)) {
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQreset(pgsql);
}
if (!PQsendQuery(pgsql, query)) {
RETURN_FALSE;
}
}
/* Wait to finish sending buffer */
while ((ret = PQflush(pgsql))) {
if (ret == -1) {
php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer");
break;
}
usleep(10000);
}
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode");
}
}
if (ret == 0) {
RETURN_TRUE;
} else if (ret == -1) {
RETURN_FALSE;
} else {
RETURN_LONG(0);
}
}
/* }}} */
#if HAVE_PQSENDQUERYPARAMS
/* {{{ proto bool pg_send_query_params(resource connection, string query, array params)
Send asynchronous parameterized query */
PHP_FUNCTION(pg_send_query_params)
{
zval *pgsql_link, *pv_param_arr, *tmp;
int num_params = 0;
char **params = NULL;
char *query;
size_t query_len;
int id = -1;
PGconn *pgsql;
int is_non_blocking;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa/", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) {
return;
}
if (pgsql_link == NULL) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
is_non_blocking = PQisnonblocking(pgsql);
if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
if (_php_pgsql_link_has_results(pgsql)) {
php_error_docref(NULL, E_NOTICE,
"There are results on this connection. Call pg_get_result() until it returns FALSE");
}
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) {
if (Z_TYPE_P(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val;
ZVAL_COPY(&tmp_val, tmp);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL, E_WARNING,"Error converting parameter");
zval_ptr_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_ptr_dtor(&tmp_val);
}
i++;
} ZEND_HASH_FOREACH_END();
}
if (PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
_php_pgsql_free_params(params, num_params);
} else if (is_non_blocking) {
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
} else {
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQreset(pgsql);
}
if (!PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
}
if (is_non_blocking) {
ret = PQflush(pgsql);
} else {
/* Wait to finish sending buffer */
while ((ret = PQflush(pgsql))) {
if (ret == -1) {
php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer");
break;
}
usleep(10000);
}
if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode");
}
}
if (ret == 0) {
RETURN_TRUE;
} else if (ret == -1) {
RETURN_FALSE;
} else {
RETURN_LONG(0);
}
}
/* }}} */
#endif
#if HAVE_PQSENDPREPARE
/* {{{ proto bool pg_send_prepare(resource connection, string stmtname, string query)
Asynchronously prepare a query for future execution */
PHP_FUNCTION(pg_send_prepare)
{
zval *pgsql_link;
char *query, *stmtname;
size_t stmtname_len, query_len;
int id = -1;
PGconn *pgsql;
int is_non_blocking;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) {
return;
}
if (pgsql_link == NULL) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
is_non_blocking = PQisnonblocking(pgsql);
if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
if (_php_pgsql_link_has_results(pgsql)) {
php_error_docref(NULL, E_NOTICE,
"There are results on this connection. Call pg_get_result() until it returns FALSE");
}
if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) {
if (is_non_blocking) {
RETURN_FALSE;
} else {
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQreset(pgsql);
}
if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) {
RETURN_FALSE;
}
}
}
if (is_non_blocking) {
ret = PQflush(pgsql);
} else {
/* Wait to finish sending buffer */
while ((ret = PQflush(pgsql))) {
if (ret == -1) {
php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer");
break;
}
usleep(10000);
}
if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode");
}
}
if (ret == 0) {
RETURN_TRUE;
} else if (ret == -1) {
RETURN_FALSE;
} else {
RETURN_LONG(0);
}
}
/* }}} */
#endif
#if HAVE_PQSENDQUERYPREPARED
/* {{{ proto bool pg_send_execute(resource connection, string stmtname, array params)
Executes prevriously prepared stmtname asynchronously */
PHP_FUNCTION(pg_send_execute)
{
zval *pgsql_link;
zval *pv_param_arr, *tmp;
int num_params = 0;
char **params = NULL;
char *stmtname;
size_t stmtname_len;
int id = -1;
PGconn *pgsql;
int is_non_blocking;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) {
return;
}
if (pgsql_link == NULL) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
is_non_blocking = PQisnonblocking(pgsql);
if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
if (_php_pgsql_link_has_results(pgsql)) {
php_error_docref(NULL, E_NOTICE,
"There are results on this connection. Call pg_get_result() until it returns FALSE");
}
num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr));
if (num_params > 0) {
int i = 0;
params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) {
if (Z_TYPE_P(tmp) == IS_NULL) {
params[i] = NULL;
} else {
zval tmp_val;
ZVAL_COPY(&tmp_val, tmp);
convert_to_string(&tmp_val);
if (Z_TYPE(tmp_val) != IS_STRING) {
php_error_docref(NULL, E_WARNING,"Error converting parameter");
zval_ptr_dtor(&tmp_val);
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val));
zval_ptr_dtor(&tmp_val);
}
i++;
} ZEND_HASH_FOREACH_END();
}
if (PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) {
_php_pgsql_free_params(params, num_params);
} else if (is_non_blocking) {
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
} else {
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
PQreset(pgsql);
}
if (!PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) {
_php_pgsql_free_params(params, num_params);
RETURN_FALSE;
}
}
if (is_non_blocking) {
ret = PQflush(pgsql);
} else {
/* Wait to finish sending buffer */
while ((ret = PQflush(pgsql))) {
if (ret == -1) {
php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer");
break;
}
usleep(10000);
}
if (PQ_SETNONBLOCKING(pgsql, 0) != 0) {
php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode");
}
}
if (ret == 0) {
RETURN_TRUE;
} else if (ret == -1) {
RETURN_FALSE;
} else {
RETURN_LONG(0);
}
}
/* }}} */
#endif
/* {{{ proto resource pg_get_result(resource connection)
Get asynchronous query result */
PHP_FUNCTION(pg_get_result)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
pgsql_result = PQgetResult(pgsql);
if (!pgsql_result) {
/* no result */
RETURN_FALSE;
}
pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pg_result->conn = pgsql;
pg_result->result = pgsql_result;
pg_result->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
}
/* }}} */
/* {{{ proto mixed pg_result_status(resource result[, long result_type])
Get status of query result */
PHP_FUNCTION(pg_result_status)
{
zval *result;
zend_long result_type = PGSQL_STATUS_LONG;
ExecStatusType status;
PGresult *pgsql_result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l",
&result, &result_type) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
pgsql_result = pg_result->result;
if (result_type == PGSQL_STATUS_LONG) {
status = PQresultStatus(pgsql_result);
RETURN_LONG((int)status);
}
else if (result_type == PGSQL_STATUS_STRING) {
RETURN_STRING(PQcmdStatus(pgsql_result));
}
else {
php_error_docref(NULL, E_WARNING, "Optional 2nd parameter should be PGSQL_STATUS_LONG or PGSQL_STATUS_STRING");
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto array pg_get_notify([resource connection[, result_type]])
Get asynchronous notification */
PHP_FUNCTION(pg_get_notify)
{
zval *pgsql_link;
int id = -1;
zend_long result_type = PGSQL_ASSOC;
PGconn *pgsql;
PGnotify *pgsql_notify;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l",
&pgsql_link, &result_type) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
PQconsumeInput(pgsql);
pgsql_notify = PQnotifies(pgsql);
if (!pgsql_notify) {
/* no notify message */
RETURN_FALSE;
}
array_init(return_value);
if (result_type & PGSQL_NUM) {
add_index_string(return_value, 0, pgsql_notify->relname);
add_index_long(return_value, 1, pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_index_string(return_value, 2, pgsql_notify->extra);
#endif
}
}
if (result_type & PGSQL_ASSOC) {
add_assoc_string(return_value, "message", pgsql_notify->relname);
add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_assoc_string(return_value, "payload", pgsql_notify->extra);
#endif
}
}
PQfreemem(pgsql_notify);
}
/* }}} */
Commit Message:
CWE ID: | 0 | 5,230 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void HTMLElement::setContentEditable(const String& enabled, ExceptionCode& ec)
{
if (equalIgnoringCase(enabled, "true"))
setAttribute(contenteditableAttr, "true");
else if (equalIgnoringCase(enabled, "false"))
setAttribute(contenteditableAttr, "false");
else if (equalIgnoringCase(enabled, "plaintext-only"))
setAttribute(contenteditableAttr, "plaintext-only");
else if (equalIgnoringCase(enabled, "inherit"))
removeAttribute(contenteditableAttr);
else
ec = SYNTAX_ERR;
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | 0 | 100,388 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: parsereq(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
register u_int len;
/*
* find the start of the req data (if we captured it)
*/
dp = (const uint32_t *)&rp->rm_call.cb_cred;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK2(dp[0], 0);
return (dp);
}
}
trunc:
return (NULL);
}
Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | 0 | 62,462 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void DeprecateAsSameValueMeasureAsSameValueOverloadedMethod1Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
impl->deprecateAsSameValueMeasureAsSameValueOverloadedMethod();
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <peria@chromium.org>
Commit-Queue: Yuki Shiino <yukishiino@chromium.org>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID: | 0 | 134,654 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: void ScriptProcessorHandler::SetChannelCount(unsigned long channel_count,
ExceptionState& exception_state) {
DCHECK(IsMainThread());
BaseAudioContext::GraphAutoLocker locker(Context());
if (channel_count != channel_count_) {
exception_state.ThrowDOMException(
kNotSupportedError, "channelCount cannot be changed from " +
String::Number(channel_count_) + " to " +
String::Number(channel_count));
}
}
Commit Message: Keep ScriptProcessorHandler alive across threads
When posting a task from the ScriptProcessorHandler::Process to fire a
process event, we need to keep the handler alive in case the
ScriptProcessorNode goes away (because it has no onaudioprocess
handler) and removes the its handler.
Bug: 765495
Test:
Change-Id: Ib4fa39d7b112c7051897700a1eff9f59a4a7a054
Reviewed-on: https://chromium-review.googlesource.com/677137
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Cr-Commit-Position: refs/heads/master@{#503629}
CWE ID: CWE-416 | 0 | 150,737 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: kadm5_chpass_principal(void *server_handle,
krb5_principal principal, char *password)
{
return
kadm5_chpass_principal_3(server_handle, principal, FALSE,
0, NULL, password);
}
Commit Message: Null pointer deref in kadmind [CVE-2012-1013]
The fix for #6626 could cause kadmind to dereference a null pointer if
a create-principal request contains no password but does contain the
KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix
name"). Only clients authorized to create principals can trigger the
bug. Fix the bug by testing for a null password in check_1_6_dummy.
CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
[ghudson@mit.edu: Minor style change and commit message]
ticket: 7152
target_version: 1.10.2
tags: pullup
CWE ID: | 0 | 21,488 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int ip6mr_fib_lookup(struct net *net, struct flowi6 *flp6,
struct mr6_table **mrt)
{
*mrt = net->ipv6.mrt6;
return 0;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <lucien.xin@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-20 | 0 | 93,526 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static void pmcraid_tasklet_function(unsigned long instance)
{
struct pmcraid_isr_param *hrrq_vector;
struct pmcraid_instance *pinstance;
unsigned long hrrq_lock_flags;
unsigned long pending_lock_flags;
unsigned long host_lock_flags;
spinlock_t *lockp; /* hrrq buffer lock */
int id;
__le32 resp;
hrrq_vector = (struct pmcraid_isr_param *)instance;
pinstance = hrrq_vector->drv_inst;
id = hrrq_vector->hrrq_id;
lockp = &(pinstance->hrrq_lock[id]);
/* loop through each of the commands responded by IOA. Each HRRQ buf is
* protected by its own lock. Traversals must be done within this lock
* as there may be multiple tasklets running on multiple CPUs. Note
* that the lock is held just for picking up the response handle and
* manipulating hrrq_curr/toggle_bit values.
*/
spin_lock_irqsave(lockp, hrrq_lock_flags);
resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
while ((resp & HRRQ_TOGGLE_BIT) ==
pinstance->host_toggle_bit[id]) {
int cmd_index = resp >> 2;
struct pmcraid_cmd *cmd = NULL;
if (pinstance->hrrq_curr[id] < pinstance->hrrq_end[id]) {
pinstance->hrrq_curr[id]++;
} else {
pinstance->hrrq_curr[id] = pinstance->hrrq_start[id];
pinstance->host_toggle_bit[id] ^= 1u;
}
if (cmd_index >= PMCRAID_MAX_CMD) {
/* In case of invalid response handle, log message */
pmcraid_err("Invalid response handle %d\n", cmd_index);
resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
continue;
}
cmd = pinstance->cmd_list[cmd_index];
spin_unlock_irqrestore(lockp, hrrq_lock_flags);
spin_lock_irqsave(&pinstance->pending_pool_lock,
pending_lock_flags);
list_del(&cmd->free_list);
spin_unlock_irqrestore(&pinstance->pending_pool_lock,
pending_lock_flags);
del_timer(&cmd->timer);
atomic_dec(&pinstance->outstanding_cmds);
if (cmd->cmd_done == pmcraid_ioa_reset) {
spin_lock_irqsave(pinstance->host->host_lock,
host_lock_flags);
cmd->cmd_done(cmd);
spin_unlock_irqrestore(pinstance->host->host_lock,
host_lock_flags);
} else if (cmd->cmd_done != NULL) {
cmd->cmd_done(cmd);
}
/* loop over until we are done with all responses */
spin_lock_irqsave(lockp, hrrq_lock_flags);
resp = le32_to_cpu(*(pinstance->hrrq_curr[id]));
}
spin_unlock_irqrestore(lockp, hrrq_lock_flags);
}
Commit Message: [SCSI] pmcraid: reject negative request size
There's a code path in pmcraid that can be reached via device ioctl that
causes all sorts of ugliness, including heap corruption or triggering the
OOM killer due to consecutive allocation of large numbers of pages.
First, the user can call pmcraid_chr_ioctl(), with a type
PMCRAID_PASSTHROUGH_IOCTL. This calls through to
pmcraid_ioctl_passthrough(). Next, a pmcraid_passthrough_ioctl_buffer
is copied in, and the request_size variable is set to
buffer->ioarcb.data_transfer_length, which is an arbitrary 32-bit
signed value provided by the user. If a negative value is provided
here, bad things can happen. For example,
pmcraid_build_passthrough_ioadls() is called with this request_size,
which immediately calls pmcraid_alloc_sglist() with a negative size.
The resulting math on allocating a scatter list can result in an
overflow in the kzalloc() call (if num_elem is 0, the sglist will be
smaller than expected), or if num_elem is unexpectedly large the
subsequent loop will call alloc_pages() repeatedly, a high number of
pages will be allocated and the OOM killer might be invoked.
It looks like preventing this value from being negative in
pmcraid_ioctl_passthrough() would be sufficient.
Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com>
Cc: <stable@kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: James Bottomley <JBottomley@Parallels.com>
CWE ID: CWE-189 | 0 | 26,530 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: static int rtnl_link_slave_info_fill(struct sk_buff *skb,
const struct net_device *dev)
{
struct net_device *master_dev;
const struct rtnl_link_ops *ops;
struct nlattr *slave_data;
int err;
master_dev = netdev_master_upper_dev_get((struct net_device *) dev);
if (!master_dev)
return 0;
ops = master_dev->rtnl_link_ops;
if (!ops)
return 0;
if (nla_put_string(skb, IFLA_INFO_SLAVE_KIND, ops->kind) < 0)
return -EMSGSIZE;
if (ops->fill_slave_info) {
slave_data = nla_nest_start(skb, IFLA_INFO_SLAVE_DATA);
if (!slave_data)
return -EMSGSIZE;
err = ops->fill_slave_info(skb, master_dev, dev);
if (err < 0)
goto err_cancel_slave_data;
nla_nest_end(skb, slave_data);
}
return 0;
err_cancel_slave_data:
nla_nest_cancel(skb, slave_data);
return err;
}
Commit Message: net: fix infoleak in rtnetlink
The stack object “map” has a total size of 32 bytes. Its last 4
bytes are padding generated by compiler. These padding bytes are
not initialized and sent out via “nla_put”.
Signed-off-by: Kangjie Lu <kjlu@gatech.edu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200 | 0 | 53,168 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: kadm5_get_principal(void *server_handle, krb5_principal principal,
kadm5_principal_ent_t entry,
long in_mask)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret = 0;
long mask;
int i;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
/*
* In version 1, all the defined fields are always returned.
* entry is a pointer to a kadm5_principal_ent_t_v1 that should be
* filled with allocated memory.
*/
mask = in_mask;
memset(entry, 0, sizeof(*entry));
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return ret;
if ((mask & KADM5_POLICY) &&
adb.policy && (adb.aux_attributes & KADM5_POLICY)) {
if ((entry->policy = strdup(adb.policy)) == NULL) {
ret = ENOMEM;
goto done;
}
}
if (mask & KADM5_AUX_ATTRIBUTES)
entry->aux_attributes = adb.aux_attributes;
if ((mask & KADM5_PRINCIPAL) &&
(ret = krb5_copy_principal(handle->context, kdb->princ,
&entry->principal))) {
goto done;
}
if (mask & KADM5_PRINC_EXPIRE_TIME)
entry->princ_expire_time = kdb->expiration;
if ((mask & KADM5_LAST_PWD_CHANGE) &&
(ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(entry->last_pwd_change)))) {
goto done;
}
if (mask & KADM5_PW_EXPIRATION)
entry->pw_expiration = kdb->pw_expiration;
if (mask & KADM5_MAX_LIFE)
entry->max_life = kdb->max_life;
/* this is a little non-sensical because the function returns two */
/* values that must be checked separately against the mask */
if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) {
ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb,
&(entry->mod_date),
&(entry->mod_name));
if (ret) {
goto done;
}
if (! (mask & KADM5_MOD_TIME))
entry->mod_date = 0;
if (! (mask & KADM5_MOD_NAME)) {
krb5_free_principal(handle->context, entry->mod_name);
entry->mod_name = NULL;
}
}
if (mask & KADM5_ATTRIBUTES)
entry->attributes = kdb->attributes;
if (mask & KADM5_KVNO)
for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++)
if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno)
entry->kvno = kdb->key_data[i].key_data_kvno;
if (mask & KADM5_MKVNO) {
ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno);
if (ret)
goto done;
}
if (mask & KADM5_MAX_RLIFE)
entry->max_renewable_life = kdb->max_renewable_life;
if (mask & KADM5_LAST_SUCCESS)
entry->last_success = kdb->last_success;
if (mask & KADM5_LAST_FAILED)
entry->last_failed = kdb->last_failed;
if (mask & KADM5_FAIL_AUTH_COUNT)
entry->fail_auth_count = kdb->fail_auth_count;
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl, *tl2;
entry->tl_data = NULL;
tl = kdb->tl_data;
while (tl) {
if (tl->tl_data_type > 255) {
if ((tl2 = dup_tl_data(tl)) == NULL) {
ret = ENOMEM;
goto done;
}
tl2->tl_data_next = entry->tl_data;
entry->tl_data = tl2;
entry->n_tl_data++;
}
tl = tl->tl_data_next;
}
}
if (mask & KADM5_KEY_DATA) {
entry->n_key_data = kdb->n_key_data;
if(entry->n_key_data) {
entry->key_data = k5calloc(entry->n_key_data,
sizeof(krb5_key_data), &ret);
if (entry->key_data == NULL)
goto done;
} else
entry->key_data = NULL;
for (i = 0; i < entry->n_key_data; i++)
ret = krb5_copy_key_data_contents(handle->context,
&kdb->key_data[i],
&entry->key_data[i]);
if (ret)
goto done;
}
ret = KADM5_OK;
done:
if (ret && entry->principal) {
krb5_free_principal(handle->context, entry->principal);
entry->principal = NULL;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
Commit Message: Return only new keys in randkey [CVE-2014-5351]
In kadmind's randkey operation, if a client specifies the keepold
flag, do not include the preserved old keys in the response.
CVE-2014-5351:
An authenticated remote attacker can retrieve the current keys for a
service principal when generating a new set of keys for that
principal. The attacker needs to be authenticated as a user who has
the elevated privilege for randomizing the keys of other principals.
Normally, when a Kerberos administrator randomizes the keys of a
service principal, kadmind returns only the new keys. This prevents
an administrator who lacks legitimate privileged access to a service
from forging tickets to authenticate to that service. If the
"keepold" flag to the kadmin randkey RPC operation is true, kadmind
retains the old keys in the KDC database as intended, but also
unexpectedly returns the old keys to the client, which exposes the
service to ticket forgery attacks from the administrator.
A mitigating factor is that legitimate clients of the affected service
will start failing to authenticate to the service once they begin to
receive service tickets encrypted in the new keys. The affected
service will be unable to decrypt the newly issued tickets, possibly
alerting the legitimate administrator of the affected service.
CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
[tlyu@mit.edu: CVE description and CVSS score]
ticket: 8018 (new)
target_version: 1.13
tags: pullup
CWE ID: CWE-255 | 0 | 36,143 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: struct kern_ipc_perm *ipcctl_pre_down_nolock(struct ipc_namespace *ns,
struct ipc_ids *ids, int id, int cmd,
struct ipc64_perm *perm, int extra_perm)
{
kuid_t euid;
int err = -EPERM;
struct kern_ipc_perm *ipcp;
down_write(&ids->rw_mutex);
rcu_read_lock();
ipcp = ipc_obtain_object_check(ids, id);
if (IS_ERR(ipcp)) {
err = PTR_ERR(ipcp);
goto out_up;
}
audit_ipc_obj(ipcp);
if (cmd == IPC_SET)
audit_ipc_set_perm(extra_perm, perm->uid,
perm->gid, perm->mode);
euid = current_euid();
if (uid_eq(euid, ipcp->cuid) || uid_eq(euid, ipcp->uid) ||
ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ipcp;
out_up:
/*
* Unsuccessful lookup, unlock and return
* the corresponding error.
*/
rcu_read_unlock();
up_write(&ids->rw_mutex);
return ERR_PTR(err);
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[davidlohr.bueso@hp.com: do not call sem_lock when bogus sma]
[davidlohr.bueso@hp.com: make refcounter atomic]
Signed-off-by: Rik van Riel <riel@redhat.com>
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Acked-by: Davidlohr Bueso <davidlohr.bueso@hp.com>
Cc: Chegu Vinod <chegu_vinod@hp.com>
Cc: Jason Low <jason.low2@hp.com>
Reviewed-by: Michel Lespinasse <walken@google.com>
Cc: Peter Hurley <peter@hurleysoftware.com>
Cc: Stanislav Kinsbursky <skinsbursky@parallels.com>
Tested-by: Emmanuel Benisty <benisty.e@gmail.com>
Tested-by: Sedat Dilek <sedat.dilek@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-189 | 0 | 29,576 |
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. | Code: pick_next_task(struct rq *rq)
{
const struct sched_class *class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(rq->nr_running == rq->cfs.nr_running)) {
p = fair_sched_class.pick_next_task(rq);
if (likely(p))
return p;
}
for_each_class(class) {
p = class->pick_next_task(rq);
if (p)
return p;
}
BUG(); /* the idle class will always have a runnable task */
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <efault@gmx.de>
Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com>
Tested-by: Yong Zhang <yong.zhang0@gmail.com>
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: stable@kernel.org
LKML-Reference: <1291802742.1417.9.camel@marge.simson.net>
Signed-off-by: Ingo Molnar <mingo@elte.hu>
CWE ID: | 0 | 22,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.