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 |
---|---|---|---|---|---|---|---|
char const* parse_int(char const* start, char const* end, char delimiter
, boost::int64_t& val, bdecode_errors::error_code_enum& ec)
{
while (start < end && *start != delimiter)
{
if (!numeric(*start))
{
ec = bdecode_errors::expected_string;
return start;
}
if (val > INT64_MAX / 10)
{
ec = bdecode_errors::overflow;
return start;
}
val *= 10;
int digit = *start - '0';
if (val > INT64_MAX - digit)
{
ec = bdecode_errors::overflow;
return start;
}
val += digit;
++start;
}
if (*start != delimiter)
ec = bdecode_errors::expected_colon;
return start;
} | 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 |
TfLiteStatus NotEqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteBool:
Comparison<bool, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteFloat32:
Comparison<float, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::NotEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::NotEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteString:
ComparisonString(reference_ops::StringRefNotEqualFn, input1, input2,
output, requires_broadcast);
break;
default:
context->ReportError(
context,
"Does not support type %d, requires bool|float|int|uint8|string",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-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 logToUSDT(const Array& bt) {
std::lock_guard<std::mutex> lock(usdt_mutex);
memset(&bt_slab, 0, sizeof(bt_slab));
int i = 0;
IterateVNoInc(
bt.get(),
[&](TypedValue tv) -> bool {
if (i >= strobelight::kMaxStackframes) {
return true;
}
assertx(isArrayLikeType(type(tv)));
ArrayData* bt_frame = val(tv).parr;
strobelight::backtrace_frame_t* frame = &bt_slab.frames[i];
auto const line = bt_frame->get(s_line.get());
if (line.is_init()) {
assertx(isIntType(type(line)));
frame->line = val(line).num;
}
auto const file_name = bt_frame->get(s_file.get());
if (file_name.is_init()) {
assertx(isStringType(type(file_name)));
strncpy(frame->file_name,
val(file_name).pstr->data(),
std::min(val(file_name).pstr->size(), strobelight::kFileNameMax));
frame->file_name[strobelight::kFileNameMax - 1] = '\0';
}
auto const class_name = bt_frame->get(s_class.get());
if (class_name.is_init()) {
assertx(isStringType(type(class_name)));
strncpy(frame->class_name,
val(class_name).pstr->data(),
std::min(val(class_name).pstr->size(), strobelight::kClassNameMax));
frame->class_name[strobelight::kClassNameMax - 1] = '\0';
}
auto const function_name = bt_frame->get(s_function.get());
if (function_name.is_init()) {
assertx(isStringType(type(function_name)));
strncpy(frame->function,
val(function_name).pstr->data(),
std::min(val(function_name).pstr->size(),
strobelight::kFunctionMax));
frame->function[strobelight::kFunctionMax - 1] = '\0';
}
i++;
return false;
}
);
bt_slab.len = i;
// Allow BPF to read the now-formatted stacktrace
FOLLY_SDT_WITH_SEMAPHORE(hhvm, hhvm_stack, &bt_slab);
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 |
bool PackLinuxElf64::calls_crt1(Elf64_Rela const *rela, int sz)
{
if (!dynsym || !dynstr) {
return false;
}
for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf64_Rela)), ++rela, ++relnum) {
unsigned const symnum = get_te64(&rela->r_info) >> 32;
char const *const symnam = get_dynsym_name(symnum, relnum);
if (0==strcmp(symnam, "__libc_start_main") // glibc
|| 0==strcmp(symnam, "__libc_init") // Android
|| 0==strcmp(symnam, "__uClibc_main")
|| 0==strcmp(symnam, "__uClibc_start_main"))
return true;
}
return false;
} | 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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
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));
if (input->type != kTfLiteFloat32) {
TF_LITE_UNSUPPORTED_TYPE(context, input->type, "Ceil");
}
optimized_ops::Ceil(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
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 |
void RegKey::setBinary(const TCHAR* valname, const void* value, int length) const {
LONG result = RegSetValueEx(key, valname, 0, REG_BINARY, (const BYTE*)value, length);
if (result != ERROR_SUCCESS) throw rdr::SystemException("setBinary", result);
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static void* OGRExpatRealloc( void *ptr, size_t size )
{
if( CanAlloc(size) )
return realloc(ptr, size);
free(ptr);
return nullptr;
} | 0 | 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 | vulnerable |
TfLiteRegistration AddOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.custom_name = "my_add";
reg.builtin_code = tflite::BuiltinOperator_CUSTOM;
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// Set output size to input size
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TF_LITE_ENSURE_EQ(context, input1->dims->size, input2->dims->size);
for (int i = 0; i < input1->dims->size; ++i) {
TF_LITE_ENSURE_EQ(context, input1->dims->data[i], input2->dims->data[i]);
}
TF_LITE_ENSURE_STATUS(context->ResizeTensor(
context, output, TfLiteIntArrayCopy(input1->dims)));
return kTfLiteOk;
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
// Copy input data to output data.
const TfLiteTensor* a0;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));
TF_LITE_ENSURE(context, a0);
TF_LITE_ENSURE(context, a0->data.f);
const TfLiteTensor* a1;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &a1));
TF_LITE_ENSURE(context, a1);
TF_LITE_ENSURE(context, a1->data.f);
TfLiteTensor* out;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out));
TF_LITE_ENSURE(context, out);
TF_LITE_ENSURE(context, out->data.f);
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
out->data.f[i] = a0->data.f[i] + a1->data.f[i];
}
return kTfLiteOk;
};
return reg;
} | 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 EvalHashtableFind(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputResourceIdTensor,
&input_resource_id_tensor));
int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kKeyTensor, &key_tensor));
const TfLiteTensor* default_value_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDefaultValueTensor,
&default_value_tensor));
TfLiteTensor* output_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output_tensor));
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
TF_LITE_ENSURE_STATUS(
lookup->CheckKeyAndValueTypes(context, key_tensor, output_tensor));
auto result =
lookup->Lookup(context, key_tensor, output_tensor, default_value_tensor);
return result;
} | 1 | C++ | CWE-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 |
R_API RBinJavaAttrInfo *r_bin_java_rti_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.rtv_annotations_attr.num_annotations; i++) {
if (offset >= sz) {
break;
}
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
}
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
attr->size = offset;
}
return attr;
} | 0 | C++ | CWE-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 |
unsigned int GetU32LE (int nPos, bool *pbSuccess)
{
//*pbSuccess = true;
if ( nPos < 0 || nPos + 3 >= m_nLen )
{
*pbSuccess = false;
return 0;
}
unsigned int nRes = m_sFile[nPos + 3];
nRes = (nRes << 8) + m_sFile[nPos + 2];
nRes = (nRes << 8) + m_sFile[nPos + 1];
nRes = (nRes << 8) + m_sFile[nPos + 0];
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 |
TfLiteStatus EluPrepare(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));
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// Use LUT to handle quantized elu path.
if (input->type == kTfLiteInt8) {
PopulateLookupTable<int8_t>(data, input, output, [](float value) {
return value < 0.0 ? std::exp(value) - 1.0f : value;
});
}
return GenericPrepare(context, node);
} | 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 |
Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) {
const Tensor first_partition_tensor =
context->input(kFirstPartitionInputIndex);
if (row_partition_types_.empty()) {
return errors::InvalidArgument("No row_partition_types given.");
}
const RowPartitionType first_partition_type = row_partition_types_[0];
switch (first_partition_type) {
case RowPartitionType::FIRST_DIM_SIZE:
*result = first_partition_tensor.scalar<INDEX_TYPE>()();
return Status::OK();
case RowPartitionType::VALUE_ROWIDS:
return errors::InvalidArgument(
"Cannot handle VALUE_ROWIDS in first dimension.");
case RowPartitionType::ROW_SPLITS:
*result = first_partition_tensor.shape().dim_size(0) - 1;
return Status::OK();
default:
return errors::InvalidArgument(
"Cannot handle type ",
RowPartitionTypeToString(first_partition_type));
}
} | 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 |
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
} | 0 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | vulnerable |
void AddBatchOffsets(Tensor* indices, const Tensor& params) {
int64_t batch_size = 1; // The size of all batch dimensions.
for (int idx = 0; idx < batch_dims_; ++idx) {
batch_size *= params.dim_size(idx);
}
auto indices_flat = indices->flat<Index>();
int64_t const index_inner_size = indices->NumElements() / batch_size;
int64_t const batch_offset = params.dim_size(batch_dims_);
for (int64_t batch_idx = 0, dest_idx = 0; batch_idx < batch_size;
++batch_idx) {
for (int64_t idx = 0; idx < index_inner_size; ++idx) {
indices_flat(dest_idx++) += batch_offset * batch_idx;
}
}
} | 0 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | vulnerable |
static size_t ntlm_av_pair_get_next_offset(NTLM_AV_PAIR* pAvPair)
{
return ntlm_av_pair_get_len(pAvPair) + sizeof(NTLM_AV_PAIR);
} | 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 SetArcInMem(byte *Data,size_t Size)
{
ArcMemData=Data;
ArcMemSize=Size;
ArcInMem=Data!=NULL && Size>0;
} | 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 SocketLineReader::dataReceived()
{
while (m_socket->canReadLine()) {
const QByteArray line = m_socket->readLine();
if (line.length() > 1) { //we don't want a single \n
m_packets.enqueue(line);
}
}
//If we still have things to read from the socket, call dataReceived again
//We do this manually because we do not trust readyRead to be emitted again
//So we call this method again just in case.
if (m_socket->bytesAvailable() > 0) {
QMetaObject::invokeMethod(this, "dataReceived", Qt::QueuedConnection);
return;
}
//If we have any packets, tell it to the world.
if (!m_packets.isEmpty()) {
Q_EMIT readyRead();
}
} | 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 |
static void nodeDestruct(struct SaveNode* node)
{
TR_ASSERT(node != NULL);
if (node->sorted != NULL)
{
tr_free(node->sorted->val.l.vals);
tr_free(node->sorted);
}
} | 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 |
void PrivateThreadPoolDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase* input,
DatasetBase** output) {
int64_t num_threads = 0;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64_t>(ctx, "num_threads", &num_threads));
OP_REQUIRES(ctx, num_threads >= 0,
errors::InvalidArgument("`num_threads` must be >= 0"));
*output = new Dataset(ctx, input, num_threads);
} | 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 |
TfLiteStatus Subgraph::AllocateTensors() {
TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "AllocateTensors");
if (!consistent_) {
ReportError("AllocateTensors() called on inconsistent model.");
return kTfLiteError;
}
// Restore delegation state if applicable.
TF_LITE_ENSURE_STATUS(RedoAllDelegates());
// Explicit (re)allocation is necessary if nodes have been changed or tensors
// have been resized. For inputs marked as dynamic, we can't short-circuit the
// allocation as the client may have done the resize manually.
if (state_ != kStateUninvokable &&
!HasDynamicTensorImpl(context_, inputs())) {
if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {
// If the only change was the release of non-persistent memory via
// ReleaseNonPersistentMemory(), just re-allocate it. For any other type
// of memory-planning change (for eg, ResizeInputTensor), the state would
// be kStateUninvokable.
memory_planner_->AcquireNonPersistentMemory();
}
return kTfLiteOk;
}
// Note `AllocateTensors` sometimes calls itself recursively above
// for delegates. Therefore only the logic below need to be guarded
// by `SubgraphGuard`.
SubgraphGuard guard(&context_, &is_subgraph_in_use_);
TF_LITE_ENSURE_OK(&context_, guard.status());
next_execution_plan_index_to_prepare_ = 0;
next_execution_plan_index_to_plan_allocation_ = 0;
next_original_execution_plan_index_to_prepare_ = 0;
if (memory_planner_) {
TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations());
}
TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());
state_ = kStateInvokable;
// Reset the variable tensors to zero after (re)allocating the tensors.
// Developers shouldn't rely on the side effect of this function to reset
// variable tensors. They should call `ResetVariableTensors` directly
// instead.
ResetVariableTensors();
return kTfLiteOk;
} | 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 |
uint32_t bounded_iostream::write_no_buffer(const void *from, size_t bytes_to_write) {
//return iostream::write(from,tpsize,dtsize);
std::pair<unsigned int, Sirikata::JpegError> retval;
if (byte_bound != 0 && byte_position + bytes_to_write > byte_bound) {
size_t real_bytes_to_write = byte_bound - byte_position;
byte_position += real_bytes_to_write;
retval = parent->Write(reinterpret_cast<const unsigned char*>(from), real_bytes_to_write);
if (retval.first < real_bytes_to_write) {
err = retval.second;
return retval.first;
}
return bytes_to_write; // pretend we wrote it all
}
size_t total = bytes_to_write;
retval = parent->Write(reinterpret_cast<const unsigned char*>(from), total);
unsigned int written = retval.first;
byte_position += written;
if (written < total ) {
err = retval.second;
return written;
}
return bytes_to_write;
} | 1 | C++ | CWE-1187 | DEPRECATED: Use of Uninitialized Resource | This entry has been deprecated because it was a duplicate of CWE-908. All content has been transferred to CWE-908. | https://cwe.mitre.org/data/definitions/1187.html | safe |
Status DoCompute(OpKernelContext* ctx) {
tensorflow::ResourceTagger tag(kTFDataResourceTag,
ctx->op_kernel().type_string());
tstring filename;
TF_RETURN_IF_ERROR(
ParseScalarArgument<tstring>(ctx, "filename", &filename));
tstring compression_type;
TF_RETURN_IF_ERROR(ParseScalarArgument<tstring>(ctx, "compression_type",
&compression_type));
std::unique_ptr<WritableFile> file;
TF_RETURN_IF_ERROR(ctx->env()->NewWritableFile(filename, &file));
auto writer = absl::make_unique<io::RecordWriter>(
file.get(),
io::RecordWriterOptions::CreateRecordWriterOptions(compression_type));
DatasetBase* dataset;
TF_RETURN_IF_ERROR(GetDatasetFromVariantTensor(ctx->input(0), &dataset));
IteratorContext::Params params(ctx);
FunctionHandleCache function_handle_cache(params.flr);
params.function_handle_cache = &function_handle_cache;
ResourceMgr resource_mgr;
params.resource_mgr = &resource_mgr;
CancellationManager cancellation_manager(ctx->cancellation_manager());
params.cancellation_manager = &cancellation_manager;
IteratorContext iter_ctx(std::move(params));
DatasetBase* finalized_dataset;
TF_RETURN_IF_ERROR(FinalizeDataset(ctx, dataset, &finalized_dataset));
std::unique_ptr<IteratorBase> iterator;
TF_RETURN_IF_ERROR(finalized_dataset->MakeIterator(
&iter_ctx, /*parent=*/nullptr, "ToTFRecordOpIterator", &iterator));
std::vector<Tensor> components;
components.reserve(finalized_dataset->output_dtypes().size());
bool end_of_sequence;
do {
TF_RETURN_IF_ERROR(
iterator->GetNext(&iter_ctx, &components, &end_of_sequence));
if (!end_of_sequence) {
TF_RETURN_IF_ERROR(
writer->WriteRecord(components[0].scalar<tstring>()()));
}
components.clear();
} while (!end_of_sequence);
return Status::OK();
} | 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 |
Http::FilterTrailersStatus Context::onRequestTrailers() {
if (!wasm_->onRequestTrailers_) {
return Http::FilterTrailersStatus::Continue;
}
if (wasm_->onRequestTrailers_(this, id_).u64_ == 0) {
return Http::FilterTrailersStatus::Continue;
}
return Http::FilterTrailersStatus::StopIteration;
} | 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 |
TfLiteRegistration OkOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
// Set output size to the input size in OkOp::Prepare(). Code exists to have
// a framework in Prepare. The input and output tensors are not used.
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* in_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));
TfLiteTensor* out_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));
TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);
return context->ResizeTensor(context, out_tensor, new_size);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
return kTfLiteOk;
};
return reg;
} | 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 |
TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNegative) {
SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}},
{TensorType_INT32, {3}});
model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6});
model.PopulateTensor<int32_t>(model.segment_ids(), {-1, 0, 1});
ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void 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 |
void expectTrailers(
std::function<void()> callback = std::function<void()>()) {
if (callback) {
EXPECT_CALL(*this, onTrailers(testing::_))
.WillOnce(testing::InvokeWithoutArgs(callback))
.RetiresOnSaturation();
} else {
EXPECT_CALL(*this, onTrailers(testing::_));
}
} | 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 unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned* lengths;
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if (!lengths)
free(tree->lengths);
tree->lengths = lengths;
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
} | 1 | C++ | CWE-401 | Missing Release of Memory after Effective Lifetime | The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
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, 0, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (!is_supported_type(input->type)) {
TF_LITE_UNSUPPORTED_TYPE(context, input->type, op_name);
}
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | 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 isCPUDevice<CPUDevice>() {
return true;
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
absl::Status IsSupported(const TfLiteContext* context,
const TfLiteNode* tflite_node,
const TfLiteRegistration* registration) final {
if (mirror_pad_) {
const TfLiteMirrorPaddingParams* tf_options;
RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options));
if (tf_options->mode !=
TfLiteMirrorPaddingMode::kTfLiteMirrorPaddingReflect) {
return absl::InvalidArgumentError(
"Only Reflective padding is supported for Mirror Pad operation.");
}
}
RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 2));
RETURN_IF_ERROR(CheckInputsOutputs(context, tflite_node,
/*runtime_inputs=*/1, /*outputs=*/1));
RETURN_IF_ERROR(CheckTensorIsAvailable(context, tflite_node, 1));
auto pad_tensor = tflite::GetInput(context, tflite_node, 1);
if (pad_tensor->dims->size != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor dimension: expected 2 dim, got ",
pad_tensor->dims->size, " dim"));
}
bool supported =
pad_tensor->dims->data[0] == 3 || pad_tensor->dims->data[0] == 4;
if (!supported || pad_tensor->dims->data[1] != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor shape: expected 4x2 or 3x2, got ",
pad_tensor->dims->data[0], "x", pad_tensor->dims->data[1]));
}
return absl::OkStatus();
} | 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 |
TfLiteRegistration CancelOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
// Set output size to the input size in CancelOp::Prepare(). Code exists to
// have a framework in Prepare. The input and output tensors are not used.
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* in_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));
TfLiteTensor* out_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));
TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);
return context->ResizeTensor(context, out_tensor, new_size);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
cancellation_data_.is_cancelled = true;
return kTfLiteOk;
};
return reg;
} | 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 |
TfLiteTensor* GetTemporary(TfLiteContext* context, const TfLiteNode* node,
int index) {
const int tensor_index = ValidateTensorIndexing(
context, index, node->temporaries->size, node->temporaries->data);
if (tensor_index < 0) {
return nullptr;
}
return GetTensorAtIndex(context, tensor_index);
} | 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 Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSubParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32 ||
output->type == kTfLiteInt64) {
EvalSub<kernel_type>(context, node, params, data, input1, input2, output);
} else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||
output->type == kTfLiteInt16) {
EvalQuantized<kernel_type>(context, node, params, data, input1, input2,
output);
} else {
context->ReportError(
context,
"output type %d is not supported, requires float|uint8|int32 types.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
UrlQuery::UrlQuery(const std::string& encoded_str) {
if (!encoded_str.empty()) {
// Split into key value pairs separated by '&'.
for (std::size_t i = 0; i != std::string::npos;) {
std::size_t j = encoded_str.find_first_of('&', i);
std::string kv;
if (j == std::string::npos) {
kv = encoded_str.substr(i);
i = std::string::npos;
} else {
kv = encoded_str.substr(i, j - i);
i = j + 1;
}
string_view key;
string_view value;
if (SplitKV(kv, '=', false, &key, &value)) {
parameters_.push_back({ DecodeUnsafe(key), DecodeUnsafe(value) });
}
}
}
} | 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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TFLITE_DCHECK(node->builtin_data != nullptr);
auto* params = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data);
L2NormalizationParams* data =
static_cast<L2NormalizationParams*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE(context, NumDimensions(input) <= 4);
TF_LITE_ENSURE(context, output->type == kTfLiteFloat32 ||
output->type == kTfLiteUInt8 ||
output->type == kTfLiteInt8);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) {
data->input_zero_point = input->params.zero_point;
} else if (output->type == kTfLiteFloat32) {
data->input_zero_point = 0;
}
// TODO(ahentz): For some reason our implementations don't support
// activations.
TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);
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 |
Status ImmutableExecutorState::BuildControlFlowInfo(const Graph* g,
ControlFlowInfo* cf_info) {
const int num_nodes = g->num_node_ids();
cf_info->frame_names.resize(num_nodes);
std::vector<Node*> parent_nodes;
parent_nodes.resize(num_nodes);
std::vector<bool> visited;
visited.resize(num_nodes);
string frame_name;
std::deque<Node*> ready;
// Initialize with the root nodes.
for (Node* n : g->nodes()) {
if (n->in_edges().empty()) {
visited[n->id()] = true;
cf_info->unique_frame_names.insert(frame_name);
ready.push_back(n);
}
}
while (!ready.empty()) {
Node* curr_node = ready.front();
int curr_id = curr_node->id();
ready.pop_front();
Node* parent = nullptr;
if (IsEnter(curr_node)) {
// Enter a child frame.
TF_RETURN_IF_ERROR(
GetNodeAttr(curr_node->attrs(), "frame_name", &frame_name));
parent = curr_node;
} else if (IsExit(curr_node)) {
// Exit to the parent frame.
parent = parent_nodes[curr_id];
if (!parent) {
return errors::InvalidArgument(
"Invalid Exit op: Cannot find a corresponding Enter op.");
}
frame_name = cf_info->frame_names[parent->id()];
parent = parent_nodes[parent->id()];
} else {
parent = parent_nodes[curr_id];
frame_name = cf_info->frame_names[curr_id];
}
for (const Edge* out_edge : curr_node->out_edges()) {
Node* out = out_edge->dst();
if (IsSink(out)) continue;
const int out_id = out->id();
// Add to ready queue if not visited.
bool is_visited = visited[out_id];
if (!is_visited) {
ready.push_back(out);
visited[out_id] = true;
// Process the node 'out'.
cf_info->frame_names[out_id] = frame_name;
parent_nodes[out_id] = parent;
cf_info->unique_frame_names.insert(frame_name);
}
}
}
return Status::OK();
} | 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 |
static Status ValidateSavedTensors(const GraphDef& graph_def) {
for (const auto& node : graph_def.node()) {
const auto node_iterator = node.attr().find("value");
if (node_iterator != node.attr().end()) {
AttrValue node_value = node_iterator->second;
if (node_value.has_tensor()) {
const PartialTensorShape node_shape(node_value.tensor().tensor_shape());
if (node_shape.num_elements() < 0) {
return errors::FailedPrecondition(
"Saved model contains node \"", node.name(), "\" (op \"",
node.op(), "\") which initializes from a tensor with ",
node_shape.num_elements(), " elements");
}
}
} else if (node.op() == "Const") {
return errors::FailedPrecondition(
"Saved model contains node \"", node.name(),
"\" which is a constant tensor but no value has been provided");
}
}
return Status::OK();
} | 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 |
DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
const BigInt& q = m_group.get_q();
BigInt i(msg, msg_len, q.bits());
while(i >= q)
i -= q;
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
BOTAN_UNUSED(rng);
const BigInt k = generate_rfc6979_nonce(m_x, q, i, m_rfc6979_hash);
#else
const BigInt k = BigInt::random_integer(rng, 1, q);
#endif
BigInt s = inverse_mod(k, q);
const BigInt r = m_mod_q.reduce(m_group.power_g_p(k));
s = m_mod_q.multiply(s, mul_add(m_x, r, i));
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("Computed zero r/s during DSA signature");
return BigInt::encode_fixed_length_int_pair(r, s, q.bytes());
} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
void CharToWideMap(const char *Src,wchar *Dest,size_t DestSize,bool &Success)
{
// Map inconvertible characters to private use Unicode area 0xE000.
// Mark such string by placing special non-character code before
// first inconvertible character.
Success=false;
bool MarkAdded=false;
uint SrcPos=0,DestPos=0;
while (DestPos<DestSize)
{
if (Src[SrcPos]==0)
{
Success=true;
break;
}
mbstate_t ps;
memset(&ps,0,sizeof(ps));
size_t res=mbrtowc(Dest+DestPos,Src+SrcPos,MB_CUR_MAX,&ps);
if (res==(size_t)-1 || res==(size_t)-2)
{
// For security reasons we do not want to map low ASCII characters,
// so we do not have additional .. and path separator codes.
if (byte(Src[SrcPos])>=0x80)
{
if (!MarkAdded)
{
Dest[DestPos++]=MappedStringMark;
MarkAdded=true;
if (DestPos>=DestSize)
break;
}
Dest[DestPos++]=byte(Src[SrcPos++])+MapAreaStart;
}
else
break;
}
else
{
memset(&ps,0,sizeof(ps));
int Length=mbrlen(Src+SrcPos,MB_CUR_MAX,&ps);
SrcPos+=Max(Length,1);
DestPos++;
}
}
Dest[Min(DestPos,DestSize-1)]=0;
} | 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 |
jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)
{
jas_matrix_t *matrix;
assert(xstart <= xend && ystart <= yend);
if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
return 0;
}
matrix->xstart_ = xstart;
matrix->ystart_ = ystart;
matrix->xend_ = xend;
matrix->yend_ = yend;
return matrix;
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
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;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static void php_array_replace_recursive(PointerSet &seen, bool check,
Array &arr1, const Array& arr2) {
if (arr1.get() == arr2.get()) {
// This is an optimization, but it also avoids an assert in
// setWithRef (Variant::setWithRef asserts that its source
// and destination are not the same).
// If the arrays are self recursive, this does change the behavior
// slightly - it skips the "recursion detected" warning.
return;
}
if (check && !seen.insert((void*)arr1.get()).second) {
raise_warning("array_replace_recursive(): recursion detected");
return;
}
for (ArrayIter iter(arr2); iter; ++iter) {
Variant key = iter.first();
const Variant& value = iter.secondRef();
if (arr1.exists(key, true) && value.isArray()) {
Variant &v = arr1.lvalAt(key, AccessFlags::Key);
if (v.isArray()) {
Array subarr1 = v.toArray();
const ArrNR& arr_value = value.toArrNR();
php_array_replace_recursive(seen, couldRecur(v, subarr1),
subarr1, arr_value);
v = subarr1;
} else {
arr1.set(key, value, true);
}
} else {
arr1.setWithRef(key, value, true);
}
}
if (check) {
seen.erase((void*)arr1.get());
}
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
void verifyDirectoryPermissions(const string &path, struct stat &buf) {
TRACE_POINT();
if (buf.st_mode != (S_IFDIR | parseModeString("u=rwx,g=rx,o=rx"))) {
throw RuntimeException("Tried to reuse existing server instance directory " +
path + ", but it has wrong permissions");
} else if (buf.st_uid != geteuid() || buf.st_gid != getegid()) {
/* The server instance directory is always created by the Watchdog. Its UID/GID never
* changes because:
* 1. Disabling user switching only lowers the privilege of the HelperAgent.
* 2. For the UID/GID to change, the web server must be completely restarted
* (not just graceful reload) so that the control process can change its UID/GID.
* This causes the PID to change, so that an entirely new server instance
* directory is created.
*/
throw RuntimeException("Tried to reuse existing server instance directory " +
path + ", but it has wrong owner and group");
}
} | 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 |
hphp_libxml_input_buffer(const char *URI, xmlCharEncoding enc) {
if (s_libxml_errors->m_entity_loader_disabled) {
return nullptr;
}
return __xmlParserInputBufferCreateFilename(URI, enc);
} | 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 do_change_user(int afdt_fd) {
std::string uname;
lwp_read(afdt_fd, uname);
if (!uname.length()) return;
auto buf = PasswdBuffer{};
struct passwd *pw;
if (getpwnam_r(uname.c_str(), &buf.ent, buf.data.get(), buf.size, &pw)) {
// TODO(alexeyt) should we log something and/or fail to start?
return;
}
if (!pw) {
// TODO(alexeyt) should we log something and/or fail to start?
return;
}
if (pw->pw_gid) {
initgroups(pw->pw_name, pw->pw_gid);
setgid(pw->pw_gid);
}
if (pw->pw_uid) {
setuid(pw->pw_uid);
}
} | 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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Check for supported activation types.
auto* params =
reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data);
const TfLiteTensor* filter;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kWeightsTensor, &filter));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const bool is_quantized =
((filter->type == kTfLiteUInt8) || (filter->type == kTfLiteInt8));
const bool is_hybrid = is_quantized && (input->type == kTfLiteFloat32);
const bool is_pie = kernel_type == kLegacyPie;
// Pie and hybrid path supports all kinds of fused activations, otherwise only
// clipping activations are supported.
if (!is_pie && !is_hybrid) {
TF_LITE_ENSURE(context, params->activation == kTfLiteActNone ||
params->activation == kTfLiteActRelu ||
params->activation == kTfLiteActReluN1To1 ||
params->activation == kTfLiteActRelu6);
}
return PrepareImpl(context, node);
} | 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 |
static int64_t adjust_scale(int64_t scale) {
if (scale < 0) {
scale = BCG(bc_precision);
if (scale < 0) scale = 0;
}
if ((uint64_t)scale > StringData::MaxSize) return StringData::MaxSize;
return scale;
} | 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 void bson_append( bson *b, const void *data, int len ) {
memcpy( b->cur , data , len );
b->cur += len;
} | 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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Check that the inputs and outputs have the right sizes and types.
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output_values = GetOutput(context, node, kOutputValues);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output_values->type);
const TfLiteTensor* top_k = GetInput(context, node, kInputTopK);
TF_LITE_ENSURE_TYPES_EQ(context, top_k->type, kTfLiteInt32);
// Set output dynamic if the input is not const.
if (IsConstantTensor(top_k)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
TfLiteTensor* output_indexes = GetOutput(context, node, kOutputIndexes);
TfLiteTensor* output_values = GetOutput(context, node, kOutputValues);
SetTensorToDynamic(output_indexes);
SetTensorToDynamic(output_values);
}
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 |
PlainPasswd::PlainPasswd(int len) : CharArray(len) {
} | 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 |
SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
} | 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 |
ALWAYS_INLINE String serialize_impl(const Variant& value,
const SerializeOptions& opts) {
switch (value.getType()) {
case KindOfClass:
case KindOfLazyClass:
case KindOfPersistentString:
case KindOfString: {
auto const str =
isStringType(value.getType()) ? value.getStringData() :
isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :
lazyClassToStringHelper(value.toLazyClassVal());
auto const size = str->size();
if (size >= RuntimeOption::MaxSerializedStringSize) {
throw Exception("Size of serialized string (%d) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, 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 |
PackLinuxElf32::elf_find_dynamic(unsigned int key) const
{
Elf32_Dyn const *dynp= dynseg;
if (dynp)
for (; (unsigned)((char const *)dynp - (char const *)dynseg) < sz_dynseg
&& Elf32_Dyn::DT_NULL!=dynp->d_tag; ++dynp) if (get_te32(&dynp->d_tag)==key) {
unsigned const t= elf_get_offset_from_address(get_te32(&dynp->d_val));
if (t) {
return t + file_image;
}
break;
}
return 0;
} | 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 String HHVM_FUNCTION(bcadd, const String& left, const String& right,
int64_t scale /* = -1 */) {
if (scale < 0) scale = BCG(bc_precision);
bc_num first, second, result;
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
bc_add(first, second, &result, scale);
if (result->n_scale > scale) {
result->n_scale = scale;
}
String ret(bc_num2str(result), AttachString);
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
return ret;
} | 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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputVariableId);
int resource_id = input_resource_id_tensor->data.i32[0];
auto& resources = subgraph->resources();
auto* variable = resource::GetResourceVariable(&resources, resource_id);
TF_LITE_ENSURE(context, variable != nullptr);
TfLiteTensor* variable_tensor = variable->GetTensor();
TfLiteTensor* output = GetOutput(context, node, kOutputValue);
TF_LITE_ENSURE_TYPES_EQ(context, variable_tensor->type, output->type);
TF_LITE_ENSURE_OK(
context, context->ResizeTensor(
context, output, TfLiteIntArrayCopy(variable_tensor->dims)));
memcpy(output->data.raw, variable_tensor->data.raw, output->bytes);
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 |
Variant HHVM_FUNCTION(apc_add,
const Variant& key_or_array,
const Variant& var /* = null */,
int64_t ttl /* = 0 */) {
if (!apcExtension::Enable) return false;
if (key_or_array.isArray()) {
Array valuesArr = key_or_array.toArray();
// errors stores all keys corresponding to entries that could not be cached
ArrayInit errors(valuesArr.size(), ArrayInit::Map{});
for (ArrayIter iter(valuesArr); iter; ++iter) {
Variant key = iter.first();
if (!key.isString()) {
throw_invalid_argument("apc key: (not a string)");
return false;
}
Variant v = iter.second();
if (!apc_store().add(key.toString(), v, ttl)) {
errors.add(key, -1);
}
}
return errors.toVariant();
}
if (!key_or_array.isString()) {
throw_invalid_argument("apc key: (not a string)");
return false;
}
String strKey = key_or_array.toString();
return apc_store().add(strKey, var, ttl);
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
ALWAYS_INLINE String serialize_impl(const Variant& value,
const SerializeOptions& opts) {
switch (value.getType()) {
case KindOfClass:
case KindOfLazyClass:
case KindOfPersistentString:
case KindOfString: {
auto const str =
isStringType(value.getType()) ? value.getStringData() :
isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :
lazyClassToStringHelper(value.toLazyClassVal());
auto const size = str->size();
if (size >= RuntimeOption::MaxSerializedStringSize) {
throw Exception("Size of serialized string (%ld) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, true);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void 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-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 Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* cond_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputConditionTensor,
&cond_tensor));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context,
ResizeOutputTensor(context, cond_tensor, output));
}
TfLiteIntArray* dims = cond_tensor->dims;
if (dims->size == 0) {
// Scalar tensors are not supported.
TF_LITE_KERNEL_LOG(context, "Where op requires condition w/ rank > 0");
return kTfLiteError;
}
reference_ops::SelectTrueCoords(GetTensorShape(cond_tensor),
GetTensorData<bool>(cond_tensor),
GetTensorData<int64_t>(output));
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 |
void ComputeAsync(OpKernelContext* c, DoneCallback done) override {
auto col_params = new CollectiveParams();
auto done_with_cleanup = [col_params, done = std::move(done)]() {
done();
col_params->Unref();
};
core::RefCountPtr<CollectiveGroupResource> resource;
OP_REQUIRES_OK_ASYNC(c, LookupResource(c, HandleFromInput(c, 1), &resource),
done);
Tensor group_assignment = c->input(2);
OP_REQUIRES_OK_ASYNC(
c,
FillCollectiveParams(col_params, group_assignment,
ALL_TO_ALL_COLLECTIVE, resource.get()),
done);
col_params->instance.shape = c->input(0).shape();
VLOG(1) << "CollectiveAllToAll group_size " << col_params->group.group_size
<< " group_key " << col_params->group.group_key << " instance_key "
<< col_params->instance.instance_key;
// Allocate the output tensor, trying to reuse the input.
Tensor* output = nullptr;
OP_REQUIRES_OK_ASYNC(c,
c->forward_input_or_allocate_output(
{0}, 0, col_params->instance.shape, &output),
done_with_cleanup);
Run(c, col_params, std::move(done_with_cleanup));
} | 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 |
void RemoteDevicePropertiesWidget::setType()
{
if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) {
sshPort->setValue(22);
}
if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) {
smbPort->setValue(445);
}
} | 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 |
bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)
{
if ( ! target_len )
return true;
int to_copy = min(*len, target_len - endp->buffer_len);
memcpy(endp->buffer + endp->buffer_len, *data, to_copy);
*data += to_copy;
*len -= to_copy;
endp->buffer_len += to_copy;
return endp->buffer_len == target_len;
} | 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 reposition(int pos) { ptr = start + pos; } | 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 |
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteDepthToSpaceParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
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), 4);
auto data_type = output->type;
TF_LITE_ENSURE(context,
data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
data_type == kTfLiteInt64);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const int block_size = params->block_size;
const int input_height = input->dims->data[1];
const int input_width = input->dims->data[2];
const int input_channels = input->dims->data[3];
int output_height = input_height * block_size;
int output_width = input_width * block_size;
int output_channels = input_channels / block_size / block_size;
TF_LITE_ENSURE_EQ(context, input_height, output_height / block_size);
TF_LITE_ENSURE_EQ(context, input_width, output_width / block_size);
TF_LITE_ENSURE_EQ(context, input_channels,
output_channels * block_size * block_size);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
output_size->data[0] = input->dims->data[0];
output_size->data[1] = output_height;
output_size->data[2] = output_width;
output_size->data[3] = output_channels;
return context->ResizeTensor(context, output, output_size);
} | 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 Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteLocalResponseNormParams*>(node->builtin_data);
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));
if (output->type == kTfLiteFloat32) {
#define TF_LITE_LOCAL_RESPONSE_NORM(type) \
tflite::LocalResponseNormalizationParams op_params; \
op_params.range = params->radius; \
op_params.bias = params->bias; \
op_params.alpha = params->alpha; \
op_params.beta = params->beta; \
type::LocalResponseNormalization( \
op_params, GetTensorShape(input), GetTensorData<float>(input), \
GetTensorShape(output), GetTensorData<float>(output))
if (kernel_type == kReference) {
TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);
}
if (kernel_type == kGenericOptimized) {
TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);
}
#undef TF_LITE_LOCAL_RESPONSE_NORM
} else {
context->ReportError(context, "Output type is %d, requires float.",
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 |
bool IsReshapeOpSupported(const TfLiteRegistration* registration,
const TfLiteNode* node, TfLiteContext* context,
int coreml_version) {
if (coreml_version >= 3) {
return false;
}
if (node->inputs->size == 1) {
const auto* params =
reinterpret_cast<TfLiteReshapeParams*>(node->builtin_data);
return params->num_dimensions == 3 || params->num_dimensions == 4;
}
const int kShapeTensor = 1;
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kShapeTensor, &shape));
if (shape->allocation_type != kTfLiteMmapRo) {
TF_LITE_KERNEL_LOG(context, "Reshape has non-const shape.");
return false;
}
const bool is_shape_tensor =
shape->dims->size == 1 && shape->type == kTfLiteInt32;
return is_shape_tensor &&
(shape->dims->data[0] == 3 || shape->dims->data[0] == 4);
} | 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 |
QPDFObjectHandle::parse(PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer& tokenizer, bool& empty,
StringDecrypter* decrypter, QPDF* context)
{
return parseInternal(input, object_description, tokenizer, empty,
decrypter, context, false);
} | 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 em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel, old_sel;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
u8 cpl = ctxt->ops->cpl(ctxt);
/* Assignment of RIP may only fail in 64-bit mode */
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_sel, &old_desc, NULL,
VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
/* assigning eip failed; restore the old cs */
ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
return rc;
} | 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) {
const TfLiteTensor* input_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input_tensor));
const TfLiteTensor* padding_matrix;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &padding_matrix));
TfLiteTensor* output_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output_tensor));
TF_LITE_ENSURE_EQ(context, NumDimensions(padding_matrix), 2);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(padding_matrix, 0),
NumDimensions(input_tensor));
if (!IsConstantTensor(padding_matrix)) {
SetTensorToDynamic(output_tensor);
return kTfLiteOk;
}
// We have constant padding, so we can infer output size.
auto output_size = GetPaddedOutputShape(input_tensor, padding_matrix);
if (output_size == nullptr) {
return kTfLiteError;
}
return context->ResizeTensor(context, output_tensor, output_size.release());
} | 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 |
Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,
const String& key,
const String& iv) {
auto pm = get_valid_mcrypt_resource(td);
if (!pm) {
return false;
}
int max_key_size = mcrypt_enc_get_key_size(pm->m_td);
int iv_size = mcrypt_enc_get_iv_size(pm->m_td);
if (key.empty()) {
raise_warning("Key size is 0");
}
unsigned char *key_s = (unsigned char *)malloc(key.size());
memset(key_s, 0, key.size());
unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
int key_size;
if (key.size() > max_key_size) {
raise_warning("Key size too large; supplied length: %d, max: %d",
key.size(), max_key_size);
key_size = max_key_size;
} else {
key_size = key.size();
}
memcpy(key_s, key.data(), key.size());
if (iv.size() != iv_size) {
raise_warning("Iv size incorrect; supplied length: %d, needed: %d",
iv.size(), iv_size);
}
memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));
mcrypt_generic_deinit(pm->m_td);
int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
pm->close();
switch (result) {
case -3:
raise_warning("Key length incorrect");
break;
case -4:
raise_warning("Memory allocation error");
break;
case -1:
default:
raise_warning("Unknown error");
break;
}
} else {
pm->m_init = true;
}
free(iv_s);
free(key_s);
return result;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
static Status ValidateSavedTensors(const GraphDef& graph_def) {
for (const auto& node : graph_def.node()) {
TF_RETURN_IF_ERROR(ValidateNode(node));
}
if (graph_def.has_library()) {
const FunctionDefLibrary& library = graph_def.library();
for (const auto& function : library.function()) {
for (const auto& node : function.node_def()) {
TF_RETURN_IF_ERROR(ValidateNode(node));
}
// Also check that there is no recursivity in the library
// TODO(mihaimaruseac): Do more than self-recursivity
TF_RETURN_IF_ERROR(ValidateFunctionNotRecursive(function));
}
}
return Status::OK();
} | 1 | 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 | safe |
TfLiteStatus ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
// Segment ids should be of same cardinality as first input dimension and they
// should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)
const int segment_id_size = segment_ids->dims->data[0];
TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);
int previous_segment_id = -1;
for (int i = 0; i < segment_id_size; i++) {
const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i];
if (i == 0) {
TF_LITE_ENSURE_EQ(context, current_segment_id, 0);
} else {
int delta = current_segment_id - previous_segment_id;
TF_LITE_ENSURE(context, delta == 0 || delta == 1);
}
previous_segment_id = current_segment_id;
}
const int max_index = previous_segment_id;
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | 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 |
ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,
const std::string& emsa) :
PK_Ops::Signature_with_EMSA(emsa),
m_group(ecdsa.domain()),
m_x(ecdsa.private_value())
{
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
m_rfc6979_hash = hash_for_emsa(emsa);
#endif
} | 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);
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));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
if (type != kTfLiteInt32 && type != kTfLiteFloat32) {
TF_LITE_KERNEL_LOG(context, "Unsupported data type %s.",
TfLiteTypeGetName(type));
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 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 |
AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
const char* profile_name = GetProfileName(m_Profile);
if (profile_name) {
inspector.AddField("Profile", profile_name);
} else {
inspector.AddField("Profile", m_Profile);
}
inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_Level);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());
}
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());
}
return AP4_SUCCESS;
} | 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 |
static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
return TRUE;
} | 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, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* data;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputDataTensor, &data));
const TfLiteTensor* segment_ids;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputSegmentIdsTensor,
&segment_ids));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE(context,
data->type == kTfLiteInt32 || data->type == kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, segment_ids->type, kTfLiteInt32);
if (!IsConstantTensor(data) || !IsConstantTensor(segment_ids)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, data, segment_ids, output);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void Lua::setParamsTable(lua_State* vm, const char* table_name,
const char* query) const {
char outbuf[FILENAME_MAX];
char *where;
char *tok;
char *query_string = query ? strdup(query) : NULL;
lua_newtable(L);
if (query_string) {
// ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string);
tok = strtok_r(query_string, "&", &where);
while(tok != NULL) {
char *_equal;
if(strncmp(tok, "csrf", strlen("csrf")) /* Do not put csrf into the params table */
&& (_equal = strchr(tok, '='))) {
char *decoded_buf;
int len;
_equal[0] = '\0';
_equal = &_equal[1];
len = strlen(_equal);
purifyHTTPParameter(tok), purifyHTTPParameter(_equal);
// ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal);
if((decoded_buf = (char*)malloc(len+1)) != NULL) {
Utils::urlDecode(_equal, decoded_buf, len+1);
Utils::purifyHTTPparam(tok, true, false);
Utils::purifyHTTPparam(decoded_buf, false, false);
/* Now make sure that decoded_buf is not a file path */
FILE *fd;
if((decoded_buf[0] == '.')
&& ((fd = fopen(decoded_buf, "r"))
|| (fd = fopen(realpath(decoded_buf, outbuf), "r")))) {
ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path",
tok, decoded_buf);
decoded_buf[0] = '\0';
fclose(fd);
}
/* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */
/* put tok and the decoded buffer in to the table */
lua_push_str_table_entry(vm, tok, decoded_buf);
free(decoded_buf);
} else
ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory");
}
tok = strtok_r(NULL, "&", &where);
} /* while */
}
if(query_string) free(query_string);
if(table_name)
lua_setglobal(L, table_name);
else
lua_setglobal(L, (char*)"_GET"); /* Default */
} | 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 |
int DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)
{
if ( ! target_len )
return 1;
if ( *len < 0 )
{
reporter->AnalyzerError(analyzer, "dnp3 negative input length: %d", *len);
return -1;
}
if ( target_len < endp->buffer_len )
{
reporter->AnalyzerError(analyzer, "dnp3 invalid target length: %d - %d",
target_len, endp->buffer_len);
return -1;
}
int to_copy = min(*len, target_len - endp->buffer_len);
if ( endp->buffer_len + to_copy > MAX_BUFFER_SIZE )
{
reporter->AnalyzerError(analyzer, "dnp3 buffer length exceeded: %d + %d",
endp->buffer_len, to_copy);
return -1;
}
memcpy(endp->buffer + endp->buffer_len, *data, to_copy);
*data += to_copy;
*len -= to_copy;
endp->buffer_len += to_copy;
if ( endp->buffer_len == target_len )
return 1;
return 0;
} | 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 |
RawTile OpenJPEGImage::getRegion( int ha, int va, unsigned int res, int layers, int x, int y, unsigned int w, unsigned int h ){
// Scale up our output bit depth to the nearest factor of 8
unsigned int obpc = bpc;
if( bpc <= 16 && bpc > 8 ) obpc = 16;
else if( bpc <= 8 ) obpc = 8;
#ifdef DEBUG
Timer timer;
timer.start();
#endif
RawTile rawtile( 0, res, ha, va, w, h, channels, obpc );
if( obpc == 16 ) rawtile.data = new unsigned short[w * h * channels];
else if( obpc == 8 ) rawtile.data = new unsigned char[w * h * channels];
else throw file_error( "OpenJPEG :: Unsupported number of bits" );
rawtile.dataLength = w*h*channels*(obpc/8);
rawtile.filename = getImagePath();
rawtile.timestamp = timestamp;
process( res, layers, x, y, w, h, rawtile.data );
#ifdef DEBUG
logfile << "OpenJPEG :: getRegion() :: " << timer.getTime() << " microseconds" << endl;
#endif
return rawtile;
} | 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 |
mptctl_readtest (unsigned long arg)
{
struct mpt_ioctl_test __user *uarg = (void __user *) arg;
struct mpt_ioctl_test karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - "
"Unable to read in mpt_ioctl_test struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_readtest() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
#ifdef MFCNT
karg.chip_type = ioc->mfcnt;
#else
karg.chip_type = ioc->pcidev->device;
#endif
strncpy (karg.name, ioc->name, MPT_MAX_NAME);
karg.name[MPT_MAX_NAME-1]='\0';
strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
karg.product[MPT_PRODUCT_LENGTH-1]='\0';
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - "
"Unable to write out mpt_ioctl_test struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
} | 0 | C++ | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | vulnerable |
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned* lengths;
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if (!lengths)
free(tree->lengths);
tree->lengths = lengths;
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
} | 1 | C++ | CWE-401 | Missing Release of Memory after Effective Lifetime | The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
static void php_array_merge_recursive(PointerSet &seen, bool check,
Array &arr1, const Array& arr2) {
if (check) {
if (seen.find((void*)arr1.get()) != seen.end()) {
raise_warning("array_merge_recursive(): recursion detected");
return;
}
seen.insert((void*)arr1.get());
}
for (ArrayIter iter(arr2); iter; ++iter) {
Variant key(iter.first());
const Variant& value(iter.secondRef());
if (key.isNumeric()) {
arr1.appendWithRef(value);
} else if (arr1.exists(key, true)) {
// There is no need to do toKey() conversion, for a key that is already
// in the array.
Variant &v = arr1.lvalAt(key, AccessFlags::Key);
auto subarr1 = v.toArray().copy();
php_array_merge_recursive(seen, v.isReferenced(), subarr1,
value.toArray());
v.unset(); // avoid contamination of the value that was strongly bound
v = subarr1;
} else {
arr1.setWithRef(key, value, true);
}
}
if (check) {
seen.erase((void*)arr1.get());
}
} | 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) {
TFLITE_DCHECK(node->builtin_data != nullptr);
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, data));
if (input->type == kTfLiteFloat32) {
CalculateActivationRange(params->activation, &data->activation_min_f32,
&data->activation_max_f32);
} else if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8) {
CalculateActivationRangeQuantized(context, params->activation, output,
&data->activation_min,
&data->activation_max);
}
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 Relu6Eval(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));
ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data);
switch (input->type) {
case kTfLiteFloat32: {
size_t elements = input->bytes / sizeof(float);
const float* in = GetTensorData<float>(input);
const float* in_end = in + elements;
float* out = GetTensorData<float>(output);
for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f);
return kTfLiteOk;
} break;
case kTfLiteUInt8:
QuantizedReluX<uint8_t>(0.0f, 6.0f, input, output, data);
return kTfLiteOk;
case kTfLiteInt8: {
QuantizedReluX<int8_t>(0.0f, 6.0f, input, output, data);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context,
"Only float32, uint8 and int8 are 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 |
TfLiteStatus LogSoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) {
LogSoftmaxOpData* data = reinterpret_cast<LogSoftmaxOpData*>(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, 0, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.scale, 16.0 / 256);
static const double kBeta = 1.0;
if (input->type == kTfLiteUInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 255);
data->params.table = data->f_table;
optimized_ops::PopulateSoftmaxLookupTable(&data->params,
input->params.scale, kBeta);
data->params.zero_point = output->params.zero_point;
data->params.scale = output->params.scale;
}
if (input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 127);
static const int kScaledDiffIntegerBits = 5;
tflite::PreprocessLogSoftmaxScalingExp(
kBeta, input->params.scale, kScaledDiffIntegerBits,
&data->input_multiplier, &data->input_left_shift,
&data->reverse_scaling_divisor, &data->reverse_scaling_right_shift);
data->reverse_scaling_right_shift *= -1;
data->diff_min =
-1.0 * tflite::CalculateInputRadius(kScaledDiffIntegerBits,
data->input_left_shift);
}
}
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | 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 CalculateOpData(TfLiteContext* context, TfLiteNode* node,
TfLiteMulParams* params, OpData* data) {
const TfLiteTensor* input1 = GetInput(context, node, kInput1Tensor);
TF_LITE_ENSURE(context, input1 != nullptr);
const TfLiteTensor* input2 = GetInput(context, node, kInput2Tensor);
TF_LITE_ENSURE(context, input2 != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) {
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
double real_multiplier = static_cast<double>(input1->params.scale) *
static_cast<double>(input2->params.scale) /
static_cast<double>(output->params.scale);
QuantizeMultiplier(real_multiplier, &data->output_multiplier,
&data->output_shift);
data->input1_zero_point = input1->params.zero_point;
data->input2_zero_point = input2->params.zero_point;
data->output_zero_point = output->params.zero_point;
} else {
CalculateActivationRange(params->activation,
&data->output_activation_min_f32,
&data->output_activation_max_f32);
}
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 |
Status CalculateOutputIndex(OpKernelContext* context, int dimension,
const vector<INDEX_TYPE>& parent_output_index,
INDEX_TYPE output_index_multiplier,
INDEX_TYPE output_size,
vector<INDEX_TYPE>* result) {
const RowPartitionTensor row_partition_tensor =
GetRowPartitionTensor(context, dimension);
auto partition_type = GetRowPartitionTypeByDimension(dimension);
switch (partition_type) {
case RowPartitionType::VALUE_ROWIDS:
CalculateOutputIndexValueRowID(
context, row_partition_tensor, parent_output_index,
output_index_multiplier, output_size, result);
return tensorflow::Status::OK();
case RowPartitionType::ROW_SPLITS:
CalculateOutputIndexRowSplit(
context, row_partition_tensor, parent_output_index,
output_index_multiplier, output_size, result);
return tensorflow::Status::OK();
default:
return errors::InvalidArgument(
"Unsupported partition type:",
RowPartitionTypeToString(partition_type));
}
} | 1 | C++ | CWE-131 | Incorrect Calculation of Buffer Size | The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow. | https://cwe.mitre.org/data/definitions/131.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Check for supported activation types.
auto* params =
reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data);
const TfLiteTensor* filter;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kWeightsTensor, &filter));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const bool is_quantized =
((filter->type == kTfLiteUInt8) || (filter->type == kTfLiteInt8));
const bool is_hybrid = is_quantized && (input->type == kTfLiteFloat32);
const bool is_pie = kernel_type == kLegacyPie;
// Pie and hybrid path supports all kinds of fused activations, otherwise only
// clipping activations are supported.
if (!is_pie && !is_hybrid) {
TF_LITE_ENSURE(context, params->activation == kTfLiteActNone ||
params->activation == kTfLiteActRelu ||
params->activation == kTfLiteActReluN1To1 ||
params->activation == kTfLiteActRelu6);
}
return PrepareImpl(context, node);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,
int c0, int r1, int c1)
{
int i;
if (mat0->data_) {
if (!(mat0->flags_ & JAS_MATRIX_REF)) {
jas_free(mat0->data_);
}
mat0->data_ = 0;
mat0->datasize_ = 0;
}
if (mat0->rows_) {
jas_free(mat0->rows_);
mat0->rows_ = 0;
}
mat0->flags_ |= JAS_MATRIX_REF;
mat0->numrows_ = r1 - r0 + 1;
mat0->numcols_ = c1 - c0 + 1;
mat0->maxrows_ = mat0->numrows_;
if (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {
/*
There is no way to indicate failure to the caller.
So, we have no choice but to abort.
Ideally, this function should have a non-void return type.
In practice, a non-void return type probably would not help
much anyways as the caller would just have to terminate anyways.
*/
abort();
}
for (i = 0; i < mat0->numrows_; ++i) {
mat0->rows_[i] = mat1->rows_[r0 + i] + c0;
}
mat0->xstart_ = mat1->xstart_ + c0;
mat0->ystart_ = mat1->ystart_ + r0;
mat0->xend_ = mat0->xstart_ + mat0->numcols_;
mat0->yend_ = mat0->ystart_ + mat0->numrows_;
} | 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 |
CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
{
size_t origin = parameters.size() > 1 ? 1 : 0;
if (parameters[origin].empty())
{
user->WriteNumeric(ERR_NOORIGIN, "No origin specified");
return CMD_FAILURE;
}
ClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : "");
user->Send(ServerInstance->GetRFCEvents().pong, pong);
return CMD_SUCCESS;
} | 0 | C++ | CWE-732 | Incorrect Permission Assignment for Critical Resource | The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. | https://cwe.mitre.org/data/definitions/732.html | vulnerable |
static inline int min(int a, int b) {return a<b ? a : b;} | 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 Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLitePackParams* data =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
return PackImpl<float>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteUInt8: {
return PackImpl<uint8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt8: {
return PackImpl<int8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt16: {
return PackImpl<int16_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt32: {
return PackImpl<int32_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt64: {
return PackImpl<int64_t>(context, node, output, data->values_count,
data->axis);
}
default: {
context->ReportError(context, "Type '%s' is not supported by pack.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void PrivateThreadPoolDatasetOp::MakeDatasetFromOptions(OpKernelContext* ctx,
DatasetBase* input,
int32_t num_threads,
DatasetBase** output) {
OP_REQUIRES_OK(ctx, ValidateNumThreads(num_threads));
*output = new Dataset(ctx,
DatasetContext(DatasetContext::Params(
{PrivateThreadPoolDatasetOp::kDatasetType,
PrivateThreadPoolDatasetOp::kDatasetOp})),
input, num_threads);
} | 1 | 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 | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
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 == kTfLiteInt16 || input_type == kTfLiteInt32 ||
input_type == kTfLiteInt64 || input_type == kTfLiteInt8);
for (int i = 0; i < NumOutputs(node); ++i) {
GetOutput(context, node, i)->type = input_type;
}
auto size_splits = op_context.size_splits;
TF_LITE_ENSURE_EQ(context, NumDimensions(size_splits), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), NumElements(size_splits));
// If we know the contents of the 'size_splits' tensor and the 'axis' tensor,
// resize all outputs. Otherwise, wait until Eval().
if (IsConstantTensor(op_context.size_splits) &&
IsConstantTensor(op_context.axis)) {
return ResizeOutputTensors(context, node, op_context.input,
op_context.size_splits, op_context.axis);
} 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 |
explicit DataFormatDimMapOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
dst_idx_ = Tensor(DT_INT32, {static_cast<int64>(src_format.size())});
for (int i = 0; i < src_format.size(); ++i) {
for (int j = 0; j < dst_format.size(); ++j) {
if (dst_format[j] == src_format[i]) {
dst_idx_.vec<int>()(i) = j;
break;
}
}
}
} | 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 |
NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,
size_t* pcbAvPairListRemaining)
{
UINT16 id;
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
pAvPair = NULL;
while (pAvPair && ntlm_av_pair_get_id(pAvPair, cbAvPair, &id))
{
if (id == AvId)
break;
if (id == MsvAvEOL)
{
pAvPair = NULL;
break;
}
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
}
if (!pAvPair)
cbAvPair = 0;
if (pcbAvPairListRemaining)
*pcbAvPairListRemaining = cbAvPair;
return pAvPair;
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.