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 |
---|---|---|---|---|---|---|---|
Status CreateTempFileBadString(Env* env, char value, uint64 size,
const string suffix, string* filename) {
const string dir = testing::TmpDir();
*filename = io::JoinPath(dir, strings::StrCat("file_", suffix));
std::unique_ptr<WritableFile> file;
TF_RETURN_IF_ERROR(env->NewWritableFile(*filename, &file));
TF_RETURN_IF_ERROR(file->Append(std::string(size, value)));
TF_RETURN_IF_ERROR(file->Close());
return Status::OK();
} | 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 |
char *uwsgi_expand_path(char *dir, int dir_len, char *ptr) {
char src[PATH_MAX + 1];
memcpy(src, dir, dir_len);
src[dir_len] = 0;
char *dst = ptr;
if (!dst)
dst = uwsgi_malloc(PATH_MAX + 1);
if (!realpath(src, dst)) {
uwsgi_error_realpath(src);
if (!ptr)
free(dst);
return NULL;
}
return dst;
} | 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 |
xmlNodePtr SimpleXMLElement_exportNode(const Object& sxe) {
if (!sxe->instanceof(SimpleXMLElement_classof())) return nullptr;
auto data = Native::data<SimpleXMLElement>(sxe.get());
return php_sxe_get_first_node(data, data->nodep());
} | 1 | C++ | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
FdInStream::FdInStream(int fd_, FdInStreamBlockCallback* blockCallback_,
int bufSize_)
: fd(fd_), timeoutms(0), blockCallback(blockCallback_),
timing(false), timeWaitedIn100us(5), timedKbits(0),
bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
{
ptr = end = start = new U8[bufSize];
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,
int index) {
if (context->tensors != nullptr) {
return &context->tensors[node->outputs->data[index]];
} else {
return context->GetTensor(context, node->outputs->data[index]);
}
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TEST(CudnnRNNOpsTest, ForwardV3Lstm_ShapeFn) {
int max_seq_length = 2;
int batch_size = 3;
int num_units = 4;
int num_layers = 5;
int dir_count = 1;
std::vector<int> input_shape = {max_seq_length, batch_size, num_units};
std::vector<int> input_h_shape = {num_layers * dir_count, batch_size,
num_units};
std::vector<int> input_c_shape = {num_layers * dir_count, batch_size,
num_units};
std::vector<int> output_shape = {max_seq_length, batch_size,
num_units * dir_count};
std::vector<int> seq_lengths_shape = {batch_size};
auto shape_to_str = [](const std::vector<int>& v) {
return strings::StrCat("[", absl::StrJoin(v, ","), "]");
};
string input_shapes_desc = strings::StrCat(
shape_to_str(input_shape), ";", shape_to_str(input_h_shape), ";",
shape_to_str(input_c_shape), ";", "[?]", ";",
shape_to_str(seq_lengths_shape));
string output_shapes_desc = "[d0_0,d0_1,d1_2];in1;in2;?;?";
ShapeInferenceTestOp op("CudnnRNNV3");
TF_ASSERT_OK(NodeDefBuilder("test", "CudnnRNNV3")
.Input({"input", 0, DT_FLOAT})
.Input({"input_h", 0, DT_FLOAT})
.Input({"input_c", 0, DT_FLOAT})
.Input({"params", 0, DT_FLOAT})
.Input({"sequence_lengths", 0, DT_INT32})
.Attr("rnn_mode", "lstm")
.Attr("input_mode", "auto_select")
.Attr("direction", "unidirectional")
.Finalize(&op.node_def));
INFER_OK(op, input_shapes_desc, output_shapes_desc);
INFER_ERROR("Shape must be rank 3 ", op, "[];[?,?,?];[?,?,?];[?];[?]");
INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[];[?,?,?];[?];[?]");
INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[?,?,?];[];[?];[?]");
INFER_ERROR("Shape must be rank 1 ", op, "[?,?,?];[?,?,?];[?,?,?];[];[?]");
INFER_ERROR("Shape must be rank 1 ", op, "[?,?,?];[?,?,?];[?,?,?];[?];[]");
} | 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 CreateNgrams(const tstring* data, tstring* output, int num_ngrams,
int ngram_width) const {
for (int ngram_index = 0; ngram_index < num_ngrams; ++ngram_index) {
int pad_width = get_pad_width(ngram_width);
int left_padding = std::max(0, pad_width - ngram_index);
int right_padding =
std::max(0, pad_width - (num_ngrams - (ngram_index + 1)));
int num_tokens = ngram_width - (left_padding + right_padding);
int data_start_index = left_padding > 0 ? 0 : ngram_index - pad_width;
// Calculate the total expected size of the ngram so we can reserve the
// correct amount of space in the string.
int ngram_size = 0;
// Size of the left padding.
ngram_size += left_padding * left_pad_.length();
// Size of the tokens.
for (int n = 0; n < num_tokens; ++n) {
ngram_size += data[data_start_index + n].length();
}
// Size of the right padding.
ngram_size += right_padding * right_pad_.length();
// Size of the separators.
int num_separators = left_padding + right_padding + num_tokens - 1;
ngram_size += num_separators * separator_.length();
// Build the ngram.
tstring* ngram = &output[ngram_index];
ngram->reserve(ngram_size);
for (int n = 0; n < left_padding; ++n) {
ngram->append(left_pad_);
ngram->append(separator_);
}
for (int n = 0; n < num_tokens - 1; ++n) {
ngram->append(data[data_start_index + n]);
ngram->append(separator_);
}
ngram->append(data[data_start_index + num_tokens - 1]);
for (int n = 0; n < right_padding; ++n) {
ngram->append(separator_);
ngram->append(right_pad_);
}
// In debug mode only: validate that we've reserved enough space for the
// ngram.
DCHECK_EQ(ngram_size, ngram->size());
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus Relu1Eval(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));
const ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data);
switch (input->type) {
case kTfLiteFloat32: {
optimized_ops::Relu1(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output),
GetTensorData<float>(output));
return kTfLiteOk;
} break;
case kTfLiteUInt8: {
QuantizedReluX<uint8_t>(-1.0f, 1.0f, input, output, data);
return kTfLiteOk;
} break;
case kTfLiteInt8: {
QuantizedReluX<int8_t>(-1, 1, input, output, data);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(context,
"Only float32, uint8, int8 supported "
"currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | 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 |
ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen) {
int klinux_flags = TokLinuxRecvSendFlag(flags);
if (klinux_flags == 0 && flags != 0) {
errno = EINVAL;
return -1;
}
MessageWriter input;
input.Push<int>(sockfd);
input.Push<uint64_t>(len);
input.Push<int>(klinux_flags);
MessageReader output;
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kRecvFromHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_recvfrom", 4);
int result = output.next<int>();
int klinux_errno = output.next<int>();
// recvfrom() returns -1 on failure, with errno set to indicate the cause
// of the error.
if (result == -1) {
errno = FromkLinuxErrorNumber(klinux_errno);
return result;
}
auto buffer_received = output.next();
memcpy(buf, buffer_received.data(), len);
// If |src_addr| is not NULL, and the underlying protocol provides the source
// address, this source address is filled in. When |src_addr| is NULL, nothing
// is filled in; in this case, |addrlen| is not used, and should also be NULL.
if (src_addr != nullptr && addrlen != nullptr) {
auto klinux_sockaddr_buf = output.next();
const struct klinux_sockaddr *klinux_addr =
klinux_sockaddr_buf.As<struct klinux_sockaddr>();
FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,
addrlen, TrustedPrimitives::BestEffortAbort);
}
return result;
} | 0 | C++ | CWE-120 | Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') | The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. | https://cwe.mitre.org/data/definitions/120.html | vulnerable |
TfLiteStatus EvalImpl(TfLiteContext* context, const TfLiteTensor* input,
TfLiteNode* node) {
// Map from value, to index in the unique elements vector.
// Note that we prefer to use map than unordered_map as it showed less
// increase in the binary size.
std::map<T, int> unique_values;
TfLiteTensor* output_indexes;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 1, &output_indexes));
std::vector<T> output_values;
I* indexes = GetTensorData<I>(output_indexes);
const T* data = GetTensorData<T>(input);
const int num_elements = NumElements(input);
for (int i = 0; i < num_elements; ++i) {
const auto element_it = unique_values.find(data[i]);
if (element_it != unique_values.end()) {
indexes[i] = element_it->second;
} else {
const int unique_index = unique_values.size();
unique_values[data[i]] = unique_index;
indexes[i] = unique_index;
output_values.push_back(data[i]);
}
}
// Allocate output tensor.
TfLiteTensor* unique_output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &unique_output));
std::unique_ptr<TfLiteIntArray, void (*)(TfLiteIntArray*)> shape(
TfLiteIntArrayCreate(NumDimensions(input)), TfLiteIntArrayFree);
shape->data[0] = unique_values.size();
TF_LITE_ENSURE_STATUS(
context->ResizeTensor(context, unique_output, shape.release()));
// Set the values in the output tensor.
T* output_unique_values = GetTensorData<T>(unique_output);
for (int i = 0; i < output_values.size(); ++i) {
output_unique_values[i] = output_values[i];
}
return kTfLiteOk;
} | 1 | C++ | CWE-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 |
Network::FilterStatus Context::onDownstreamData(int data_length, bool end_of_stream) {
if (!wasm_->onDownstreamData_) {
return Network::FilterStatus::Continue;
}
auto result = wasm_->onDownstreamData_(this, id_, static_cast<uint32_t>(data_length),
static_cast<uint32_t>(end_of_stream));
// TODO(PiotrSikora): pull Proxy-WASM's FilterStatus values.
return result.u64_ == 0 ? Network::FilterStatus::Continue : Network::FilterStatus::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 |
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);
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
bool ConstantFolding::IsSimplifiableReshape(
const NodeDef& node, const GraphProperties& properties) const {
if (!IsReshape(node)) {
return false;
}
CHECK_LE(2, node.input_size());
const NodeDef* new_shape = node_map_->GetNode(node.input(1));
if (!IsReallyConstant(*new_shape)) {
return false;
}
TensorVector outputs;
auto outputs_cleanup = gtl::MakeCleanup([&outputs] {
for (const auto& output : outputs) {
delete output.tensor;
}
});
Status s = EvaluateNode(*new_shape, TensorVector(), &outputs);
if (!s.ok()) {
return false;
}
CHECK_EQ(1, outputs.size());
const std::vector<OpInfo::TensorProperties>& props =
properties.GetInputProperties(node.name());
if (props.empty()) {
return false;
}
const OpInfo::TensorProperties& prop = props[0];
if (prop.dtype() == DT_INVALID) {
return false;
}
const PartialTensorShape shape(prop.shape());
if (!shape.IsFullyDefined()) {
return false;
}
PartialTensorShape new_dims;
if (outputs[0]->dtype() == DT_INT32) {
std::vector<int32> shp;
for (int i = 0; i < outputs[0]->NumElements(); ++i) {
int32_t dim = outputs[0]->flat<int32>()(i);
shp.push_back(dim);
}
TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims));
} else {
std::vector<int64_t> shp;
for (int i = 0; i < outputs[0]->NumElements(); ++i) {
int64_t dim = outputs[0]->flat<int64_t>()(i);
shp.push_back(dim);
}
TF_CHECK_OK(TensorShapeUtils::MakeShape(shp, &new_dims));
}
return shape.IsCompatibleWith(new_dims);
} | 0 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | vulnerable |
void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {
if (is_draining_for_deletion_) {
closeIdleConnectionsForDrainingPool();
}
if (isIdleImpl()) {
ENVOY_LOG(debug, "invoking idle callbacks - is_draining_for_deletion_={}",
is_draining_for_deletion_);
for (const Instance::IdleCb& cb : idle_callbacks_) {
cb();
}
}
} | 0 | 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 | vulnerable |
Http::FilterTrailersStatus Context::onResponseTrailers() {
if (!wasm_->onResponseTrailers_) {
return Http::FilterTrailersStatus::Continue;
}
if (wasm_->onResponseTrailers_(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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);
const TfLiteTensor* segment_ids =
GetInput(context, node, kInputSegmentIdsTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context,
ResizeOutputTensor(context, data, segment_ids, output));
}
#define TF_LITE_SEGMENT_SUM(dtype) \
reference_ops::SegmentSum<dtype>( \
GetTensorShape(data), GetTensorData<dtype>(data), \
GetTensorShape(segment_ids), GetTensorData<int32_t>(segment_ids), \
GetTensorShape(output), GetTensorData<dtype>(output));
switch (data->type) {
case kTfLiteInt32:
TF_LITE_SEGMENT_SUM(int32_t);
break;
case kTfLiteFloat32:
TF_LITE_SEGMENT_SUM(float);
break;
default:
context->ReportError(context,
"Currently SegmentSum doesn't support type: %s",
TfLiteTypeGetName(data->type));
return kTfLiteError;
}
#undef TF_LITE_SEGMENT_SUM
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 |
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-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int em_call(struct x86_emulate_ctxt *ctxt)
{
int rc;
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
rc = jmp_rel(ctxt, rel);
if (rc != X86EMUL_CONTINUE)
return rc;
return em_push(ctxt);
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
CString CWebSock::GetSkinPath(const CString& sSkinName) {
CString sRet = CZNC::Get().GetZNCPath() + "/webskins/" + sSkinName;
if (!CFile::IsDir(sRet)) {
sRet = CZNC::Get().GetCurPath() + "/webskins/" + sSkinName;
if (!CFile::IsDir(sRet)) {
sRet = CString(_SKINDIR_) + "/" + sSkinName;
}
}
return sRet + "/";
} | 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 |
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
FALSE,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
} | 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 |
Pl_AES_PDF::flush(bool strip_padding)
{
assert(this->offset == this->buf_size);
if (first)
{
first = false;
bool return_after_init = false;
if (this->cbc_mode)
{
if (encrypt)
{
// Set cbc_block to the initialization vector, and if
// not zero, write it to the output stream.
initializeVector();
if (! (this->use_zero_iv || this->use_specified_iv))
{
getNext()->write(this->cbc_block, this->buf_size);
}
}
else if (this->use_zero_iv || this->use_specified_iv)
{
// Initialize vector with zeroes; zero vector was not
// written to the beginning of the input file.
initializeVector();
}
else
{
// Take the first block of input as the initialization
// vector. There's nothing to write at this time.
memcpy(this->cbc_block, this->inbuf, this->buf_size);
this->offset = 0;
return_after_init = true;
}
}
this->crypto->rijndael_init(
encrypt, this->key.get(), key_bytes,
this->cbc_mode, this->cbc_block);
if (return_after_init)
{
return;
}
}
if (this->encrypt)
{
this->crypto->rijndael_process(this->inbuf, this->outbuf);
}
else
{
this->crypto->rijndael_process(this->inbuf, this->outbuf);
}
unsigned int bytes = this->buf_size;
if (strip_padding)
{
unsigned char last = this->outbuf[this->buf_size - 1];
if (last <= this->buf_size)
{
bool strip = true;
for (unsigned int i = 1; i <= last; ++i)
{
if (this->outbuf[this->buf_size - i] != last)
{
strip = false;
break;
}
}
if (strip)
{
bytes -= last;
}
}
}
getNext()->write(this->outbuf, bytes);
this->offset = 0;
} | 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 GetIntermediatesSafe(const TfLiteContext* context,
const TfLiteNode* node, int index,
TfLiteTensor** tensor) {
int tensor_index;
TF_LITE_ENSURE_OK(context, ValidateTensorIndexingSafe(
context, index, node->intermediates->size,
node->intermediates->data, &tensor_index));
*tensor = GetTensorAtIndex(context, tensor_index);
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void QuantizeMultiplier(double double_multiplier, int32_t* quantized_multiplier,
int* left_shift) {
if (double_multiplier < 1.0) {
QuantizeMultiplierSmallerThanOneExp(double_multiplier, quantized_multiplier,
left_shift);
} else {
QuantizeMultiplierGreaterThanOne(double_multiplier, quantized_multiplier,
left_shift);
}
} | 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 |
uint64_t HeaderMapImpl::byteSize() const {
uint64_t byte_size = 0;
for (const HeaderEntryImpl& header : headers_) {
byte_size += header.key().size();
byte_size += header.value().size();
}
return byte_size;
} | 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 |
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-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 int mptctl_do_reset(MPT_ADAPTER *iocp, unsigned long arg)
{
struct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;
struct mpt_ioctl_diag_reset krinfo;
if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_reset - "
"Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
__FILE__, __LINE__, urinfo);
return -EFAULT;
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "mptctl_do_reset called.\n",
iocp->name));
if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
printk (MYIOC_s_ERR_FMT "%s@%d::mptctl_do_reset - reset failed.\n",
iocp->name, __FILE__, __LINE__);
return -1;
}
return 0;
} | 1 | 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 | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE(context, NumInputs(node) == 1 || NumInputs(node) == 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Always postpone sizing string tensors, even if we could in principle
// calculate their shapes now. String tensors don't benefit from having their
// shapes precalculated because the actual memory can only be allocated after
// we know all the content.
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (output->type != kTfLiteString) {
if (NumInputs(node) == 1 ||
IsConstantTensor(GetInput(context, node, kShapeTensor))) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
}
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 |
Status OpLevelCostEstimator::PredictAvgPoolGrad(const OpContext& op_context,
NodeCosts* node_costs) const {
bool found_unknown_shapes = false;
const auto& op_info = op_context.op_info;
// x's shape: op_info.inputs(0)
// y_grad: op_info.inputs(1)
// Extract x_shape from op_info.inputs(0).value() or op_info.outputs(0).
bool shape_found = false;
TensorShapeProto x_shape;
if (op_info.inputs_size() >= 1 && op_info.inputs(0).has_value()) {
const TensorProto& value = op_info.inputs(0).value();
shape_found = GetTensorShapeProtoFromTensorProto(value, &x_shape);
}
if (!shape_found && op_info.outputs_size() > 0) {
x_shape = op_info.outputs(0).shape();
shape_found = true;
}
if (!shape_found) {
// Set the minimum shape that's feasible.
x_shape.Clear();
for (int i = 0; i < 4; ++i) {
x_shape.add_dim()->set_size(1);
}
found_unknown_shapes = true;
}
TF_ASSIGN_OR_RETURN(
ConvolutionDimensions dims,
OpDimensionsFromInputs(x_shape, op_info, &found_unknown_shapes));
int64_t ops = 0;
if (dims.kx <= dims.sx && dims.ky <= dims.sy) {
// Non-overlapping window.
ops = dims.batch * dims.iz * (dims.ix * dims.iy + dims.ox * dims.oy);
} else {
// Overlapping window.
ops = dims.batch * dims.iz *
(dims.ix * dims.iy + dims.ox * dims.oy * (dims.kx * dims.ky + 1));
}
auto s = PredictDefaultNodeCosts(ops, op_context, &found_unknown_shapes,
node_costs);
node_costs->max_memory = node_costs->num_total_output_bytes();
return s;
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
void CFontFileType1::DecryptEexec(unsigned char** ppEexecBuffer, int nLen)
{
// Согласно спецификации Type1, первый байт не должен быть ASCII пробелом
// (пробел, таб, перенос каретки или перенос строки).
unsigned char *sCur = (unsigned char*)(*ppEexecBuffer);
while( sCur < (unsigned char*)(*ppEexecBuffer) + nLen && ( ' ' == *sCur || '\t' == *sCur || '\r' == *sCur || '\n' == *sCur ) )
++sCur;
// Теперь нам надо определить в каком формате у нас данные: ASKII или бинарные данные.
// Если первые четыре байта являются шестнадцатиричными символами, значит, кодировка ASCII.
bool bASCII = false;
if ( isxdigit( sCur[0] ) && isxdigit( sCur[1] ) && isxdigit( sCur[2] ) && isxdigit( sCur[3] ) )
bASCII = true;
if ( bASCII )
ASCIIHexDecode( &sCur, sCur + nLen, sCur, nLen );
unsigned short ushKey = 55665U;
EexecDecode( &sCur, *ppEexecBuffer + nLen, sCur, nLen, &ushKey );
} | 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 |
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
if (looks_like_pbl(filename)) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
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 = GetInput(context, node, 0);
TfLiteTensor* out_tensor = GetOutput(context, node, 0);
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;
} | 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 ssize_t _hostsock_recv(
oe_fd_t* sock_,
void* buf,
size_t count,
int flags)
{
ssize_t ret = -1;
sock_t* sock = _cast_sock(sock_);
oe_errno = 0;
if (!sock || (count && !buf))
OE_RAISE_ERRNO(OE_EINVAL);
if (buf)
{
if (oe_memset_s(buf, count, 0, count) != OE_OK)
OE_RAISE_ERRNO(OE_EINVAL);
}
if (oe_syscall_recv_ocall(&ret, sock->host_fd, buf, count, flags) != OE_OK)
OE_RAISE_ERRNO(OE_EINVAL);
done:
return ret;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
CmdResult AddSilence(LocalUser* user, const std::string& mask, uint32_t flags)
{
SilenceList* list = ext.get(user);
if (list && list->size() > maxsilence)
{
user->WriteNumeric(ERR_SILELISTFULL, mask, SilenceEntry::BitsToFlags(flags), "Your silence list is full");
return CMD_FAILURE;
}
else if (!list)
{
// There is no list; create it.
list = new SilenceList();
ext.set(user, list);
}
if (!list->insert(SilenceEntry(flags, mask)).second)
{
user->WriteNumeric(ERR_SILENCE, mask, SilenceEntry::BitsToFlags(flags), "The silence entry you specified already exists");
return CMD_FAILURE;
}
SilenceMessage msg("+" + mask, SilenceEntry::BitsToFlags(flags));
user->Send(msgprov, msg);
return CMD_SUCCESS;
} | 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 ecall_external_sort(uint8_t *sort_order, size_t sort_order_length,
uint8_t *input_rows, size_t input_rows_length,
uint8_t **output_rows, size_t *output_rows_length) {
// Guard against operating on arbitrary enclave memory
assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1);
sgx_lfence();
try {
external_sort(sort_order, sort_order_length,
input_rows, input_rows_length,
output_rows, output_rows_length);
} catch (const std::runtime_error &e) {
ocall_throw(e.what());
}
} | 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) {
const TfLiteUnpackParams* data =
reinterpret_cast<TfLiteUnpackParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
switch (input->type) {
case kTfLiteFloat32: {
UnpackImpl<float>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt32: {
UnpackImpl<int32_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteUInt8: {
UnpackImpl<uint8_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt8: {
UnpackImpl<int8_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteBool: {
UnpackImpl<bool>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt16: {
UnpackImpl<int16_t>(context, node, input, data->num, data->axis);
break;
}
default: {
context->ReportError(context, "Type '%s' is not supported by unpack.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
string gen_dkg_poly(int _t) {
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint32_t enc_len = 0;
vector <uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
sgx_status_t status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
uint64_t length = enc_len;;
vector<char> hexEncrPoly(BUF_LEN, 0);
CHECK_STATE(encrypted_dkg_secret.size() >= length);
carray2Hex(encrypted_dkg_secret.data(), length, hexEncrPoly.data(), BUF_LEN);
string result(hexEncrPoly.data());
return result;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Reinterprete the opaque data provided by user.
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;
switch (type) {
case kTfLiteFloat32:
case kTfLiteInt32:
break;
default:
context->ReportError(context, "Type '%s' is not supported by floor_div.",
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 |
TEST_F(RouterTest, MissingRequiredHeaders) {
NiceMock<Http::MockRequestEncoder> encoder;
Http::ResponseDecoder* response_decoder = nullptr;
expectNewStreamWithImmediateEncoder(encoder, &response_decoder, Http::Protocol::Http10);
expectResponseTimerCreate();
Http::TestRequestHeaderMapImpl headers;
HttpTestUtility::addDefaultHeaders(headers);
headers.removeMethod();
EXPECT_CALL(encoder, encodeHeaders(_, _))
.WillOnce(Invoke([](const Http::RequestHeaderMap& headers, bool) -> Http::Status {
return Http::HeaderUtility::checkRequiredRequestHeaders(headers);
}));
EXPECT_CALL(
callbacks_,
sendLocalReply(Http::Code::ServiceUnavailable,
testing::Eq("missing required header: :method"), _, _,
"filter_removed_required_request_headers{missing_required_header:_:method}"))
.WillOnce(testing::InvokeWithoutArgs([] {}));
router_.decodeHeaders(headers, true);
router_.onDestroy();
} | 0 | C++ | CWE-670 | Always-Incorrect Control Flow Implementation | The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated. | https://cwe.mitre.org/data/definitions/670.html | vulnerable |
inline typename V::VariantType FBUnserializer<V>::unserialize(
folly::StringPiece serialized) {
FBUnserializer<V> unserializer(serialized);
return unserializer.unserializeThing();
} | 0 | 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 | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteMulParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const bool requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||
output->type == kTfLiteInt16) {
TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized(
context, params->activation, output, &data->output_activation_min,
&data->output_activation_max));
double real_multiplier =
input1->params.scale * input2->params.scale / output->params.scale;
QuantizeMultiplier(real_multiplier, &data->output_multiplier,
&data->output_shift);
}
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 |
TypedValue HHVM_FUNCTION(substr_compare,
const String& main_str,
const String& str,
int offset,
int length /* = INT_MAX */,
bool case_insensitivity /* = false */) {
int s1_len = main_str.size();
int s2_len = str.size();
if (length <= 0) {
raise_warning("The length must be greater than zero");
return make_tv<KindOfBoolean>(false);
}
if (offset < 0) {
offset = s1_len + offset;
if (offset < 0) offset = 0;
}
if (offset >= s1_len) {
raise_warning("The start position cannot exceed initial string length");
return make_tv<KindOfBoolean>(false);
}
int cmp_len = s1_len - offset;
if (cmp_len < s2_len) cmp_len = s2_len;
if (cmp_len > length) cmp_len = length;
const char *s1 = main_str.data();
if (case_insensitivity) {
return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len));
}
return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_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 |
TEST(DefaultCertValidatorTest, TestMatchSubjectAltNameNotMatched) {
bssl::UniquePtr<X509> cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_dns_cert.pem"));
envoy::type::matcher::v3::StringMatcher matcher;
matcher.MergeFrom(TestUtility::createRegexMatcher(".*.foo.com"));
std::vector<Matchers::StringMatcherImpl<envoy::type::matcher::v3::StringMatcher>>
subject_alt_name_matchers;
subject_alt_name_matchers.push_back(Matchers::StringMatcherImpl(matcher));
EXPECT_FALSE(DefaultCertValidator::matchSubjectAltName(cert.get(), subject_alt_name_matchers));
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
size_t jsuGetFreeStack() {
#ifdef ARM
void *frame = __builtin_frame_address(0);
size_t stackPos = (size_t)((char*)frame);
size_t stackEnd = (size_t)((char*)&LINKER_END_VAR);
if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow!
return stackPos - stackEnd;
#elif defined(LINUX)
// On linux, we set STACK_BASE from `main`.
char ptr; // this is on the stack
extern void *STACK_BASE;
uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr);
return 1000000 - count; // give it 1 megabyte of stack
#else
// stack depth seems pretty platform-specific :( Default to a value that disables it
return 1000000; // no stack depth check on this platform
#endif
} | 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;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,
&input_resource_id_tensor));
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;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputValue, &output));
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;
} | 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 |
check_owner_password_V4(std::string& user_password,
std::string const& owner_password,
QPDF::EncryptionData const& data)
{
// Algorithm 3.7 from the PDF 1.7 Reference Manual
unsigned char key[OU_key_bytes_V4];
compute_O_rc4_key(user_password, owner_password, data, key);
unsigned char O_data[key_bytes];
memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);
std::string k1(reinterpret_cast<char*>(key), OU_key_bytes_V4);
pad_short_parameter(k1, data.getLengthBytes());
iterate_rc4(O_data, key_bytes, QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(),
(data.getR() >= 3) ? 20 : 1, true);
std::string new_user_password =
std::string(reinterpret_cast<char*>(O_data), key_bytes);
bool result = false;
if (check_user_password(new_user_password, data))
{
result = true;
user_password = new_user_password;
}
return result;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_rti_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 offset = 0;
if (buf_offset + 32 >= sz) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_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;
} | 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 TestJlCompress::extractDir_data()
{
QTest::addColumn<QString>("zipName");
QTest::addColumn<QStringList>("fileNames");
QTest::addColumn<QStringList>("expectedExtracted");
QTest::newRow("simple") << "jlextdir.zip"
<< (QStringList() << "test0.txt" << "testdir1/test1.txt"
<< "testdir2/test2.txt" << "testdir2/subdir/test2sub.txt")
<< (QStringList() << "test0.txt" << "testdir1/test1.txt"
<< "testdir2/test2.txt" << "testdir2/subdir/test2sub.txt");
QTest::newRow("separate dir") << "sepdir.zip"
<< (QStringList() << "laj/" << "laj/lajfile.txt")
<< (QStringList() << "laj/" << "laj/lajfile.txt");
QTest::newRow("Zip Slip") << "zipslip.zip"
<< (QStringList() << "test0.txt" << "../zipslip.txt")
<< (QStringList() << "test0.txt");
} | 1 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
CAMLprim value caml_bitvect_test(value bv, value n)
{
int pos = Int_val(n);
return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));
} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
static UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
rdpPrintJob* printjob = NULL;
UINT error = CHANNEL_RC_OK;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
Stream_Seek(irp->input, 20); /* Padding */
if (printer_dev->printer)
printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);
if (!printjob)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
}
else
{
error = printjob->Write(printjob, Stream_Pointer(irp->input), Length);
}
if (error)
{
WLog_ERR(TAG, "printjob->Write failed with error %" PRIu32 "!", error);
return error;
}
Stream_Write_UINT32(irp->output, Length);
Stream_Write_UINT8(irp->output, 0); /* Padding */
return irp->Complete(irp);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
ruy::profiler::ScopeLabel label("SquaredDifference");
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (output->type == kTfLiteFloat32) {
EvalSquaredDifference<float>(context, node, data, input1, input2, output);
} else if (output->type == kTfLiteInt32) {
EvalSquaredDifference<int32_t>(context, node, data, input1, input2, output);
} else {
context->ReportError(
context,
"SquaredDifference only supports FLOAT32 and INT32 now, got %d.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-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) {
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* diag;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kDiagonalTensor, &diag));
FillDiagHelper(input, diag, 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 |
int CephxSessionHandler::_calc_signature(Message *m, uint64_t *psig)
{
const ceph_msg_header& header = m->get_header();
const ceph_msg_footer& footer = m->get_footer();
// optimized signature calculation
// - avoid temporary allocated buffers from encode_encrypt[_enc_bl]
// - skip the leading 4 byte wrapper from encode_encrypt
struct {
__u8 v;
__le64 magic;
__le32 len;
__le32 header_crc;
__le32 front_crc;
__le32 middle_crc;
__le32 data_crc;
} __attribute__ ((packed)) sigblock = {
1, mswab(AUTH_ENC_MAGIC), mswab<uint32_t>(4*4),
mswab<uint32_t>(header.crc), mswab<uint32_t>(footer.front_crc),
mswab<uint32_t>(footer.middle_crc), mswab<uint32_t>(footer.data_crc)
};
char exp_buf[CryptoKey::get_max_outbuf_size(sizeof(sigblock))];
try {
const CryptoKey::in_slice_t in {
sizeof(sigblock),
reinterpret_cast<const unsigned char*>(&sigblock)
};
const CryptoKey::out_slice_t out {
sizeof(exp_buf),
reinterpret_cast<unsigned char*>(&exp_buf)
};
key.encrypt(cct, in, out);
} catch (std::exception& e) {
lderr(cct) << __func__ << " failed to encrypt signature block" << dendl;
return -1;
}
*psig = *reinterpret_cast<__le64*>(exp_buf);
ldout(cct, 10) << __func__ << " seq " << m->get_seq()
<< " front_crc_ = " << footer.front_crc
<< " middle_crc = " << footer.middle_crc
<< " data_crc = " << footer.data_crc
<< " sig = " << *psig
<< dendl;
return 0;
} | 0 | C++ | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
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 = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
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));
} | 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 ecall_project(uint8_t *condition, size_t condition_length,
uint8_t *input_rows, size_t input_rows_length,
uint8_t **output_rows, size_t *output_rows_length) {
// Guard against operating on arbitrary enclave memory
assert(sgx_is_outside_enclave(input_rows, input_rows_length) == 1);
sgx_lfence();
try {
project(condition, condition_length,
input_rows, input_rows_length,
output_rows, output_rows_length);
} catch (const std::runtime_error &e) {
ocall_throw(e.what());
}
} | 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 onComplete(const Status& status, ContextImpl& context) const override {
auto& completion_state = context.getCompletionState(this);
if (completion_state.is_completed_) {
return;
}
// If any of children is OK, return OK
if (Status::Ok == status) {
completion_state.is_completed_ = true;
completeWithStatus(status, context);
return;
}
// Then wait for all children to be done.
if (++completion_state.number_completed_children_ == verifiers_.size()) {
// Aggregate all children status into a final status.
// JwtMissing should be treated differently than other failure status
// since it simply means there is not Jwt token for the required provider.
// If there is a failure status other than JwtMissing in the children,
// it should be used as the final status.
Status final_status = Status::JwtMissed;
for (const auto& it : verifiers_) {
// If a Jwt is extracted from a location not specified by the required provider,
// the authenticator returns JwtUnknownIssuer. It should be treated the same as
// JwtMissed.
Status child_status = context.getCompletionState(it.get()).status_;
if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) {
final_status = child_status;
}
}
if (is_allow_missing_or_failed_) {
final_status = Status::Ok;
} else if (is_allow_missing_ && final_status == Status::JwtMissed) {
final_status = Status::Ok;
}
completion_state.is_completed_ = true;
completeWithStatus(final_status, context);
}
} | 0 | C++ | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
TypedValue HHVM_FUNCTION(substr_compare,
const String& main_str,
const String& str,
int offset,
int length /* = INT_MAX */,
bool case_insensitivity /* = false */) {
int s1_len = main_str.size();
int s2_len = str.size();
if (length <= 0) {
raise_warning("The length must be greater than zero");
return make_tv<KindOfBoolean>(false);
}
if (offset < 0) {
offset = s1_len + offset;
if (offset < 0) offset = 0;
}
if (offset >= s1_len) {
raise_warning("The start position cannot exceed initial string length");
return make_tv<KindOfBoolean>(false);
}
int cmp_len = s1_len - offset;
if (cmp_len < s2_len) cmp_len = s2_len;
if (cmp_len > length) cmp_len = length;
const char *s1 = main_str.data();
if (case_insensitivity) {
return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len));
}
return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_len));
} | 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 |
int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)
{
CNetChunk Packet;
if(!pMsg)
return -1;
// drop packet to dummy client
if(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID))
return 0;
mem_zero(&Packet, sizeof(CNetChunk));
Packet.m_ClientID = ClientID;
Packet.m_pData = pMsg->Data();
Packet.m_DataSize = pMsg->Size();
if(Flags&MSGFLAG_VITAL)
Packet.m_Flags |= NETSENDFLAG_VITAL;
if(Flags&MSGFLAG_FLUSH)
Packet.m_Flags |= NETSENDFLAG_FLUSH;
// write message to demo recorder
if(!(Flags&MSGFLAG_NORECORD))
m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());
if(!(Flags&MSGFLAG_NOSEND))
{
if(ClientID == -1)
{
// broadcast
int i;
for(i = 0; i < MAX_CLIENTS; i++)
if(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)
{
Packet.m_ClientID = i;
m_NetServer.Send(&Packet);
}
}
else
m_NetServer.Send(&Packet);
}
return 0;
} | 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 |
unique_ptr<IOBuf> IOBuf::create(std::size_t capacity) {
if (capacity > kMaxIOBufSize) {
throw_exception<std::bad_alloc>();
}
// For smaller-sized buffers, allocate the IOBuf, SharedInfo, and the buffer
// all with a single allocation.
//
// We don't do this for larger buffers since it can be wasteful if the user
// needs to reallocate the buffer but keeps using the same IOBuf object.
// In this case we can't free the data space until the IOBuf is also
// destroyed. Callers can explicitly call createCombined() or
// createSeparate() if they know their use case better, and know if they are
// likely to reallocate the buffer later.
if (capacity <= kDefaultCombinedBufSize) {
return createCombined(capacity);
}
// if we have nallocx, we want to allocate the capacity and the overhead in
// a single allocation only if we do not cross into the next allocation class
// for some buffer sizes, this can use about 25% extra memory
if (canNallocx()) {
auto mallocSize = goodMallocSize(capacity);
// round capacity to a multiple of 8
size_t minSize = ((capacity + 7) & ~7) + sizeof(SharedInfo);
// if we do not have space for the overhead, allocate the mem separateley
if (mallocSize < minSize) {
auto* buf = checkedMalloc(mallocSize);
return takeOwnership(SIZED_FREE, buf, mallocSize, 0, 0);
}
}
return createSeparate(capacity);
} | 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 int mptctl_do_reset(unsigned long arg)
{
struct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;
struct mpt_ioctl_diag_reset krinfo;
MPT_ADAPTER *iocp;
if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_reset - "
"Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
__FILE__, __LINE__, urinfo);
return -EFAULT;
}
if (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {
printk(KERN_DEBUG MYNAM "%s@%d::mptctl_do_reset - ioc%d not found!\n",
__FILE__, __LINE__, krinfo.hdr.iocnum);
return -ENODEV; /* (-6) No such device or address */
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "mptctl_do_reset called.\n",
iocp->name));
if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
printk (MYIOC_s_ERR_FMT "%s@%d::mptctl_do_reset - reset failed.\n",
iocp->name, __FILE__, __LINE__);
return -1;
}
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 |
TfLiteStatus LogicalImpl(TfLiteContext* context, TfLiteNode* node,
bool (*func)(bool, bool)) {
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 (data->requires_broadcast) {
reference_ops::BroadcastBinaryFunction4DSlow<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
} else {
reference_ops::BinaryFunction<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
static 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());
}
} | 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 |
Status GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx,
TensorHandle* tensor_handle, Device** result) {
Device* cpu_device = ctx.HostCPU();
string device_name;
if (tensor_handle->Type() != TensorHandle::LOCAL) {
Device* device = tensor_handle->device();
device_name = device != nullptr ? device->name() : cpu_device->name();
*result = (device == nullptr ? cpu_device : device);
} else if (tensor_handle->dtype == DT_RESOURCE) {
// Use the resource's actual device because it is the device that will
// influence partitioning the multi-device function.
const Tensor* tensor;
// TODO(fishx): Avoid blocking here.
TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));
if (tensor->NumElements() == 0) {
return errors::InvalidArgument("Empty resource handle");
}
const ResourceHandle& handle = tensor->flat<ResourceHandle>()(0);
device_name = handle.device();
Device* input_device;
TF_RETURN_IF_ERROR(
ctx.FindDeviceFromName(device_name.c_str(), &input_device));
*result = input_device;
} else {
Device* device = tensor_handle->device();
const bool is_tpu = device != nullptr && device->device_type() == "TPU";
// int32 return values can be placed on TPUs.
const bool use_host_memory =
is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)
: MTypeFromDType(tensor_handle->dtype);
if (use_host_memory) {
*result = cpu_device;
} else {
// Eager ops executing as functions should have their preferred inputs set
// to the op's device. This allows us to avoid expensive D2H copies if a
// mirror of the tensor already exists on the op's device.
if (!op.is_function() && device != nullptr && device != cpu_device) {
device = absl::get<Device*>(op.Device());
}
*result = (device == nullptr ? cpu_device : device);
}
}
return Status::OK();
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
static int em_sysexit(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data, rcx, rdx;
int usermode;
u16 cs_sel = 0, ss_sel = 0;
/* inject #GP if in real mode or Virtual 8086 mode */
if (ctxt->mode == X86EMUL_MODE_REAL ||
ctxt->mode == X86EMUL_MODE_VM86)
return emulate_gp(ctxt, 0);
setup_syscalls_segments(ctxt, &cs, &ss);
if ((ctxt->rex_prefix & 0x8) != 0x0)
usermode = X86EMUL_MODE_PROT64;
else
usermode = X86EMUL_MODE_PROT32;
rcx = reg_read(ctxt, VCPU_REGS_RCX);
rdx = reg_read(ctxt, VCPU_REGS_RDX);
cs.dpl = 3;
ss.dpl = 3;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
switch (usermode) {
case X86EMUL_MODE_PROT32:
cs_sel = (u16)(msr_data + 16);
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = (u16)(msr_data + 24);
break;
case X86EMUL_MODE_PROT64:
cs_sel = (u16)(msr_data + 32);
if (msr_data == 0x0)
return emulate_gp(ctxt, 0);
ss_sel = cs_sel + 8;
cs.d = 0;
cs.l = 1;
if (is_noncanonical_address(rcx) ||
is_noncanonical_address(rdx))
return emulate_gp(ctxt, 0);
break;
}
cs_sel |= SELECTOR_RPL_MASK;
ss_sel |= SELECTOR_RPL_MASK;
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ctxt->_eip = rdx;
*reg_write(ctxt, VCPU_REGS_RSP) = rcx;
return X86EMUL_CONTINUE;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
OpLevelCostEstimator::OpDimensionsFromInputs(
const TensorShapeProto& original_image_shape, const OpInfo& op_info,
bool* found_unknown_shapes) {
VLOG(2) << "op features: " << op_info.DebugString();
VLOG(2) << "Original image shape: " << original_image_shape.DebugString();
auto image_shape =
MaybeGetMinimumShape(original_image_shape, 4, found_unknown_shapes);
VLOG(2) << "Image shape: " << image_shape.DebugString();
int x_index, y_index, channel_index;
const std::string& data_format = GetDataFormat(op_info);
if (data_format == "NCHW") {
channel_index = 1;
y_index = 2;
x_index = 3;
} else {
y_index = 1;
x_index = 2;
channel_index = 3;
}
int64_t batch = image_shape.dim(0).size();
int64_t ix = image_shape.dim(x_index).size();
int64_t iy = image_shape.dim(y_index).size();
int64_t iz = image_shape.dim(channel_index).size();
// Note that FusedBatchNorm doesn't have ksize attr, but GetKernelSize returns
// {1, 1, 1, 1} in that case.
std::vector<int64_t> ksize = GetKernelSize(op_info);
int64_t kx = ksize[x_index];
int64_t ky = ksize[y_index];
// These ops don't support groupwise operation, therefore kz == iz.
int64_t kz = iz;
std::vector<int64_t> strides = GetStrides(op_info);
int64_t sx = strides[x_index];
int64_t sy = strides[y_index];
if (sx == 0 || sy == 0) {
return errors::InvalidArgument(
"Stride must be > 0 for Height and Width, but got (", sy, ", ", sx,
")");
}
const auto padding = GetPadding(op_info);
int64_t ox = GetOutputSize(ix, kx, sx, padding);
int64_t oy = GetOutputSize(iy, ky, sy, padding);
int64_t oz = iz;
OpLevelCostEstimator::ConvolutionDimensions conv_dims = {
batch, ix, iy, iz, kx, ky, kz, oz, ox, oy, sx, sy, padding};
return conv_dims;
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
TfLiteStatus GreaterEqualEval(TfLiteContext* context, TfLiteNode* node) {
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));
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteFloat32:
Comparison<float, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
default:
context->ReportError(context,
"Does not support type %d, requires float|int|uint8",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 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 CalculateArithmeticOpData(TfLiteContext* context, TfLiteNode* node,
OpData* 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_TYPES_EQ(context, input->type, output->type);
if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) {
static constexpr int kInputIntegerBits = 4;
const double input_real_multiplier =
static_cast<double>(input->params.scale) *
static_cast<double>(1 << (31 - kInputIntegerBits));
const double q = std::frexp(input_real_multiplier, &data->input_left_shift);
data->input_multiplier = static_cast<int32_t>(TfLiteRound(q * (1ll << 31)));
data->input_range_radius =
CalculateInputRadius(kInputIntegerBits, data->input_left_shift, 31);
}
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 MutateSavedTensorSlices(
const std::string& fname,
const std::function<std::string(SavedTensorSlices)>& mutator) {
table::Options options;
options.compression = table::kNoCompression;
// Read all entres from the table.
std::vector<std::pair<std::string, std::string>> entries;
{
std::unique_ptr<RandomAccessFile> file;
TF_CHECK_OK(Env::Default()->NewRandomAccessFile(fname, &file));
uint64 file_size;
TF_CHECK_OK(Env::Default()->GetFileSize(fname, &file_size));
table::Table* t;
TF_CHECK_OK(table::Table::Open(options, file.get(), file_size, &t));
std::unique_ptr<table::Table> table(t);
std::unique_ptr<table::Iterator> it(table->NewIterator());
for (it->Seek(""); it->Valid(); it->Next()) {
entries.emplace_back(it->key(), it->value());
}
TF_CHECK_OK(it->status());
}
// Rewrite the table, mutating each value.
{
std::unique_ptr<WritableFile> file;
TF_CHECK_OK(Env::Default()->NewWritableFile(fname, &file));
table::TableBuilder builder(options, file.get());
for (const auto& entry : entries) {
SavedTensorSlices sts;
CHECK(sts.ParseFromString(entry.second));
builder.Add(entry.first, mutator(std::move(sts)));
}
TF_CHECK_OK(builder.Finish());
TF_CHECK_OK(file->Close());
}
} | 1 | C++ | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
int pnm_validate(jas_stream_t *in)
{
jas_uchar buf[2];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, buf, 2)) < 0) {
return -1;
}
/* Put these characters back to the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < 2) {
return -1;
}
/* Is this the correct signature for a PNM file? */
if (buf[0] == 'P' && isdigit(buf[1])) {
return 0;
}
return -1;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
static uint8_t *extend_raw_data(LHAFileHeader **header,
LHAInputStream *stream,
size_t nbytes)
{
LHAFileHeader *new_header;
size_t new_raw_len;
uint8_t *result;
if (nbytes > LEVEL_3_MAX_HEADER_LEN) {
return NULL;
}
// Reallocate the header and raw_data area to be larger.
new_raw_len = RAW_DATA_LEN(header) + nbytes;
new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len);
if (new_header == NULL) {
return NULL;
}
// Update the header pointer to point to the new area.
*header = new_header;
new_header->raw_data = (uint8_t *) (new_header + 1);
result = new_header->raw_data + new_header->raw_data_len;
// Read data from stream into new area.
if (!lha_input_stream_read(stream, result, nbytes)) {
return NULL;
}
new_header->raw_data_len = new_raw_len;
return result;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
void Rectangle(double x,double y,double w,double h) {
outpos += sprintf(outpos,"\n %12.3f %12.3f %12.3f %12.3f re",x,y,w,h);
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
String StringUtil::Crypt(const String& input, const char *salt /* = "" */) {
assertx(salt);
if (salt[0] == '\0') {
raise_notice("crypt(): No salt parameter was specified."
" You must use a randomly generated salt and a strong"
" hash function to produce a secure hash.");
}
return String(string_crypt(input.c_str(), salt), AttachString);
} | 1 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (sz < 8) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = 6;
return attr;
} | 1 | C++ | CWE-788 | Access of Memory Location After End of Buffer | The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer. | https://cwe.mitre.org/data/definitions/788.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* data =
reinterpret_cast<TfLiteAudioMicrofrontendParams*>(node->user_data);
FrontendReset(data->state);
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 (data->out_float) {
GenerateFeatures<float>(data, input, output);
} else {
GenerateFeatures<int32>(data, input, output);
}
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 |
int firstBitSet(int x)
{
int position=0;
while (x!=0)
{
x>>=1;
++position;
}
return position;
} | 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 |
virtual void requestInit() {
m_use_error = false;
m_errors.reset();
xmlParserInputBufferCreateFilenameDefault(nullptr);
} | 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* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) {
const Tensor* tensor = GetTensorFromHandle(h, status);
TF_DataType data_type = static_cast<TF_DataType>(tensor->dtype());
TensorReference tensor_ref(*tensor); // This will call buf_->Ref()
auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref);
tf_dlm_tensor_ctx->reference = tensor_ref;
DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor;
dlm_tensor->manager_ctx = tf_dlm_tensor_ctx;
dlm_tensor->deleter = &DLManagedTensorDeleter;
dlm_tensor->dl_tensor.ctx = GetDlContext(h, status);
int ndim = tensor->dims();
dlm_tensor->dl_tensor.ndim = ndim;
dlm_tensor->dl_tensor.data = TFE_TensorHandleDevicePointer(h, status);
dlm_tensor->dl_tensor.dtype = GetDlDataType(data_type, status);
std::vector<int64_t>* shape_arr = &tf_dlm_tensor_ctx->shape;
std::vector<int64_t>* stride_arr = &tf_dlm_tensor_ctx->strides;
shape_arr->resize(ndim);
stride_arr->resize(ndim, 1);
for (int i = 0; i < ndim; i++) {
(*shape_arr)[i] = tensor->dim_size(i);
}
for (int i = ndim - 2; i >= 0; --i) {
(*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1];
}
dlm_tensor->dl_tensor.shape = &(*shape_arr)[0];
// There are two ways to represent compact row-major data
// 1) nullptr indicates tensor is compact and row-majored.
// 2) fill in the strides array as the real case for compact row-major data.
// Here we choose option 2, since some frameworks didn't handle the strides
// argument properly.
dlm_tensor->dl_tensor.strides = &(*stride_arr)[0];
dlm_tensor->dl_tensor.byte_offset =
0; // TF doesn't handle the strides and byte_offsets here
return static_cast<void*>(dlm_tensor);
} | 0 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | vulnerable |
TestCertificateValidationContextConfig(
envoy::config::core::v3::TypedExtensionConfig config, bool allow_expired_certificate = false,
std::vector<envoy::type::matcher::v3::StringMatcher> san_matchers = {})
: allow_expired_certificate_(allow_expired_certificate), api_(Api::createApiForTest()),
custom_validator_config_(config), san_matchers_(san_matchers){}; | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
inline void ComputeInterpolationWeights(
const int64 out_size, const int64 in_size, const float scale,
const int resolution, InterpolationCache<T_SCALE>* interpolation) {
const Scaler scaler;
interpolation->lower.resize(out_size + 1);
interpolation->upper.resize(out_size + 1);
interpolation->lerp.resize(out_size + 1);
interpolation->ilerp.resize(out_size + 1);
interpolation->lower[out_size] = 0;
interpolation->upper[out_size] = 0;
for (int64 i = out_size - 1; i >= 0; --i) {
const float in = scaler(i, scale);
const float in_f = std::floor(in);
interpolation->lower[i] =
std::max(static_cast<int64>(in_f), static_cast<int64>(0));
interpolation->upper[i] =
std::min(static_cast<int64>(std::ceil(in)), in_size - 1);
interpolation->lower[i] =
std::min(interpolation->lower[i], interpolation->upper[i]);
interpolation->lerp[i] = in - in_f;
interpolation->ilerp[i] =
static_cast<T_SCALE>((in - in_f) * (1 << resolution));
}
} | 1 | C++ | CWE-193 | Off-by-one Error | A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value. | https://cwe.mitre.org/data/definitions/193.html | safe |
ZlibInStream::ZlibInStream(int bufSize_)
: underlying(0), bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0),
zs(NULL), bytesIn(0)
{
ptr = end = start = new U8[bufSize];
init();
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
if (rc != X86EMUL_CONTINUE)
return rc;
if (fx_state.mxcsr >> 16)
return emulate_gp(ctxt, 0);
ctxt->ops->get_fpu(ctxt);
if (ctxt->mode < X86EMUL_MODE_PROT64)
rc = fxrstor_fixup(ctxt, &fx_state);
if (rc == X86EMUL_CONTINUE)
rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
ctxt->ops->put_fpu(ctxt);
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 Eval(TfLiteContext* context, TfLiteNode* node) {
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);
switch (input1->type) {
case kTfLiteInt32: {
return EvalImpl<int32_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteFloat32: {
return EvalImpl<float>(context, data->requires_broadcast, input1, input2,
output);
}
default: {
context->ReportError(context, "Type '%s' is not supported by floor_div.",
TfLiteTypeGetName(input1->type));
return kTfLiteError;
}
}
} | 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 |
R_API RBinJavaVerificationObj *r_bin_java_read_from_buffer_verification_info_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (sz < 8) {
return NULL;
}
ut64 offset = 0;
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (!se) {
return NULL;
}
se->file_offset = buf_offset;
se->tag = buffer[offset];
offset += 1;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
se->info.uninit_offset = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
}
if (R_BIN_JAVA_STACKMAP_UNINIT < se->tag) {
r_bin_java_verification_info_free (se);
return NULL;
}
se->size = offset;
return se;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const Details &d)
: FsDevice(m, d.name, createUdi(d.name))
, mountToken(0)
, currentMountStatus(false)
, details(d)
, proc(0)
, mounterIface(0)
, messageSent(false)
{
// details.path=Utils::fixPath(details.path);
setup();
icn=MonoIcon::icon(details.isLocalFile()
? FontAwesome::foldero
: constSshfsProtocol==details.url.scheme()
? FontAwesome::linux_os
: FontAwesome::windows, Utils::monoIconColor());
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static bool php_mb_parse_encoding(const Variant& encoding,
mbfl_encoding ***return_list,
int *return_size, bool persistent) {
bool ret;
if (encoding.isArray()) {
ret = php_mb_parse_encoding_array(encoding.toArray(),
return_list, return_size,
persistent ? 1 : 0);
} else {
String enc = encoding.toString();
ret = php_mb_parse_encoding_list(enc.data(), enc.size(),
return_list, return_size,
persistent ? 1 : 0);
}
if (!ret) {
if (return_list && *return_list) {
free(*return_list);
*return_list = nullptr;
}
return_size = 0;
}
return ret;
} | 0 | C++ | CWE-763 | Release of Invalid Pointer or Reference | The application attempts to return a memory resource to the system, but calls the wrong release function or calls the appropriate release function incorrectly. | https://cwe.mitre.org/data/definitions/763.html | vulnerable |
void RemoteFsDevice::serviceAdded(const QString &name)
{
if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {
sub=tr("Available");
updateStatus();
}
} | 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 |
TEST_F(GroupVerifierTest, TestRequiresAnyWithAllowMissingButOk) {
TestUtility::loadFromYaml(RequiresAnyConfig, proto_config_);
proto_config_.mutable_rules(0)
->mutable_requires()
->mutable_requires_any()
->add_requirements()
->mutable_allow_missing();
createAsyncMockAuthsAndVerifier(std::vector<std::string>{"example_provider", "other_provider"});
EXPECT_CALL(mock_cb_, onComplete(Status::Ok));
auto headers = Http::TestRequestHeaderMapImpl{};
context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);
verifier_->verify(context_);
callbacks_["example_provider"](Status::JwtMissed);
callbacks_["other_provider"](Status::JwtUnknownIssuer);
} | 0 | C++ | CWE-303 | Incorrect Implementation of Authentication Algorithm | The requirements for the software dictate the use of an established authentication algorithm, but the implementation of the algorithm is incorrect. | https://cwe.mitre.org/data/definitions/303.html | vulnerable |
Status SparseReduceShapeFn(InferenceContext* c) {
// Input 0: input_indices
// Input 1: input_values
// Input 2: input_shape
// Input 3: reduction_axes
// Attr: keep_dims
bool keep_dims = false;
TF_RETURN_IF_ERROR(c->GetAttr("keep_dims", &keep_dims));
const Tensor* shape_tensor = c->input_tensor(2);
const Tensor* axes_tensor = c->input_tensor(3);
if (shape_tensor != nullptr && axes_tensor != nullptr) {
auto shape_vec = shape_tensor->flat<int64>();
auto axes_vec = axes_tensor->flat<int32>();
int64_t ndims = shape_vec.size();
absl::flat_hash_set<int64> axes;
if (ndims == 0)
return errors::InvalidArgument(
"Number of dims in shape tensor must not be 0");
for (int i = 0; i < axes_vec.size(); i++) {
axes.insert((axes_vec(i) + ndims) % ndims);
}
std::vector<DimensionHandle> dims;
if (keep_dims) {
dims.reserve(ndims);
for (int d = 0; d < ndims; ++d) {
if (axes.find(d) == axes.end()) {
dims.push_back(c->MakeDim(shape_vec(d)));
} else {
dims.push_back(c->MakeDim(1));
}
}
} else {
for (int d = 0; d < ndims; ++d) {
if (axes.find(d) == axes.end()) {
dims.push_back(c->MakeDim(shape_vec(d)));
}
}
}
c->set_output(0, c->MakeShape(dims));
return Status::OK();
}
return UnknownShape(c);
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const DeviceOptions &options, const Details &d)
: FsDevice(m, d.name, createUdi(d.name))
, mountToken(0)
, currentMountStatus(false)
, details(d)
, proc(0)
, mounterIface(0)
, messageSent(false)
{
opts=options;
// details.path=Utils::fixPath(details.path);
load();
mount();
icn=MonoIcon::icon(details.isLocalFile()
? FontAwesome::foldero
: constSshfsProtocol==details.url.scheme()
? FontAwesome::linux_os
: FontAwesome::windows, Utils::monoIconColor());
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
void RemoteFsDevice::load()
{
if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {
// Start Avahi listener...
Avahi::self();
QUrlQuery q(details.url);
if (q.hasQueryItem(constServiceNameQuery)) {
details.serviceName=q.queryItemValue(constServiceNameQuery);
}
if (!details.serviceName.isEmpty()) {
AvahiService *srv=Avahi::self()->getService(details.serviceName);
if (!srv || srv->getHost().isEmpty()) {
sub=tr("Not Available");
} else {
sub=tr("Available");
}
}
connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));
connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));
}
if (isConnected()) {
setAudioFolder();
readOpts(settingsFileName(), opts, true);
rescan(false); // Read from cache if we have it!
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static inline jas_ulong encode_twos_comp(long n, int prec)
{
jas_ulong result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
// NOTE: Is this correct?
if (n < 0) {
result = -n;
result = (result ^ 0xffffffffUL) + 1;
result &= (1 << prec) - 1;
} else {
result = n;
}
return result;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
void onComplete(const Status& status, ContextImpl& context) const override {
auto& completion_state = context.getCompletionState(this);
if (completion_state.is_completed_) {
return;
}
// If any of children is OK, return OK
if (Status::Ok == status) {
completion_state.is_completed_ = true;
completeWithStatus(status, context);
return;
}
// Then wait for all children to be done.
if (++completion_state.number_completed_children_ == verifiers_.size()) {
// Aggregate all children status into a final status.
// JwtMissing should be treated differently than other failure status
// since it simply means there is not Jwt token for the required provider.
// If there is a failure status other than JwtMissing in the children,
// it should be used as the final status.
Status final_status = Status::JwtMissed;
for (const auto& it : verifiers_) {
// If a Jwt is extracted from a location not specified by the required provider,
// the authenticator returns JwtUnknownIssuer. It should be treated the same as
// JwtMissed.
Status child_status = context.getCompletionState(it.get()).status_;
if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) {
final_status = child_status;
}
}
if (is_allow_missing_or_failed_) {
final_status = Status::Ok;
} else if (is_allow_missing_ && final_status == Status::JwtMissed) {
final_status = Status::Ok;
}
completion_state.is_completed_ = true;
completeWithStatus(final_status, context);
}
} | 0 | C++ | CWE-303 | Incorrect Implementation of Authentication Algorithm | The requirements for the software dictate the use of an established authentication algorithm, but the implementation of the algorithm is incorrect. | https://cwe.mitre.org/data/definitions/303.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
static const int kOutputUniqueTensor = 0;
static const int kOutputIndexTensor = 1;
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output_unique_tensor =
GetOutput(context, node, kOutputUniqueTensor);
TfLiteTensor* output_index_tensor =
GetOutput(context, node, kOutputIndexTensor);
// The op only supports 1D input.
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1);
TfLiteIntArray* output_index_shape = TfLiteIntArrayCopy(input->dims);
// The unique values are determined during evaluation, so we don't know yet
// the size of the output tensor.
SetTensorToDynamic(output_unique_tensor);
return context->ResizeTensor(context, output_index_tensor,
output_index_shape);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (!sz) {
return NULL;
}
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;
// if (buffer + offset > buffer + sz) return NULL;
attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
return attr;
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
TEST(BasicInterpreter, AllocateTwice) {
Interpreter interpreter;
ASSERT_EQ(interpreter.AddTensors(2), kTfLiteOk);
ASSERT_EQ(interpreter.SetInputs({0}), kTfLiteOk);
ASSERT_EQ(interpreter.SetOutputs({1}), kTfLiteOk);
TfLiteQuantizationParams quantized;
ASSERT_EQ(interpreter.SetTensorParametersReadWrite(0, kTfLiteFloat32, "", {3},
quantized),
kTfLiteOk);
ASSERT_EQ(interpreter.SetTensorParametersReadWrite(1, kTfLiteFloat32, "", {3},
quantized),
kTfLiteOk);
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* tensor0 = GetInput(context, node, 0);
TfLiteTensor* tensor1 = GetOutput(context, node, 0);
TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);
return context->ResizeTensor(context, tensor1, newSize);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* a0 = GetInput(context, node, 0);
TfLiteTensor* a1 = GetOutput(context, node, 0);
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
a1->data.f[i] = a0->data.f[i];
}
return kTfLiteOk;
};
ASSERT_EQ(
interpreter.AddNodeWithParameters({0}, {1}, nullptr, 0, nullptr, ®),
kTfLiteOk);
ASSERT_EQ(interpreter.ResizeInputTensor(0, {3}), kTfLiteOk);
ASSERT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
ASSERT_EQ(interpreter.Invoke(), kTfLiteOk);
char* old_tensor0_ptr = interpreter.tensor(0)->data.raw;
char* old_tensor1_ptr = interpreter.tensor(1)->data.raw;
ASSERT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
ASSERT_EQ(interpreter.Invoke(), kTfLiteOk);
ASSERT_EQ(old_tensor0_ptr, interpreter.tensor(0)->data.raw);
ASSERT_EQ(old_tensor1_ptr, interpreter.tensor(1)->data.raw);
} | 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 |
const String& setSize(int64_t len) {
assertx(m_str);
m_str->setSize(len);
return *this;
} | 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_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
} | 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 |
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;
AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
char* name = new char[name_size+1];
if (name == NULL) return;
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* size;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSizeTensor, &size));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
// TODO(ahentz): Our current implementations rely on the input being 4D,
// and the size being 1D tensor with exactly 2 elements.
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1);
TF_LITE_ENSURE_TYPES_EQ(context, size->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, size->dims->data[0], 2);
output->type = input->type;
if (!IsConstantTensor(size)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, input, size, output);
} | 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 PngImg::InitStorage_() {
rowPtrs_.resize(info_.height, nullptr);
data_ = new png_byte[info_.height * info_.rowbytes];
for(size_t i = 0; i < info_.height; ++i) {
rowPtrs_[i] = data_ + i * info_.rowbytes;
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int makeDirDirective(MaState *state, cchar *key, cchar *value)
{
MprPath info;
char *auth, *dirs, *path, *perms, *tok;
cchar *dir, *group, *owner;
int gid, mode, uid;
if (!maTokenize(state, value, "%S ?*", &auth, &dirs)) {
return MPR_ERR_BAD_SYNTAX;
}
uid = gid = 0;
mode = 0750;
if (schr(auth, ':')) {
owner = stok(auth, ":", &tok);
if (owner && *owner) {
if (snumber(owner)) {
uid = (int) stoi(owner);
} else if (smatch(owner, "APPWEB")) {
uid = HTTP->uid;
} else {
uid = userToID(owner);
}
}
group = stok(tok, ":", &perms);
if (group && *group) {
if (snumber(group)) {
gid = (int) stoi(group);
} else if (smatch(owner, "APPWEB")) {
gid = HTTP->gid;
} else {
gid = groupToID(group);
}
}
if (perms && snumber(perms)) {
mode = (int) stoiradix(perms, -1, NULL);
} else {
mode = 0;
}
if (gid < 0 || uid < 0) {
return MPR_ERR_BAD_SYNTAX;
}
} else {
dirs = auth;
auth = 0;
}
tok = dirs;
for (tok = sclone(dirs); (dir = stok(tok, ",", &tok)) != 0; ) {
path = httpMakePath(state->route, state->configDir, dir);
if (mprGetPathInfo(path, &info) == 0 && info.isDir) {
continue;
}
if (mprMakeDir(path, mode, uid, gid, 1) < 0) {
return MPR_ERR_BAD_SYNTAX;
}
}
return 0;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.