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
void jspReplaceWithOrAddToRoot(JsVar *dst, JsVar *src) { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(dst) && jsvIsName(dst)) { if (!jsvIsArrayBufferName(dst) && !jsvIsNewChild(dst)) jsvAddName(execInfo.root, dst); } jspReplaceWith(dst, src); }
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 PreluPrepare(TfLiteContext* context, TfLiteNode* node) { TFLITE_DCHECK(node->user_data != nullptr); PreluParams* params = static_cast<PreluParams*>(node->user_data); const TfLiteTensor* input = GetInput(context, node, 0); TF_LITE_ENSURE(context, input != nullptr); const TfLiteTensor* alpha = GetInput(context, node, 1); TF_LITE_ENSURE(context, alpha != nullptr); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE(context, output != nullptr); return CalculatePreluParams(input, alpha, output, params); }
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* seq_lengths = GetInput(context, node, kSeqLengthsTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(seq_lengths), 1); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64) { context->ReportError(context, "Type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (seq_lengths->type != kTfLiteInt32 && seq_lengths->type != kTfLiteInt64) { context->ReportError( context, "Seq_lengths type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(seq_lengths->type)); return kTfLiteError; } TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type); return context->ResizeTensor(context, output, output_shape); }
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 ocall_malloc(size_t size, uint8_t **ret) { unsafe_ocall_malloc(size, ret); // Guard against overwriting enclave memory assert(sgx_is_outside_enclave(*ret, size) == 1); sgx_lfence(); }
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
unsigned int GetU32BE (int nPos, bool *pbSuccess) { //*pbSuccess = true; if ( nPos < 0 || nPos + 3 >= m_nLen ) { *pbSuccess = false; return 0; } unsigned int nRes = m_sFile[nPos]; nRes = (nRes << 8) + m_sFile[nPos + 1]; nRes = (nRes << 8) + m_sFile[nPos + 2]; nRes = (nRes << 8) + m_sFile[nPos + 3]; return nRes; }
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 skip(Protocol_& prot, TType arg_type) { switch (arg_type) { case TType::T_BOOL: { bool boolv; prot.readBool(boolv); return; } case TType::T_BYTE: { int8_t bytev; prot.readByte(bytev); return; } case TType::T_I16: { int16_t i16; prot.readI16(i16); return; } case TType::T_I32: { int32_t i32; prot.readI32(i32); return; } case TType::T_I64: { int64_t i64; prot.readI64(i64); return; } case TType::T_DOUBLE: { double dub; prot.readDouble(dub); return; } case TType::T_FLOAT: { float flt; prot.readFloat(flt); return; } case TType::T_STRING: { std::string str; prot.readBinary(str); return; } case TType::T_STRUCT: { std::string name; int16_t fid; TType ftype; prot.readStructBegin(name); while (true) { prot.readFieldBegin(name, ftype, fid); if (ftype == TType::T_STOP) { break; } apache::thrift::skip(prot, ftype); prot.readFieldEnd(); } prot.readStructEnd(); return; } case TType::T_MAP: { TType keyType; TType valType; uint32_t i, size; prot.readMapBegin(keyType, valType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, keyType); apache::thrift::skip(prot, valType); } prot.readMapEnd(); return; } case TType::T_SET: { TType elemType; uint32_t i, size; prot.readSetBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readSetEnd(); return; } case TType::T_LIST: { TType elemType; uint32_t i, size; prot.readListBegin(elemType, size); for (i = 0; i < size; i++) { apache::thrift::skip(prot, elemType); } prot.readListEnd(); return; } default: return; } }
0
C++
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
vulnerable
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; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* axis; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis)); TF_LITE_ENSURE_EQ(context, NumDimensions(axis), 1); TF_LITE_ENSURE(context, NumDimensions(input) >= NumElements(axis)); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64 && input->type != kTfLiteBool) { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (axis->type != kTfLiteInt32) { context->ReportError(context, "Axis Type '%s' is not supported by reverse.", TfLiteTypeGetName(axis->type)); return kTfLiteError; } // TODO(renjieliu): support multi-axis case. if (NumElements(axis) > 1) { context->ReportError(context, "Current does not support more than 1 axis."); } TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims); TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type); return context->ResizeTensor(context, output, output_shape); }
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
TEST_P(SslSocketTest, Ipv4San) { const std::string client_ctx_yaml = R"EOF( common_tls_context: validation_context: trusted_ca: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamcacert.pem" match_subject_alt_names: exact: "127.0.0.1" )EOF"; const std::string server_ctx_yaml = R"EOF( common_tls_context: tls_certificates: certificate_chain: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamlocalhostcert.pem" private_key: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamlocalhostkey.pem" )EOF"; TestUtilOptions test_options(client_ctx_yaml, server_ctx_yaml, true, GetParam()); testUtil(test_options); }
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
void Triangle(double x1,double y1,double x2,double y2,double x3,double y3) { sprintf(outputbuffer,"\n %12.3f %12.3f m %12.3f %12.3f l %12.3f %12.3f l h",x1,y1,x2,y2,x3,y3); sendClean(outputbuffer); }
1
C++
NVD-CWE-noinfo
null
null
null
safe
void PCRECache::dump(const std::string& filename) { std::ofstream out(filename.c_str()); switch (m_kind) { case CacheKind::Static: for (auto& it : *m_staticCache) { out << it.first->data() << "\n"; } break; case CacheKind::Lru: case CacheKind::Scalable: { std::vector<LRUCacheKey> keys; if (m_kind == CacheKind::Lru) { m_lruCache->snapshotKeys(keys); } else { m_scalableCache->snapshotKeys(keys); } for (auto& key: keys) { out << key.c_str() << "\n"; } } break; } out.close(); }
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
MONGO_EXPORT int bson_buffer_size( const bson *b ) { return (b->cur - b->data + 1); }
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 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 if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; }
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
CharString *Formattable::internalGetCharString(UErrorCode &status) { if(fDecimalStr == NULL) { if (fDecimalQuantity == NULL) { // No decimal number for the formattable yet. Which means the value was // set directly by the user as an int, int64 or double. If the value came // from parsing, or from the user setting a decimal number, fDecimalNum // would already be set. // LocalPointer<DecimalQuantity> dq(new DecimalQuantity(), status); if (U_FAILURE(status)) { return nullptr; } populateDecimalQuantity(*dq, status); if (U_FAILURE(status)) { return nullptr; } fDecimalQuantity = dq.orphan(); } fDecimalStr = new CharString(); if (fDecimalStr == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } // Older ICUs called uprv_decNumberToString here, which is not exactly the same as // DecimalQuantity::toScientificString(). The biggest difference is that uprv_decNumberToString does // not print scientific notation for magnitudes greater than -5 and smaller than some amount (+5?). if (fDecimalQuantity->isZero()) { fDecimalStr->append("0", -1, status); } else if (fDecimalQuantity->getMagnitude() != INT32_MIN && std::abs(fDecimalQuantity->getMagnitude()) < 5) { fDecimalStr->appendInvariantChars(fDecimalQuantity->toPlainString(), status); } else { fDecimalStr->appendInvariantChars(fDecimalQuantity->toScientificString(), status); } } return fDecimalStr; }
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
void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval, jas_seqent_t maxval) { jas_matind_t i; jas_matind_t j; jas_seqent_t v; jas_seqent_t *rowstart; jas_seqent_t *data; jas_matind_t rowstep; 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) { data = rowstart; for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { v = *data; if (v < minval) { *data = minval; } else if (v > maxval) { *data = maxval; } } } } }
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
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: %ld, 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: %ld, needed: %d", iv.size(), iv_size); } memcpy(iv_s, iv.data(), std::min<int64_t>(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; }
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 IsSupported(const NodeDef* node) const override { if (!node || node->input_size() < 2) { // Invalid node return false; } return IsAnyMul(*node) && node->input(0) == node->input(1); }
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
Node* Graph::AddNode(NodeDef node_def, Status* status) { const OpRegistrationData* op_reg_data; status->Update(ops_.LookUp(node_def.op(), &op_reg_data)); if (!status->ok()) return nullptr; DataTypeVector inputs; DataTypeVector outputs; status->Update( InOutTypesForNode(node_def, op_reg_data->op_def, &inputs, &outputs)); if (!status->ok()) { *status = AttachDef(*status, node_def); return nullptr; } Node::NodeClass node_class = op_reg_data->is_function_op ? Node::NC_FUNCTION_OP : Node::GetNodeClassForOp(node_def.op()); if (op_reg_data->type_ctor != nullptr) { VLOG(3) << "AddNode: found type constructor for " << node_def.name(); const auto ctor_type = full_type::SpecializeType(AttrSlice(node_def), op_reg_data->op_def); if (!ctor_type.ok()) { *status = errors::InvalidArgument("type error: ", ctor_type.status().ToString()); return nullptr; } const FullTypeDef ctor_typedef = ctor_type.ValueOrDie(); if (ctor_typedef.type_id() != TFT_UNSET) { *(node_def.mutable_experimental_type()) = ctor_typedef; } } else { VLOG(3) << "AddNode: no type constructor for " << node_def.name(); } Node* node = AllocateNode(std::make_shared<NodeProperties>( &op_reg_data->op_def, std::move(node_def), inputs, outputs, op_reg_data->fwd_type_fn), nullptr, node_class); return node; }
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
CAMLprim value caml_bitvect_test(value bv, value n) { intnat pos = Long_val(n); return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7))); }
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 int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; ctxt->_eip = ctxt->src.val; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ ctxt->_eip = ctxt->src.val; break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; }
0
C++
NVD-CWE-noinfo
null
null
null
vulnerable
static int em_fxsave(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; size_t size; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ctxt->ops->get_fpu(ctxt); rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state)); ctxt->ops->put_fpu(ctxt); if (rc != X86EMUL_CONTINUE) return rc; if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR) size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]); else size = offsetof(struct fxregs_state, xmm_space[0]); return segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size); }
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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* dims = GetInput(context, node, kDimsTensor); const TfLiteTensor* value = GetInput(context, node, kValueTensor); // Make sure the 1st input tensor is 1-D. TF_LITE_ENSURE_EQ(context, NumDimensions(dims), 1); // Make sure the 1st input tensor is int32 or int64. const auto dtype = dims->type; TF_LITE_ENSURE(context, dtype == kTfLiteInt32 || dtype == kTfLiteInt64); // Make sure the 2nd input tensor is a scalar. TF_LITE_ENSURE_EQ(context, NumDimensions(value), 0); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = value->type; if (IsConstantTensor(dims)) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, dims, output)); } else { SetTensorToDynamic(output); } 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
void Logger::addPeer(const QString &ip, bool blocked, const QString &reason) { QWriteLocker locker(&lock); Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason }; m_peers.push_back(temp); if (m_peers.size() >= MAX_LOG_MESSAGES) m_peers.pop_front(); emit newLogPeer(temp); }
0
C++
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
TfLiteStatus Relu6Prepare(TfLiteContext* context, TfLiteNode* node) { TFLITE_DCHECK(node->user_data != nullptr); Relu6OpData* data = static_cast<Relu6OpData*>(node->user_data); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TF_LITE_ENSURE(context, input != nullptr); if (input->type == kTfLiteInt8) { data->six_int8 = FloatToAsymmetricQuantizedInt8(6.0f, input->params.scale, input->params.zero_point); data->zero_int8 = input->params.zero_point; } else if (input->type == kTfLiteUInt8) { data->six_uint8 = FloatToAsymmetricQuantizedUInt8(6.0f, input->params.scale, input->params.zero_point); data->zero_uint8 = input->params.zero_point; } 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
void Compute(OpKernelContext* context) override { // Get the stamp token. const Tensor* stamp_token_t; OP_REQUIRES_OK(context, context->input("stamp_token", &stamp_token_t)); int64_t stamp_token = stamp_token_t->scalar<int64>()(); // Get the tree ensemble proto. const Tensor* tree_ensemble_serialized_t; OP_REQUIRES_OK(context, context->input("tree_ensemble_serialized", &tree_ensemble_serialized_t)); std::unique_ptr<BoostedTreesEnsembleResource> result( new BoostedTreesEnsembleResource()); if (!result->InitFromSerialized( tree_ensemble_serialized_t->scalar<tstring>()(), stamp_token)) { result->Unref(); result.release(); // Needed due to the `->Unref` above, to prevent UAF OP_REQUIRES( context, false, errors::InvalidArgument("Unable to parse tree ensemble proto.")); } // Only create one, if one does not exist already. Report status for all // other exceptions. auto status = CreateResource(context, HandleFromInput(context, 0), result.release()); if (status.code() != tensorflow::error::ALREADY_EXISTS) { OP_REQUIRES_OK(context, status); } }
1
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
safe
BGD_DECLARE(void) gdImageWBMPCtx(gdImagePtr image, int fg, gdIOCtx *out) { _gdImageWBMPCtx(image, fg, out); }
1
C++
CWE-415
Double Free
The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.
https://cwe.mitre.org/data/definitions/415.html
safe
int64_t OpLevelCostEstimator::CalculateOutputSize(const OpInfo& op_info, bool* found_unknown_shapes) { int64_t total_output_size = 0; // Use float as default for calculations. for (const auto& output : op_info.outputs()) { DataType dt = output.dtype(); const auto& original_output_shape = output.shape(); int64_t output_size = DataTypeSize(BaseType(dt)); int num_dims = std::max(1, original_output_shape.dim_size()); auto output_shape = MaybeGetMinimumShape(original_output_shape, num_dims, found_unknown_shapes); for (const auto& dim : output_shape.dim()) { output_size *= dim.size(); } total_output_size += output_size; VLOG(1) << "Output Size: " << output_size << " Total Output Size:" << total_output_size; } return total_output_size; }
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
void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int kwidth, int kheight, float* output_data, const Dims<4>& output_dims) { float output_activation_min, output_activation_max; GetActivationMinMax(Ac, &output_activation_min, &output_activation_max); AveragePool(input_data, input_dims, stride_width, stride_height, pad_width, pad_height, kwidth, kheight, output_activation_min, output_activation_max, output_data, output_dims); }
0
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
Status FillCollectiveParams(CollectiveParams* col_params, CollectiveType collective_type, const Tensor& group_size, const Tensor& group_key, const Tensor& instance_key) { if (group_size.dims() > 0) { return errors::Internal("Unexpected dimensions on input group_size, got ", group_size.shape().DebugString()); } if (group_key.dims() > 0) { return errors::Internal("Unexpected dimensions on input group_key, got ", group_key.shape().DebugString()); } if (instance_key.dims() > 0) { return errors::Internal( "Unexpected dimensions on input instance_key, got ", instance_key.shape().DebugString()); } col_params->name = name_; col_params->group.device_type = device_type_; col_params->group.group_size = group_size.unaligned_flat<int32>()(0); if (col_params->group.group_size <= 0) { return errors::InvalidArgument( "group_size must be positive integer but got ", col_params->group.group_size); } col_params->group.group_key = group_key.unaligned_flat<int32>()(0); col_params->instance.type = collective_type; col_params->instance.instance_key = instance_key.unaligned_flat<int32>()(0); col_params->instance.data_type = data_type_; col_params->instance.impl_details.communication_hint = communication_hint_; col_params->instance.impl_details.timeout_seconds = timeout_seconds_; return Status::OK(); }
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
bool AES_GCM_EncryptContext::Encrypt( const void *pPlaintextData, size_t cbPlaintextData, const void *pIV, void *pEncryptedDataAndTag, uint32 *pcbEncryptedDataAndTag, const void *pAdditionalAuthenticationData, size_t cbAuthenticationData ) { unsigned long long pcbEncryptedDataAndTag_longlong = *pcbEncryptedDataAndTag; crypto_aead_aes256gcm_encrypt_afternm( static_cast<unsigned char*>( pEncryptedDataAndTag ), &pcbEncryptedDataAndTag_longlong, static_cast<const unsigned char*>( pPlaintextData ), cbPlaintextData, static_cast<const unsigned char*>(pAdditionalAuthenticationData), cbAuthenticationData, nullptr, static_cast<const unsigned char*>( pIV ), static_cast<const crypto_aead_aes256gcm_state*>( m_ctx ) ); *pcbEncryptedDataAndTag = pcbEncryptedDataAndTag_longlong; 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
size_t CxMemFile::Read(void *buffer, size_t size, size_t count) { if (buffer==NULL) return 0; if (m_pBuffer==NULL) return 0; if (m_Position >= (int32_t)m_Size){ m_bEOF = true; return 0; } int32_t nCount = (int32_t)(count*size); if (nCount == 0) return 0; int32_t nRead; if (m_Position + nCount > (int32_t)m_Size){ m_bEOF = true; nRead = (m_Size - m_Position); } else nRead = nCount; memcpy(buffer, m_pBuffer + m_Position, nRead); m_Position += nRead; return (size_t)(nRead/size); }
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
inline TfLiteStatus ValidateTensorIndexingSafe(const TfLiteContext* context, int index, int max_size, const int* tensor_indices, int* tensor_index) { if (index < 0 || index >= max_size) { TF_LITE_KERNEL_LOG(const_cast<TfLiteContext*>(context), "Invalid tensor index %d (not in [0, %d))\n", index, max_size); return kTfLiteError; } if (tensor_indices[index] == kTfLiteOptionalTensor) { TF_LITE_KERNEL_LOG(const_cast<TfLiteContext*>(context), "Tensor at index %d was optional but was expected\n", index); return kTfLiteError; } *tensor_index = tensor_indices[index]; 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
TfLiteStatus ReshapeOutput(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); // Tensorflow's Reshape allows one of the shape components to have the // special -1 value, meaning it will be calculated automatically based on the // input. Here we calculate what that dimension should be so that the number // of output elements in the same as the number of input elements. int num_input_elements = NumElements(input); TfLiteIntArray* output_shape = output->dims; if (NumInputs(node) == 1 && // Legacy scalar supported with params. output_shape->size == 1 && output_shape->data[0] == 0) { // Legacy tflite models use a shape parameter of [0] to indicate scalars, // so adjust accordingly. TODO(b/111614235): Allow zero-sized buffers during // toco conversion. output_shape->size = 0; } int num_output_elements = 1; int stretch_dim = -1; for (int i = 0; i < output_shape->size; ++i) { int value = output_shape->data[i]; if (value == -1) { TF_LITE_ENSURE_EQ(context, stretch_dim, -1); stretch_dim = i; } else { num_output_elements *= value; } } if (stretch_dim != -1) { output_shape->data[stretch_dim] = num_input_elements / num_output_elements; num_output_elements *= output_shape->data[stretch_dim]; } TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements); 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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, node->inputs->size, 1); TF_LITE_ENSURE_EQ(context, node->outputs->size, 1); const TfLiteTensor* input_resource_id_tensor = GetInput(context, node, kInputVariableId); TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1); TfLiteTensor* output = GetOutput(context, node, kOutputValue); 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
jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) { jas_matrix_t *y; int i; int j; y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x)); assert(y); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; }
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
Jsi_Value *Jsi_ValueArrayIndex(Jsi_Interp *interp, Jsi_Value *args, int index) { Jsi_Obj *obj = args->d.obj; Jsi_Value *v; assert(args->vt == JSI_VT_OBJECT); if (obj->isarrlist && obj->arr) return ((index < 0 || (uint)index >= obj->arrCnt) ? NULL : obj->arr[index]); char unibuf[100]; Jsi_NumberItoA10(index, unibuf, sizeof(unibuf)); v = Jsi_TreeObjGetValue(args->d.obj, unibuf, 0); return v; }
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
inline typename V::VectorType FBUnserializer<V>::unserializeList(size_t depth) { p_ += CODE_SIZE; // the list size is written so we can reserve it in the vector // in future. Skip past it for now. unserializeInt64(); typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1
C++
CWE-674
Uncontrolled Recursion
The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.
https://cwe.mitre.org/data/definitions/674.html
safe
void PacketReader::getLabelFromContent(const vector<uint8_t>& content, uint16_t& frompos, string& ret, int recurs) { if(recurs > 100) // the forward reference-check below should make this test 100% obsolete throw MOADNSException("Loop"); int pos = frompos; // it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop for(;;) { unsigned char labellen=content.at(frompos++); if(!labellen) { if(ret.empty()) ret.append(1,'.'); break; } else if((labellen & 0xc0) == 0xc0) { uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader); // cout<<"This is an offset, need to go to: "<<offset<<endl; if(offset >= pos) throw MOADNSException("forward reference during label decompression"); return getLabelFromContent(content, offset, ret, ++recurs); } else if(labellen > 63) throw MOADNSException("Overly long label during label decompression ("+lexical_cast<string>((unsigned int)labellen)+")"); else { // XXX FIXME THIS MIGHT BE VERY SLOW! for(string::size_type n = 0 ; n < labellen; ++n, frompos++) { if(content.at(frompos)=='.' || content.at(frompos)=='\\') { ret.append(1, '\\'); ret.append(1, content[frompos]); } else if(content.at(frompos)==' ') { ret+="\\032"; } else ret.append(1, content[frompos]); } ret.append(1,'.'); } if (ret.length() > 1024) throw MOADNSException("Total name too long"); } }
0
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
vulnerable
static void setAppend(SetType& set, const VariantType& v) { if (!v.isInteger() && !v.isString()) { throw HPHP::serialize::UnserializeError( "Keysets can only contain integers or strings" ); } set.append(v); }
1
C++
CWE-674
Uncontrolled Recursion
The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack.
https://cwe.mitre.org/data/definitions/674.html
safe
TfLiteStatus Relu1Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); const ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Relu1(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); return kTfLiteOk; } break; case kTfLiteUInt8: { QuantizedReluX<uint8_t>(-1.0f, 1.0f, input, output, data); return kTfLiteOk; } break; case kTfLiteInt8: { QuantizedReluX<int8_t>(-1, 1, input, output, data); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG(context, "Only float32, uint8, int8 supported " "currently, got %s.", TfLiteTypeGetName(input->type)); return kTfLiteError; } }
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
jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) { jas_matrix_t *y; jas_matind_t i; jas_matind_t j; y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x)); assert(y); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; }
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
static ssize_t _hostsock_writev( oe_fd_t* desc, const struct oe_iovec* iov, int iovcnt) { ssize_t ret = -1; sock_t* sock = _cast_sock(desc); void* buf = NULL; size_t buf_size = 0; if (!sock || !iov || iovcnt < 0 || iovcnt > OE_IOV_MAX) OE_RAISE_ERRNO(OE_EINVAL); /* Flatten the IO vector into contiguous heap memory. */ if (oe_iov_pack(iov, iovcnt, &buf, &buf_size) != 0) OE_RAISE_ERRNO(OE_ENOMEM); /* Call the host. */ if (oe_syscall_sendv_ocall(&ret, sock->host_fd, buf, iovcnt, buf_size) != OE_OK) { OE_RAISE_ERRNO(OE_EINVAL); } done: if (buf) oe_free(buf); return ret; }
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
void Init(void) { for(int i = 0;i < 19;i++) { #ifdef DEBUG_QMCODER char string[5] = "X0 "; string[1] = (i / 10) + '0'; string[2] = (i % 10) + '0'; X[i].Init(string); string[0] = 'M'; M[i].Init(string); #else X[i].Init(); M[i].Init(); #endif } }
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 jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; 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 = val; } } } }
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
R_API RBinJavaAttrInfo *r_bin_java_source_debug_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 6; if (sz < 8) { return NULL; } RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); if (!attr) { return NULL; } attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_DEBUG_EXTENTSION_ATTR; if (attr->length == 0) { eprintf ("r_bin_java_source_debug_attr_new: Attempting to allocate 0 bytes for debug_extension.\n"); attr->info.debug_extensions.debug_extension = NULL; return attr; } else if ((attr->length + offset) > sz) { eprintf ("r_bin_java_source_debug_attr_new: Expected %d byte(s) got %" PFMT64d " bytes for debug_extension.\n", attr->length, (offset + sz)); } attr->info.debug_extensions.debug_extension = (ut8 *) malloc (attr->length); if (attr->info.debug_extensions.debug_extension && (attr->length > (sz - offset))) { memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, sz - offset); } else if (attr->info.debug_extensions.debug_extension) { memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, attr->length); } else { eprintf ("r_bin_java_source_debug_attr_new: Unable to allocate the data for the debug_extension.\n"); } offset += attr->length; attr->size = offset; return attr; }
1
C++
CWE-805
Buffer Access with Incorrect Length Value
The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.
https://cwe.mitre.org/data/definitions/805.html
safe
otError Commissioner::GeneratePskc(const char * aPassPhrase, const char * aNetworkName, const Mac::ExtendedPanId &aExtPanId, Pskc & aPskc) { otError error = OT_ERROR_NONE; const char *saltPrefix = "Thread"; uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; uint16_t saltLen = 0; VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) && (strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, strlen(saltPrefix)); saltLen += static_cast<uint16_t>(strlen(saltPrefix)); memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId)); saltLen += OT_EXT_PAN_ID_SIZE; memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName)); saltLen += static_cast<uint16_t>(strlen(aNetworkName)); otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), static_cast<uint16_t>(strlen(aPassPhrase)), reinterpret_cast<const uint8_t *>(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8); exit: return error; }
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 HardSwishPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_STATUS(GenericPrepare(context, node)); TfLiteTensor* output = GetOutput(context, node, 0); if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { HardSwishData* data = static_cast<HardSwishData*>(node->user_data); HardSwishParams* params = &data->params; const TfLiteTensor* input = GetInput(context, node, 0); params->input_zero_point = input->params.zero_point; params->output_zero_point = output->params.zero_point; const float input_scale = input->params.scale; const float hires_input_scale = (1.0f / 128.0f) * input_scale; const float reluish_scale = 3.0f / 32768.0f; const float output_scale = output->params.scale; const float output_multiplier = hires_input_scale / output_scale; int32_t output_multiplier_fixedpoint_int32; QuantizeMultiplier(output_multiplier, &output_multiplier_fixedpoint_int32, &params->output_multiplier_exponent); DownScaleInt32ToInt16Multiplier( output_multiplier_fixedpoint_int32, &params->output_multiplier_fixedpoint_int16); TF_LITE_ENSURE(context, params->output_multiplier_exponent <= 0); const float reluish_multiplier = hires_input_scale / reluish_scale; int32_t reluish_multiplier_fixedpoint_int32; QuantizeMultiplier(reluish_multiplier, &reluish_multiplier_fixedpoint_int32, &params->reluish_multiplier_exponent); DownScaleInt32ToInt16Multiplier( reluish_multiplier_fixedpoint_int32, &params->reluish_multiplier_fixedpoint_int16); } 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
AP4_VisualSampleEntry::ReadFields(AP4_ByteStream& stream) { // sample entry AP4_Result result = AP4_SampleEntry::ReadFields(stream); if (result < 0) return result; // read fields from this class stream.ReadUI16(m_Predefined1); stream.ReadUI16(m_Reserved2); stream.Read(m_Predefined2, sizeof(m_Predefined2)); stream.ReadUI16(m_Width); stream.ReadUI16(m_Height); stream.ReadUI32(m_HorizResolution); stream.ReadUI32(m_VertResolution); stream.ReadUI32(m_Reserved3); stream.ReadUI16(m_FrameCount); char compressor_name[33]; compressor_name[32] = 0; stream.Read(compressor_name, 32); int name_length = compressor_name[0]; if (name_length < 32) { compressor_name[name_length+1] = 0; // force null termination m_CompressorName = &compressor_name[1]; } stream.ReadUI16(m_Depth); stream.ReadUI16(m_Predefined3); return AP4_SUCCESS; }
0
C++
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
vulnerable
TEST(ComparisonsTest, QuantizedInt8GreaterWithBroadcastMultiplierGreaterThanOne) { const float kMin = -127.f; const float kMax = 127.f; std::vector<std::vector<int>> test_shapes = { {6}, {2, 3}, {2, 1, 3}, {1, 3, 1, 2}}; for (int i = 0; i < test_shapes.size(); ++i) { ComparisonOpModel model({TensorType_INT8, test_shapes[i], kMin, kMax}, {TensorType_INT8, {}, kMin, kMax}, TensorType_INT8, BuiltinOperator_GREATER); model.QuantizeAndPopulate<int8_t>(model.input1(), {572, -2, -71, 8, 11, 20}); model.QuantizeAndPopulate<int8_t>(model.input2(), {8}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAre(true, false, false, false, true, true)) << "With shape number " << i; } }
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 CxImage::Transfer(CxImage &from, bool bTransferFrames /*=true*/) { if (!Destroy()) return false; memcpy(&head,&from.head,sizeof(BITMAPINFOHEADER)); memcpy(&info,&from.info,sizeof(CXIMAGEINFO)); pDib = from.pDib; pSelection = from.pSelection; pAlpha = from.pAlpha; ppLayers = from.ppLayers; memset(&from.head,0,sizeof(BITMAPINFOHEADER)); memset(&from.info,0,sizeof(CXIMAGEINFO)); from.pDib = from.pSelection = from.pAlpha = NULL; from.ppLayers = NULL; if (bTransferFrames){ DestroyFrames(); ppFrames = from.ppFrames; from.ppFrames = NULL; } return true; }
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
static inline int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst, int cs_l) { switch (ctxt->op_bytes) { case 2: ctxt->_eip = (u16)dst; break; case 4: ctxt->_eip = (u32)dst; break; case 8: if ((cs_l && is_noncanonical_address(dst)) || (!cs_l && (dst & ~(u32)-1))) return emulate_gp(ctxt, 0); ctxt->_eip = dst; break; default: WARN(1, "unsupported eip assignment size\n"); } return X86EMUL_CONTINUE; }
1
C++
NVD-CWE-noinfo
null
null
null
safe
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { ut64 offset = 0; if (sz < 8) { return NULL; } RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); offset += 6; if (attr && sz >= offset) { attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR; attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset); if (attr->info.annotation_default_attr.default_value) { offset += attr->info.annotation_default_attr.default_value->size; } } r_bin_java_print_annotation_default_attr_summary (attr); return attr; }
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
BOOL nego_read_request(rdpNego* nego, wStream* s) { BYTE li; BYTE type; UINT16 length; if (!tpkt_read_header(s, &length)) return FALSE; if (!tpdu_read_connection_request(s, &li, length)) return FALSE; if (li != Stream_GetRemainingLength(s) + 6) { WLog_ERR(TAG, "Incorrect TPDU length indicator."); return FALSE; } if (!nego_read_request_token_or_cookie(nego, s)) { WLog_ERR(TAG, "Failed to parse routing token or cookie."); return FALSE; } if (Stream_GetRemainingLength(s) >= 8) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ if (type != TYPE_RDP_NEG_REQ) { WLog_ERR(TAG, "Incorrect negotiation request type %" PRIu8 "", type); return FALSE; } nego_process_negotiation_request(nego, s); } return tpkt_ensure_stream_consumed(s, 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
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* data = reinterpret_cast<TfLiteAudioMicrofrontendParams*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt16); output->type = kTfLiteInt32; if (data->out_float) { output->type = kTfLiteFloat32; } TfLiteIntArray* output_size = TfLiteIntArrayCreate(2); int num_frames = 0; if (input->dims->data[0] >= data->state->window.size) { num_frames = (input->dims->data[0] - data->state->window.size) / data->state->window.step / data->frame_stride + 1; } output_size->data[0] = num_frames; output_size->data[1] = data->state->filterbank.num_channels * (1 + data->left_context + data->right_context); return context->ResizeTensor(context, output, output_size); }
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* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); 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
TEST(TensorSliceReaderTest, NegativeTensorShapeDimension) { const string fname = io::JoinPath(testing::TmpDir(), "negative_dim_checkpoint"); TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder); const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TF_CHECK_OK(writer.Add("test", TensorShape({4, 5}), TensorSlice::ParseOrDie("0,2:-"), data)); TF_CHECK_OK(writer.Finish()); MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) { if (sts.has_meta()) { for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) { for (auto& dim : *tensor.mutable_shape()->mutable_dim()) { dim.set_size(-dim.size()); } } } return sts.SerializeAsString(); }); TensorSliceReader reader(fname, OpenTableTensorSliceReader); // The negative dimension should cause loading to fail. EXPECT_FALSE(reader.status().ok()); }
1
C++
CWE-345
Insufficient Verification of Data Authenticity
The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
https://cwe.mitre.org/data/definitions/345.html
safe
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); if (w == NULL) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; }
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
static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; }
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
void *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; }
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
void DoRealForwardFFT(OpKernelContext* ctx, uint64* fft_shape, const Tensor& in, Tensor* out) { // Create the axes (which are always trailing). const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank); auto device = ctx->eigen_device<CPUDevice>(); auto input = Tensor(in).flat_inner_dims<RealT, FFTRank + 1>(); const auto input_dims = input.dimensions(); // Slice input to fft_shape on its inner-most dimensions. Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> input_slice_sizes; input_slice_sizes[0] = input_dims[0]; TensorShape temp_shape{input_dims[0]}; for (int i = 1; i <= FFTRank; ++i) { input_slice_sizes[i] = fft_shape[i - 1]; temp_shape.AddDim(fft_shape[i - 1]); } OP_REQUIRES(ctx, temp_shape.num_elements() > 0, errors::InvalidArgument("Obtained a FFT shape of 0 elements: ", temp_shape.DebugString())); auto output = out->flat_inner_dims<ComplexT, FFTRank + 1>(); const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> zero_start_indices; // Compute the full FFT using a temporary tensor. Tensor temp; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<ComplexT>::v(), temp_shape, &temp)); auto full_fft = temp.flat_inner_dims<ComplexT, FFTRank + 1>(); full_fft.device(device) = input.slice(zero_start_indices, input_slice_sizes) .template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(axes); // Slice away the negative frequency components. output.device(device) = full_fft.slice(zero_start_indices, output.dimensions()); }
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
static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel) { return assign_eip_near(ctxt, ctxt->_eip + rel); }
1
C++
NVD-CWE-noinfo
null
null
null
safe
void Compute(OpKernelContext* ctx) override { auto x = ctx->input(0); auto i = ctx->input(1); auto v = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(i.shape()), errors::InvalidArgument("i must be a vector. ", i.shape().DebugString())); OP_REQUIRES(ctx, x.dims() == v.dims(), errors::InvalidArgument( "x and v shape doesn't match (ranks differ): ", x.shape().DebugString(), " vs. ", v.shape().DebugString())); for (int i = 1; i < x.dims(); ++i) { OP_REQUIRES( ctx, x.dim_size(i) == v.dim_size(i), errors::InvalidArgument("x and v shape doesn't match at index ", i, " : ", x.shape().DebugString(), " vs. ", v.shape().DebugString())); } OP_REQUIRES(ctx, i.dim_size(0) == v.dim_size(0), errors::InvalidArgument( "i and x shape doesn't match at index 0: ", i.shape().DebugString(), " vs. ", v.shape().DebugString())); Tensor y = x; // This creates an alias intentionally. // Skip processing if tensors are empty. if (x.NumElements() > 0 || v.NumElements() > 0) { OP_REQUIRES_OK(ctx, DoCompute(ctx, i, v, &y)); } ctx->set_output(0, y); }
0
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
vulnerable
int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; }
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
Status BuildInputArgIndex(const OpDef::ArgDef& arg_def, AttrSlice attr_values, const FunctionDef::ArgAttrs* arg_attrs, bool ints_on_device, int64_t resource_arg_unique_id) { bool is_type_list; DataTypeVector dtypes; TF_RETURN_IF_ERROR( ArgNumType(attr_values, arg_def, &is_type_list, &dtypes)); CHECK_GE(dtypes.size(), size_t{1}); int arg_index = result_.nodes.size(); TF_RETURN_IF_ERROR( AddItem(arg_def.name(), {true, arg_index, 0, is_type_list, dtypes})); // Creates dtypes.size() nodes in the graph. for (size_t i = 0; i < dtypes.size(); ++i) { TF_RETURN_IF_ERROR(AddItem(strings::StrCat(arg_def.name(), ":", i), {true, arg_index, 0, false, {dtypes[i]}})); DCHECK_EQ(arg_index, result_.nodes.size()); string name = arg_def.name(); if (dtypes.size() > 1) { strings::StrAppend(&name, "_", i); } NodeDef* gnode = AddNode(name); if (ints_on_device && dtypes[i] == DataType::DT_INT32) { gnode->set_op(FunctionLibraryDefinition::kDeviceArgOp); } else { gnode->set_op(FunctionLibraryDefinition::kArgOp); } DataType dtype = arg_def.is_ref() ? MakeRefType(dtypes[i]) : dtypes[i]; AddAttr("T", dtype, gnode); AddAttr("index", arg_index, gnode); if (resource_arg_unique_id >= 0) { AddAttr("_resource_arg_unique_id", resource_arg_unique_id, gnode); } if (arg_attrs) { for (const auto& arg_attr : arg_attrs->attr()) { AddAttr(arg_attr.first, arg_attr.second, gnode->mutable_attr()); } } result_.arg_types.push_back(dtypes[i]); ++arg_index; } return Status::OK(); }
0
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
vulnerable
static void nodeConstruct(struct SaveNode* node, tr_variant const* v, bool sort_dicts) { node->isVisited = false; node->childIndex = 0; if (sort_dicts && tr_variantIsDict(v)) { /* make node->sorted a sorted version of this dictionary */ size_t const n = v->val.l.count; struct KeyIndex* tmp = tr_new(struct KeyIndex, n); for (size_t i = 0; i < n; i++) { tmp[i].val = v->val.l.vals + i; tmp[i].keystr = tr_quark_get_string(tmp[i].val->key, NULL); } qsort(tmp, n, sizeof(struct KeyIndex), compareKeyIndex); tr_variantInitDict(&node->sorted, n); for (size_t i = 0; i < n; ++i) { node->sorted.val.l.vals[i] = *tmp[i].val; } node->sorted.val.l.count = n; tr_free(tmp); node->v = &node->sorted; } else { node->v = v; } }
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
bool __fastcall TSiteRawDialog::Execute(TSessionData * Data) { std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L"")); std::unique_ptr<TSessionData> RawData(new TSessionData(L"")); RawData->Assign(Data); // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that if (RawData->FSProtocol != fsSFTPonly) { RawData->FSProtocol = FactoryDefaults->FSProtocol; } RawData->HostName = FactoryDefaults->HostName; RawData->PortNumber = FactoryDefaults->PortNumber; RawData->UserName = FactoryDefaults->UserName; RawData->Password = FactoryDefaults->Password; RawData->Ftps = FactoryDefaults->Ftps; std::unique_ptr<TStrings> Options(RawData->SaveToOptions(FactoryDefaults.get(), false, false)); SettingsMemo->Lines = Options.get(); bool Result = TCustomDialog::Execute(); if (Result) { std::unique_ptr<TSessionData> BackupData(new TSessionData(L"")); BackupData->Assign(Data); Data->DefaultSettings(); Data->FSProtocol = BackupData->FSProtocol; Data->HostName = BackupData->HostName; Data->PortNumber = BackupData->PortNumber; Data->UserName = BackupData->UserName; Data->Password = BackupData->Password; Data->Ftps = BackupData->Ftps; Data->ApplyRawSettings(SettingsMemo->Lines); } return Result; }
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 Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); OpContext op_context(context, node); TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits); auto input_type = op_context.input->type; TF_LITE_ENSURE(context, input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 || input_type == kTfLiteInt8 || input_type == kTfLiteInt16 || input_type == kTfLiteInt32); for (int i = 0; i < NumOutputs(node); ++i) { GetOutput(context, node, i)->type = input_type; } // If we know the contents of the 'axis' tensor, resize all outputs. // Otherwise, wait until Eval(). if (IsConstantTensor(op_context.axis)) { return ResizeOutputTensors(context, node, op_context.axis, op_context.input, op_context.params->num_splits); } else { return UseDynamicOutputTensors(context, node); } }
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_F(ZNCTest, StatusEchoMessage) { auto znc = Run(); auto ircd = ConnectIRCd(); auto client = LoginClient(); client.Write("CAP REQ :echo-message"); client.Write("PRIVMSG *status :blah"); client.ReadUntil(":[email protected] PRIVMSG *status :blah"); client.ReadUntil(":*[email protected] PRIVMSG nick :Unknown command"); client.Write("znc delnetwork test"); client.ReadUntil("Network deleted"); auto client2 = LoginClient(); client2.Write("PRIVMSG *status :blah2"); client2.ReadUntil(":*[email protected] PRIVMSG nick :Unknown command"); auto client3 = LoginClient(); client3.Write("PRIVMSG *status :blah3"); client3.ReadUntil(":*[email protected] PRIVMSG nick :Unknown command"); }
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
TfLiteStatus EvalImpl(TfLiteContext* context, const TfLiteTensor* input, TfLiteNode* node) { // Map from value, to index in the unique elements vector. // Note that we prefer to use map than unordered_map as it showed less // increase in the binary size. std::map<T, int> unique_values; TfLiteTensor* output_indexes; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 1, &output_indexes)); std::vector<T> output_values; I* indexes = GetTensorData<I>(output_indexes); const T* data = GetTensorData<T>(input); const int num_elements = NumElements(input); for (int i = 0; i < num_elements; ++i) { const auto element_it = unique_values.find(data[i]); if (element_it != unique_values.end()) { indexes[i] = element_it->second; } else { const int unique_index = unique_values.size(); unique_values[data[i]] = unique_index; indexes[i] = unique_index; output_values.push_back(data[i]); } } // Allocate output tensor. TfLiteTensor* unique_output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &unique_output)); std::unique_ptr<TfLiteIntArray, void (*)(TfLiteIntArray*)> shape( TfLiteIntArrayCreate(NumDimensions(input)), TfLiteIntArrayFree); shape->data[0] = unique_values.size(); TF_LITE_ENSURE_STATUS( context->ResizeTensor(context, unique_output, shape.release())); // Set the values in the output tensor. T* output_unique_values = GetTensorData<T>(unique_output); for (int i = 0; i < output_values.size(); ++i) { output_unique_values[i] = output_values[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
void nego_process_negotiation_response(rdpNego* nego, wStream* s) { UINT16 length; WLog_DBG(TAG, "RDP_NEG_RSP"); if (Stream_GetRemainingLength(s) < 7) { WLog_ERR(TAG, "Invalid RDP_NEG_RSP"); nego->state = NEGO_STATE_FAIL; return; } Stream_Read_UINT8(s, nego->flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->SelectedProtocol); nego->state = NEGO_STATE_FINAL; }
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
RectangleRequest &operator=(const struct RectangleRequest &req) { // Not nice, but this is really faster and simpler memcpy(this,&req,sizeof(struct RectangleRequest)); // Not linked in any way if this is new. rr_pNext = NULL; // return *this; }
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
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node, int index) { if (context->tensors != nullptr) { return &context->tensors[node->outputs->data[index]]; } else { return context->GetTensor(context, node->outputs->data[index]); } }
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
bool Tensor::FromProto(Allocator* a, const TensorProto& proto) { CHECK_NOTNULL(a); TensorBuffer* p = nullptr; if (!TensorShape::IsValid(proto.tensor_shape())) return false; if (proto.dtype() == DT_INVALID) return false; TensorShape shape(proto.tensor_shape()); const int64_t N = shape.num_elements(); if (N > 0 && proto.dtype()) { bool dtype_error = false; if (!proto.tensor_content().empty()) { const auto& content = proto.tensor_content(); CASES_WITH_DEFAULT(proto.dtype(), p = Helper<T>::Decode(a, content, N), dtype_error = true, dtype_error = true); } else { CASES_WITH_DEFAULT(proto.dtype(), p = FromProtoField<T>(a, proto, N), dtype_error = true, dtype_error = true); } if (dtype_error || p == nullptr) return false; } else { // Handle the case of empty tensors (N = 0) or tensors with incomplete shape // (N = -1). All other values of `shape.num_elements()` should be invalid by // construction. // Here, we just need to validate that the `proto.dtype()` value is valid. bool dtype_error = false; CASES_WITH_DEFAULT(proto.dtype(), break, dtype_error = true, dtype_error = true); if (dtype_error) return false; } shape_ = shape; set_dtype(proto.dtype()); UnrefIfNonNull(buf_); buf_ = p; // TODO(misard) add tracking of which kernels and steps are calling // FromProto. if (MemoryLoggingEnabled() && buf_ != nullptr && buf_->data() != nullptr) { LogMemory::RecordTensorAllocation("Unknown (from Proto)", LogMemory::UNKNOWN_STEP_ID, *this); } return true; }
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 writeStats(Array& /*ret*/) override { fprintf(stderr, "writeStats start\n"); // RetSame: the return value is the same instance every time // HasThis: call has a this argument // AllSame: all returns were the same data even though args are different // MemberCount: number of different arg sets (including this) fprintf(stderr, "Count Function MinSerLen MaxSerLen RetSame HasThis " "AllSame MemberCount\n"); for (auto& me : m_memos) { if (me.second.m_ignore) continue; if (me.second.m_count == 1) continue; int min_ser_len = 999999999; int max_ser_len = 0; int count = 0; int member_count = 0; bool all_same = true; if (me.second.m_has_this) { bool any_multiple = false; auto& fr = me.second.m_member_memos.begin()->second.m_return_value; member_count = me.second.m_member_memos.size(); for (auto& mme : me.second.m_member_memos) { if (mme.second.m_return_value != fr) all_same = false; count += mme.second.m_count; auto ser_len = mme.second.m_return_value.length(); min_ser_len = std::min(min_ser_len, ser_len); max_ser_len = std::max(max_ser_len, ser_len); if (mme.second.m_count > 1) any_multiple = true; } if (!any_multiple && !all_same) continue; } else { min_ser_len = max_ser_len = me.second.m_return_value.length(); count = me.second.m_count; all_same = me.second.m_ret_tv_same; } fprintf(stderr, "%d %s %d %d %s %s %s %d\n", count, me.first.data(), min_ser_len, max_ser_len, me.second.m_ret_tv_same ? " true" : "false", me.second.m_has_this ? " true" : "false", all_same ? " true" : "false", member_count ); } fprintf(stderr, "writeStats end\n"); }
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 MaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: MaxEvalFloat<kernel_type>(context, node, params, data, input, output); break; case kTfLiteUInt8: MaxEvalQuantizedUInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt8: MaxEvalQuantizedInt8<kernel_type>(context, node, params, data, input, output); break; case kTfLiteInt16: MaxEvalQuantizedInt16<kernel_type>(context, node, params, data, input, output); break; default: TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.", TfLiteTypeGetName(input->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
Archive::Archive(RAROptions *InitCmd) { Cmd=NULL; // Just in case we'll have an exception in 'new' below. DummyCmd=(InitCmd==NULL); Cmd=DummyCmd ? (new RAROptions):InitCmd; OpenShared=Cmd->OpenShared; Format=RARFMT15; Solid=false; Volume=false; MainComment=false; Locked=false; Signed=false; FirstVolume=false; NewNumbering=false; SFXSize=0; LatestTime.Reset(); Protected=false; Encrypted=false; FailedHeaderDecryption=false; BrokenHeader=false; LastReadBlock=0; CurBlockPos=0; NextBlockPos=0; RecoverySize=-1; RecoveryPercent=-1; memset(&MainHead,0,sizeof(MainHead)); memset(&CryptHead,0,sizeof(CryptHead)); memset(&EndArcHead,0,sizeof(EndArcHead)); VolNumber=0; VolWrite=0; AddingFilesSize=0; AddingHeadersSize=0; *FirstVolumeName=0; Splitting=false; NewArchive=false; SilentOpen=false; #ifdef USE_QOPEN ProhibitQOpen=false; #endif }
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 load_face(Face & face, unsigned int options) { #ifdef GRAPHITE2_TELEMETRY telemetry::category _misc_cat(face.tele.misc); #endif Face::Table silf(face, Tag::Silf, 0x00050000); if (!silf) return false; if (!face.readGlyphs(options)) return false; if (silf) { if (!face.readFeatures() || !face.readGraphite(silf)) { #if !defined GRAPHITE2_NTRACING if (global_log) { *global_log << json::object << "type" << "fontload" << "failure" << face.error() << "context" << face.error_context() << json::close; } #endif return false; } else return true; } else return false; }
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
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* size = GetInput(context, node, kSizeTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); // TODO(ahentz): Our current implementations rely on the input being 4D, // and the size being 1D tensor with exactly 2 elements. TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1); TF_LITE_ENSURE_TYPES_EQ(context, size->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, size->dims->data[0], 2); output->type = input->type; if (!IsConstantTensor(size)) { SetTensorToDynamic(output); return kTfLiteOk; } return ResizeOutputTensor(context, input, size, output); }
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
_forceinline void Unpack::CopyString(uint Length,uint Distance) { size_t SrcPtr=UnpPtr-Distance; if (SrcPtr<MaxWinSize-MAX_INC_LZ_MATCH && UnpPtr<MaxWinSize-MAX_INC_LZ_MATCH) { // If we are not close to end of window, we do not need to waste time // to "& MaxWinMask" pointer protection. byte *Src=Window+SrcPtr; byte *Dest=Window+UnpPtr; UnpPtr+=Length; #ifdef FAST_MEMCPY if (Distance<Length) // Overlapping strings #endif while (Length>=8) { Dest[0]=Src[0]; Dest[1]=Src[1]; Dest[2]=Src[2]; Dest[3]=Src[3]; Dest[4]=Src[4]; Dest[5]=Src[5]; Dest[6]=Src[6]; Dest[7]=Src[7]; Src+=8; Dest+=8; Length-=8; } #ifdef FAST_MEMCPY else while (Length>=8) { // In theory we still could overlap here. // Supposing Distance == MaxWinSize - 1 we have memcpy(Src, Src + 1, 8). // But for real RAR archives Distance <= MaxWinSize - MAX_INC_LZ_MATCH // always, so overlap here is impossible. // This memcpy expanded inline by MSVC. We could also use uint64 // assignment, which seems to provide about the same speed. memcpy(Dest,Src,8); Src+=8; Dest+=8; Length-=8; } #endif // Unroll the loop for 0 - 7 bytes left. Note that we use nested "if"s. if (Length>0) { Dest[0]=Src[0]; if (Length>1) { Dest[1]=Src[1]; if (Length>2) { Dest[2]=Src[2]; if (Length>3) { Dest[3]=Src[3]; if (Length>4) { Dest[4]=Src[4]; if (Length>5) { Dest[5]=Src[5]; if (Length>6) { Dest[6]=Src[6]; } } } } } } } // Close all nested "if"s. } else while (Length-- > 0) // Slow copying with all possible precautions. { Window[UnpPtr]=Window[SrcPtr++ & MaxWinMask]; // We need to have masked UnpPtr after quit from loop, so it must not // be replaced with 'Window[UnpPtr++ & MaxWinMask]' UnpPtr=(UnpPtr+1) & MaxWinMask; } }
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* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) { auto tf_dlm_context = GetDlContext(h, status); if (!status->status.ok()) { return nullptr; } auto* tf_dlm_data = TFE_TensorHandleDevicePointer(h, status); if (!status->status.ok()) { return nullptr; } const Tensor* tensor = GetTensorFromHandle(h, status); TF_DataType data_type = static_cast<TF_DataType>(tensor->dtype()); auto tf_dlm_type = GetDlDataType(data_type, status); if (!status->status.ok()) { return nullptr; } TensorReference tensor_ref(*tensor); // This will call buf_->Ref() auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref); tf_dlm_tensor_ctx->reference = tensor_ref; DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor; dlm_tensor->manager_ctx = tf_dlm_tensor_ctx; dlm_tensor->deleter = &DLManagedTensorDeleter; dlm_tensor->dl_tensor.ctx = tf_dlm_context; int ndim = tensor->dims(); dlm_tensor->dl_tensor.ndim = ndim; dlm_tensor->dl_tensor.data = tf_dlm_data; dlm_tensor->dl_tensor.dtype = tf_dlm_type; std::vector<int64_t>* shape_arr = &tf_dlm_tensor_ctx->shape; std::vector<int64_t>* stride_arr = &tf_dlm_tensor_ctx->strides; shape_arr->resize(ndim); stride_arr->resize(ndim, 1); for (int i = 0; i < ndim; i++) { (*shape_arr)[i] = tensor->dim_size(i); } for (int i = ndim - 2; i >= 0; --i) { (*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1]; } dlm_tensor->dl_tensor.shape = shape_arr->data(); // There are two ways to represent compact row-major data // 1) nullptr indicates tensor is compact and row-majored. // 2) fill in the strides array as the real case for compact row-major data. // Here we choose option 2, since some frameworks didn't handle the strides // argument properly. dlm_tensor->dl_tensor.strides = stride_arr->data(); dlm_tensor->dl_tensor.byte_offset = 0; // TF doesn't handle the strides and byte_offsets here return static_cast<void*>(dlm_tensor); }
1
C++
CWE-252
Unchecked Return Value
The software does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.
https://cwe.mitre.org/data/definitions/252.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-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
inline bool ShapeIsVector(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* shape = GetInput(context, node, kShapeTensor); return (shape != nullptr && shape->dims->size == 1 && shape->type == kTfLiteInt32); }
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
const String& setSize(int len) { assertx(m_str); m_str->setSize(len); return *this; }
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
TEST_F(QuantizedConv2DTest, OddPaddingBatch) { const int stride = 2; TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D") .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Attr("out_type", DataTypeToEnum<qint32>::v()) .Attr("strides", {1, stride, stride, 1}) .Attr("padding", "SAME") .Finalize(node_def())); TF_ASSERT_OK(InitOp()); const int depth = 1; const int image_width = 4; const int image_height = 4; const int image_batch_count = 3; AddInputFromArray<quint8>( TensorShape({image_batch_count, image_height, image_width, depth}), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); const int filter_size = 3; const int filter_count = 1; AddInputFromArray<quint8>( TensorShape({filter_size, filter_size, depth, filter_count}), {1, 2, 3, 4, 5, 6, 7, 8, 9}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); TF_ASSERT_OK(RunOpKernel()); const int expected_width = image_width / stride; const int expected_height = (image_height * filter_count) / stride; Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<qint32>(&expected, {348, 252, 274, 175, // 348, 252, 274, 175, // 348, 252, 274, 175}); test::ExpectTensorEqual<qint32>(expected, *GetOutput(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
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-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 EluEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Elu(GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); return kTfLiteOk; } break; case kTfLiteInt8: { OpData* data = reinterpret_cast<OpData*>(node->user_data); EvalUsingLookupTable(data, input, output); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, "Only float32 and int8 is supported currently, got %s.", TfLiteTypeGetName(input->type)); return 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 jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, jas_matind_t xstart, jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend) { jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_, yend - s1->ystart_ - 1, xend - s1->xstart_ - 1); }
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
TfLiteStatus ResizeOutput(TfLiteContext* context, const TfLiteTensor* input, const TfLiteTensor* axis, TfLiteTensor* output) { int axis_value; // Retrive all 8 bytes when axis type is kTfLiteInt64 to avoid data loss. if (axis->type == kTfLiteInt64) { axis_value = static_cast<int>(*GetTensorData<int64_t>(axis)); } else { axis_value = *GetTensorData<int>(axis); } if (axis_value < 0) { axis_value += NumDimensions(input); } TF_LITE_ENSURE(context, axis_value >= 0); TF_LITE_ENSURE(context, axis_value < NumDimensions(input)); // Copy the input dimensions to output except the axis dimension. TfLiteIntArray* output_dims = TfLiteIntArrayCreate(NumDimensions(input) - 1); int j = 0; for (int i = 0; i < NumDimensions(input); ++i) { if (i != axis_value) { output_dims->data[j] = SizeOfDimension(input, i); ++j; } } return context->ResizeTensor(context, output, output_dims); }
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 HeaderMapImpl::insertByKey(HeaderString&& key, HeaderString&& value) { EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(key.getStringView()); if (cb) { key.clear(); StaticLookupResponse ref_lookup_response = cb(*this); if (*ref_lookup_response.entry_ == nullptr) { maybeCreateInline(ref_lookup_response.entry_, *ref_lookup_response.key_, std::move(value)); } else { appendToHeader((*ref_lookup_response.entry_)->value(), value.getStringView()); value.clear(); } } else { std::list<HeaderEntryImpl>::iterator i = headers_.insert(std::move(key), std::move(value)); i->entry_ = i; } }
0
C++
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
Status OpLevelCostEstimator::PredictMaxPool(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) TF_ASSIGN_OR_RETURN(ConvolutionDimensions dims, OpDimensionsFromInputs(op_info.inputs(0).shape(), op_info, &found_unknown_shapes)); // kx * ky - 1 comparisons per output (kx * xy > 1) // or 1 copy per output (kx * k1 = 1). int per_output_ops = dims.kx * dims.ky == 1 ? 1 : dims.kx * dims.ky - 1; int64_t ops = dims.batch * dims.ox * dims.oy * dims.oz * per_output_ops; node_costs->num_compute_ops = ops; int64_t input_size = 0; if (dims.ky >= dims.sy) { input_size = CalculateTensorSize(op_info.inputs(0), &found_unknown_shapes); } else { // dims.ky < dims.sy // Vertical stride is larger than vertical kernel; assuming row-major // format, skip unnecessary rows (or read every kx rows per sy rows, as the // others are not used for output). const auto data_size = DataTypeSize(BaseType(op_info.inputs(0).dtype())); input_size = data_size * dims.batch * dims.ix * dims.ky * dims.oy * dims.iz; } node_costs->num_input_bytes_accessed = {input_size}; const int64_t output_size = CalculateOutputSize(op_info, &found_unknown_shapes); node_costs->num_output_bytes_accessed = {output_size}; node_costs->max_memory = output_size; if (found_unknown_shapes) { node_costs->inaccurate = true; node_costs->num_nodes_with_unknown_shapes = 1; } return Status::OK(); }
1
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S' && type() == VariableUnserializer::Type::APCSerialize) { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast<StringData*const*>(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\"') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\"') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }
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
bool Decode(string_view encoded, std::string* raw) { for (auto iter = encoded.begin(); iter != encoded.end(); ++iter) { if (*iter == '%') { if (++iter == encoded.end()) { // Invalid URI string, two hexadecimal digits must follow '%'. return false; } int h_decimal = 0; if (!HexToDecimal(*iter, &h_decimal)) { return false; } if (++iter == encoded.end()) { // Invalid URI string, two hexadecimal digits must follow '%'. return false; } int l_decimal = 0; if (!HexToDecimal(*iter, &l_decimal)) { return false; } raw->push_back(static_cast<char>((h_decimal << 4) + l_decimal)); } else if (*iter > 127 || *iter < 0) { // Invalid encoded URI string, must be entirely ASCII. return false; } else { raw->push_back(*iter); } } return true; }
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
boost::system::error_code make_error_code(error_code_enum e) { return boost::system::error_code(e, get_bdecode_category()); }
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
v8::Local<v8::Object> CreateNativeEvent( v8::Isolate* isolate, v8::Local<v8::Object> sender, content::RenderFrameHost* frame, electron::mojom::ElectronBrowser::MessageSyncCallback callback) { v8::Local<v8::Object> event; if (frame && callback) { gin::Handle<Event> native_event = Event::Create(isolate); native_event->SetCallback(std::move(callback)); event = v8::Local<v8::Object>::Cast(native_event.ToV8()); } else { // No need to create native event if we do not need to send reply. event = CreateEvent(isolate); } Dictionary dict(isolate, event); dict.Set("sender", sender); // Should always set frameId even when callback is null. if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; }
1
C++
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
safe
void writeErr(size_t, const AsyncSocketException& ex) noexcept override { LOG(ERROR) << "write error: " << ex.what(); EXPECT_NE( ex.getType(), AsyncSocketException::AsyncSocketExceptionType::SSL_ERROR); }
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
std::string get_wml_location(const std::string &filename, const std::string &current_dir) { DBG_FS << "Looking for '" << filename << "'." << std::endl; assert(game_config::path.empty() == false); std::string result; if (filename.empty()) { LOG_FS << " invalid filename" << std::endl; return result; } if (filename.find("..") != std::string::npos) { ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl; return result; } if (ends_with(filename, ".pbl")) { ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl; return result; } bool already_found = false; if (filename[0] == '~') { // If the filename starts with '~', look in the user data directory. result = get_user_data_dir() + "/data/" + filename.substr(1); DBG_FS << " trying '" << result << "'" << std::endl; already_found = file_exists(result) || is_directory(result); } else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/') { // If the filename begins with a "./", look in the same directory // as the file currently being preprocessed. if (!current_dir.empty()) { result = current_dir; } else { result = game_config::path; } result += filename.substr(2); } else if (!game_config::path.empty()) result = game_config::path + "/data/" + filename; DBG_FS << " trying '" << result << "'" << std::endl; if (result.empty() || (!already_found && !file_exists(result) && !is_directory(result))) { DBG_FS << " not found" << std::endl; result.clear(); } else DBG_FS << " found: '" << result << "'" << std::endl; return result; }
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
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); 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 || output->type == kTfLiteInt32) { EvalDiv<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_OK( context, EvalQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError( context, "Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.", output->type); return kTfLiteError; } 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
void initialize(const string &path, bool owner) { TRACE_POINT(); this->path = path; this->owner = owner; /* Create the server instance directory. We only need to write to this * directory for these reasons: * 1. Initial population of structure files (structure_version.txt, instance.pid). * 2. Creating/removing a generation directory. * 3. Removing the entire server instance directory (after all * generations are removed). * * 1 and 2 are done by the helper server during initialization and before lowering * privilege. 3 is done during helper server shutdown by a cleanup process that's * running as the same user the helper server was running as before privilege * lowering. * Therefore, we make the directory only writable by the user the helper server * was running as before privilege is lowered. Everybody else has read and execute * rights though, because we want admin tools to be able to list the available * generations no matter what user they're running as. */ makeDirTree(path, "u=rwx,g=rx,o=rx"); }
0
C++
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
static int traceDirective(MaState *state, cchar *key, cchar *value) { HttpRoute *route; char *option, *ovalue, *tok; route = state->route; route->trace = httpCreateTrace(route->trace); for (option = stok(sclone(value), " \t", &tok); option; option = stok(0, " \t", &tok)) { option = ssplit(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (smatch(option, "content")) { httpSetTraceContentSize(route->trace, (ssize) getnum(ovalue)); } else { httpSetTraceEventLevel(route->trace, option, atoi(ovalue)); } } return 0; }
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
void TLSOutStream::flush() { U8* sentUpTo = start; while (sentUpTo < ptr) { int n = writeTLS(sentUpTo, ptr - sentUpTo); sentUpTo += n; offset += n; } ptr = start; out->flush(); }
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
TEST_F(QuantizedConv2DTest, OddPaddingBatch) { const int stride = 2; TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D") .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_QUINT8)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Input(FakeInput(DT_FLOAT)) .Attr("out_type", DataTypeToEnum<qint32>::v()) .Attr("strides", {1, stride, stride, 1}) .Attr("padding", "SAME") .Finalize(node_def())); TF_ASSERT_OK(InitOp()); const int depth = 1; const int image_width = 4; const int image_height = 4; const int image_batch_count = 3; AddInputFromArray<quint8>( TensorShape({image_batch_count, image_height, image_width, depth}), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); const int filter_size = 3; const int filter_count = 1; AddInputFromArray<quint8>( TensorShape({filter_size, filter_size, depth, filter_count}), {1, 2, 3, 4, 5, 6, 7, 8, 9}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); AddInputFromArray<float>(TensorShape({}), {0}); AddInputFromArray<float>(TensorShape({}), {255.0f}); TF_ASSERT_OK(RunOpKernel()); const int expected_width = image_width / stride; const int expected_height = (image_height * filter_count) / stride; Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height, expected_width, filter_count})); test::FillValues<qint32>(&expected, {348, 252, 274, 175, // 348, 252, 274, 175, // 348, 252, 274, 175}); test::ExpectTensorEqual<qint32>(expected, *GetOutput(0)); }
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