instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LoadingStatsCollectorTest::TestRedirectStatusHistogram(
const std::string& initial_url,
const std::string& prediction_url,
const std::string& navigation_url,
RedirectStatus expected_status) {
const std::string& script_url = "https://cdn.google.com/script.js";
PreconnectPrediction prediction = CreatePreconnectPrediction(
GURL(prediction_url).host(), initial_url != prediction_url,
{{GURL(script_url).GetOrigin(), 1, net::NetworkIsolationKey()}});
EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _))
.WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true)));
std::vector<content::mojom::ResourceLoadInfoPtr> resources;
resources.push_back(
CreateResourceLoadInfoWithRedirects({initial_url, navigation_url}));
resources.push_back(
CreateResourceLoadInfo(script_url, content::ResourceType::kScript));
PageRequestSummary summary =
CreatePageRequestSummary(navigation_url, initial_url, resources);
stats_collector_->RecordPageRequestSummary(summary);
histogram_tester_->ExpectUniqueSample(
internal::kLoadingPredictorPreconnectLearningRedirectStatus,
static_cast<int>(expected_status), 1);
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void LoadingStatsCollectorTest::TestRedirectStatusHistogram(
const std::string& initial_url,
const std::string& prediction_url,
const std::string& navigation_url,
RedirectStatus expected_status) {
const std::string& script_url = "https://cdn.google.com/script.js";
PreconnectPrediction prediction = CreatePreconnectPrediction(
GURL(prediction_url).host(), initial_url != prediction_url,
{{url::Origin::Create(GURL(script_url)), 1, net::NetworkIsolationKey()}});
EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _))
.WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true)));
std::vector<content::mojom::ResourceLoadInfoPtr> resources;
resources.push_back(
CreateResourceLoadInfoWithRedirects({initial_url, navigation_url}));
resources.push_back(
CreateResourceLoadInfo(script_url, content::ResourceType::kScript));
PageRequestSummary summary =
CreatePageRequestSummary(navigation_url, initial_url, resources);
stats_collector_->RecordPageRequestSummary(summary);
histogram_tester_->ExpectUniqueSample(
internal::kLoadingPredictorPreconnectLearningRedirectStatus,
static_cast<int>(expected_status), 1);
}
| 172,373
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void fe_netjoin_init(void)
{
settings_add_bool("misc", "hide_netsplit_quits", TRUE);
settings_add_int("misc", "netjoin_max_nicks", 10);
join_tag = -1;
printing_joins = FALSE;
read_settings();
signal_add("setup changed", (SIGNAL_FUNC) read_settings);
}
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
CWE ID: CWE-416
|
void fe_netjoin_init(void)
{
settings_add_bool("misc", "hide_netsplit_quits", TRUE);
settings_add_int("misc", "netjoin_max_nicks", 10);
join_tag = -1;
printing_joins = FALSE;
read_settings();
signal_add("setup changed", (SIGNAL_FUNC) read_settings);
signal_add("server disconnected", (SIGNAL_FUNC) sig_server_disconnected);
}
| 168,291
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 len;
UINT32 left;
BYTE value;
left = originalSize;
while (left > 4)
{
value = *in++;
if (left == 5)
{
*out++ = value;
left--;
}
else if (value == *in)
{
in++;
if (*in < 0xFF)
{
len = (UINT32) * in++;
len += 2;
}
else
{
in++;
len = *((UINT32*) in);
in += 4;
}
FillMemory(out, len, value);
out += len;
left -= len;
}
else
{
*out++ = value;
left--;
}
}
*((UINT32*)out) = *((UINT32*)in);
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787
|
static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize)
static BOOL nsc_rle_decode(BYTE* in, BYTE* out, UINT32 outSize, UINT32 originalSize)
{
UINT32 len;
UINT32 left;
BYTE value;
left = originalSize;
while (left > 4)
{
value = *in++;
if (left == 5)
{
if (outSize < 1)
return FALSE;
outSize--;
*out++ = value;
left--;
}
else if (value == *in)
{
in++;
if (*in < 0xFF)
{
len = (UINT32) * in++;
len += 2;
}
else
{
in++;
len = *((UINT32*) in);
in += 4;
}
if (outSize < len)
return FALSE;
outSize -= len;
FillMemory(out, len, value);
out += len;
left -= len;
}
else
{
if (outSize < 1)
return FALSE;
outSize--;
*out++ = value;
left--;
}
}
if ((outSize < 4) || (left < 4))
return FALSE;
memcpy(out, in, 4);
return TRUE;
}
| 169,284
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
if (a == NULL)
return (0);
neg = a->type & V_ASN1_NEG;
if (a->length == 0)
ret = 1;
else {
ret = a->length;
i = a->data[0];
if (!neg && (i > 127)) {
pad = 1;
pb = 0;
pad = 1;
pb = 0xFF;
} else if (i == 128) {
/*
* Special case: if any other bytes non zero we pad:
* otherwise we don't.
*/
for (i = 1; i < a->length; i++)
if (a->data[i]) {
pad = 1;
pb = 0xFF;
break;
}
}
}
ret += pad;
}
Commit Message:
CWE ID: CWE-119
|
int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
if (a == NULL)
return (0);
neg = a->type & V_ASN1_NEG;
if (a->length == 0)
ret = 1;
else {
ret = a->length;
i = a->data[0];
if (ret == 1 && i == 0)
neg = 0;
if (!neg && (i > 127)) {
pad = 1;
pb = 0;
pad = 1;
pb = 0xFF;
} else if (i == 128) {
/*
* Special case: if any other bytes non zero we pad:
* otherwise we don't.
*/
for (i = 1; i < a->length; i++)
if (a->data[i]) {
pad = 1;
pb = 0xFF;
break;
}
}
}
ret += pad;
}
| 165,210
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void FrameworkListener::init(const char *socketName UNUSED, bool withSeq) {
mCommands = new FrameworkCommandCollection();
errorRate = 0;
mCommandCount = 0;
mWithSeq = withSeq;
}
Commit Message: Fix vold vulnerability in FrameworkListener
Modify FrameworkListener to ignore commands that exceed the maximum
buffer length and send an error message.
Bug: 29831647
Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950
Signed-off-by: Connor O'Brien <connoro@google.com>
(cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a)
(cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e)
CWE ID: CWE-264
|
void FrameworkListener::init(const char *socketName UNUSED, bool withSeq) {
mCommands = new FrameworkCommandCollection();
errorRate = 0;
mCommandCount = 0;
mWithSeq = withSeq;
mSkipToNextNullByte = false;
}
| 173,390
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-13052/CFM: refine decoding of the Sender ID TLV
In cfm_network_addr_print() add a length argument and use it to validate
the input buffer.
In cfm_print() add a length check for MAC address chassis ID. Supply
cfm_network_addr_print() with the length of its buffer and a correct
pointer to the buffer (it was off-by-one before). Change some error
handling blocks to skip to the next TLV in the current PDU rather than to
stop decoding the PDU. Print the management domain and address contents,
although in hex only so far.
Add some comments to clarify the code flow and to tell exact sections in
IEEE standard documents. Add new error messages and make some existing
messages more specific.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr, const u_int length)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
if (length < 1) {
ND_PRINT((ndo, "\n\t Network Address Type (invalid, no data"));
return hexdump;
}
/* The calling function must make any due ND_TCHECK calls. */
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
if (length != 1 + 4) {
ND_PRINT((ndo, "(invalid IPv4 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
if (length != 1 + 16) {
ND_PRINT((ndo, "(invalid IPv6 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,821
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
size_t imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
|
static sk_sp<SkImage> newSkImageFromRaster(const SkImageInfo& info,
PassRefPtr<Uint8Array> imagePixels,
unsigned imageRowBytes) {
SkPixmap pixmap(info, imagePixels->data(), imageRowBytes);
return SkImage::MakeFromRaster(pixmap,
[](const void*, void* pixels) {
static_cast<Uint8Array*>(pixels)->deref();
},
imagePixels.leakRef());
}
| 172,503
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
| 171,422
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ConvertProperty(IBusProperty* ibus_prop,
int selection_item_id,
ImePropertyList* out_prop_list) {
DCHECK(ibus_prop);
DCHECK(ibus_prop->key);
DCHECK(out_prop_list);
const bool has_sub_props = PropertyHasChildren(ibus_prop);
if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) {
LOG(ERROR) << "The property has sub properties, "
<< "but the type of the property is not PROP_TYPE_MENU";
return false;
}
if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) {
DLOG(INFO) << "Property list is empty";
return false;
}
if (ibus_prop->type == PROP_TYPE_SEPARATOR ||
ibus_prop->type == PROP_TYPE_MENU) {
return true;
}
const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO);
selection_item_id = is_selection_item ?
selection_item_id : ImeProperty::kInvalidSelectionItemId;
bool is_selection_item_checked = false;
if (ibus_prop->state == PROP_STATE_INCONSISTENT) {
LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, "
<< "which is not supported.";
} else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) {
LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is "
<< "PROP_TYPE_RADIO.";
} else {
is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED);
}
if (!ibus_prop->key) {
LOG(ERROR) << "key is NULL";
}
if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) {
LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
if (ibus_prop->label && (!ibus_prop->label->text)) {
LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
std::string label =
((ibus_prop->tooltip &&
ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : "");
if (label.empty()) {
label = (ibus_prop->label && ibus_prop->label->text)
? ibus_prop->label->text : "";
}
if (label.empty()) {
label = Or(ibus_prop->key, "");
}
out_prop_list->push_back(ImeProperty(ibus_prop->key,
label,
is_selection_item,
is_selection_item_checked,
selection_item_id));
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ConvertProperty(IBusProperty* ibus_prop,
int selection_item_id,
ImePropertyList* out_prop_list) {
DCHECK(ibus_prop);
DCHECK(ibus_prop->key);
DCHECK(out_prop_list);
const bool has_sub_props = PropertyHasChildren(ibus_prop);
if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) {
LOG(ERROR) << "The property has sub properties, "
<< "but the type of the property is not PROP_TYPE_MENU";
return false;
}
if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) {
VLOG(1) << "Property list is empty";
return false;
}
if (ibus_prop->type == PROP_TYPE_SEPARATOR ||
ibus_prop->type == PROP_TYPE_MENU) {
return true;
}
const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO);
selection_item_id = is_selection_item ?
selection_item_id : ImeProperty::kInvalidSelectionItemId;
bool is_selection_item_checked = false;
if (ibus_prop->state == PROP_STATE_INCONSISTENT) {
LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, "
<< "which is not supported.";
} else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) {
LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is "
<< "PROP_TYPE_RADIO.";
} else {
is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED);
}
if (!ibus_prop->key) {
LOG(ERROR) << "key is NULL";
}
if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) {
LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
if (ibus_prop->label && (!ibus_prop->label->text)) {
LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
std::string label =
((ibus_prop->tooltip &&
ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : "");
if (label.empty()) {
label = (ibus_prop->label && ibus_prop->label->text)
? ibus_prop->label->text : "";
}
if (label.empty()) {
label = Or(ibus_prop->key, "");
}
out_prop_list->push_back(ImeProperty(ibus_prop->key,
label,
is_selection_item,
is_selection_item_checked,
selection_item_id));
return true;
}
| 170,531
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(readlink)
{
char *link;
int link_len;
char buff[MAXPATHLEN];
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &link, &link_len) == FAILURE) {
return;
}
if (php_check_open_basedir(link TSRMLS_CC)) {
RETURN_FALSE;
}
ret = php_sys_readlink(link, buff, MAXPATHLEN-1);
if (ret == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno));
RETURN_FALSE;
}
/* Append NULL to the end of the string */
buff[ret] = '\0';
RETURN_STRING(buff, 1);
}
Commit Message:
CWE ID: CWE-254
|
PHP_FUNCTION(readlink)
{
char *link;
int link_len;
char buff[MAXPATHLEN];
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &link, &link_len) == FAILURE) {
return;
}
if (php_check_open_basedir(link TSRMLS_CC)) {
RETURN_FALSE;
}
ret = php_sys_readlink(link, buff, MAXPATHLEN-1);
if (ret == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno));
RETURN_FALSE;
}
/* Append NULL to the end of the string */
buff[ret] = '\0';
RETURN_STRING(buff, 1);
}
| 165,316
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool has_byte(const eager_reader_t *reader) {
assert(reader != NULL);
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(reader->bytes_available_fd, &read_fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
select(reader->bytes_available_fd + 1, &read_fds, NULL, NULL, &timeout);
return FD_ISSET(reader->bytes_available_fd, &read_fds);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static bool has_byte(const eager_reader_t *reader) {
assert(reader != NULL);
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(reader->bytes_available_fd, &read_fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
TEMP_FAILURE_RETRY(select(reader->bytes_available_fd + 1, &read_fds, NULL, NULL, &timeout));
return FD_ISSET(reader->bytes_available_fd, &read_fds);
}
| 173,480
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
Commit Message: bpf: force strict alignment checks for stack pointers
Force strict alignment checks for stack pointers because the tracking of
stack spills relies on it; unaligned stack accesses can lead to corruption
of spilled registers, which is exploitable.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
CWE ID: CWE-119
|
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size)
{
bool strict = env->strict_alignment;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
| 167,641
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
TIFFSwabArrayOfShort(wp, wc);
horAcc16(tif, cp0, cc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
TIFFSwabArrayOfShort(wp, wc);
return horAcc16(tif, cp0, cc);
}
| 166,888
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Error: invalid .Xauthority file\n");
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) == -1)
errExit("fchown");
if (chmod(dest, 0600) == -1)
errExit("fchmod");
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269
|
static int store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600); // regular user
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 170,100
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
| 167,207
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void UrlFetcherDownloader::OnNetworkFetcherComplete(base::FilePath file_path,
int net_error,
int64_t content_size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
const base::TimeTicks download_end_time(base::TimeTicks::Now());
const base::TimeDelta download_time =
download_end_time >= download_start_time_
? download_end_time - download_start_time_
: base::TimeDelta();
int error = -1;
if (!file_path.empty() && response_code_ == 200) {
DCHECK_EQ(0, net_error);
error = 0;
} else if (response_code_ != -1) {
error = response_code_;
} else {
error = net_error;
}
const bool is_handled = error == 0 || IsHttpServerError(error);
Result result;
result.error = error;
if (!error) {
result.response = file_path;
}
DownloadMetrics download_metrics;
download_metrics.url = url();
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = error;
download_metrics.downloaded_bytes = error ? -1 : content_size;
download_metrics.total_bytes = total_bytes_;
download_metrics.download_time_ms = download_time.InMilliseconds();
VLOG(1) << "Downloaded " << content_size << " bytes in "
<< download_time.InMilliseconds() << "ms from " << url().spec()
<< " to " << result.response.value();
if (error && !download_dir_.empty()) {
base::PostTask(FROM_HERE, kTaskTraits,
base::BindOnce(IgnoreResult(&base::DeleteFileRecursively),
download_dir_));
}
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), is_handled, result,
download_metrics));
}
Commit Message: Fix error handling in the request sender and url fetcher downloader.
That means handling the network errors by primarily looking at net_error.
Bug: 1028369
Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Commit-Queue: Sorin Jianu <sorin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#719199}
CWE ID: CWE-20
|
void UrlFetcherDownloader::OnNetworkFetcherComplete(base::FilePath file_path,
void UrlFetcherDownloader::OnNetworkFetcherComplete(int net_error,
int64_t content_size) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
const base::TimeTicks download_end_time(base::TimeTicks::Now());
const base::TimeDelta download_time =
download_end_time >= download_start_time_
? download_end_time - download_start_time_
: base::TimeDelta();
int error = -1;
if (!net_error && response_code_ == 200)
error = 0;
else if (response_code_ != -1)
error = response_code_;
else
error = net_error;
const bool is_handled = error == 0 || IsHttpServerError(error);
Result result;
result.error = error;
if (!error)
result.response = file_path_;
DownloadMetrics download_metrics;
download_metrics.url = url();
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = error;
download_metrics.downloaded_bytes = error ? -1 : content_size;
download_metrics.total_bytes = total_bytes_;
download_metrics.download_time_ms = download_time.InMilliseconds();
VLOG(1) << "Downloaded " << content_size << " bytes in "
<< download_time.InMilliseconds() << "ms from " << url().spec()
<< " to " << result.response.value();
if (error && !download_dir_.empty()) {
base::PostTask(FROM_HERE, kTaskTraits,
base::BindOnce(IgnoreResult(&base::DeleteFileRecursively),
download_dir_));
}
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), is_handled, result,
download_metrics));
}
| 172,365
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by, int div_by)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count >> div_by;
bc_rem = block_count - (bc_quot << div_by);
return bc_quot * mul_by + ((bc_rem * mul_by) >> div_by);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
|
static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by, int div_by)
static lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by,
int right_shift)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count >> right_shift;
bc_rem = block_count - (bc_quot << right_shift);
return bc_quot * mul_by + ((bc_rem * mul_by) >> right_shift);
}
| 169,641
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void vrend_set_framebuffer_state(struct vrend_context *ctx,
uint32_t nr_cbufs, uint32_t surf_handle[8],
uint32_t zsurf_handle)
{
struct vrend_surface *surf, *zsurf;
int i;
int old_num;
GLenum status;
GLint new_height = -1;
bool new_ibf = false;
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
if (zsurf_handle) {
zsurf = vrend_object_lookup(ctx->sub->object_hash, zsurf_handle, VIRGL_OBJECT_SURFACE);
if (!zsurf) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, zsurf_handle);
return;
}
} else
zsurf = NULL;
if (ctx->sub->zsurf != zsurf) {
vrend_surface_reference(&ctx->sub->zsurf, zsurf);
vrend_hw_set_zsurf_texture(ctx);
}
old_num = ctx->sub->nr_cbufs;
ctx->sub->nr_cbufs = nr_cbufs;
ctx->sub->old_nr_cbufs = old_num;
for (i = 0; i < nr_cbufs; i++) {
if (surf_handle[i] != 0) {
surf = vrend_object_lookup(ctx->sub->object_hash, surf_handle[i], VIRGL_OBJECT_SURFACE);
if (!surf) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, surf_handle[i]);
return;
}
} else
surf = NULL;
if (ctx->sub->surf[i] != surf) {
vrend_surface_reference(&ctx->sub->surf[i], surf);
vrend_hw_set_color_surface(ctx, i);
}
}
if (old_num > ctx->sub->nr_cbufs) {
for (i = ctx->sub->nr_cbufs; i < old_num; i++) {
vrend_surface_reference(&ctx->sub->surf[i], NULL);
vrend_hw_set_color_surface(ctx, i);
}
}
/* find a buffer to set fb_height from */
if (ctx->sub->nr_cbufs == 0 && !ctx->sub->zsurf) {
new_height = 0;
new_ibf = false;
} else if (ctx->sub->nr_cbufs == 0) {
new_height = u_minify(ctx->sub->zsurf->texture->base.height0, ctx->sub->zsurf->val0);
new_ibf = ctx->sub->zsurf->texture->y_0_top ? true : false;
}
else {
surf = NULL;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i]) {
surf = ctx->sub->surf[i];
break;
}
}
if (surf == NULL) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, i);
return;
}
new_height = u_minify(surf->texture->base.height0, surf->val0);
new_ibf = surf->texture->y_0_top ? true : false;
}
if (new_height != -1) {
if (ctx->sub->fb_height != new_height || ctx->sub->inverted_fbo_content != new_ibf) {
ctx->sub->fb_height = new_height;
ctx->sub->inverted_fbo_content = new_ibf;
ctx->sub->scissor_state_dirty = (1 << 0);
ctx->sub->viewport_state_dirty = (1 << 0);
}
}
vrend_hw_emit_framebuffer_state(ctx);
if (ctx->sub->nr_cbufs > 0 || ctx->sub->zsurf) {
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
fprintf(stderr,"failed to complete framebuffer 0x%x %s\n", status, ctx->debug_name);
}
ctx->sub->shader_dirty = true;
}
Commit Message:
CWE ID: CWE-476
|
void vrend_set_framebuffer_state(struct vrend_context *ctx,
uint32_t nr_cbufs, uint32_t surf_handle[PIPE_MAX_COLOR_BUFS],
uint32_t zsurf_handle)
{
struct vrend_surface *surf, *zsurf;
int i;
int old_num;
GLenum status;
GLint new_height = -1;
bool new_ibf = false;
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
if (zsurf_handle) {
zsurf = vrend_object_lookup(ctx->sub->object_hash, zsurf_handle, VIRGL_OBJECT_SURFACE);
if (!zsurf) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, zsurf_handle);
return;
}
} else
zsurf = NULL;
if (ctx->sub->zsurf != zsurf) {
vrend_surface_reference(&ctx->sub->zsurf, zsurf);
vrend_hw_set_zsurf_texture(ctx);
}
old_num = ctx->sub->nr_cbufs;
ctx->sub->nr_cbufs = nr_cbufs;
ctx->sub->old_nr_cbufs = old_num;
for (i = 0; i < nr_cbufs; i++) {
if (surf_handle[i] != 0) {
surf = vrend_object_lookup(ctx->sub->object_hash, surf_handle[i], VIRGL_OBJECT_SURFACE);
if (!surf) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, surf_handle[i]);
return;
}
} else
surf = NULL;
if (ctx->sub->surf[i] != surf) {
vrend_surface_reference(&ctx->sub->surf[i], surf);
vrend_hw_set_color_surface(ctx, i);
}
}
if (old_num > ctx->sub->nr_cbufs) {
for (i = ctx->sub->nr_cbufs; i < old_num; i++) {
vrend_surface_reference(&ctx->sub->surf[i], NULL);
vrend_hw_set_color_surface(ctx, i);
}
}
/* find a buffer to set fb_height from */
if (ctx->sub->nr_cbufs == 0 && !ctx->sub->zsurf) {
new_height = 0;
new_ibf = false;
} else if (ctx->sub->nr_cbufs == 0) {
new_height = u_minify(ctx->sub->zsurf->texture->base.height0, ctx->sub->zsurf->val0);
new_ibf = ctx->sub->zsurf->texture->y_0_top ? true : false;
}
else {
surf = NULL;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i]) {
surf = ctx->sub->surf[i];
break;
}
}
if (surf == NULL) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SURFACE, i);
return;
}
new_height = u_minify(surf->texture->base.height0, surf->val0);
new_ibf = surf->texture->y_0_top ? true : false;
}
if (new_height != -1) {
if (ctx->sub->fb_height != new_height || ctx->sub->inverted_fbo_content != new_ibf) {
ctx->sub->fb_height = new_height;
ctx->sub->inverted_fbo_content = new_ibf;
ctx->sub->scissor_state_dirty = (1 << 0);
ctx->sub->viewport_state_dirty = (1 << 0);
}
}
vrend_hw_emit_framebuffer_state(ctx);
if (ctx->sub->nr_cbufs > 0 || ctx->sub->zsurf) {
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
fprintf(stderr,"failed to complete framebuffer 0x%x %s\n", status, ctx->debug_name);
}
ctx->sub->shader_dirty = true;
}
| 164,959
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int rndis_set_response(USBNetState *s,
rndis_set_msg_type *buf, unsigned int length)
{
rndis_set_cmplt_type *resp =
rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
uint32_t bufoffs, buflen;
int ret;
if (!resp)
return USB_RET_STALL;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
ret = ndis_set(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen);
resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
if (ret < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
return 0;
}
Commit Message:
CWE ID: CWE-189
|
static int rndis_set_response(USBNetState *s,
rndis_set_msg_type *buf, unsigned int length)
{
rndis_set_cmplt_type *resp =
rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
uint32_t bufoffs, buflen;
int ret;
if (!resp)
return USB_RET_STALL;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
return USB_RET_STALL;
}
ret = ndis_set(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen);
resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
if (ret < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
return 0;
}
| 165,186
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1)
pbi->decoding_thread_count = num_token_partitions - 1;
#endif
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID:
|
static void setup_token_decoder(VP8D_COMP *pbi,
const unsigned char* token_part_sizes)
{
vp8_reader *bool_decoder = &pbi->mbc[0];
unsigned int partition_idx;
unsigned int fragment_idx;
unsigned int num_token_partitions;
const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
TOKEN_PARTITION multi_token_partition =
(TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2);
if (!vp8dx_bool_error(&pbi->mbc[8]))
pbi->common.multi_token_partition = multi_token_partition;
num_token_partitions = 1 << pbi->common.multi_token_partition;
/* Check for partitions within the fragments and unpack the fragments
* so that each fragment pointer points to its corresponding partition. */
for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx)
{
unsigned int fragment_size = pbi->fragments.sizes[fragment_idx];
const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] +
fragment_size;
/* Special case for handling the first partition since we have already
* read its size. */
if (fragment_idx == 0)
{
/* Size of first partition + token partition sizes element */
ptrdiff_t ext_first_part_size = token_part_sizes -
pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1);
fragment_size -= (unsigned int)ext_first_part_size;
if (fragment_size > 0)
{
pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size;
/* The fragment contains an additional partition. Move to
* next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] +
pbi->fragments.sizes[0];
}
}
/* Split the chunk into partitions read from the bitstream */
while (fragment_size > 0)
{
ptrdiff_t partition_size = read_available_partition_size(
pbi,
token_part_sizes,
pbi->fragments.ptrs[fragment_idx],
first_fragment_end,
fragment_end,
fragment_idx - 1,
num_token_partitions);
pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size;
fragment_size -= (unsigned int)partition_size;
assert(fragment_idx <= num_token_partitions);
if (fragment_size > 0)
{
/* The fragment contains an additional partition.
* Move to next. */
fragment_idx++;
pbi->fragments.ptrs[fragment_idx] =
pbi->fragments.ptrs[fragment_idx - 1] + partition_size;
}
}
}
pbi->fragments.count = num_token_partitions + 1;
for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx)
{
if (vp8dx_start_decode(bool_decoder,
pbi->fragments.ptrs[partition_idx],
pbi->fragments.sizes[partition_idx],
pbi->decrypt_cb, pbi->decrypt_state))
vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
"Failed to allocate bool decoder %d",
partition_idx);
bool_decoder++;
}
#if CONFIG_MULTITHREAD
/* Clamp number of decoder threads */
if (pbi->decoding_thread_count > num_token_partitions - 1) {
pbi->decoding_thread_count = num_token_partitions - 1;
}
if (pbi->decoding_thread_count > pbi->common.mb_rows - 1) {
pbi->decoding_thread_count = pbi->common.mb_rows - 1;
}
#endif
}
| 174,064
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->RegisterProperties(prop_list);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
static void RegisterPropertiesHandler(
// IBusController override.
virtual void OnRegisterImeProperties(
const input_method::ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
RegisterProperties(prop_list);
}
| 170,502
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mIsBackup) {
return;
}
sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */);
memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size());
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mCopyFromOmx) {
return;
}
sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */);
memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size());
}
| 174,127
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)));
}
Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas
BUG=354356
Review URL: https://codereview.chromium.org/211313003
git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), canvas->buffer() ? ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)) : nullptr);
}
| 171,394
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: open_patch_file (char const *filename)
{
file_offset file_pos = 0;
file_offset pos;
struct stat st;
if (!filename || !*filename || strEQ (filename, "-"))
pfp = stdin;
else
{
pfp = fopen (filename, binary_transput ? "rb" : "r");
if (!pfp)
pfatal ("Can't open patch file %s", quotearg (filename));
}
#if HAVE_SETMODE_DOS
if (binary_transput)
{
if (isatty (fileno (pfp)))
fatal ("cannot read binary data from tty on this platform");
setmode (fileno (pfp), O_BINARY);
}
#endif
if (fstat (fileno (pfp), &st) != 0)
pfatal ("fstat");
if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1)
file_pos = pos;
else
{
size_t charsread;
int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0);
FILE *read_pfp = pfp;
TMPPATNAME_needs_removal = true;
pfp = fdopen (fd, "w+b");
if (! pfp)
pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME));
for (st.st_size = 0;
(charsread = fread (buf, 1, bufsize, read_pfp)) != 0;
st.st_size += charsread)
if (fwrite (buf, 1, charsread, pfp) != charsread)
write_fatal ();
if (ferror (read_pfp) || fclose (read_pfp) != 0)
read_fatal ();
if (fflush (pfp) != 0
|| file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
write_fatal ();
}
p_filesize = st.st_size;
if (p_filesize != (file_offset) p_filesize)
fatal ("patch file is too long");
next_intuit_at (file_pos, 1);
set_hunkmax();
}
Commit Message:
CWE ID: CWE-399
|
open_patch_file (char const *filename)
{
file_offset file_pos = 0;
file_offset pos;
struct stat st;
if (!filename || !*filename || strEQ (filename, "-"))
pfp = stdin;
else
{
pfp = fopen (filename, binary_transput ? "rb" : "r");
if (!pfp)
pfatal ("Can't open patch file %s", quotearg (filename));
}
#if HAVE_SETMODE_DOS
if (binary_transput)
{
if (isatty (fileno (pfp)))
fatal ("cannot read binary data from tty on this platform");
setmode (fileno (pfp), O_BINARY);
}
#endif
if (fstat (fileno (pfp), &st) != 0)
pfatal ("fstat");
if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1)
file_pos = pos;
else
{
size_t charsread;
int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0);
FILE *read_pfp = pfp;
TMPPATNAME_needs_removal = true;
pfp = fdopen (fd, "w+b");
if (! pfp)
pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME));
for (st.st_size = 0;
(charsread = fread (buf, 1, bufsize, read_pfp)) != 0;
st.st_size += charsread)
if (fwrite (buf, 1, charsread, pfp) != charsread)
write_fatal ();
if (ferror (read_pfp) || fclose (read_pfp) != 0)
read_fatal ();
if (fflush (pfp) != 0
|| file_seek (pfp, (file_offset) 0, SEEK_SET) != 0)
write_fatal ();
}
p_filesize = st.st_size;
if (p_filesize != (file_offset) p_filesize)
fatal ("patch file is too long");
next_intuit_at (file_pos, 1);
}
| 165,400
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
blink::MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
blink::MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, page_request_id, requester_id_,
device_id, type, std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
Commit Message: [MediaStream] Pass request ID parameters in the right order for OpenDevice()
Prior to this CL, requester_id and page_request_id parameters were
passed in incorrect order from MediaStreamDispatcherHost to
MediaStreamManager for the OpenDevice() operation, which could lead to
errors.
Bug: 948564
Change-Id: Iadcf3fe26adaac50564102138ce212269cf32d62
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1569113
Reviewed-by: Marina Ciocea <marinaciocea@chromium.org>
Commit-Queue: Guido Urdaneta <guidou@chromium.org>
Cr-Commit-Position: refs/heads/master@{#651255}
CWE ID: CWE-119
|
void MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
blink::MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
blink::MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, requester_id_, page_request_id,
device_id, type, std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
| 173,015
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool KeyMap::Press(const scoped_refptr<WindowProxy>& window,
const ui::KeyboardCode key_code,
const wchar_t& key) {
if (key_code == ui::VKEY_SHIFT) {
shift_ = !shift_;
} else if (key_code == ui::VKEY_CONTROL) {
control_ = !control_;
} else if (key_code == ui::VKEY_MENU) { // ALT
alt_ = !alt_;
} else if (key_code == ui::VKEY_COMMAND) {
command_ = !command_;
}
int modifiers = 0;
if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) {
modifiers = modifiers | ui::EF_SHIFT_DOWN;
}
if (control_) {
modifiers = modifiers | ui::EF_CONTROL_DOWN;
}
if (alt_) {
modifiers = modifiers | ui::EF_ALT_DOWN;
}
if (command_) {
VLOG(1) << "Pressing command key on linux!!";
modifiers = modifiers | ui::EF_COMMAND_DOWN;
}
window->SimulateOSKeyPress(key_code, modifiers);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool KeyMap::Press(const scoped_refptr<WindowProxy>& window,
const ui::KeyboardCode key_code,
const wchar_t& key) {
if (key_code == ui::VKEY_SHIFT) {
shift_ = !shift_;
} else if (key_code == ui::VKEY_CONTROL) {
control_ = !control_;
} else if (key_code == ui::VKEY_MENU) { // ALT
alt_ = !alt_;
} else if (key_code == ui::VKEY_COMMAND) {
command_ = !command_;
}
int modifiers = 0;
if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) {
modifiers = modifiers | ui::EF_SHIFT_DOWN;
}
if (control_) {
modifiers = modifiers | ui::EF_CONTROL_DOWN;
}
if (alt_) {
modifiers = modifiers | ui::EF_ALT_DOWN;
}
if (command_) {
LOG(INFO) << "Pressing command key on linux!!";
modifiers = modifiers | ui::EF_COMMAND_DOWN;
}
window->SimulateOSKeyPress(key_code, modifiers);
return true;
}
| 170,459
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID:
|
krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
| 166,822
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: struct ipv6_txoptions *ipv6_update_options(struct sock *sk,
struct ipv6_txoptions *opt)
{
if (inet_sk(sk)->is_icsk) {
if (opt &&
!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) {
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
}
}
opt = xchg(&inet6_sk(sk)->opt, opt);
sk_dst_reset(sk);
return opt;
}
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
|
struct ipv6_txoptions *ipv6_update_options(struct sock *sk,
struct ipv6_txoptions *opt)
{
if (inet_sk(sk)->is_icsk) {
if (opt &&
!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) {
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
}
}
opt = xchg((__force struct ipv6_txoptions **)&inet6_sk(sk)->opt,
opt);
sk_dst_reset(sk);
return opt;
}
| 167,337
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool DataReductionProxySettings::IsDataReductionProxyManaged() {
return spdy_proxy_auth_enabled_.IsManaged();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
bool DataReductionProxySettings::IsDataReductionProxyManaged() {
const PrefService::Preference* pref =
GetOriginalProfilePrefs()->FindPreference(prefs::kDataSaverEnabled);
return pref && pref->IsManaged();
}
| 172,555
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
u_char *p;
size_t slen, rlen;
int r, ssh1cipher;
if (!compat20) {
ssh1cipher = cipher_ctx_get_number(state->receive_context);
slen = cipher_get_keyiv_len(state->send_context);
rlen = cipher_get_keyiv_len(state->receive_context);
if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
(r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
(r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
(r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0 ||
(r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
(r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0 ||
(r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
return r;
} else {
if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
(r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
return r;
}
slen = cipher_get_keycontext(state->send_context, NULL);
rlen = cipher_get_keycontext(state->receive_context, NULL);
if ((r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, p) != (int)slen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
(r = sshbuf_put_stringb(m, state->input)) != 0 ||
(r = sshbuf_put_stringb(m, state->output)) != 0)
return r;
return 0;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
u_char *p;
size_t slen, rlen;
int r, ssh1cipher;
if (!compat20) {
ssh1cipher = cipher_ctx_get_number(state->receive_context);
slen = cipher_get_keyiv_len(state->send_context);
rlen = cipher_get_keyiv_len(state->receive_context);
if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
(r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
(r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
(r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0 ||
(r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
(r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0 ||
(r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
return r;
} else {
if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
(r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
return r;
}
slen = cipher_get_keycontext(state->send_context, NULL);
rlen = cipher_get_keycontext(state->receive_context, NULL);
if ((r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, p) != (int)slen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
(r = sshbuf_put_stringb(m, state->output)) != 0)
return r;
return 0;
}
| 168,653
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
}
Commit Message: Fixed head buffer overflow reported in: https://github.com/ImageMagick/ImageMagick/issues/98
CWE ID: CWE-125
|
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
| 168,804
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: tt_cmap12_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_groups;
if ( table + 16 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 4;
length = TT_NEXT_ULONG( p );
p = table + 12;
p = table + 12;
num_groups = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 16 + 12 * num_groups )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
for ( n = 0; n < num_groups; n++ )
{
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
last = end;
}
}
Commit Message:
CWE ID: CWE-189
|
tt_cmap12_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_groups;
if ( table + 16 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 4;
length = TT_NEXT_ULONG( p );
p = table + 12;
p = table + 12;
num_groups = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
length < 16 + 12 * num_groups )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
for ( n = 0; n < num_groups; n++ )
{
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
last = end;
}
}
| 164,740
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Track::Info::~Info()
{
Clear();
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Track::Info::~Info()
| 174,468
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool CopyDirectory(const FilePath& from_path,
const FilePath& to_path,
bool recursive) {
base::ThreadRestrictions::AssertIOAllowed();
DCHECK(to_path.value().find('*') == std::string::npos);
DCHECK(from_path.value().find('*') == std::string::npos);
char top_dir[PATH_MAX];
if (base::strlcpy(top_dir, from_path.value().c_str(),
arraysize(top_dir)) >= arraysize(top_dir)) {
return false;
}
FilePath real_to_path = to_path;
if (PathExists(real_to_path)) {
if (!AbsolutePath(&real_to_path))
return false;
} else {
real_to_path = real_to_path.DirName();
if (!AbsolutePath(&real_to_path))
return false;
}
FilePath real_from_path = from_path;
if (!AbsolutePath(&real_from_path))
return false;
if (real_to_path.value().size() >= real_from_path.value().size() &&
real_to_path.value().compare(0, real_from_path.value().size(),
real_from_path.value()) == 0)
return false;
bool success = true;
int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
if (recursive)
traverse_type |= FileEnumerator::DIRECTORIES;
FileEnumerator traversal(from_path, recursive, traverse_type);
FileEnumerator::FindInfo info;
FilePath current = from_path;
if (stat(from_path.value().c_str(), &info.stat) < 0) {
DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
<< from_path.value() << " errno = " << errno;
success = false;
}
struct stat to_path_stat;
FilePath from_path_base = from_path;
if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
S_ISDIR(to_path_stat.st_mode)) {
from_path_base = from_path.DirName();
}
DCHECK(recursive || S_ISDIR(info.stat.st_mode));
while (success && !current.empty()) {
std::string suffix(¤t.value().c_str()[from_path_base.value().size()]);
if (!suffix.empty()) {
DCHECK_EQ('/', suffix[0]);
suffix.erase(0, 1);
}
const FilePath target_path = to_path.Append(suffix);
if (S_ISDIR(info.stat.st_mode)) {
if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
errno != EEXIST) {
DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
<< target_path.value() << " errno = " << errno;
success = false;
}
} else if (S_ISREG(info.stat.st_mode)) {
if (!CopyFile(current, target_path)) {
DLOG(ERROR) << "CopyDirectory() couldn't create file: "
<< target_path.value();
success = false;
}
} else {
DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
<< current.value();
}
current = traversal.Next();
traversal.GetFindInfo(&info);
}
return success;
}
Commit Message: Fix creating target paths in file_util_posix CopyDirectory.
BUG=167840
Review URL: https://chromiumcodereview.appspot.com/11773018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176659 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-22
|
bool CopyDirectory(const FilePath& from_path,
const FilePath& to_path,
bool recursive) {
base::ThreadRestrictions::AssertIOAllowed();
DCHECK(to_path.value().find('*') == std::string::npos);
DCHECK(from_path.value().find('*') == std::string::npos);
char top_dir[PATH_MAX];
if (base::strlcpy(top_dir, from_path.value().c_str(),
arraysize(top_dir)) >= arraysize(top_dir)) {
return false;
}
FilePath real_to_path = to_path;
if (PathExists(real_to_path)) {
if (!AbsolutePath(&real_to_path))
return false;
} else {
real_to_path = real_to_path.DirName();
if (!AbsolutePath(&real_to_path))
return false;
}
FilePath real_from_path = from_path;
if (!AbsolutePath(&real_from_path))
return false;
if (real_to_path.value().size() >= real_from_path.value().size() &&
real_to_path.value().compare(0, real_from_path.value().size(),
real_from_path.value()) == 0)
return false;
bool success = true;
int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
if (recursive)
traverse_type |= FileEnumerator::DIRECTORIES;
FileEnumerator traversal(from_path, recursive, traverse_type);
FileEnumerator::FindInfo info;
FilePath current = from_path;
if (stat(from_path.value().c_str(), &info.stat) < 0) {
DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
<< from_path.value() << " errno = " << errno;
success = false;
}
struct stat to_path_stat;
FilePath from_path_base = from_path;
if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
S_ISDIR(to_path_stat.st_mode)) {
from_path_base = from_path.DirName();
}
DCHECK(recursive || S_ISDIR(info.stat.st_mode));
while (success && !current.empty()) {
// current is the source path, including from_path, so append
// the suffix after from_path to to_path to create the target_path.
FilePath target_path(to_path);
if (from_path_base != current) {
if (!from_path_base.AppendRelativePath(current, &target_path)) {
success = false;
break;
}
}
if (S_ISDIR(info.stat.st_mode)) {
if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
errno != EEXIST) {
DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
<< target_path.value() << " errno = " << errno;
success = false;
}
} else if (S_ISREG(info.stat.st_mode)) {
if (!CopyFile(current, target_path)) {
DLOG(ERROR) << "CopyDirectory() couldn't create file: "
<< target_path.value();
success = false;
}
} else {
DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
<< current.value();
}
current = traversal.Next();
traversal.GetFindInfo(&info);
}
return success;
}
| 171,409
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void fz_init_cached_color_converter(fz_context *ctx, fz_color_converter *cc, fz_colorspace *is, fz_colorspace *ds, fz_colorspace *ss, const fz_color_params *params)
{
int n = ss->n;
fz_cached_color_converter *cached = fz_malloc_struct(ctx, fz_cached_color_converter);
cc->opaque = cached;
cc->convert = fz_cached_color_convert;
cc->ds = ds ? ds : fz_device_gray(ctx);
cc->ss = ss;
cc->is = is;
fz_try(ctx)
{
fz_find_color_converter(ctx, &cached->base, is, cc->ds, ss, params);
cached->hash = fz_new_hash_table(ctx, 256, n * sizeof(float), -1, fz_free);
}
fz_catch(ctx)
{
fz_drop_color_converter(ctx, &cached->base);
fz_drop_hash_table(ctx, cached->hash);
fz_free(ctx, cached);
fz_rethrow(ctx);
}
}
Commit Message:
CWE ID: CWE-20
|
void fz_init_cached_color_converter(fz_context *ctx, fz_color_converter *cc, fz_colorspace *is, fz_colorspace *ds, fz_colorspace *ss, const fz_color_params *params)
{
int n = ss->n;
fz_cached_color_converter *cached = fz_malloc_struct(ctx, fz_cached_color_converter);
cc->opaque = cached;
cc->convert = fz_cached_color_convert;
cc->ds = ds ? ds : fz_device_gray(ctx);
cc->ss = ss;
cc->is = is;
fz_try(ctx)
{
fz_find_color_converter(ctx, &cached->base, is, cc->ds, ss, params);
cached->hash = fz_new_hash_table(ctx, 256, n * sizeof(float), -1, fz_free);
}
fz_catch(ctx)
{
fz_drop_color_converter(ctx, &cached->base);
fz_drop_hash_table(ctx, cached->hash);
fz_free(ctx, cached);
cc->opaque = NULL;
fz_rethrow(ctx);
}
}
| 164,576
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SchedulerObject::hold(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-20
|
SchedulerObject::hold(std::string key, std::string &reason, std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster <= 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (!holdJob(id.cluster,
id.proc,
reason.c_str(),
true, // Always perform this action within a transaction
true, // Always notify the shadow of the hold
false, // Do not email the user about this action
false, // Do not email admin about this action
false // This is not a system related (internal) hold
)) {
text = "Failed to hold job";
return false;
}
return true;
}
| 164,832
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SPL_METHOD(SplFileObject, hasChildren)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto bool SplFileObject::getChildren()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileObject, hasChildren)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto bool SplFileObject::getChildren()
| 167,060
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_terminate (MyObject *obj, GError **error)
{
g_main_loop_quit (loop);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_terminate (MyObject *obj, GError **error)
| 165,123
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
image_transform_png_set_strip_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
| 173,653
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
Commit Message: mlx4_en: Fix out of bounds array access
When searching for a free entry in either mlx4_register_vlan() or
mlx4_register_mac(), and there is no free entry, the loop terminates without
updating the local variable free thus causing out of array bounds access. Fix
this by adding a proper check outside the loop.
Signed-off-by: Eli Cohen <eli@mellanox.co.il>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-119
|
int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index)
{
struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table;
int i, err = 0;
int free = -1;
mutex_lock(&table->mutex);
for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) {
if (free < 0 && (table->refs[i] == 0)) {
free = i;
continue;
}
if (table->refs[i] &&
(vlan == (MLX4_VLAN_MASK &
be32_to_cpu(table->entries[i])))) {
/* Vlan already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
if (free < 0) {
err = -ENOMEM;
goto out;
}
if (table->total == table->max) {
/* No free vlan entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID);
err = mlx4_set_port_vlan_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_warn(dev, "Failed adding vlan: %u\n", vlan);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
| 169,872
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void server_real_connect(SERVER_REC *server, IPADDR *ip,
const char *unix_socket)
{
GIOChannel *handle;
IPADDR *own_ip = NULL;
const char *errmsg;
char *errmsg2;
char ipaddr[MAX_IP_LEN];
int port;
g_return_if_fail(ip != NULL || unix_socket != NULL);
signal_emit("server connecting", 2, server, ip);
if (server->connrec->no_connect)
return;
if (ip != NULL) {
own_ip = ip == NULL ? NULL :
(IPADDR_IS_V6(ip) ? server->connrec->own_ip6 :
server->connrec->own_ip4);
port = server->connrec->proxy != NULL ?
server->connrec->proxy_port : server->connrec->port;
handle = server->connrec->use_ssl ?
net_connect_ip_ssl(ip, port, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey,
server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) :
net_connect_ip(ip, port, own_ip);
} else {
handle = net_connect_unix(unix_socket);
}
if (handle == NULL) {
/* failed */
errmsg = g_strerror(errno);
errmsg2 = NULL;
if (errno == EADDRNOTAVAIL) {
if (own_ip != NULL) {
/* show the IP which is causing the error */
net_ip2host(own_ip, ipaddr);
errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL);
}
server->no_reconnect = TRUE;
}
if (server->connrec->use_ssl && errno == ENOSYS)
server->no_reconnect = TRUE;
server->connection_lost = TRUE;
server_connect_failed(server, errmsg2 ? errmsg2 : errmsg);
g_free(errmsg2);
} else {
server->handle = net_sendbuffer_create(handle, 0);
#ifdef HAVE_OPENSSL
if (server->connrec->use_ssl)
server_connect_callback_init_ssl(server, handle);
else
#endif
server->connect_tag =
g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ,
(GInputFunction)
server_connect_callback_init,
server);
}
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20
|
static void server_real_connect(SERVER_REC *server, IPADDR *ip,
const char *unix_socket)
{
GIOChannel *handle;
IPADDR *own_ip = NULL;
const char *errmsg;
char *errmsg2;
char ipaddr[MAX_IP_LEN];
int port;
g_return_if_fail(ip != NULL || unix_socket != NULL);
signal_emit("server connecting", 2, server, ip);
if (server->connrec->no_connect)
return;
if (ip != NULL) {
own_ip = ip == NULL ? NULL :
(IPADDR_IS_V6(ip) ? server->connrec->own_ip6 :
server->connrec->own_ip4);
port = server->connrec->proxy != NULL ?
server->connrec->proxy_port : server->connrec->port;
handle = server->connrec->use_ssl ?
net_connect_ip_ssl(ip, port, server->connrec->address, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey,
server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) :
net_connect_ip(ip, port, own_ip);
} else {
handle = net_connect_unix(unix_socket);
}
if (handle == NULL) {
/* failed */
errmsg = g_strerror(errno);
errmsg2 = NULL;
if (errno == EADDRNOTAVAIL) {
if (own_ip != NULL) {
/* show the IP which is causing the error */
net_ip2host(own_ip, ipaddr);
errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL);
}
server->no_reconnect = TRUE;
}
if (server->connrec->use_ssl && errno == ENOSYS)
server->no_reconnect = TRUE;
server->connection_lost = TRUE;
server_connect_failed(server, errmsg2 ? errmsg2 : errmsg);
g_free(errmsg2);
} else {
server->handle = net_sendbuffer_create(handle, 0);
#ifdef HAVE_OPENSSL
if (server->connrec->use_ssl)
server_connect_callback_init_ssl(server, handle);
else
#endif
server->connect_tag =
g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ,
(GInputFunction)
server_connect_callback_init,
server);
}
}
| 165,520
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* if we knew anything about the old value, we're not
* equal, because we can't know anything about the
* scalar value of the pointer in the new value.
*/
return rold->umin_value == 0 &&
rold->umax_value == U64_MAX &&
rold->smin_value == S64_MIN &&
rold->smax_value == S64_MAX &&
tnum_is_unknown(rold->var_off);
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
Commit Message: bpf: don't prune branches when a scalar is replaced with a pointer
This could be made safe by passing through a reference to env and checking
for env->allow_ptr_leaks, but it would only work one way and is probably
not worth the hassle - not doing it will not directly lead to program
rejection.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
CWE ID: CWE-119
|
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* We're trying to use a pointer in place of a scalar.
* Even if the scalar was unbounded, this could lead to
* pointer leaks because scalars are allowed to leak
* while pointers are not. We could make this safe in
* special cases if root is calling us, but it's
* probably not worth the hassle.
*/
return false;
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_STACK:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
| 167,642
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TestResultCallback()
: callback_(base::Bind(&TestResultCallback::SetResult,
base::Unretained(this))) {}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <rockot@chromium.org>
Commit-Queue: Taiju Tsuiki <tzik@chromium.org>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID:
|
TestResultCallback()
| 171,977
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
void SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
vpx_memset16(input16_, value, kInputBufferSize);
#endif
}
void CopyOutputToRef() {
memcpy(output_ref_, output_, kOutputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
memcpy(output16_ref_, output16_, kOutputBufferSize);
#endif
}
| 174,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
IncludePrivacySensitiveFields include_privacy_sensitive_fields) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
if (include_privacy_sensitive_fields == INCLUDE_PRIVACY_SENSITIVE_FIELDS) {
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index) {
if (!tab_strip)
ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index);
DictionaryValue* result = new DictionaryValue();
bool is_loading = contents->IsLoading();
result->SetInteger(keys::kIdKey, GetTabId(contents));
result->SetInteger(keys::kIndexKey, tab_index);
result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents));
result->SetString(keys::kStatusKey, GetTabStatusText(is_loading));
result->SetBoolean(keys::kActiveKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kSelectedKey,
tab_strip && tab_index == tab_strip->active_index());
result->SetBoolean(keys::kHighlightedKey,
tab_strip && tab_strip->IsTabSelected(tab_index));
result->SetBoolean(keys::kPinnedKey,
tab_strip && tab_strip->IsTabPinned(tab_index));
result->SetBoolean(keys::kIncognitoKey,
contents->GetBrowserContext()->IsOffTheRecord());
// Privacy-sensitive fields: these should be stripped off by
// ScrubTabValueForExtension if the extension should not see them.
result->SetString(keys::kUrlKey, contents->GetURL().spec());
result->SetString(keys::kTitleKey, contents->GetTitle());
if (!is_loading) {
NavigationEntry* entry = contents->GetController().GetActiveEntry();
if (entry && entry->GetFavicon().valid)
result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec());
}
if (tab_strip) {
WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index);
if (opener)
result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener));
}
return result;
}
| 171,455
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_increment_val (MyObject *obj, GError **error)
{
obj->val++;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_increment_val (MyObject *obj, GError **error)
| 165,108
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RegisterProperties(IBusPropList* ibus_prop_list) {
DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
RegisterProperties(NULL);
return;
}
}
register_ime_properties_(language_library_, prop_list);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void RegisterProperties(IBusPropList* ibus_prop_list) {
void DoRegisterProperties(IBusPropList* ibus_prop_list) {
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
ImePropertyList prop_list; // our representation.
if (ibus_prop_list) {
if (!FlattenPropertyList(ibus_prop_list, &prop_list)) {
DoRegisterProperties(NULL);
return;
}
}
VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)");
| 170,544
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void AcceleratedStaticBitmapImage::CheckThread() {
if (detach_thread_at_next_check_) {
thread_checker_.DetachFromThread();
detach_thread_at_next_check_ = false;
}
CHECK(thread_checker_.CalledOnValidThread());
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
void AcceleratedStaticBitmapImage::CheckThread() {
| 172,590
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ConnectIBusSignals() {
if (!ibus_) {
return;
}
g_signal_connect_after(ibus_,
"connected",
G_CALLBACK(IBusBusConnectedCallback),
this);
g_signal_connect(ibus_,
"disconnected",
G_CALLBACK(IBusBusDisconnectedCallback),
this);
g_signal_connect(ibus_,
"global-engine-changed",
G_CALLBACK(IBusBusGlobalEngineChangedCallback),
this);
g_signal_connect(ibus_,
"name-owner-changed",
G_CALLBACK(IBusBusNameOwnerChangedCallback),
this);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ConnectIBusSignals() {
if (!ibus_) {
return;
}
g_signal_connect_after(ibus_,
"connected",
G_CALLBACK(IBusBusConnectedThunk),
this);
g_signal_connect(ibus_,
"disconnected",
G_CALLBACK(IBusBusDisconnectedThunk),
this);
g_signal_connect(ibus_,
"global-engine-changed",
G_CALLBACK(IBusBusGlobalEngineChangedThunk),
this);
g_signal_connect(ibus_,
"name-owner-changed",
G_CALLBACK(IBusBusNameOwnerChangedThunk),
this);
}
| 170,529
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
Commit Message: Fixed ##72433: Use After Free Vulnerability in PHP's GC algorithm and unserialize
CWE ID: CWE-416
|
PHP_MINIT_FUNCTION(spl_array)
{
REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate);
REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable);
memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_ArrayObject.clone_obj = spl_array_object_clone;
spl_handler_ArrayObject.read_dimension = spl_array_read_dimension;
spl_handler_ArrayObject.write_dimension = spl_array_write_dimension;
spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension;
spl_handler_ArrayObject.has_dimension = spl_array_has_dimension;
spl_handler_ArrayObject.count_elements = spl_array_object_count_elements;
spl_handler_ArrayObject.get_properties = spl_array_get_properties;
spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info;
spl_handler_ArrayObject.get_gc = spl_array_get_gc;
spl_handler_ArrayObject.read_property = spl_array_read_property;
spl_handler_ArrayObject.write_property = spl_array_write_property;
spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr;
spl_handler_ArrayObject.has_property = spl_array_has_property;
spl_handler_ArrayObject.unset_property = spl_array_unset_property;
spl_handler_ArrayObject.compare_objects = spl_array_compare_objects;
REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable);
REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable);
memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers));
spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator);
REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator);
spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator;
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST);
REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS);
REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY);
return SUCCESS;
}
| 167,025
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PrintPreviewDataService::SetDataEntry(
const std::string& preview_ui_addr_str,
int index,
const base::RefCountedBytes* data_bytes) {
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it == data_store_map_.end())
data_store_map_[preview_ui_addr_str] = new PrintPreviewDataStore();
data_store_map_[preview_ui_addr_str]->SetPreviewDataForIndex(index,
data_bytes);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewDataService::SetDataEntry(
int32 preview_ui_id,
int index,
const base::RefCountedBytes* data_bytes) {
if (!ContainsKey(data_store_map_, preview_ui_id))
data_store_map_[preview_ui_id] = new PrintPreviewDataStore();
data_store_map_[preview_ui_id]->SetPreviewDataForIndex(index, data_bytes);
}
| 170,824
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LocalFileSystem::fileSystemNotAvailable(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void LocalFileSystem::fileSystemNotAvailable(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
CallbackWrapper* callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 171,428
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = s->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
Commit Message:
CWE ID: CWE-119
|
int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
| 165,402
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
| 173,639
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_METHOD(Phar, copy)
{
char *oldfile, *newfile, *error;
const char *pcr_error;
size_t oldfile_len, newfile_len;
phar_entry_info *oldentry, newentry = {0}, *temp;
int tmp_len = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
return;
}
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
RETURN_FALSE;
}
if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) {
if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
}
tmp_len = (int)newfile_len;
if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
RETURN_FALSE;
}
newfile_len = tmp_len;
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate with copied-on-write entry */
oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len);
}
memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
zval_copy_ctor(&newentry.metadata);
newentry.metadata_str.s = NULL;
}
newentry.filename = estrndup(newfile, newfile_len);
newentry.filename_len = newfile_len;
newentry.fp_refcount = 0;
if (oldentry->fp_type != PHAR_FP) {
if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
efree(newentry.filename);
php_stream_close(newentry.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
}
zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
phar_obj->archive->is_modified = 1;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, copy)
{
char *oldfile, *newfile, *error;
const char *pcr_error;
size_t oldfile_len, newfile_len;
phar_entry_info *oldentry, newentry = {0}, *temp;
int tmp_len = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
return;
}
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
RETURN_FALSE;
}
if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
/* can't copy a meta file */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len)) || oldentry->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) {
if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint) newfile_len)) || !temp->is_deleted) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
RETURN_FALSE;
}
}
tmp_len = (int)newfile_len;
if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
RETURN_FALSE;
}
newfile_len = tmp_len;
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate with copied-on-write entry */
oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint) oldfile_len);
}
memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
zval_copy_ctor(&newentry.metadata);
newentry.metadata_str.s = NULL;
}
newentry.filename = estrndup(newfile, newfile_len);
newentry.filename_len = newfile_len;
newentry.fp_refcount = 0;
if (oldentry->fp_type != PHAR_FP) {
if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
efree(newentry.filename);
php_stream_close(newentry.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
return;
}
}
zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
phar_obj->archive->is_modified = 1;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
| 165,064
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int zero_bits = *in & 0x07;
size_t octets_left = inlen - 1;
int i, count = 0;
memset(outbuf, 0, outlen);
in++;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
Commit Message: fixed out of bounds access of ASN.1 Bitstring
Credit to OSS-Fuzz
CWE ID: CWE-119
|
static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf,
size_t outlen, int invert)
{
const u8 *in = inbuf;
u8 *out = (u8 *) outbuf;
int i, count = 0;
int zero_bits;
size_t octets_left;
if (outlen < octets_left)
return SC_ERROR_BUFFER_TOO_SMALL;
if (inlen < 1)
return SC_ERROR_INVALID_ASN1_OBJECT;
zero_bits = *in & 0x07;
octets_left = inlen - 1;
in++;
memset(outbuf, 0, outlen);
while (octets_left) {
/* 1st octet of input: ABCDEFGH, where A is the MSB */
/* 1st octet of output: HGFEDCBA, where A is the LSB */
/* first bit in bit string is the LSB in first resulting octet */
int bits_to_go;
*out = 0;
if (octets_left == 1)
bits_to_go = 8 - zero_bits;
else
bits_to_go = 8;
if (invert)
for (i = 0; i < bits_to_go; i++) {
*out |= ((*in >> (7 - i)) & 1) << i;
}
else {
*out = *in;
}
out++;
in++;
octets_left--;
count++;
}
return (count * 8) - zero_bits;
}
| 169,515
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
Commit Message: netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs
The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks
will get as much data as they expect; callbacks have to check the `datalen`
parameter before looking at `data`. Make sure that snmp_version() and
snmp_helper() don't read/write beyond the end of the packet data.
(Also move the assignment to `pdata` down below the check to make it clear
that it isn't necessarily a pointer we can use before the `datalen` check.)
Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library")
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
CWE ID: CWE-129
|
int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata;
if (datalen != 4)
return -EINVAL;
pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
| 169,723
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RenderWidgetHostImpl::AcknowledgeBufferPresent(
int32 route_id, int gpu_host_id, bool presented, uint32 sync_point) {
GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
if (ui_shim)
ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
presented,
sync_point));
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void RenderWidgetHostImpl::AcknowledgeBufferPresent(
int32 route_id, int gpu_host_id, uint64 surface_handle, uint32 sync_point) {
GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id);
if (ui_shim)
ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id,
surface_handle,
sync_point));
}
| 171,366
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <sdy@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
|
void Browser::AddNewContents(WebContents* source,
std::unique_ptr<WebContents> new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
#if defined(OS_MACOSX)
// On the Mac, the convention is to turn popups into new tabs when in
// fullscreen mode. Only worry about user-initiated fullscreen as showing a
// popup in HTML5 fullscreen would have kicked the page out of fullscreen.
if (disposition == WindowOpenDisposition::NEW_POPUP &&
exclusive_access_manager_->fullscreen_controller()
->IsFullscreenForBrowser()) {
disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
#endif
if (source && PopupBlockerTabHelper::ConsiderForPopupBlocking(disposition))
PopupTracker::CreateForWebContents(new_contents.get(), source);
chrome::AddWebContents(this, source, std::move(new_contents), disposition,
initial_rect);
}
| 173,205
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
Commit Message: Added missing null check.
CWE ID: CWE-476
|
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
mask->matte=MagickFalse;
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
| 168,332
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
// GetNamedPipeClientProcessId() is available starting from Vista.
HMODULE kernel32 = ::GetModuleHandle(L"kernel32.dll");
CHECK(kernel32 != NULL);
get_named_pipe_client_pid_ =
reinterpret_cast<GetNamedPipeClientProcessIdFn>(
GetProcAddress(kernel32, "GetNamedPipeClientProcessId"));
CHECK(get_named_pipe_client_pid_ != NULL);
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
| 171,558
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: explicit LogoDelegateImpl(
std::unique_ptr<image_fetcher::ImageDecoder> image_decoder)
: image_decoder_(std::move(image_decoder)) {}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <sdefresne@chromium.org>
Reviewed-by: Marc Treib <treib@chromium.org>
Commit-Queue: Chris Pickel <sfiera@chromium.org>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
explicit LogoDelegateImpl(
| 171,954
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
R=ben@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
if (!is_frameless_) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
}
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
| 170,715
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void WebUIExtension::Send(gin::Arguments* args) {
blink::WebLocalFrame* frame;
RenderFrame* render_frame;
if (!ShouldRespondToRequest(&frame, &render_frame))
return;
std::string message;
if (!args->GetNext(&message)) {
args->ThrowError();
return;
}
if (base::EndsWith(message, "RequiringGesture",
base::CompareCase::SENSITIVE) &&
!blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) {
NOTREACHED();
return;
}
std::unique_ptr<base::ListValue> content;
if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) {
content.reset(new base::ListValue());
} else {
v8::Local<v8::Object> obj;
if (!args->GetNext(&obj)) {
args->ThrowError();
return;
}
content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value(
obj, frame->MainWorldScriptContext()));
DCHECK(content);
}
render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(),
frame->GetDocument().Url(),
message, *content));
}
Commit Message: Validate frame after conversion in chrome.send
BUG=797511
TEST=Manually, see https://crbug.com/797511#c1
Change-Id: Ib1a99db4d7648fb1325eb6d7af4ef111d6dda4cb
Reviewed-on: https://chromium-review.googlesource.com/844076
Commit-Queue: Rob Wu <rob@robwu.nl>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#526197}
CWE ID: CWE-416
|
void WebUIExtension::Send(gin::Arguments* args) {
blink::WebLocalFrame* frame;
RenderFrame* render_frame;
if (!ShouldRespondToRequest(&frame, &render_frame))
return;
std::string message;
if (!args->GetNext(&message)) {
args->ThrowError();
return;
}
if (base::EndsWith(message, "RequiringGesture",
base::CompareCase::SENSITIVE) &&
!blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) {
NOTREACHED();
return;
}
std::unique_ptr<base::ListValue> content;
if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) {
content.reset(new base::ListValue());
} else {
v8::Local<v8::Object> obj;
if (!args->GetNext(&obj)) {
args->ThrowError();
return;
}
content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value(
obj, frame->MainWorldScriptContext()));
DCHECK(content);
// The conversion of |obj| could have triggered arbitrary JavaScript code,
// so check that the frame is still valid to avoid dereferencing a stale
// pointer.
if (frame != blink::WebLocalFrame::FrameForCurrentContext()) {
NOTREACHED();
return;
}
}
render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(),
frame->GetDocument().Url(),
message, *content));
}
| 172,695
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
if (url.SchemeIsBlob()) {
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <alexmos@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Commit-Queue: Charlie Reis <creis@chromium.org>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285
|
GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
// that might allow two URLs created by different sites to share a process.
// See https://crbug.com/863623 and https://crbug.com/863069.
// schemes, such as file:.
// TODO(creis): This currently causes problems with tests on Android and
// Android WebView. For now, skip it when Site Isolation is not enabled,
// since there's no need to isolate data and blob URLs from each other in
// that case.
bool is_site_isolation_enabled =
SiteIsolationPolicy::UseDedicatedProcessesForAllSites() ||
SiteIsolationPolicy::AreIsolatedOriginsEnabled();
if (is_site_isolation_enabled &&
(url.SchemeIsBlob() || url.scheme() == url::kDataScheme)) {
// origins from each other. We also get here for browser-initiated
// navigations to data URLs, which have a unique origin and should only
// share a process when they are identical. Remove hash from the URL in
// either case, since same-document navigations shouldn't use a different
// site URL.
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
| 173,183
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void NetworkHandler::GetCookies(Maybe<Array<String>> protocol_urls,
std::unique_ptr<GetCookiesCallback> callback) {
if (!host_) {
callback->sendFailure(Response::InternalError());
return;
}
std::vector<GURL> urls = ComputeCookieURLs(host_, protocol_urls);
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveCookiesOnIO, retriever,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
urls));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::GetCookies(Maybe<Array<String>> protocol_urls,
std::unique_ptr<GetCookiesCallback> callback) {
if (!host_) {
callback->sendFailure(Response::InternalError());
return;
}
std::vector<GURL> urls = ComputeCookieURLs(host_, protocol_urls);
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveCookiesOnIO, retriever,
base::Unretained(storage_partition_->GetURLRequestContext()), urls));
}
| 172,757
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint32 *wp = (uint32*) cp0;
tmsize_t wc = cc/4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horDiff32",
"%s", "(cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] -= wp[0]; wp--)
wc -= stride;
} while (wc > 0);
}
return 1;
}
| 166,886
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int UDPSocketLibevent::DoBind(const IPEndPoint& address) {
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len))
return ERR_ADDRESS_INVALID;
int rv = bind(socket_, storage.addr, storage.addr_len);
if (rv == 0)
return OK;
int last_error = errno;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromPosix", last_error);
return MapSystemError(last_error);
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
int UDPSocketLibevent::DoBind(const IPEndPoint& address) {
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len))
return ERR_ADDRESS_INVALID;
int rv = bind(socket_, storage.addr, storage.addr_len);
if (rv == 0)
return OK;
int last_error = errno;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromPosix", last_error);
#if defined(OS_CHROMEOS)
if (last_error == EINVAL)
return ERR_ADDRESS_IN_USE;
#elif defined(OS_MACOSX)
if (last_error == EADDRNOTAVAIL)
return ERR_ADDRESS_IN_USE;
#endif
return MapSystemError(last_error);
}
| 171,315
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAAC2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = 0;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
aacParams->eAACStreamFormat =
mIsADTS
? OMX_AUDIO_AACStreamFormatMP4ADTS
: OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
if (!isConfigured()) {
aacParams->nChannels = 1;
aacParams->nSampleRate = 44100;
aacParams->nFrameLength = 0;
} else {
aacParams->nChannels = mStreamInfo->numChannels;
aacParams->nSampleRate = mStreamInfo->sampleRate;
aacParams->nFrameLength = mStreamInfo->frameSize;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mStreamInfo->numChannels;
pcmParams->nSamplingRate = mStreamInfo->sampleRate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAAC2::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
aacParams->nBitRate = 0;
aacParams->nAudioBandWidth = 0;
aacParams->nAACtools = 0;
aacParams->nAACERtools = 0;
aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
aacParams->eAACStreamFormat =
mIsADTS
? OMX_AUDIO_AACStreamFormatMP4ADTS
: OMX_AUDIO_AACStreamFormatMP4FF;
aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
if (!isConfigured()) {
aacParams->nChannels = 1;
aacParams->nSampleRate = 44100;
aacParams->nFrameLength = 0;
} else {
aacParams->nChannels = mStreamInfo->numChannels;
aacParams->nSampleRate = mStreamInfo->sampleRate;
aacParams->nFrameLength = mStreamInfo->frameSize;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
if (!isConfigured()) {
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 44100;
} else {
pcmParams->nChannels = mStreamInfo->numChannels;
pcmParams->nSamplingRate = mStreamInfo->sampleRate;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,186
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: raptor_libxml_getEntity(void* user_data, const xmlChar *name) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_getEntity(sax2->xc, name);
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
|
raptor_libxml_getEntity(void* user_data, const xmlChar *name) {
raptor_libxml_getEntity(void* user_data, const xmlChar *name)
{
raptor_sax2* sax2 = (raptor_sax2*)user_data;
xmlParserCtxtPtr xc = sax2->xc;
xmlEntityPtr ret = NULL;
if(!xc)
return NULL;
if(!xc->inSubset) {
/* looks for hardcoded set of entity names - lt, gt etc. */
ret = xmlGetPredefinedEntity(name);
if(ret) {
RAPTOR_DEBUG2("Entity '%s' found in predefined set\n", name);
return ret;
}
}
/* This section uses xmlGetDocEntity which looks for entities in
* memory only, never from a file or URI
*/
if(xc->myDoc && (xc->myDoc->standalone == 1)) {
RAPTOR_DEBUG2("Entity '%s' document is standalone\n", name);
/* Document is standalone: no entities are required to interpret doc */
if(xc->inSubset == 2) {
xc->myDoc->standalone = 0;
ret = xmlGetDocEntity(xc->myDoc, name);
xc->myDoc->standalone = 1;
} else {
ret = xmlGetDocEntity(xc->myDoc, name);
if(!ret) {
xc->myDoc->standalone = 0;
ret = xmlGetDocEntity(xc->myDoc, name);
xc->myDoc->standalone = 1;
}
}
} else {
ret = xmlGetDocEntity(xc->myDoc, name);
}
if(ret && !ret->children &&
(ret->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
/* Entity is an external general parsed entity. It may be in a
* catalog file, user file or user URI
*/
int val = 0;
xmlNodePtr children;
int load_entity = 0;
load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES);
if(load_entity)
load_entity = raptor_sax2_check_load_uri_string(sax2, ret->URI);
if(!load_entity) {
RAPTOR_DEBUG2("Not getting entity URI %s by policy\n", ret->URI);
children = xmlNewText((const xmlChar*)"");
} else {
/* Disable SAX2 handlers so that the SAX2 events do not all get
* sent to callbacks during dealing with the entity parsing.
*/
sax2->enabled = 0;
val = xmlParseCtxtExternalEntity(xc, ret->URI, ret->ExternalID, &children);
sax2->enabled = 1;
}
if(!val) {
xmlAddChildList((xmlNodePtr)ret, children);
} else {
xc->validate = 0;
return NULL;
}
ret->owner = 1;
/* Mark this entity as having been checked - never do this again */
if(!ret->checked)
ret->checked = 1;
}
return ret;
}
| 165,658
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
return ::SanitizeFrontendURL(url, content::kChromeDevToolsScheme,
chrome::kChromeUIDevToolsHost, SanitizeFrontendPath(url.path()), true);
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
|
GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
| 172,461
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
PassRefPtr<CallbackWrapper> callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void LocalFileSystem::fileSystemNotAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
CallbackWrapper* callbacks)
{
context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR));
}
| 171,427
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SvcTest()
: codec_iface_(0),
test_file_name_("hantro_collage_w352h288.yuv"),
stats_file_name_("hantro_collage_w352h288.stat"),
codec_initialized_(false),
decoder_(0) {
memset(&svc_, 0, sizeof(svc_));
memset(&codec_, 0, sizeof(codec_));
memset(&codec_enc_, 0, sizeof(codec_enc_));
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
|
SvcTest()
: codec_iface_(0),
test_file_name_("hantro_collage_w352h288.yuv"),
codec_initialized_(false),
decoder_(0) {
memset(&svc_, 0, sizeof(svc_));
memset(&codec_, 0, sizeof(codec_));
memset(&codec_enc_, 0, sizeof(codec_enc_));
}
| 174,581
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_scale_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
}
this->next->mod(this->next, that, pp, display);
}
| 173,646
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void DetachWebContentsTest(DiscardReason reason) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit,
&second_lifecycle_unit);
ExpectCanDiscardTrueAllReasons(first_lifecycle_unit);
std::unique_ptr<content::WebContents> owned_contents =
tab_strip_model_->DetachWebContentsAt(0);
ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit);
NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate;
TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate,
profile());
other_tab_strip_model.AddObserver(source_);
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_));
other_tab_strip_model.AppendWebContents(CreateTestWebContents(),
/*foreground=*/true);
other_tab_strip_model.AppendWebContents(std::move(owned_contents), false);
ExpectCanDiscardTrueAllReasons(first_lifecycle_unit);
EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
first_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
first_lifecycle_unit);
CloseTabsAndExpectNotifications(&other_tab_strip_model,
{first_lifecycle_unit});
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void DetachWebContentsTest(DiscardReason reason) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit,
&second_lifecycle_unit);
ExpectCanDiscardTrueAllReasons(first_lifecycle_unit);
std::unique_ptr<content::WebContents> owned_contents =
tab_strip_model_->DetachWebContentsAt(0);
ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit);
NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate;
TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate,
profile());
other_tab_strip_model.AddObserver(source_);
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_));
other_tab_strip_model.AppendWebContents(CreateTestWebContents(),
/*foreground=*/true);
other_tab_strip_model.AppendWebContents(std::move(owned_contents), false);
ExpectCanDiscardTrueAllReasons(first_lifecycle_unit);
EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true));
first_lifecycle_unit->Discard(reason);
::testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
first_lifecycle_unit);
CloseTabsAndExpectNotifications(&other_tab_strip_model,
{first_lifecycle_unit});
}
| 172,223
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap
This is pretty serious bug. map->count is never initialized after the
call to kmalloc making the count start at some random trash value. The
end result is leaking videobufs.
Also, fix up the debug statements to print unsigned values.
Pushed to http://ifup.org/hg/v4l-dvb too
Signed-off-by: Brandon Philips <bphilips@suse.de>
Signed-off-by: Mauro Carvalho Chehab <mchehab@infradead.org>
CWE ID: CWE-119
|
static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kzalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
| 168,917
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: mm_answer_pam_free_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
(sshpam_device.free_ctx)(sshpam_ctxt);
buffer_clear(m);
mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
return (sshpam_authok == sshpam_ctxt);
}
Commit Message: set sshpam_ctxt to NULL after free
Avoids use-after-free in monitor when privsep child is compromised.
Reported by Moritz Jodeit; ok dtucker@
CWE ID: CWE-264
|
mm_answer_pam_free_ctx(int sock, Buffer *m)
{
int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
debug3("%s", __func__);
(sshpam_device.free_ctx)(sshpam_ctxt);
sshpam_ctxt = sshpam_authok = NULL;
buffer_clear(m);
mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
return r;
}
| 166,584
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119
|
void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
luaL_checkstack(L, 1, "in function mp_decode_to_lua_array");
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
| 169,238
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int append_camera_metadata(camera_metadata_t *dst,
const camera_metadata_t *src) {
if (dst == NULL || src == NULL ) return ERROR;
if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR;
if (dst->data_capacity < src->data_count + dst->data_count) return ERROR;
memcpy(get_entries(dst) + dst->entry_count, get_entries(src),
sizeof(camera_metadata_buffer_entry_t[src->entry_count]));
memcpy(get_data(dst) + dst->data_count, get_data(src),
sizeof(uint8_t[src->data_count]));
if (dst->data_count != 0) {
camera_metadata_buffer_entry_t *entry = get_entries(dst) + dst->entry_count;
for (size_t i = 0; i < src->entry_count; i++, entry++) {
if ( calculate_camera_metadata_entry_data_size(entry->type,
entry->count) > 0 ) {
entry->data.offset += dst->data_count;
}
}
}
if (dst->entry_count == 0) {
dst->flags |= src->flags & FLAG_SORTED;
} else if (src->entry_count != 0) {
dst->flags &= ~FLAG_SORTED;
} else {
}
dst->entry_count += src->entry_count;
dst->data_count += src->data_count;
assert(validate_camera_metadata_structure(dst, NULL) == OK);
return OK;
}
Commit Message: Camera metadata: Check for inconsistent data count
Resolve merge conflict for nyc-release
Also check for overflow of data/entry count on append.
Bug: 30591838
Change-Id: Ibf4c3c6e236cdb28234f3125055d95ef0a2416a2
CWE ID: CWE-264
|
int append_camera_metadata(camera_metadata_t *dst,
const camera_metadata_t *src) {
if (dst == NULL || src == NULL ) return ERROR;
// Check for overflow
if (src->entry_count + dst->entry_count < src->entry_count) return ERROR;
if (src->data_count + dst->data_count < src->data_count) return ERROR;
// Check for space
if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR;
if (dst->data_capacity < src->data_count + dst->data_count) return ERROR;
memcpy(get_entries(dst) + dst->entry_count, get_entries(src),
sizeof(camera_metadata_buffer_entry_t[src->entry_count]));
memcpy(get_data(dst) + dst->data_count, get_data(src),
sizeof(uint8_t[src->data_count]));
if (dst->data_count != 0) {
camera_metadata_buffer_entry_t *entry = get_entries(dst) + dst->entry_count;
for (size_t i = 0; i < src->entry_count; i++, entry++) {
if ( calculate_camera_metadata_entry_data_size(entry->type,
entry->count) > 0 ) {
entry->data.offset += dst->data_count;
}
}
}
if (dst->entry_count == 0) {
dst->flags |= src->flags & FLAG_SORTED;
} else if (src->entry_count != 0) {
dst->flags &= ~FLAG_SORTED;
} else {
}
dst->entry_count += src->entry_count;
dst->data_count += src->data_count;
assert(validate_camera_metadata_structure(dst, NULL) == OK);
return OK;
}
| 173,396
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) {
ContentSettingsObserver* content_settings =
new ContentSettingsObserver(render_view);
new DevToolsAgent(render_view);
new ExtensionHelper(render_view, extension_dispatcher_.get());
new PageLoadHistograms(render_view, histogram_snapshots_.get());
new PrintWebViewHelper(render_view);
new SearchBox(render_view);
new SpellCheckProvider(render_view, spellcheck_.get());
#if defined(ENABLE_SAFE_BROWSING)
safe_browsing::MalwareDOMDetails::Create(render_view);
#endif
#if defined(OS_MACOSX)
new TextInputClientObserver(render_view);
#endif // defined(OS_MACOSX)
PasswordAutofillManager* password_autofill_manager =
new PasswordAutofillManager(render_view);
AutofillAgent* autofill_agent = new AutofillAgent(render_view,
password_autofill_manager);
PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
page_click_tracker->AddListener(password_autofill_manager);
page_click_tracker->AddListener(autofill_agent);
TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent);
new ChromeRenderViewObserver(
render_view, content_settings, extension_dispatcher_.get(), translate);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
new AutomationRendererHelper(render_view);
}
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) {
ContentSettingsObserver* content_settings =
new ContentSettingsObserver(render_view);
new ExtensionHelper(render_view, extension_dispatcher_.get());
new PageLoadHistograms(render_view, histogram_snapshots_.get());
new PrintWebViewHelper(render_view);
new SearchBox(render_view);
new SpellCheckProvider(render_view, spellcheck_.get());
#if defined(ENABLE_SAFE_BROWSING)
safe_browsing::MalwareDOMDetails::Create(render_view);
#endif
#if defined(OS_MACOSX)
new TextInputClientObserver(render_view);
#endif // defined(OS_MACOSX)
PasswordAutofillManager* password_autofill_manager =
new PasswordAutofillManager(render_view);
AutofillAgent* autofill_agent = new AutofillAgent(render_view,
password_autofill_manager);
PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
page_click_tracker->AddListener(password_autofill_manager);
page_click_tracker->AddListener(autofill_agent);
TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent);
new ChromeRenderViewObserver(
render_view, content_settings, extension_dispatcher_.get(), translate);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
new AutomationRendererHelper(render_view);
}
}
| 170,324
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static enum led_brightness k90_backlight_get(struct led_classdev *led_cdev)
{
int ret;
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
struct device *dev = led->cdev.dev->parent;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int brightness;
char data[8];
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_STATUS,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 8,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial state (error %d).\n",
ret);
return -EIO;
}
brightness = data[4];
if (brightness < 0 || brightness > 3) {
dev_warn(dev,
"Read invalid backlight brightness: %02hhx.\n",
data[4]);
return -EIO;
}
return brightness;
}
Commit Message: HID: corsair: fix DMA buffers on stack
Not all platforms support DMA to the stack, and specifically since v4.9
this is no longer supported on x86 with VMAP_STACK either.
Note that the macro-mode buffer was larger than necessary.
Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver")
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Johan Hovold <johan@kernel.org>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static enum led_brightness k90_backlight_get(struct led_classdev *led_cdev)
{
int ret;
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
struct device *dev = led->cdev.dev->parent;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int brightness;
char *data;
data = kmalloc(8, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_STATUS,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 8,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial state (error %d).\n",
ret);
ret = -EIO;
goto out;
}
brightness = data[4];
if (brightness < 0 || brightness > 3) {
dev_warn(dev,
"Read invalid backlight brightness: %02hhx.\n",
data[4]);
ret = -EIO;
goto out;
}
ret = brightness;
out:
kfree(data);
return ret;
}
| 168,393
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData,
HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds)
: Shaper(font, run, emphasisData, fallbackFonts, bounds)
, m_normalizedBufferLength(0)
, m_wordSpacingAdjustment(font->fontDescription().wordSpacing())
, m_letterSpacing(font->fontDescription().letterSpacing())
, m_expansionOpportunityCount(0)
, m_fromIndex(0)
, m_toIndex(m_run.length())
{
m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]);
normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength);
setExpansion(m_run.expansion());
setFontFeatures();
}
Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape.
R=leviw@chromium.org
BUG=476647
Review URL: https://codereview.chromium.org/1108663003
git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData,
HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds)
: Shaper(font, run, emphasisData, fallbackFonts, bounds)
, m_normalizedBufferLength(0)
, m_wordSpacingAdjustment(font->fontDescription().wordSpacing())
, m_letterSpacing(font->fontDescription().letterSpacing())
, m_expansionOpportunityCount(0)
, m_fromIndex(0)
, m_toIndex(m_run.length())
, m_totalWidth(0)
{
m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]);
normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength);
setExpansion(m_run.expansion());
setFontFeatures();
}
| 172,004
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int svc_rdma_sendto(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct rpcrdma_msg *rdma_argp;
struct rpcrdma_msg *rdma_resp;
struct rpcrdma_write_array *wr_ary, *rp_ary;
int ret;
int inline_bytes;
struct page *res_page;
struct svc_rdma_req_map *vec;
u32 inv_rkey;
__be32 *p;
dprintk("svcrdma: sending response for rqstp=%p\n", rqstp);
/* Get the RDMA request header. The receive logic always
* places this at the start of page 0.
*/
rdma_argp = page_address(rqstp->rq_pages[0]);
svc_rdma_get_write_arrays(rdma_argp, &wr_ary, &rp_ary);
inv_rkey = 0;
if (rdma->sc_snd_w_inv)
inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_ary, rp_ary);
/* Build an req vec for the XDR */
vec = svc_rdma_get_req_map(rdma);
ret = svc_rdma_map_xdr(rdma, &rqstp->rq_res, vec, wr_ary != NULL);
if (ret)
goto err0;
inline_bytes = rqstp->rq_res.len;
/* Create the RDMA response header. xprt->xpt_mutex,
* acquired in svc_send(), serializes RPC replies. The
* code path below that inserts the credit grant value
* into each transport header runs only inside this
* critical section.
*/
ret = -ENOMEM;
res_page = alloc_page(GFP_KERNEL);
if (!res_page)
goto err0;
rdma_resp = page_address(res_page);
p = &rdma_resp->rm_xid;
*p++ = rdma_argp->rm_xid;
*p++ = rdma_argp->rm_vers;
*p++ = rdma->sc_fc_credits;
*p++ = rp_ary ? rdma_nomsg : rdma_msg;
/* Start with empty chunks */
*p++ = xdr_zero;
*p++ = xdr_zero;
*p = xdr_zero;
/* Send any write-chunk data and build resp write-list */
if (wr_ary) {
ret = send_write_chunks(rdma, wr_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret + xdr_padsize(ret);
}
/* Send any reply-list data and update resp reply-list */
if (rp_ary) {
ret = send_reply_chunks(rdma, rp_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret;
}
/* Post a fresh Receive buffer _before_ sending the reply */
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = send_reply(rdma, rqstp, res_page, rdma_resp, vec,
inline_bytes, inv_rkey);
if (ret < 0)
goto err0;
svc_rdma_put_req_map(rdma, vec);
dprintk("svcrdma: send_reply returns %d\n", ret);
return ret;
err1:
put_page(res_page);
err0:
svc_rdma_put_req_map(rdma, vec);
pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n",
ret);
set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags);
return -ENOTCONN;
}
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
|
int svc_rdma_sendto(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
__be32 *p, *rdma_argp, *rdma_resp, *wr_lst, *rp_ch;
struct xdr_buf *xdr = &rqstp->rq_res;
struct page *res_page;
int ret;
/* Find the call's chunk lists to decide how to send the reply.
* Receive places the Call's xprt header at the start of page 0.
*/
rdma_argp = page_address(rqstp->rq_pages[0]);
svc_rdma_get_write_arrays(rdma_argp, &wr_lst, &rp_ch);
dprintk("svcrdma: preparing response for XID 0x%08x\n",
be32_to_cpup(rdma_argp));
/* Create the RDMA response header. xprt->xpt_mutex,
* acquired in svc_send(), serializes RPC replies. The
* code path below that inserts the credit grant value
* into each transport header runs only inside this
* critical section.
*/
ret = -ENOMEM;
res_page = alloc_page(GFP_KERNEL);
if (!res_page)
goto err0;
rdma_resp = page_address(res_page);
p = rdma_resp;
*p++ = *rdma_argp;
*p++ = *(rdma_argp + 1);
*p++ = rdma->sc_fc_credits;
*p++ = rp_ch ? rdma_nomsg : rdma_msg;
/* Start with empty chunks */
*p++ = xdr_zero;
*p++ = xdr_zero;
*p = xdr_zero;
if (wr_lst) {
/* XXX: Presume the client sent only one Write chunk */
ret = svc_rdma_send_write_chunk(rdma, wr_lst, xdr);
if (ret < 0)
goto err2;
svc_rdma_xdr_encode_write_list(rdma_resp, wr_lst, ret);
}
if (rp_ch) {
ret = svc_rdma_send_reply_chunk(rdma, rp_ch, wr_lst, xdr);
if (ret < 0)
goto err2;
svc_rdma_xdr_encode_reply_chunk(rdma_resp, rp_ch, ret);
}
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = svc_rdma_send_reply_msg(rdma, rdma_argp, rdma_resp, rqstp,
wr_lst, rp_ch);
if (ret < 0)
goto err0;
return 0;
err2:
if (ret != -E2BIG)
goto err1;
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = svc_rdma_send_error_msg(rdma, rdma_resp, rqstp);
if (ret < 0)
goto err0;
return 0;
err1:
put_page(res_page);
err0:
pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n",
ret);
set_bit(XPT_CLOSE, &xprt->xpt_flags);
return -ENOTCONN;
}
| 168,175
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
if (numrows < 0 || numcols < 0) {
return 0;
}
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
return 0;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = numrows * numcols;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
}
Commit Message: Fixed an integer overflow problem.
CWE ID: CWE-190
|
jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
size_t size;
matrix = 0;
if (numrows < 0 || numcols < 0) {
goto error;
}
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
goto error;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = 0;
// matrix->datasize_ = numrows * numcols;
if (!jas_safe_size_mul(numrows, numcols, &size)) {
goto error;
}
matrix->datasize_ = size;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
goto error;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
goto error;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
error:
if (matrix) {
jas_matrix_destroy(matrix);
}
return 0;
}
| 168,476
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long Chapters::Atom::GetStartTimecode() const
{
return m_start_timecode;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Chapters::Atom::GetStartTimecode() const
| 174,356
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
struct passwd *pwd;
FILE *fp = NULL;
int i, fd = -1, save_errno;
uid_t fsuid;
struct stat st;
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
pam_syslog(pamh, LOG_ERR,
"error determining home directory for '%s'",
this_user);
return PAM_SESSION_ERR;
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
if (!stat(path, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
fd = open(path, O_RDONLY | O_NOCTTY);
fd = open(path, O_RDONLY | O_NOCTTY);
}
save_errno = errno;
setfsuid(fsuid);
if (fd >= 0) {
if (!fstat(fd, &st)) {
if (!S_ISREG(st.st_mode))
save_errno = errno;
close(fd);
}
}
if (fp) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
tmp = memchr(buf, '\r', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
tmp = memchr(buf, '\n', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
if (fnmatch(buf, other_user, 0) == 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s %s allowed by %s",
other_user, sense, path);
}
fclose(fp);
return PAM_SUCCESS;
}
}
/* If there's no match in the file, we fail. */
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s",
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
Commit Message:
CWE ID:
|
check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
struct passwd *pwd;
FILE *fp = NULL;
int i, fd = -1, save_errno;
struct stat st;
PAM_MODUTIL_DEF_PRIVS(privs);
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
pam_syslog(pamh, LOG_ERR,
"error determining home directory for '%s'",
this_user);
return PAM_SESSION_ERR;
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
if (pam_modutil_drop_priv(pamh, &privs, pwd))
return PAM_SESSION_ERR;
if (!stat(path, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
fd = open(path, O_RDONLY | O_NOCTTY);
fd = open(path, O_RDONLY | O_NOCTTY);
}
save_errno = errno;
if (pam_modutil_regain_priv(pamh, &privs)) {
if (fd >= 0)
close(fd);
return PAM_SESSION_ERR;
}
if (fd >= 0) {
if (!fstat(fd, &st)) {
if (!S_ISREG(st.st_mode))
save_errno = errno;
close(fd);
}
}
if (fp) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
tmp = memchr(buf, '\r', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
tmp = memchr(buf, '\n', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
if (fnmatch(buf, other_user, 0) == 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s %s allowed by %s",
other_user, sense, path);
}
fclose(fp);
return PAM_SUCCESS;
}
}
/* If there's no match in the file, we fail. */
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s",
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
| 164,818
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SeekHead::~SeekHead()
{
delete[] m_entries;
delete[] m_void_elements;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
SeekHead::~SeekHead()
SeekHead::~SeekHead() {
delete[] m_entries;
delete[] m_void_elements;
}
| 174,469
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) {
mAACProfile = aacParams->eAACProfile;
}
if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 0;
mSBRRatio = 0;
} else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 1;
} else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 2;
} else {
mSBRMode = -1; // codec default sbr mode
mSBRRatio = 0;
}
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) {
mAACProfile = aacParams->eAACProfile;
}
if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 0;
mSBRRatio = 0;
} else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 1;
} else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 2;
} else {
mSBRMode = -1; // codec default sbr mode
mSBRRatio = 0;
}
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,191
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void Sp_split_regexp(js_State *J)
{
js_Regexp *re;
const char *text;
int limit, len, k;
const char *p, *a, *b, *c, *e;
Resub m;
text = checkstring(J, 0);
re = js_toregexp(J, 1);
limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30;
js_newarray(J);
len = 0;
e = text + strlen(text);
/* splitting the empty string */
if (e == text) {
if (js_regexec(re->prog, text, &m, 0)) {
if (len == limit) return;
js_pushliteral(J, "");
js_setindex(J, -2, 0);
}
return;
}
p = a = text;
while (a < e) {
if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0))
break; /* no match */
b = m.sub[0].sp;
c = m.sub[0].ep;
/* empty string at end of last match */
if (b == p) {
++a;
continue;
}
if (len == limit) return;
js_pushlstring(J, p, b - p);
js_setindex(J, -2, len++);
for (k = 1; k < m.nsub; ++k) {
if (len == limit) return;
js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp);
js_setindex(J, -2, len++);
}
a = p = c;
}
if (len == limit) return;
js_pushstring(J, p);
js_setindex(J, -2, len);
}
Commit Message: Bug 700937: Limit recursion in regexp matcher.
Also handle negative return code as an error in the JS bindings.
CWE ID: CWE-400
|
static void Sp_split_regexp(js_State *J)
{
js_Regexp *re;
const char *text;
int limit, len, k;
const char *p, *a, *b, *c, *e;
Resub m;
text = checkstring(J, 0);
re = js_toregexp(J, 1);
limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30;
js_newarray(J);
len = 0;
e = text + strlen(text);
/* splitting the empty string */
if (e == text) {
if (js_doregexec(J, re->prog, text, &m, 0)) {
if (len == limit) return;
js_pushliteral(J, "");
js_setindex(J, -2, 0);
}
return;
}
p = a = text;
while (a < e) {
if (js_doregexec(J, re->prog, a, &m, a > text ? REG_NOTBOL : 0))
break; /* no match */
b = m.sub[0].sp;
c = m.sub[0].ep;
/* empty string at end of last match */
if (b == p) {
++a;
continue;
}
if (len == limit) return;
js_pushlstring(J, p, b - p);
js_setindex(J, -2, len++);
for (k = 1; k < m.nsub; ++k) {
if (len == limit) return;
js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp);
js_setindex(J, -2, len++);
}
a = p = c;
}
if (len == limit) return;
js_pushstring(J, p);
js_setindex(J, -2, len);
}
| 169,701
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: image_transform_png_set_strip_alpha_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_strip_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
| 173,651
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
if (parent_widget_)
return parent_widget_->GetClientAreaBoundsInScreen();
return PopupViewCommon().GetWindowBounds(delegate_->container_view());
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <rkaplow@chromium.org>
Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org>
Reviewed-by: Fabio Tirelo <ftirelo@chromium.org>
Reviewed-by: Tommy Martino <tmartino@chromium.org>
Commit-Queue: Mathieu Perreault <mathp@chromium.org>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416
|
gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
| 172,093
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
Commit Message:
CWE ID: CWE-17
|
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
| 164,811
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type)
{
M_list_str_t *parts;
const char *part;
char *out;
size_t len;
size_t i;
size_t count;
if (path == NULL) {
return NULL;
}
len = M_list_str_len(path);
if (len == 0) {
return NULL;
}
sys_type = M_fs_path_get_system_type(sys_type);
/* Remove any empty parts (except for the first part which denotes an abs path on Unix
* or a UNC path on Windows). */
parts = M_list_str_duplicate(path);
for (i=len-1; i>0; i--) {
part = M_list_str_at(parts, i);
if (part == NULL || *part == '\0') {
M_list_str_remove_at(parts, i);
}
}
len = M_list_str_len(parts);
/* Join puts the sep between items. If there are no items then the sep
* won't be written. */
part = M_list_str_at(parts, 0);
if (len == 1 && (part == NULL || *part == '\0')) {
M_list_str_destroy(parts);
if (sys_type == M_FS_SYSTEM_WINDOWS) {
return M_strdup("\\\\");
}
return M_strdup("/");
}
/* Handle windows abs path because they need two separators. */
if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) {
part = M_list_str_at(parts, 0);
/* If we have 1 item we need to add two empties so we get the second separator. */
count = (len == 1) ? 2 : 1;
/* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */
if (part != NULL && *part == '\0') {
for (i=0; i<count; i++) {
M_list_str_insert_at(parts, "", 0);
}
} else if (M_fs_path_isabs(part, sys_type) && len == 1) {
/* We need to add an empty so we get a separator after the drive. */
M_list_str_insert_at(parts, "", 1);
}
}
out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type));
M_list_str_destroy(parts);
return out;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732
|
char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type)
{
M_list_str_t *parts;
const char *part;
char *out;
size_t len;
size_t i;
size_t count;
if (path == NULL) {
return NULL;
}
len = M_list_str_len(path);
if (len == 0) {
return NULL;
}
sys_type = M_fs_path_get_system_type(sys_type);
/* Remove any empty parts (except for the first part which denotes an abs path on Unix
* or a UNC path on Windows). */
parts = M_list_str_duplicate(path);
for (i=len-1; i>0; i--) {
part = M_list_str_at(parts, i);
if (part == NULL || *part == '\0') {
M_list_str_remove_at(parts, i);
}
}
len = M_list_str_len(parts);
/* Join puts the sep between items. If there are no items then the sep
* won't be written. */
part = M_list_str_at(parts, 0);
if (len == 1 && (part == NULL || *part == '\0')) {
M_list_str_destroy(parts);
if (sys_type == M_FS_SYSTEM_WINDOWS) {
return M_strdup("\\\\");
}
return M_strdup("/");
}
/* Handle windows abs path because they need two separators. */
if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) {
part = M_list_str_at(parts, 0);
/* If we have 1 item we need to add two empties so we get the second separator. */
count = (len == 1) ? 2 : 1;
/* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */
if (part != NULL && *part == '\0') {
for (i=0; i<count; i++) {
M_list_str_insert_at(parts, "", 0);
}
} else if (M_fs_path_isabs(part, sys_type) && len == 1) {
/* We need to add an empty so we get a separator after the drive. */
M_list_str_insert_at(parts, "", 1);
}
}
out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type));
M_list_str_destroy(parts);
return out;
}
| 169,146
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
clock_for_test_ = std::move(clock);
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <sdefresne@chromium.org>
Reviewed-by: Marc Treib <treib@chromium.org>
Commit-Queue: Chris Pickel <sfiera@chromium.org>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
| 171,959
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) {
SkImageInfo info = SkImageInfo::Make(input->width(), input->height(),
kN32_SkColorType, kPremul_SkAlphaType);
RefPtr<Uint8Array> dstPixels = copySkImageData(input, info);
if (!dstPixels)
return nullptr;
return newSkImageFromRaster(
info, std::move(dstPixels),
static_cast<size_t>(input->width()) * info.bytesPerPixel());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
|
static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) {
SkImageInfo info = SkImageInfo::Make(input->width(), input->height(),
kN32_SkColorType, kPremul_SkAlphaType);
RefPtr<Uint8Array> dstPixels = copySkImageData(input, info);
if (!dstPixels)
return nullptr;
return newSkImageFromRaster(
info, std::move(dstPixels),
static_cast<unsigned>(input->width()) * info.bytesPerPixel());
}
| 172,507
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data)
{
struct Context *ctx = (struct Context *) data;
if (!ctx)
return -1;
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return -1;
#ifdef USE_HCACHE
/* keep hcache file if hcache == bcache */
if (strcmp(HC_FNAME "." HC_FEXT, id) == 0)
return 0;
#endif
for (int i = 0; i < ctx->msgcount; i++)
{
/* if the id we get is known for a header: done (i.e. keep in cache) */
if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))
return 0;
}
/* message not found in context -> remove it from cache
* return the result of bcache, so we stop upon its first error
*/
return mutt_bcache_del(bcache, id);
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <jeriko.one@gmx.us>
CWE ID: CWE-22
|
static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data)
{
struct Context *ctx = (struct Context *) data;
if (!ctx)
return -1;
struct PopData *pop_data = (struct PopData *) ctx->data;
if (!pop_data)
return -1;
#ifdef USE_HCACHE
/* keep hcache file if hcache == bcache */
if (strcmp(HC_FNAME "." HC_FEXT, id) == 0)
return 0;
#endif
for (int i = 0; i < ctx->msgcount; i++)
{
/* if the id we get is known for a header: done (i.e. keep in cache) */
if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0))
return 0;
}
/* message not found in context -> remove it from cache
* return the result of bcache, so we stop upon its first error
*/
return mutt_bcache_del(bcache, cache_id(id));
}
| 169,120
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int number, str_len = 0;
xmlChar *str = NULL, *ret = NULL, *tmp;
if ((nargs < 1) || (nargs > 2)) {
xmlXPathSetArityError(ctxt);
return;
}
if (nargs == 2) {
str = xmlXPathPopString(ctxt);
str_len = xmlUTF8Strlen(str);
}
if (str_len == 0) {
if (str != NULL) xmlFree(str);
str = xmlStrdup((const xmlChar *) " ");
str_len = 1;
}
number = (int) xmlXPathPopNumber(ctxt);
if (number <= 0) {
xmlXPathReturnEmptyString(ctxt);
xmlFree(str);
return;
}
while (number >= str_len) {
ret = xmlStrncat(ret, str, str_len);
number -= str_len;
}
tmp = xmlUTF8Strndup (str, number);
ret = xmlStrcat(ret, tmp);
if (tmp != NULL)
xmlFree (tmp);
xmlXPathReturnString(ctxt, ret);
if (str != NULL)
xmlFree(str);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
|
exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int number, str_len = 0, str_size = 0;
xmlChar *str = NULL, *ret = NULL;
if ((nargs < 1) || (nargs > 2)) {
xmlXPathSetArityError(ctxt);
return;
}
if (nargs == 2) {
str = xmlXPathPopString(ctxt);
str_len = xmlUTF8Strlen(str);
str_size = xmlStrlen(str);
}
if (str_len == 0) {
if (str != NULL) xmlFree(str);
str = xmlStrdup((const xmlChar *) " ");
str_len = 1;
str_size = 1;
}
number = (int) xmlXPathPopNumber(ctxt);
if (number <= 0) {
xmlXPathReturnEmptyString(ctxt);
xmlFree(str);
return;
}
while (number >= str_len) {
ret = xmlStrncat(ret, str, str_size);
number -= str_len;
}
if (number > 0) {
str_size = xmlUTF8Strsize(str, number);
ret = xmlStrncat(ret, str, str_size);
}
xmlXPathReturnString(ctxt, ret);
if (str != NULL)
xmlFree(str);
}
| 173,296
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
Commit Message:
CWE ID: CWE-682
|
XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + rlen;
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
| 164,747
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void uwbd_stop(struct uwb_rc *rc)
{
kthread_stop(rc->uwbd.task);
uwbd_flush(rc);
}
Commit Message: uwb: properly check kthread_run return value
uwbd_start() calls kthread_run() and checks that the return value is
not NULL. But the return value is not NULL in case kthread_run() fails,
it takes the form of ERR_PTR(-EINTR).
Use IS_ERR() instead.
Also add a check to uwbd_stop().
Signed-off-by: Andrey Konovalov <andreyknvl@google.com>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-119
|
void uwbd_stop(struct uwb_rc *rc)
{
if (rc->uwbd.task)
kthread_stop(rc->uwbd.task);
uwbd_flush(rc);
}
| 167,686
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void PluginModule::InstanceDeleted(PluginInstance* instance) {
if (out_of_process_proxy_.get())
out_of_process_proxy_->RemoveInstance(instance->pp_instance());
instances_.erase(instance);
if (nacl_ipc_proxy_) {
out_of_process_proxy_.reset();
reserve_instance_id_ = NULL;
}
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
TBR=bbudge@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PluginModule::InstanceDeleted(PluginInstance* instance) {
if (out_of_process_proxy_.get())
out_of_process_proxy_->RemoveInstance(instance->pp_instance());
instances_.erase(instance);
}
| 170,746
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.