code
stringlengths 12
2.05k
| label
int64 0
1
| programming_language
stringclasses 9
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
103
⌀ | description
stringlengths 36
1.23k
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
bool hex2carray(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin, uint64_t _max_length) {
CHECK_STATE(_hex);
CHECK_STATE(_bin);
CHECK_STATE(_bin_len)
int len = strnlen(_hex, 2 * _max_length + 1);
CHECK_STATE(len != 2 * _max_length + 1);
CHECK_STATE(len <= 2 * _max_length );
if (len == 0 && len % 2 == 1)
return false;
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char) _hex[i * 2]);
int low = char2int((char) _hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low);
}
return true;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
int length() const {
return m_str ? m_str->size() : 0;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
static void php_array_replace_recursive(PointerSet &seen, bool check,
Array &arr1, const Array& arr2) {
if (check) {
if (seen.find((void*)arr1.get()) != seen.end()) {
raise_warning("array_replace_recursive(): recursion detected");
return;
}
seen.insert((void*)arr1.get());
}
for (ArrayIter iter(arr2); iter; ++iter) {
Variant key = iter.first();
const Variant& value = iter.secondRef();
if (arr1.exists(key, true) && value.isArray()) {
Variant &v = arr1.lvalAt(key, AccessFlags::Key);
if (v.isArray()) {
Array subarr1 = v.toArray();
const ArrNR& arr_value = value.toArrNR();
php_array_replace_recursive(seen, v.isReferenced(), subarr1,
arr_value);
v = subarr1;
} else {
arr1.set(key, value, true);
}
} else {
arr1.setWithRef(key, value, true);
}
}
if (check) {
seen.erase((void*)arr1.get());
}
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
const int32_t* input_data = input->data.i32;
const TfLiteTensor* weight;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &weight));
const uint8_t* weight_data = weight->data.uint8;
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
int32_t* output_data = output->data.i32;
output_data[0] =
0; // Catch output tensor sharing memory with an input tensor
output_data[0] = input_data[0] + weight_data[0];
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
IniSection (const IniParser *p, string n)
: IniBase (n),
ip (p),
end_comment (), rewrite_by(0),
container(), ivalues (), isections ()
{} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
friend bool operator==(const TensorKey& t1, const TensorKey& t2) {
if (t1.dtype() != t2.dtype() || t1.shape() != t2.shape()) {
return false;
}
if (DataTypeCanUseMemcpy(t1.dtype())) {
return t1.tensor_data() == t2.tensor_data();
}
if (t1.dtype() == DT_STRING) {
const auto s1 = t1.unaligned_flat<tstring>();
const auto s2 = t2.unaligned_flat<tstring>();
for (int64_t i = 0, n = t1.NumElements(); i < n; ++i) {
if (TF_PREDICT_FALSE(s1(i) != s2(i))) {
return false;
}
}
return true;
}
return false;
} | 0 | C++ | CWE-120 | Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') | The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. | https://cwe.mitre.org/data/definitions/120.html | vulnerable |
void UnicodeStringTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char *par)
{
if (exec) logln("TestSuite UnicodeStringTest: ");
TESTCASE_AUTO_BEGIN;
TESTCASE_AUTO_CREATE_CLASS(StringCaseTest);
TESTCASE_AUTO(TestBasicManipulation);
TESTCASE_AUTO(TestCompare);
TESTCASE_AUTO(TestExtract);
TESTCASE_AUTO(TestRemoveReplace);
TESTCASE_AUTO(TestSearching);
TESTCASE_AUTO(TestSpacePadding);
TESTCASE_AUTO(TestPrefixAndSuffix);
TESTCASE_AUTO(TestFindAndReplace);
TESTCASE_AUTO(TestBogus);
TESTCASE_AUTO(TestReverse);
TESTCASE_AUTO(TestMiscellaneous);
TESTCASE_AUTO(TestStackAllocation);
TESTCASE_AUTO(TestUnescape);
TESTCASE_AUTO(TestCountChar32);
TESTCASE_AUTO(TestStringEnumeration);
TESTCASE_AUTO(TestNameSpace);
TESTCASE_AUTO(TestUTF32);
TESTCASE_AUTO(TestUTF8);
TESTCASE_AUTO(TestReadOnlyAlias);
TESTCASE_AUTO(TestAppendable);
TESTCASE_AUTO(TestUnicodeStringImplementsAppendable);
TESTCASE_AUTO(TestSizeofUnicodeString);
TESTCASE_AUTO(TestStartsWithAndEndsWithNulTerminated);
TESTCASE_AUTO(TestMoveSwap);
TESTCASE_AUTO(TestUInt16Pointers);
TESTCASE_AUTO(TestWCharPointers);
TESTCASE_AUTO(TestNullPointers);
TESTCASE_AUTO(TestUnicodeStringInsertAppendToSelf);
TESTCASE_AUTO(TestLargeAppend);
TESTCASE_AUTO_END;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
ResourceHandle::ResourceHandle(const ResourceHandleProto& proto) {
TF_CHECK_OK(FromProto(proto));
} | 1 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)
{
CNetChunk Packet;
if(!pMsg)
return -1;
// drop invalid packet
if(ClientID != -1 && (ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY || m_aClients[ClientID].m_Quitting))
return 0;
mem_zero(&Packet, sizeof(CNetChunk));
Packet.m_ClientID = ClientID;
Packet.m_pData = pMsg->Data();
Packet.m_DataSize = pMsg->Size();
if(Flags&MSGFLAG_VITAL)
Packet.m_Flags |= NETSENDFLAG_VITAL;
if(Flags&MSGFLAG_FLUSH)
Packet.m_Flags |= NETSENDFLAG_FLUSH;
// write message to demo recorder
if(!(Flags&MSGFLAG_NORECORD))
m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());
if(!(Flags&MSGFLAG_NOSEND))
{
if(ClientID == -1)
{
// broadcast
int i;
for(i = 0; i < MAX_CLIENTS; i++)
if(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)
{
Packet.m_ClientID = i;
m_NetServer.Send(&Packet);
}
}
else
m_NetServer.Send(&Packet);
}
return 0;
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
bool JavascriptArray::IsMissingItem(uint32 index)
{
if (this->length <= index)
{
return false;
}
bool isIntArray = false, isFloatArray = false;
this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
if (isIntArray)
{
return IsMissingItemAt<int32>(index);
}
else if (isFloatArray)
{
return IsMissingItemAt<double>(index);
}
else
{
return IsMissingItemAt<Var>(index);
}
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
CxFile(void) { };
| 0 | C++ | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
void XfccIntegrationTest::initialize() {
config_helper_.addConfigModifier(
[&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager&
hcm) -> void {
hcm.set_forward_client_cert_details(fcc_);
hcm.mutable_set_current_client_cert_details()->CopyFrom(sccd_);
});
config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void {
auto transport_socket =
bootstrap.mutable_static_resources()->mutable_clusters(0)->mutable_transport_socket();
envoy::extensions::transport_sockets::tls::v3::UpstreamTlsContext context;
auto* validation_context = context.mutable_common_tls_context()->mutable_validation_context();
validation_context->mutable_trusted_ca()->set_filename(
TestEnvironment::runfilesPath("test/config/integration/certs/upstreamcacert.pem"));
validation_context->add_match_subject_alt_names()->set_suffix("lyft.com");
transport_socket->set_name("envoy.transport_sockets.tls");
transport_socket->mutable_typed_config()->PackFrom(context);
});
if (tls_) {
config_helper_.addSslConfig();
}
context_manager_ =
std::make_unique<Extensions::TransportSockets::Tls::ContextManagerImpl>(timeSystem());
client_tls_ssl_ctx_ = createClientSslContext(false);
client_mtls_ssl_ctx_ = createClientSslContext(true);
HttpIntegrationTest::initialize();
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
std::string controller::bookmark(
const std::string& url,
const std::string& title,
const std::string& description,
const std::string& feed_title)
{
std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd");
bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive");
if (bookmark_cmd.length() > 0) {
std::string cmdline = strprintf::fmt("%s '%s' '%s' '%s' '%s'",
bookmark_cmd,
utils::replace_all(url,"'", "%27"),
utils::replace_all(title,"'", "%27"),
utils::replace_all(description,"'", "%27"),
utils::replace_all(feed_title,"'", "%27"));
LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline);
if (is_interactive) {
v->push_empty_formaction();
stfl::reset();
utils::run_interactively(cmdline, "controller::bookmark");
v->pop_current_formaction();
return "";
} else {
char * my_argv[4];
my_argv[0] = const_cast<char *>("/bin/sh");
my_argv[1] = const_cast<char *>("-c");
my_argv[2] = const_cast<char *>(cmdline.c_str());
my_argv[3] = nullptr;
return utils::run_program(my_argv, "");
}
} else {
return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly.");
}
} | 1 | C++ | CWE-943 | Improper Neutralization of Special Elements in Data Query Logic | The application generates a query intended to access or manipulate data in a data store such as a database, but it does not neutralize or incorrectly neutralizes special elements that can modify the intended logic of the query. | https://cwe.mitre.org/data/definitions/943.html | safe |
void SetBackgroundColor(int par)
{
if ( par == STROKING ) { outpos += sprintf(outpos," 0 0 0 0 K"); }
else { outpos += sprintf(outpos," 0 0 0 0 k"); }
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
void ValidateInputTensors(OpKernelContext* ctx, const Tensor& in0,
const Tensor& in1) override {
const auto in0_num_dims = in0.dims();
OP_REQUIRES(
ctx, in0_num_dims >= 2,
errors::InvalidArgument("In[0] ndims must be >= 2: ", in0_num_dims));
const auto in1_num_dims = in1.dims();
OP_REQUIRES(
ctx, in1_num_dims >= 2,
errors::InvalidArgument("In[1] ndims must be >= 2: ", in1_num_dims));
const auto in0_last_dim = in0.dim_size(in0_num_dims - 1);
const auto in0_prev_dim = in0.dim_size(in0_num_dims - 2);
OP_REQUIRES(ctx, in0_last_dim == in0_prev_dim,
errors::InvalidArgument(
"In[0] matrices in the last dimensions must be square (",
in0_last_dim, " =/= ", in0_prev_dim, ")"));
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
int cpl = ctxt->ops->cpl(ctxt);
old_eip = ctxt->_eip;
ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return X86EMUL_CONTINUE;
rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
/* If we failed, we tainted the memory, but the very least we should
restore cs */
if (rc != X86EMUL_CONTINUE)
goto fail;
return rc;
fail:
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
return rc;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (se) {
se->tag = type;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = (ut16) value;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
se->info.uninit_offset = (ut16) value;
}
}
return se;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
void RemoteFsDevice::unmount()
{
if (details.isLocalFile()) {
return;
}
if (!isConnected() || proc) {
return;
}
if (messageSent) {
return;
}
if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {
mounter()->umount(mountPoint(details, false), getpid());
setStatusMessage(tr("Disconnecting..."));
messageSent=true;
return;
}
QString cmd;
QStringList args;
if (!details.isLocalFile()) {
QString mp=mountPoint(details, false);
if (!mp.isEmpty()) {
cmd=Utils::findExe("fusermount");
if (!cmd.isEmpty()) {
args << QLatin1String("-u") << QLatin1String("-z") << mp;
} else {
emit error(tr("\"fusermount\" is not installed!"));
}
}
}
if (!cmd.isEmpty()) {
setStatusMessage(tr("Disconnecting..."));
proc=new QProcess(this);
proc->setProperty("unmount", true);
connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));
proc->start(cmd, args, QIODevice::ReadOnly);
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TfLiteStatus PrepareMeanOrSum(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_OK(context, PrepareSimple(context, node));
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// reduce_mean requires a buffer to store intermediate sum result.
OpContext op_context(context, node);
if (op_context.input->type == kTfLiteInt8 ||
op_context.input->type == kTfLiteUInt8 ||
op_context.input->type == kTfLiteInt16) {
const double real_multiplier =
static_cast<double>(op_context.input->params.scale) /
static_cast<double>(op_context.output->params.scale);
int exponent;
QuantizeMultiplier(real_multiplier, &data->multiplier, &exponent);
data->shift = exponent;
}
TfLiteTensor* temp_sum = GetTemporary(context, node, /*index=*/2);
if (!IsConstantTensor(op_context.axis)) {
SetTensorToDynamic(temp_sum);
return kTfLiteOk;
}
temp_sum->allocation_type = kTfLiteArenaRw;
return ResizeTempSum(context, &op_context, temp_sum);
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void Context::onUpstreamConnectionClose(PeerType peer_type) {
if (wasm_->onUpstreamConnectionClose_) {
wasm_->onUpstreamConnectionClose_(this, id_, static_cast<uint32_t>(peer_type));
}
} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
QUInt8() : value(0) {} | 1 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | safe |
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,
int index) {
if (index >= 0 && index < node->outputs->size) {
const int tensor_index = node->outputs->data[index];
if (tensor_index != kTfLiteOptionalTensor) {
if (context->tensors != nullptr) {
return &context->tensors[tensor_index];
} else {
return context->GetTensor(context, tensor_index);
}
}
}
return nullptr;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
void InferenceContext::PreInputInit(
const OpDef& op_def, const std::vector<const Tensor*>& input_tensors,
const std::vector<ShapeHandle>& input_tensors_as_shapes) {
// TODO(mdan): This is also done at graph construction. Run only here instead?
const auto ret = full_type::SpecializeType(attrs_, op_def);
DCHECK(ret.status().ok()) << "while instantiating types: " << ret.status();
ret_types_ = ret.ValueOrDie();
input_tensors_ = input_tensors;
input_tensors_as_shapes_ = input_tensors_as_shapes;
construction_status_ =
NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_);
if (!construction_status_.ok()) return;
int num_outputs = 0;
for (const auto& e : output_name_map_) {
num_outputs = std::max(num_outputs, e.second.second);
}
outputs_.assign(num_outputs, nullptr);
output_handle_shapes_and_types_.resize(num_outputs);
} | 0 | C++ | CWE-754 | Improper Check for Unusual or Exceptional Conditions | The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software. | https://cwe.mitre.org/data/definitions/754.html | vulnerable |
void AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return; // Already allocated
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteMfccParams*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input_wav = GetInput(context, node, kInputTensorWav);
const TfLiteTensor* input_rate = GetInput(context, node, kInputTensorRate);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(input_wav), 3);
TF_LITE_ENSURE_EQ(context, NumElements(input_rate), 1);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
TF_LITE_ENSURE_TYPES_EQ(context, input_wav->type, output->type);
TF_LITE_ENSURE_TYPES_EQ(context, input_rate->type, kTfLiteInt32);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(3);
output_size->data[0] = input_wav->dims->data[0];
output_size->data[1] = input_wav->dims->data[1];
output_size->data[2] = params->dct_coefficient_count;
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus EqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteBool:
Comparison<bool, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteFloat32:
Comparison<float, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::EqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::EqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::EqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteString:
ComparisonString(reference_ops::StringRefEqualFn, input1, input2, output,
requires_broadcast);
break;
default:
context->ReportError(
context,
"Does not support type %d, requires bool|float|int|uint8|string",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void AddBatchOffsets(OpKernelContext* ctx, Tensor* indices,
const Tensor& params) {
int64_t batch_size = 1; // The size of all batch dimensions.
for (int idx = 0; idx < batch_dims_; ++idx) {
batch_size *= params.dim_size(idx);
}
OP_REQUIRES(
ctx, batch_size != 0,
errors::InvalidArgument(
"Inner size of indices would result in batch_size of 0 and a ",
"division by 0 in the implementation. This is illegal"));
auto indices_flat = indices->flat<Index>();
int64_t const index_inner_size = indices->NumElements() / batch_size;
int64_t const batch_offset = params.dim_size(batch_dims_);
for (int64_t batch_idx = 0, dest_idx = 0; batch_idx < batch_size;
++batch_idx) {
for (int64_t idx = 0; idx < index_inner_size; ++idx) {
indices_flat(dest_idx++) += batch_offset * batch_idx;
}
}
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
TfLiteStatus EvalHashtableImport(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
const int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
const TfLiteTensor* value_tensor = GetInput(context, node, kValueTensor);
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
TF_LITE_ENSURE_STATUS(
lookup->CheckKeyAndValueTypes(context, key_tensor, value_tensor));
// The hashtable resource will only be initialized once, attempting to
// initialize it multiple times will be a no-op.
auto result = lookup->Import(context, key_tensor, value_tensor);
return result;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static Array HHVM_METHOD(Memcache, getextendedstats,
const String& /*type*/ /* = null_string */,
int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) {
auto data = Native::data<MemcacheData>(this_);
memcached_return_t ret;
memcached_stat_st *stats;
stats = memcached_stat(&data->m_memcache, nullptr, &ret);
if (ret != MEMCACHED_SUCCESS) {
return Array();
}
int server_count = memcached_server_count(&data->m_memcache);
Array return_val;
for (int server_id = 0; server_id < server_count; server_id++) {
memcached_stat_st *stat;
LMCD_SERVER_POSITION_INSTANCE_TYPE instance =
memcached_server_instance_by_position(&data->m_memcache, server_id);
const char *hostname = LMCD_SERVER_HOSTNAME(instance);
in_port_t port = LMCD_SERVER_PORT(instance);
stat = stats + server_id;
Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret);
if (ret != MEMCACHED_SUCCESS) {
continue;
}
auto const port_str = folly::to<std::string>(port);
auto const key_len = strlen(hostname) + 1 + port_str.length();
auto key = String(key_len, ReserveString);
key += hostname;
key += ":";
key += port_str;
return_val.set(key, server_stats);
}
free(stats);
return return_val;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix)
{
int stride;
U8 *buf;
int w, h, b;
w = r.width();
h = r.height();
b = format.bpp/8;
if (h == 0)
return;
buf = getBufferRW(r, &stride);
if (b == 1) {
while (h--) {
memset(buf, *(const U8*)pix, w);
buf += stride * b;
}
} else {
U8 *start;
int w1;
start = buf;
w1 = w;
while (w1--) {
memcpy(buf, pix, b);
buf += b;
}
buf += (stride - w) * b;
h--;
while (h--) {
memcpy(buf, start, w * b);
buf += stride * b;
}
}
commitBufferRW(r);
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
Status OpLevelCostEstimator::PredictFusedBatchNorm(
const OpContext& op_context, NodeCosts* node_costs) const {
bool found_unknown_shapes = false;
const auto& op_info = op_context.op_info;
// x: op_info.inputs(0)
// scale: op_info.inputs(1)
// offset: op_info.inputs(2)
// mean: op_info.inputs(3) --> only for inference
// variance: op_info.inputs(4) --> only for inference
ConvolutionDimensions dims = OpDimensionsFromInputs(
op_info.inputs(0).shape(), op_info, &found_unknown_shapes);
const bool is_training = IsTraining(op_info);
int64_t ops = 0;
const auto rsqrt_cost = Eigen::internal::functor_traits<
Eigen::internal::scalar_rsqrt_op<float>>::Cost;
if (is_training) {
ops = dims.iz * (dims.batch * dims.ix * dims.iy * 4 + 6 + rsqrt_cost);
} else {
ops = dims.batch * dims.ix * dims.iy * dims.iz * 2;
}
node_costs->num_compute_ops = ops;
const int64_t size_nhwc =
CalculateTensorSize(op_info.inputs(0), &found_unknown_shapes);
const int64_t size_c =
CalculateTensorSize(op_info.inputs(1), &found_unknown_shapes);
if (is_training) {
node_costs->num_input_bytes_accessed = {size_nhwc, size_c, size_c};
node_costs->num_output_bytes_accessed = {size_nhwc, size_c, size_c, size_c,
size_c};
// FusedBatchNorm in training mode internally re-reads the input tensor:
// one for mean/variance, and the 2nd internal read forthe actual scaling.
// Assume small intermediate data such as mean / variance (size_c) can be
// cached on-chip.
node_costs->internal_read_bytes = size_nhwc;
} else {
node_costs->num_input_bytes_accessed = {size_nhwc, size_c, size_c, size_c,
size_c};
node_costs->num_output_bytes_accessed = {size_nhwc};
}
node_costs->max_memory = node_costs->num_total_output_bytes();
if (found_unknown_shapes) {
node_costs->inaccurate = true;
node_costs->num_nodes_with_unknown_shapes = 1;
}
return Status::OK();
} | 0 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteDepthToSpaceParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
auto data_type = output->type;
TF_LITE_ENSURE(context,
data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
data_type == kTfLiteInt64);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const int block_size = params->block_size;
const int input_height = input->dims->data[1];
const int input_width = input->dims->data[2];
const int input_channels = input->dims->data[3];
int output_height = input_height * block_size;
int output_width = input_width * block_size;
int output_channels = input_channels / block_size / block_size;
TF_LITE_ENSURE_EQ(context, input_height, output_height / block_size);
TF_LITE_ENSURE_EQ(context, input_width, output_width / block_size);
TF_LITE_ENSURE_EQ(context, input_channels,
output_channels * block_size * block_size);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
output_size->data[0] = input->dims->data[0];
output_size->data[1] = output_height;
output_size->data[2] = output_width;
output_size->data[3] = output_channels;
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
//do padding ourselves
if (direction)
{
while ((temp.length() % 8) != 0) temp.append('\0');
}
else
{
temp = b64ToByte(temp);
while ((temp.length() % 8) != 0) temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
temp2 += cipher.final().toByteArray();
if (!cipher.ok())
return cipherText;
if (direction)
temp2 = byteToB64(temp2);
return temp2;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
auto* params = reinterpret_cast<TfLiteShapeParams*>(node->builtin_data);
switch (params->out_type) {
case kTfLiteInt32:
output->type = kTfLiteInt32;
break;
case kTfLiteInt64:
output->type = kTfLiteInt64;
break;
default:
context->ReportError(context, "Unknown shape output data type: %d",
params->out_type);
return kTfLiteError;
}
// By design, the input shape is always known at the time of Prepare, even
// if the preceding op that generates |input| is dynamic. Thus, we can
// always compute the shape immediately, without waiting for Eval.
SetTensorToPersistentRo(output);
// Shape always produces a 1-dimensional output tensor, where each output
// element is the length of the corresponding input tensor's dimension.
TfLiteIntArray* output_size = TfLiteIntArrayCreate(1);
output_size->data[0] = NumDimensions(input);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));
TFLITE_DCHECK_EQ(NumDimensions(output), 1);
TFLITE_DCHECK_EQ(SizeOfDimension(output, 0), NumDimensions(input));
// Immediately propagate the known shape to the output tensor. This allows
// downstream ops that rely on the value to use it during prepare.
switch (output->type) {
case kTfLiteInt32:
ExtractShape(input, GetTensorData<int32_t>(output));
break;
case kTfLiteInt64:
ExtractShape(input, GetTensorData<int64_t>(output));
break;
default:
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static inline jas_ulong encode_twos_comp(long n, int prec)
{
jas_ulong result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
// NOTE: Is this correct?
if (n < 0) {
result = -n;
result = (result ^ 0xffffffffUL) + 1;
result &= (1 << prec) - 1;
} else {
result = n;
}
return result;
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// TODO(ahentz): these two checks would make the new implementation
// incompatible with some existing models, where params is not specified. It
// is OK not to have them because toco would have set input and output types
// to match the parameters.
// auto* params = reinterpret_cast<TfLiteCastParams*>(node->builtin_data);
// TF_LITE_ENSURE_EQ(context, input->type, params->in_data_type);
// TF_LITE_ENSURE_EQ(context, output->type, params->out_data_type);
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void CLASS panasonic_load_raw()
{
int row, col, i, j, sh = 0, pred[2], nonz[2];
pana_bits(0);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
if ((i = col % 14) == 0)
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
if (i % 3 == 2)
sh = 4 >> (3 - pana_bits(2));
if (nonz[i & 1])
{
if ((j = pana_bits(8)))
{
if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
pred[i & 1] &= ~((~0u) << sh);
pred[i & 1] += j << sh;
}
}
else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height)
derror();
}
}
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
ZlibOutStream::ZlibOutStream(OutStream* os, int bufSize_, int compressLevel)
: underlying(os), compressionLevel(compressLevel), newLevel(compressLevel),
bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
{
zs = new z_stream;
zs->zalloc = Z_NULL;
zs->zfree = Z_NULL;
zs->opaque = Z_NULL;
zs->next_in = Z_NULL;
zs->avail_in = 0;
if (deflateInit(zs, compressLevel) != Z_OK) {
delete zs;
throw Exception("ZlibOutStream: deflateInit failed");
}
ptr = start = new U8[bufSize];
end = start + bufSize;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void InferenceContext::PreInputInit(
const OpDef& op_def, const std::vector<const Tensor*>& input_tensors,
const std::vector<ShapeHandle>& input_tensors_as_shapes) {
// TODO(mdan): This is also done at graph construction. Run only here instead?
const auto ret = full_type::SpecializeType(attrs_, op_def);
if (!ret.status().ok()) {
construction_status_ = ret.status();
return;
}
ret_types_ = ret.ValueOrDie();
input_tensors_ = input_tensors;
input_tensors_as_shapes_ = input_tensors_as_shapes;
construction_status_ =
NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_);
if (!construction_status_.ok()) return;
int num_outputs = 0;
for (const auto& e : output_name_map_) {
num_outputs = std::max(num_outputs, e.second.second);
}
outputs_.assign(num_outputs, nullptr);
output_handle_shapes_and_types_.resize(num_outputs);
} | 1 | C++ | CWE-754 | Improper Check for Unusual or Exceptional Conditions | The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software. | https://cwe.mitre.org/data/definitions/754.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 offset = 0;
if (buf_offset + 8 > sz) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.annotation_array.num_annotations; i++) {
if (offset >= sz) {
break;
}
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
}
attr->size = offset;
}
return attr;
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
void pcre_dump_cache(folly::File& file) {
s_pcreCache.dump(file);
} | 1 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
string PacketReader::getLabel(unsigned int recurs)
{
string ret;
size_t wirelength = 0;
ret.reserve(40);
getLabelFromContent(d_content, d_pos, ret, recurs++, wirelength);
return ret;
} | 1 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | safe |
TEST(ArrayOpsTest, QuantizeAndDequantizeV2_ShapeFn) {
ShapeInferenceTestOp op("QuantizeAndDequantizeV2");
op.input_tensors.resize(3);
TF_ASSERT_OK(NodeDefBuilder("test", "QuantizeAndDequantizeV2")
.Input("input", 0, DT_FLOAT)
.Input("input_min", 1, DT_FLOAT)
.Input("input_max", 2, DT_FLOAT)
.Attr("signed_input", true)
.Attr("num_bits", 8)
.Attr("range_given", false)
.Attr("narrow_range", false)
.Attr("axis", -1)
.Finalize(&op.node_def));
INFER_OK(op, "?;?;?", "in0");
INFER_OK(op, "[];?;?", "in0");
INFER_OK(op, "[1,2,?,4,5];?;?", "in0");
INFER_ERROR("Shape must be rank 0 but is rank 1", op, "[1,2,?,4,5];[1];[]");
INFER_ERROR("Shapes must be equal rank, but are 1 and 0", op,
"[1,2,?,4,5];[];[1]");
INFER_ERROR("Shape must be rank 0 but is rank 1", op, "[1,2,?,4,5];[1];[1]");
(*op.node_def.mutable_attr())["axis"].set_i(-2);
INFER_ERROR("axis should be at least -1, got -2", op, "?;?;?");
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
inline bool ShapeIsVector(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);
return (shape->dims->size == 1 && shape->type == kTfLiteInt32);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TEST(DepthToSpaceOpModel, NoBlockSize) {
EXPECT_DEATH(DepthToSpaceOpModel({TensorType_FLOAT32, {1, 1, 1, 4}}, 0),
"Cannot allocate tensors");
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
void ArrowHead()
/*
Jaxodraw style arrows
*/
{
int k;
double length;
SaveGraphicsState;
if ( flip ) length = -arrow.length;
else length = arrow.length;
SetDashSize(0,0);
if ( arrow.stroke ) {
SetLineWidth(arrow.stroke);
for (k = 1; k <= 2; k++ ) {
SaveGraphicsState;
MoveTo(length*0.5,0);
LineTo(-length*0.5,arrow.width);
LineTo(-length*0.5+length*arrow.inset,0);
LineTo(-length*0.5,-arrow.width);
if (k == 1) {
SetBackgroundColor(NONSTROKING);
outpos += sprintf(outpos," h f");
}
else {
outpos += sprintf(outpos," s");
}
RestoreGraphicsState;
}
}
else {
MoveTo(length*0.5,0);
LineTo(-length*0.5,arrow.width);
LineTo(-length*0.5+length*arrow.inset,0);
LineTo(-length*0.5,-arrow.width);
outpos += sprintf(outpos," h f");
}
RestoreGraphicsState;
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR;
if (offset + 4 < sz) {
attr->info.constant_value_attr.constantvalue_idx = R_BIN_JAVA_USHORT (buffer, offset);
}
offset += 2;
attr->size = offset;
}
// IFDBG r_bin_java_print_constant_value_attr_summary(attr);
return attr;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg)
{
u8 cpl = ctxt->ops->cpl(ctxt);
return __load_segment_descriptor(ctxt, selector, seg, cpl, false, NULL);
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, size)
{
// make a copy of our configuration bytes
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
m_ConfigurationVersion = payload[0];
m_Profile = payload[1];
m_ProfileCompatibility = payload[2];
m_Level = payload[3];
m_NaluLengthSize = 1+(payload[4]&3);
AP4_UI08 num_seq_params = payload[5]&31;
m_SequenceParameters.EnsureCapacity(num_seq_params);
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
m_SequenceParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
AP4_UI08 num_pic_params = payload[cursor++];
m_PictureParameters.EnsureCapacity(num_pic_params);
for (unsigned int i=0; i<num_pic_params; i++) {
m_PictureParameters.Append(AP4_DataBuffer());
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
m_PictureParameters[i].SetData(&payload[cursor]+2, param_length);
cursor += 2+param_length;
}
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
int64_t MemFile::readImpl(char *buffer, int64_t length) {
assertx(m_len != -1);
assertx(length > 0);
assertx(m_cursor >= 0);
int64_t remaining = m_len - m_cursor;
if (remaining < length) length = remaining;
if (length > 0) {
memcpy(buffer, (const void *)(m_data + m_cursor), length);
m_cursor += length;
return length;
}
return 0;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
int linenoiseHistorySave(const char* filename) {
FILE* fp = fopen(filename, "wt");
if (fp == NULL) {
return -1;
}
for (int j = 0; j < historyLen; ++j) {
if (history[j][0] != '\0') {
fprintf(fp, "%s\n", history[j]);
}
}
fclose(fp);
return 0;
} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
void create_test_key() {
int errStatus = 0;
vector<char> errMsg(1024, 0);
uint32_t enc_len;
SAFE_UINT8_BUF(encrypted_key, BUF_LEN);
string key = TEST_VALUE;
sgx_status_t status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_key, enc_len, hexEncrKey.data(), 2 * enc_len + 1);
LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data());
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
int64_t BZ2File::readImpl(char * buf, int64_t length) {
if (length == 0) {
return 0;
}
assertx(m_bzFile);
int len = BZ2_bzread(m_bzFile, buf, length);
/* Sometimes libbz2 will return fewer bytes than requested, and set bzerror
* to BZ_STREAM_END, but it's not actually EOF, and you can keep reading from
* the file - so, only set EOF after a failed read. This matches PHP5.
*/
if (len <= 0) {
setEof(true);
if (len < 0) {
return 0;
}
}
return len;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,
const String& key,
const String& iv) {
auto pm = get_valid_mcrypt_resource(td);
if (!pm) {
return false;
}
int max_key_size = mcrypt_enc_get_key_size(pm->m_td);
int iv_size = mcrypt_enc_get_iv_size(pm->m_td);
if (key.empty()) {
raise_warning("Key size is 0");
}
unsigned char *key_s = (unsigned char *)malloc(key.size());
memset(key_s, 0, key.size());
unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
int key_size;
if (key.size() > max_key_size) {
raise_warning("Key size too large; supplied length: %d, max: %d",
key.size(), max_key_size);
key_size = max_key_size;
} else {
key_size = key.size();
}
memcpy(key_s, key.data(), key.size());
if (iv.size() != iv_size) {
raise_warning("Iv size incorrect; supplied length: %d, needed: %d",
iv.size(), iv_size);
}
memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));
mcrypt_generic_deinit(pm->m_td);
int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
pm->close();
switch (result) {
case -3:
raise_warning("Key length incorrect");
break;
case -4:
raise_warning("Memory allocation error");
break;
case -1:
default:
raise_warning("Unknown error");
break;
}
} else {
pm->m_init = true;
}
free(iv_s);
free(key_s);
return result;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus GreaterEqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteFloat32:
Comparison<float, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
default:
context->ReportError(context,
"Does not support type %d, requires float|int|uint8",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, new_desc.l);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
TEST(DefaultCertValidatorTest, TestMultiLevelMatch) {
// san_multiple_dns_cert matches *.example.com
bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir "
"}}/test/extensions/transport_sockets/tls/test_data/san_multiple_dns_cert.pem"));
envoy::type::matcher::v3::StringMatcher matcher;
matcher.set_exact("foo.api.example.com");
std::vector<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>
subject_alt_name_matchers;
subject_alt_name_matchers.push_back(Matchers::StringMatcherImpl(matcher));
EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotTheRightCardinality) {
SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}},
{TensorType_INT32, {2}});
model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6});
model.PopulateTensor<int32_t>(model.segment_ids(), {0, 1});
ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void Compute(OpKernelContext* c) override {
PartialTensorShape element_shape;
OP_REQUIRES_OK(c, TensorShapeFromTensor(c->input(0), &element_shape));
int32 num_elements = c->input(1).scalar<int32>()();
OP_REQUIRES(c, num_elements >= 0,
errors::InvalidArgument("The num_elements to reserve must be a "
"non negative number, but got ",
num_elements));
TensorList output;
output.element_shape = element_shape;
output.element_dtype = element_dtype_;
output.tensors().resize(num_elements, Tensor(DT_INVALID));
Tensor* result;
AllocatorAttributes attr;
attr.set_on_host(true);
OP_REQUIRES_OK(c, c->allocate_output(0, TensorShape{}, &result, attr));
result->scalar<Variant>()() = std::move(output);
} | 1 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
void preprocessNodes(std::vector<Proxy> &nodes, extra_settings &ext)
{
std::for_each(nodes.begin(), nodes.end(), [&ext](Proxy &x)
{
if(ext.remove_emoji)
x.Remark = trim(removeEmoji(x.Remark));
nodeRename(x, ext.rename_array, ext);
if(ext.add_emoji)
x.Remark = addEmoji(x, ext.emoji_array, ext);
});
if(ext.sort_flag)
{
bool failed = true;
if(ext.sort_script.size())
{
std::string script = ext.sort_script;
if(startsWith(script, "path:"))
script = fileGet(script.substr(5), false);
script_safe_runner(ext.js_runtime, ext.js_context, [&](qjs::Context &ctx)
{
try
{
ctx.eval(script);
auto compare = (std::function<int(const Proxy&, const Proxy&)>) ctx.eval("compare");
auto comparer = [&](const Proxy &a, const Proxy &b)
{
if(a.Type == ProxyType::Unknow)
return 1;
if(b.Type == ProxyType::Unknow)
return 0;
return compare(a, b);
};
std::stable_sort(nodes.begin(), nodes.end(), comparer);
failed = false;
}
catch(qjs::exception)
{
script_print_stack(ctx);
}
}, global.scriptCleanContext);
}
if(failed) std::stable_sort(nodes.begin(), nodes.end(), [](const Proxy &a, const Proxy &b)
{
return a.Remark < b.Remark;
});
}
} | 0 | C++ | CWE-434 | Unrestricted Upload of File with Dangerous Type | The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
TfLiteStatus ComparisonPrepareCommon(TfLiteContext* context, TfLiteNode* node,
bool is_string_allowed) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
// Don't support string.
if (!is_string_allowed) {
TF_LITE_ENSURE(context, input1->type != kTfLiteString);
}
// Currently only support tensors have the same type.
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
output->type = kTfLiteBool;
bool requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* axis = GetInput(context, node, kAxis);
// Make sure the axis is only 1 dimension.
TF_LITE_ENSURE_EQ(context, NumElements(axis), 1);
// Make sure the axis is only either int32 or int64.
TF_LITE_ENSURE(context,
axis->type == kTfLiteInt32 || axis->type == kTfLiteInt64);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
auto* params = reinterpret_cast<TfLiteArgMaxParams*>(node->builtin_data);
switch (params->output_type) {
case kTfLiteInt32:
output->type = kTfLiteInt32;
break;
case kTfLiteInt64:
output->type = kTfLiteInt64;
break;
default:
context->ReportError(context, "Unknown index output data type: %d",
params->output_type);
return kTfLiteError;
}
// Check conditions for different types.
switch (input->type) {
case kTfLiteFloat32:
case kTfLiteUInt8:
case kTfLiteInt8:
case kTfLiteInt32:
break;
default:
context->ReportError(
context,
"Unknown input type: %d, only float32 and int types are supported",
input->type);
return kTfLiteError;
}
TF_LITE_ENSURE(context, NumDimensions(input) >= 1);
if (IsConstantTensor(axis)) {
TF_LITE_ENSURE_STATUS(ResizeOutput(context, input, axis, output));
} else {
SetTensorToDynamic(output);
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
static String HHVM_FUNCTION(bcsub, const String& left, const String& right,
int64_t scale /* = -1 */) {
scale = adjust_scale(scale);
bc_num first, second, result;
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
bc_sub(first, second, &result, scale);
if (result->n_scale > scale) {
result->n_scale = scale;
}
String ret(bc_num2str(result), AttachString);
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
return ret;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
Http::FilterDataStatus Context::onRequestBody(int body_buffer_length, bool end_of_stream) {
if (!wasm_->onRequestBody_) {
return Http::FilterDataStatus::Continue;
}
switch (wasm_
->onRequestBody_(this, id_, static_cast<uint32_t>(body_buffer_length),
static_cast<uint32_t>(end_of_stream))
.u64_) {
case 0:
return Http::FilterDataStatus::Continue;
case 1:
return Http::FilterDataStatus::StopIterationAndBuffer;
case 2:
return Http::FilterDataStatus::StopIterationAndWatermark;
default:
return Http::FilterDataStatus::StopIterationNoBuffer;
}
} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
static void php_array_merge_recursive(PointerSet &seen, bool check,
Array &arr1, const Array& arr2) {
if (check && !seen.insert((void*)arr1.get()).second) {
raise_warning("array_merge_recursive(): recursion detected");
return;
}
for (ArrayIter iter(arr2); iter; ++iter) {
Variant key(iter.first());
const Variant& value(iter.secondRef());
if (key.isNumeric()) {
arr1.appendWithRef(value);
} else if (arr1.exists(key, true)) {
// There is no need to do toKey() conversion, for a key that is already
// in the array.
Variant &v = arr1.lvalAt(key, AccessFlags::Key);
auto subarr1 = v.toArray().copy();
php_array_merge_recursive(seen,
couldRecur(v, subarr1.get()),
subarr1,
value.toArray());
v.unset(); // avoid contamination of the value that was strongly bound
v = subarr1;
} else {
arr1.setWithRef(key, value, true);
}
}
if (check) {
seen.erase((void*)arr1.get());
}
} | 1 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
bool isCPUDevice() {
return false;
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
bool Messageheader::Parser::state_fieldbody_crlf(char ch)
{
if (ch == '\r')
SET_STATE(state_end_cr);
else if (ch == '\n')
{
log_debug("header " << fieldnamePtr << ": " << fieldbodyPtr);
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK:
case END: return true;
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
}
*headerdataPtr = '\0';
return true;
}
else if (std::isspace(ch))
{
// continuation line
checkHeaderspace(1);
*(headerdataPtr - 1) = '\n';
*headerdataPtr++ = ch;
SET_STATE(state_fieldbody);
}
else if (ch >= 33 && ch <= 126)
{
switch (header.onField(fieldnamePtr, fieldbodyPtr))
{
case OK: SET_STATE(state_fieldname);
break;
case FAIL: failedFlag = true;
log_warn("invalid character " << chartoprint(ch) << " in fieldbody");
break;
case END: return true;
break;
}
fieldnamePtr = headerdataPtr;
checkHeaderspace(1);
*headerdataPtr++ = ch;
}
return false;
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
static Status ValidateNode(const NodeDef& node) {
const auto node_iterator = node.attr().find("value");
if (node_iterator != node.attr().end()) {
AttrValue node_value = node_iterator->second;
if (node_value.has_tensor()) {
const PartialTensorShape node_shape(node_value.tensor().tensor_shape());
if (node_shape.num_elements() < 0) {
return errors::FailedPrecondition(
"Saved model contains node \"", node.name(), "\" (op \"", node.op(),
"\") which initializes from a tensor with ",
node_shape.num_elements(), " elements");
}
}
} else if (node.op() == "Const") {
return errors::FailedPrecondition(
"Saved model contains node \"", node.name(),
"\" which is a constant tensor but no value has been provided");
}
return Status::OK();
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
String HHVM_FUNCTION(ldap_escape,
const String& value,
const String& ignores /* = "" */,
int flags /* = 0 */) {
char esc[256] = {};
if (flags & k_LDAP_ESCAPE_FILTER) { // llvm.org/bugs/show_bug.cgi?id=18389
esc['*'*1u] = esc['('*1u] = esc[')'*1u] = esc['\0'*1u] = esc['\\'*1u] = 1;
}
if (flags & k_LDAP_ESCAPE_DN) {
esc[','*1u] = esc['='*1u] = esc['+'*1u] = esc['<'*1u] = esc['\\'*1u] = 1;
esc['>'*1u] = esc[';'*1u] = esc['"'*1u] = esc['#'*1u] = 1;
}
if (!flags) {
memset(esc, 1, sizeof(esc));
}
for (int i = 0; i < ignores.size(); i++) {
esc[(unsigned char)ignores[i]] = 0;
}
char hex[] = "0123456789abcdef";
String result(3UL * value.size(), ReserveString);
char *rdata = result.get()->mutableData(), *r = rdata;
for (int i = 0; i < value.size(); i++) {
auto c = (unsigned char)value[i];
if (esc[c]) {
*r++ = '\\';
*r++ = hex[c >> 4];
*r++ = hex[c & 0xf];
} else {
*r++ = c;
}
}
result.setSize(r - rdata);
return result;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void DefaultEnv::Initialize()
{
sLog = new Log();
SetUpLog();
sEnv = new DefaultEnv();
sForkHandler = new ForkHandler();
sFileTimer = new FileTimer();
sPlugInManager = new PlugInManager();
sPlugInManager->ProcessEnvironmentSettings();
sForkHandler->RegisterFileTimer( sFileTimer );
//--------------------------------------------------------------------------
// MacOSX library loading is completely moronic. We cannot dlopen a library
// from a thread other than a main thread, so we-pre dlopen all the
// libraries that we may potentially want.
//--------------------------------------------------------------------------
#ifdef __APPLE__
char *errBuff = new char[1024];
const char *libs[] =
{
"libXrdSeckrb5.so",
"libXrdSecgsi.so",
"libXrdSecgsiAuthzVO.so",
"libXrdSecgsiGMAPDN.so",
"libXrdSecgsiGMAPLDAP.so",
"libXrdSecpwd.so",
"libXrdSecsss.so",
"libXrdSecunix.so",
0
};
for( int i = 0; libs[i]; ++i )
{
sLog->Debug( UtilityMsg, "Attempting to pre-load: %s", libs[i] );
bool ok = XrdOucPreload( libs[i], errBuff, 1024 );
if( !ok )
sLog->Error( UtilityMsg, "Unable to pre-load %s: %s", libs[i], errBuff );
}
delete [] errBuff;
#endif
} | 0 | C++ | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
CString CWebSock::GetSkinPath(const CString& sSkinName) {
const CString sSkin = sSkinName.Replace_n("/", "_").Replace_n(".", "_");
CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkin;
if (!CFile::IsDir(sRet)) {
sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkin;
if (!CFile::IsDir(sRet)) {
sRet = CString(_SKINDIR_) + "/" + sSkin;
}
}
return sRet + "/";
} | 1 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle))
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
void readErr(const AsyncSocketException& ex) noexcept override {
LOG(ERROR) << ex.what();
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
IniSection (const IniParser *p)
: IniBase (-1),
ip (p),
end_comment (), rewrite_by(-1),
container (), ivalues (), isections ()
{} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct new_desc;
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_RET,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, &new_desc);
/* Error handling is not implemented. */
if (rc != X86EMUL_CONTINUE)
return X86EMUL_UNHANDLEABLE;
return rc;
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
QInt32() {} | 0 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | vulnerable |
TEST_F(HeaderTableTests, set_capacity) {
HPACKHeader accept("accept-encoding", "gzip");
uint32_t max = 10;
uint32_t capacity = accept.bytes() * max;
HeaderTable table(capacity);
// fill the table
for (size_t i = 0; i < max; i++) {
EXPECT_EQ(table.add(accept), true);
}
// change capacity
table.setCapacity(capacity / 2);
EXPECT_EQ(table.size(), max / 2);
EXPECT_EQ(table.bytes(), capacity / 2);
} | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
ruy::profiler::ScopeLabel label("SquaredDifference");
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (output->type == kTfLiteFloat32) {
EvalSquaredDifference<float>(context, node, data, input1, input2, output);
} else if (output->type == kTfLiteInt32) {
EvalSquaredDifference<int32_t>(context, node, data, input1, input2, output);
} else {
context->ReportError(
context,
"SquaredDifference only supports FLOAT32 and INT32 now, got %d.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
bool FontData::Bound(int32_t offset, int32_t length) {
if (offset + length > Size() || offset < 0 || length < 0)
return false;
bound_offset_ += offset;
bound_length_ = length;
return true;
} | 0 | C++ | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | https://cwe.mitre.org/data/definitions/189.html | vulnerable |
void RemoteFsDevice::load()
{
if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {
// Start Avahi listener...
Avahi::self();
QUrlQuery q(details.url);
if (q.hasQueryItem(constServiceNameQuery)) {
details.serviceName=q.queryItemValue(constServiceNameQuery);
}
if (!details.serviceName.isEmpty()) {
AvahiService *srv=Avahi::self()->getService(details.serviceName);
if (!srv || srv->getHost().isEmpty()) {
sub=tr("Not Available");
} else {
sub=tr("Available");
}
}
connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));
connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));
}
if (isConnected()) {
setAudioFolder();
readOpts(settingsFileName(), opts, true);
rescan(false); // Read from cache if we have it!
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static inline bool isValid(const RemoteFsDevice::Details &d)
{
return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||
RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
int HexInStream::overrun(int itemSize, int nItems, bool wait) {
if (itemSize > bufSize)
throw Exception("HexInStream overrun: max itemSize exceeded");
if (end - ptr != 0)
memmove(start, ptr, end - ptr);
end -= ptr - start;
offset += ptr - start;
ptr = start;
while (end < ptr + itemSize) {
int n = in_stream.check(2, 1, wait);
if (n == 0) return 0;
const U8* iptr = in_stream.getptr();
const U8* eptr = in_stream.getend();
int length = min((eptr - iptr)/2, start + bufSize - end);
U8* optr = (U8*) end;
for (int i=0; i<length; i++) {
int v = 0;
readHexAndShift(iptr[i*2], &v);
readHexAndShift(iptr[i*2+1], &v);
optr[i] = v;
}
in_stream.setptr(iptr + length*2);
end += length;
}
if (itemSize * nItems > end - ptr)
nItems = (end - ptr) / itemSize;
return nItems;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
tTcpIpPacketParsingResult ParaNdis_CheckSumVerifyFlat(
PVOID pBuffer,
ULONG ulDataLength,
ULONG flags,
LPCSTR caller)
{
tCompletePhysicalAddress SGBuffer;
SGBuffer.Virtual = pBuffer;
SGBuffer.size = ulDataLength;
return ParaNdis_CheckSumVerify(&SGBuffer, ulDataLength, 0, flags, caller);
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TIFFWriteDirectoryTagTransferfunction(TIFF* tif, uint32* ndir, TIFFDirEntry* dir)
{
static const char module[] = "TIFFWriteDirectoryTagTransferfunction";
uint32 m;
uint16 n;
uint16* o;
int p;
if (dir==NULL)
{
(*ndir)++;
return(1);
}
m=(1<<tif->tif_dir.td_bitspersample);
n=tif->tif_dir.td_samplesperpixel-tif->tif_dir.td_extrasamples;
/*
* Check if the table can be written as a single column,
* or if it must be written as 3 columns. Note that we
* write a 3-column tag if there are 2 samples/pixel and
* a single column of data won't suffice--hmm.
*/
if (n>3)
n=3;
if (n==3)
{
if (tif->tif_dir.td_transferfunction[2] == NULL ||
!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16)))
n=2;
}
if (n==2)
{
if (tif->tif_dir.td_transferfunction[1] == NULL ||
!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16)))
n=1;
}
if (n==0)
n=1;
o=_TIFFmalloc(n*m*sizeof(uint16));
if (o==NULL)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
_TIFFmemcpy(&o[0],tif->tif_dir.td_transferfunction[0],m*sizeof(uint16));
if (n>1)
_TIFFmemcpy(&o[m],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16));
if (n>2)
_TIFFmemcpy(&o[2*m],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16));
p=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,TIFFTAG_TRANSFERFUNCTION,n*m,o);
_TIFFfree(o);
return(p);
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
assert(n >= 0);
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
//*data >>= n;
*data = jas_seqent_asr(*data, n);
}
}
}
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
CallOpDimensionsFromInputs(const int n, const int h, const int w, const int c,
const int kx, const int ky, const int sx,
const int sy, const string& data_format,
const string& padding) {
OpContext op_context;
const std::vector<int> x = {n, h, w, c};
const std::vector<int> ksize = {1, kx, ky, 1};
std::vector<int> strides;
if (data_format == "NHWC") {
strides = {1, sy, sx, 1};
} else {
strides = {1, 1, sy, sx};
}
auto& op_info = op_context.op_info;
SetCpuDevice(&op_info);
op_info.set_op("MaxPool");
DescribeTensor4D(x[0], x[1], x[2], x[3], op_info.add_inputs());
auto* attr = op_info.mutable_attr();
SetAttrValue(data_format, &(*attr)["data_format"]);
SetAttrValue(padding, &(*attr)["padding"]);
SetAttrValue(strides, &(*attr)["strides"]);
SetAttrValue(ksize, &(*attr)["ksize"]);
bool found_unknown_shapes;
return OpLevelCostEstimator::OpDimensionsFromInputs(
op_context.op_info.inputs(0).shape(), op_context.op_info,
&found_unknown_shapes);
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
TfLiteTensor* GetVariableInput(TfLiteContext* context, const TfLiteNode* node,
int index) {
TfLiteTensor* tensor = GetMutableInput(context, node, index);
if (tensor == nullptr) return nullptr;
return tensor->is_variable ? tensor : nullptr;
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
inline int ValidateTensorIndexing(const TfLiteContext* context, int index,
int max_size, const int* tensor_indices) {
if (index >= 0 && index < max_size) {
const int tensor_index = tensor_indices[index];
if (tensor_index != kTfLiteOptionalTensor) {
return tensor_index;
}
}
return -1;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,
const uint8_t sig[], size_t sig_len)
{
if(sig_len != m_group.get_order_bytes() * 2)
return false;
const BigInt e(msg, msg_len, m_group.get_order_bits());
const BigInt r(sig, sig_len / 2);
const BigInt s(sig + sig_len / 2, sig_len / 2);
if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())
return false;
const BigInt w = m_group.inverse_mod_order(s);
const BigInt u1 = m_group.multiply_mod_order(m_group.mod_order(e), w);
const BigInt u2 = m_group.multiply_mod_order(r, w);
const PointGFp R = m_gy_mul.multi_exp(u1, u2);
if(R.is_zero())
return false;
const BigInt v = m_group.mod_order(R.get_affine_x());
return (v == r);
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
int pkt_len;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header */
pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data */
return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,
wth->frame_buffer, err, err_info);
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
void ValidateOpDimensionsFromInputs(const int n, const int h, const int w,
const int c, const int kx, const int ky,
const int sx, const int sy,
const string& data_format,
const string& padding) {
OpContext op_context;
int ho;
int wo;
if (data_format == "NHWC") {
op_context = DescribePoolingOp("MaxPool", {n, h, w, c}, {1, kx, ky, 1},
{1, sx, sy, 1}, "NHWC", padding);
ho = op_context.op_info.outputs(0).shape().dim(1).size();
wo = op_context.op_info.outputs(0).shape().dim(2).size();
} else {
op_context = DescribePoolingOp("MaxPool", {n, c, h, w}, {1, 1, kx, ky},
{1, 1, sx, sy}, "NCHW", padding);
ho = op_context.op_info.outputs(0).shape().dim(2).size();
wo = op_context.op_info.outputs(0).shape().dim(3).size();
}
bool found_unknown_shapes;
TF_ASSERT_OK_AND_ASSIGN(
auto dims, OpLevelCostEstimator::OpDimensionsFromInputs(
op_context.op_info.inputs(0).shape(), op_context.op_info,
&found_unknown_shapes));
Padding padding_enum;
if (padding == "VALID") {
padding_enum = Padding::VALID;
} else {
padding_enum = Padding::SAME;
}
EXPECT_EQ(n, dims.batch);
EXPECT_EQ(h, dims.ix);
EXPECT_EQ(w, dims.iy);
EXPECT_EQ(c, dims.iz);
EXPECT_EQ(kx, dims.kx);
EXPECT_EQ(ky, dims.ky);
EXPECT_EQ(sx, dims.sx);
EXPECT_EQ(sy, dims.sy);
EXPECT_EQ(ho, dims.ox);
EXPECT_EQ(wo, dims.oy);
EXPECT_EQ(c, dims.oz);
EXPECT_EQ(padding_enum, dims.padding);
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const DeviceOptions &options, const Details &d)
: FsDevice(m, d.name, createUdi(d.name))
, mountToken(0)
, currentMountStatus(false)
, details(d)
, proc(0)
, mounterIface(0)
, messageSent(false)
{
opts=options;
// details.path=Utils::fixPath(details.path);
load();
mount();
icn=MonoIcon::icon(details.isLocalFile()
? FontAwesome::foldero
: constSshfsProtocol==details.url.scheme()
? FontAwesome::linux_os
: FontAwesome::windows, Utils::monoIconColor());
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);
TF_LITE_ENSURE_EQ(context, output->bytes, input->bytes);
TF_LITE_ENSURE_EQ(context, output->dims->size, input->dims->size);
for (int i = 0; i < output->dims->size; ++i) {
TF_LITE_ENSURE_EQ(context, output->dims->data[i], input->dims->data[i]);
}
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
const String& setSize(int len) {
assertx(m_str);
m_str->setSize(len);
return *this;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts)
{
int rowsize;
int pad;
unsigned int z;
int nz;
int c;
int x;
int y;
int v;
jas_matrix_t *data[3];
int i;
for (i = 0; i < numcmpts; ++i) {
data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image));
assert(data[i]);
}
rowsize = RAS_ROWSIZE(hdr);
pad = rowsize - (hdr->width * hdr->depth + 7) / 8;
hdr->length = hdr->height * rowsize;
for (y = 0; y < hdr->height; y++) {
for (i = 0; i < numcmpts; ++i) {
if (jas_image_readcmpt(image, cmpts[i], 0, y,
jas_image_width(image), 1, data[i])) {
return -1;
}
}
z = 0;
nz = 0;
for (x = 0; x < hdr->width; x++) {
z <<= hdr->depth;
if (RAS_ISRGB(hdr)) {
v = RAS_RED((jas_matrix_getv(data[0], x))) |
RAS_GREEN((jas_matrix_getv(data[1], x))) |
RAS_BLUE((jas_matrix_getv(data[2], x)));
} else {
v = (jas_matrix_getv(data[0], x));
}
z |= v & RAS_ONES(hdr->depth);
nz += hdr->depth;
while (nz >= 8) {
c = (z >> (nz - 8)) & 0xff;
if (jas_stream_putc(out, c) == EOF) {
return -1;
}
nz -= 8;
z &= RAS_ONES(nz);
}
}
if (nz > 0) {
c = (z >> (8 - nz)) & RAS_ONES(nz);
if (jas_stream_putc(out, c) == EOF) {
return -1;
}
}
if (pad % 2) {
if (jas_stream_putc(out, 0) == EOF) {
return -1;
}
}
}
for (i = 0; i < numcmpts; ++i) {
jas_matrix_destroy(data[i]);
}
return 0;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
TfLiteStatus EvalHashtableFind(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputResourceIdTensor,
&input_resource_id_tensor));
int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kKeyTensor, &key_tensor));
const TfLiteTensor* default_value_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDefaultValueTensor,
&default_value_tensor));
TfLiteTensor* output_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output_tensor));
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
TF_LITE_ENSURE_STATUS(
lookup->CheckKeyAndValueTypes(context, key_tensor, output_tensor));
auto result =
lookup->Lookup(context, key_tensor, output_tensor, default_value_tensor);
return result;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
if (type != kTfLiteInt32 && type != kTfLiteFloat32) {
TF_LITE_KERNEL_LOG(context, "Unsupported data type %s.",
TfLiteTypeGetName(type));
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.