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 |
---|---|---|---|---|---|---|---|
static BOOL ntlm_av_pair_check_data(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair, size_t size)
{
size_t offset;
if (!pAvPair || cbAvPair < sizeof(NTLM_AV_PAIR) + size)
return FALSE;
if (!ntlm_av_pair_get_next_offset(pAvPair, cbAvPair, &offset))
return FALSE;
return cbAvPair >= offset;
} | 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 |
int64_t OpLevelCostEstimator::CalculateTensorSize(
const OpInfo::TensorProperties& tensor, bool* found_unknown_shapes) {
int64_t count = CalculateTensorElementCount(tensor, found_unknown_shapes);
int size = DataTypeSize(BaseType(tensor.dtype()));
VLOG(2) << "Count: " << count << " DataTypeSize: " << size;
return count * size;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TFLITE_DCHECK(node->builtin_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const auto params =
static_cast<const TfLiteFullyConnectedParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);
TF_LITE_ENSURE(context, filter != nullptr);
const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
TF_LITE_ENSURE_MSG(context, input->type == filter->type,
"Hybrid models are not supported on TFLite Micro.");
return CalculateOpData(context, params->activation, input->type, input,
filter, bias, output, data);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus TanhPrepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
data->input_zero_point = input->params.zero_point;
return CalculateArithmeticOpData(context, node, data);
} | 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 length() const {
return m_str ? m_str->size() : 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 |
inline bool checkNoWait(int length) { return check(length, 1, false)!=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 |
int FdOutStream::overrun(int itemSize, int nItems)
{
if (itemSize > bufSize)
throw Exception("FdOutStream overrun: max itemSize exceeded");
// First try to get rid of the data we have
flush();
// Still not enough space?
if (itemSize > end - ptr) {
// Can we shuffle things around?
// (don't do this if it gains us less than 25%)
if ((sentUpTo - start > bufSize / 4) &&
(itemSize < bufSize - (ptr - sentUpTo))) {
memmove(start, sentUpTo, ptr - sentUpTo);
ptr = start + (ptr - sentUpTo);
sentUpTo = start;
} else {
// Have to get rid of more data, so turn off non-blocking
// for a bit...
bool realBlocking;
realBlocking = blocking;
blocking = true;
flush();
blocking = realBlocking;
}
}
// Can we fit all the items asked for?
if (itemSize * nItems > end - ptr)
nItems = (end - ptr) / itemSize;
return nItems;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
IniSection (const IniParser *p, string n)
: IniBase (n),
ip (p),
end_comment (), is_private(false), rewrite_by(0),
container(), ivalues (), isections ()
{} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
static int em_jcxz(struct x86_emulate_ctxt *ctxt)
{
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
R_API ut8 *r_bin_java_get_attr_buf(RBinJavaObj *bin, ut64 sz, const ut64 offset, const ut8 *buf, const ut64 len) {
ut8 *attr_buf = NULL;
int pending = len - offset;
const ut8 *a_buf = offset + buf;
attr_buf = (ut8 *) calloc (pending + 1, 1);
if (!attr_buf) {
eprintf ("Unable to allocate enough bytes (0x%04"PFMT64x
") to read in the attribute.\n", sz);
return attr_buf;
}
memcpy (attr_buf, a_buf, pending); // sz+1);
return attr_buf;
} | 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 port::StatusOr<CudnnRnnSequenceTensorDescriptor> Create(
GpuExecutor* parent, int max_seq_length, int batch_size, int data_size,
const absl::Span<const int>& seq_lengths, bool time_major,
cudnnDataType_t data_type) {
CHECK_GT(max_seq_length, 0);
int dims[] = {batch_size, data_size, 1};
int strides[] = {dims[1] * dims[2], dims[2], 1};
TensorDescriptor tensor_desc = CreateTensorDescriptor();
RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor(
/*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type,
/*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims,
/*strideA=*/strides));
const int* seq_lengths_array = seq_lengths.data();
RNNDataDescriptor data_desc = CreateRNNDataDescriptor();
float padding_fill = 0.0f;
cudnnRNNDataLayout_t layout;
if (time_major) {
layout = CUDNN_RNN_DATA_LAYOUT_SEQ_MAJOR_UNPACKED;
} else {
layout = CUDNN_RNN_DATA_LAYOUT_BATCH_MAJOR_UNPACKED;
}
RETURN_IF_CUDNN_ERROR(cudnnSetRNNDataDescriptor(
/*RNNDataDesc=*/data_desc.get(), /*dataType*/ data_type,
/*layout=*/layout,
/*maxSeqLength=*/max_seq_length,
/*batchSize=*/batch_size, /*vectorSize=*/data_size,
/*seqLengthArray=*/seq_lengths_array,
/*paddingFill*/ (void*)&padding_fill));
return CudnnRnnSequenceTensorDescriptor(
parent, max_seq_length, batch_size, data_size, data_type,
std::move(data_desc), std::move(tensor_desc));
} | 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 |
CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,
value n)
{
memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Long_val(n));
return Val_unit;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {
for (int i = 0; i < NumOutputs(node); ++i) {
TfLiteTensor* tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, i, &tensor));
SetTensorToDynamic(tensor);
}
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));
FillDiagHelper(input, output);
return kTfLiteOk;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void ecall_non_oblivious_aggregate_step2(
uint8_t *agg_op, size_t agg_op_length,
uint8_t *input_rows, size_t input_rows_length,
uint8_t *next_partition_first_row, size_t next_partition_first_row_length,
uint8_t *prev_partition_last_group, size_t prev_partition_last_group_length,
uint8_t *prev_partition_last_row, size_t prev_partition_last_row_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);
assert(sgx_is_outside_enclave(next_partition_first_row, next_partition_first_row_length) == 1);
assert(sgx_is_outside_enclave(prev_partition_last_group, prev_partition_last_group_length) == 1);
assert(sgx_is_outside_enclave(prev_partition_last_row, prev_partition_last_row_length) == 1);
sgx_lfence();
try {
non_oblivious_aggregate_step2(
agg_op, agg_op_length,
input_rows, input_rows_length,
next_partition_first_row, next_partition_first_row_length,
prev_partition_last_group, prev_partition_last_group_length,
prev_partition_last_row, prev_partition_last_row_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 |
NTLM_AV_PAIR* ntlm_av_pair_get(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList, NTLM_AV_ID AvId,
size_t* pcbAvPairListRemaining)
{
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
pAvPair = NULL;
while (pAvPair)
{
UINT16 id = ntlm_av_pair_get_id(pAvPair);
if (id == AvId)
break;
if (id == MsvAvEOL)
{
pAvPair = NULL;
break;
}
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
}
if (!pAvPair)
cbAvPair = 0;
if (pcbAvPairListRemaining)
*pcbAvPairListRemaining = cbAvPair;
return pAvPair;
} | 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 |
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
if (streamId == 0) {
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: received streamID=", streamId,
" as invalid new stream for lastStreamID_=", lastStreamID_);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
}
parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
if (parsingDownstreamTrailers_) {
VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
}
if (sessionClosing_ != ClosingState::CLOSED) {
lastStreamID_ = streamId;
}
if (isInitiatedStream(streamId)) {
// this stream should be initiated by us, not by peer
goawayErrorMessage_ = folly::to<string>(
"GOAWAY error: invalid new stream received with streamID=", streamId);
VLOG(4) << goawayErrorMessage_;
return ErrorCode::PROTOCOL_ERROR;
} else {
return ErrorCode::NO_ERROR;
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_source_debug_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
if (sz < 8) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_DEBUG_EXTENTSION_ATTR;
if (attr->length == 0) {
eprintf ("r_bin_java_source_debug_attr_new: Attempting to allocate 0 bytes for debug_extension.\n");
attr->info.debug_extensions.debug_extension = NULL;
return attr;
} else if ((attr->length + offset) > sz) {
eprintf ("r_bin_java_source_debug_attr_new: Expected %d byte(s) got %"
PFMT64d " bytes for debug_extension.\n", attr->length, (offset + sz));
}
attr->info.debug_extensions.debug_extension = (ut8 *) malloc (attr->length);
if (attr->info.debug_extensions.debug_extension && (attr->length > (sz - offset))) {
memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, sz - offset);
} else if (attr->info.debug_extensions.debug_extension) {
memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, attr->length);
} else {
eprintf ("r_bin_java_source_debug_attr_new: Unable to allocate the data for the debug_extension.\n");
}
offset += attr->length;
attr->size = offset;
return attr;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, GetInput(context, node, 0)->type,
kTfLiteString);
TF_LITE_ENSURE_TYPES_EQ(context, GetOutput(context, node, 0)->type,
kTfLiteString);
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
bool Archive::Close()
{
#ifdef USE_ARCMEM
if (ArcMem.Unload())
return true;
#endif
return File::Close();
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = offset;
return attr;
} | 0 | C++ | CWE-805 | Buffer Access with Incorrect Length Value | The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer. | https://cwe.mitre.org/data/definitions/805.html | vulnerable |
void Compute(OpKernelContext* context) override {
const Tensor& tensor_in = context->input(0);
const Tensor& grad_in = context->input(1);
const Tensor& argmax = context->input(2);
PoolParameters params{context,
ksize_,
stride_,
padding_,
/*explicit_paddings=*/{},
FORMAT_NHWC,
tensor_in.shape()};
if (!context->status().ok()) {
return;
}
OP_REQUIRES(context, grad_in.shape() == params.forward_output_shape(),
errors::InvalidArgument("Expected grad shape to be ",
params.forward_output_shape(),
", but got ", grad_in.shape()));
OP_REQUIRES(context, argmax.shape() == params.forward_output_shape(),
errors::InvalidArgument("Expected argmax shape to be ",
params.forward_output_shape(),
", but got ", argmax.shape()));
TensorShape out_shape({params.tensor_in_batch, params.tensor_in_rows,
params.tensor_in_cols, params.depth});
Tensor* grad_out = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 0, out_shape, &grad_out));
if (out_shape.num_elements() == 0) return; // nothing to be done
LaunchMaxPoolingGradWithArgmax<Device, T>::launch(
context, params, grad_in, argmax, grad_out, include_batch_in_index_);
} | 1 | C++ | CWE-354 | Improper Validation of Integrity Check Value | The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. | https://cwe.mitre.org/data/definitions/354.html | safe |
string PacketReader::getLabel(unsigned int recurs)
{
string ret;
ret.reserve(40);
getLabelFromContent(d_content, d_pos, ret, recurs++);
return ret;
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
{
#define MAXLINELEN 80
jas_matind_t i;
jas_matind_t j;
jas_seqent_t x;
char buf[MAXLINELEN + 1];
char sbuf[MAXLINELEN + 1];
int n;
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix),
jas_seq2d_ystart(matrix));
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix),
jas_matrix_numrows(matrix));
buf[0] = '\0';
for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
x = jas_matrix_get(matrix, i, j);
sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
JAS_CAST(long, x));
n = JAS_CAST(int, strlen(buf));
if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
strcat(buf, sbuf);
if (j == jas_matrix_numcols(matrix) - 1) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
}
}
fputs(buf, out);
return 0;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
static inline int GetFirstGlobbingEntry(const std::vector<std::string>& dirs) {
int i = 0;
for (const auto& d : dirs) {
if (IsGlobbingPattern(d)) {
break;
}
i++;
}
return i;
} | 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(HTTP2CodecTest, DuplicateBadHeaderPriority) {
// Sent an initial header with a circular dependency
HTTPMessage req = getGetRequest();
req.setHTTP2Priority(HTTPMessage::HTTPPriority(0, false, 7));
upstreamCodec_.generateHeader(output_, 1, req, true /* eom */);
// Hack ingress with circular dependency.
EXPECT_TRUE(parse([&](IOBuf* ingress) {
folly::io::RWPrivateCursor c(ingress);
c.skip(http2::kFrameHeaderSize + http2::kConnectionPreface.length());
c.writeBE<uint32_t>(1);
}));
EXPECT_EQ(callbacks_.streamErrors, 1);
EXPECT_EQ(callbacks_.sessionErrors, 0);
// On the same stream, send another request.
HTTPMessage nextRequest = getGetRequest();
upstreamCodec_.generateHeader(output_, 1, nextRequest, true /* eom */);
parse();
EXPECT_EQ(callbacks_.streamErrors, 2);
EXPECT_EQ(callbacks_.sessionErrors, 0);
} | 1 | C++ | CWE-388 | 7PK - Errors | This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses that occur when an application does not properly handle errors that occur during processing. According to the authors of the Seven Pernicious Kingdoms, "Errors and error handling represent a class of API. Errors related to error handling are so common that they deserve a special kingdom of their own. As with 'API Abuse,' there are two ways to introduce an error-related security vulnerability: the most common one is handling errors poorly (or not at all). The second is producing errors that either give out too much information (to possible attackers) or are difficult to handle." | https://cwe.mitre.org/data/definitions/388.html | safe |
void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
{
Q_UNUSED(bufferInfo);
if (!msg.contains(' '))
return;
QString target = msg.section(' ', 0, 0);
QByteArray encMsg = userEncode(target, msg.section(' ', 1));
#ifdef HAVE_QCA2
putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));
#else
putPrivmsg(serverEncode(target), encMsg);
#endif
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
void CommandData::ProcessCommand()
{
#ifndef SFX_MODULE
const wchar *SingleCharCommands=L"FUADPXETK";
if (Command[0]!=0 && Command[1]!=0 && wcschr(SingleCharCommands,Command[0])!=NULL || *ArcName==0)
OutHelp(*Command==0 ? RARX_SUCCESS:RARX_USERERROR); // Return 'success' for 'rar' without parameters.
const wchar *ArcExt=GetExt(ArcName);
#ifdef _UNIX
if (ArcExt==NULL && (!FileExist(ArcName) || IsDir(GetFileAttr(ArcName))))
wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#else
if (ArcExt==NULL)
wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#endif
// Treat arcname.part1 as arcname.part1.rar.
if (ArcExt!=NULL && wcsnicomp(ArcExt,L".part",5)==0 && IsDigit(ArcExt[5]) &&
!FileExist(ArcName))
{
wchar Name[NM];
wcsncpyz(Name,ArcName,ASIZE(Name));
wcsncatz(Name,L".rar",ASIZE(Name));
if (FileExist(Name))
wcsncpyz(ArcName,Name,ASIZE(ArcName));
}
if (wcschr(L"AFUMD",*Command)==NULL && !ArcInMem)
{
if (GenerateArcName)
GenerateArchiveName(ArcName,ASIZE(ArcName),GenerateMask,false);
StringList ArcMasks;
ArcMasks.AddString(ArcName);
ScanTree Scan(&ArcMasks,Recurse,SaveSymLinks,SCAN_SKIPDIRS);
FindData FindData;
while (Scan.GetNext(&FindData)==SCAN_SUCCESS)
AddArcName(FindData.Name);
}
else
AddArcName(ArcName);
#endif
switch(Command[0])
{
case 'P':
case 'X':
case 'E':
case 'T':
case 'I':
{
CmdExtract Extract(this);
Extract.DoExtract();
}
break;
#ifndef SILENT
case 'V':
case 'L':
ListArchive(this);
break;
default:
OutHelp(RARX_USERERROR);
#endif
}
if (!BareOutput)
mprintf(L"\n");
} | 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 |
int64_t LineBasedFrameDecoder::findEndOfLine(IOBufQueue& buf) {
Cursor c(buf.front());
for (uint32_t i = 0; i < maxLength_ && i < buf.chainLength(); i++) {
auto b = c.read<char>();
if (b == '\n' && terminatorType_ != TerminatorType::CARRIAGENEWLINE) {
return i;
} else if (terminatorType_ != TerminatorType::NEWLINE &&
b == '\r' && !c.isAtEnd() && c.read<char>() == '\n') {
return i;
}
}
return -1;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
int main()
{
gdImagePtr im1, im2;
FILE *fp;
int size;
fp = gdTestFileOpen2("webp", "bug_double_free.jpg");
gdTestAssert(fp != NULL);
im1 = gdImageCreateFromJpeg(fp);
gdTestAssert(im1 != NULL);
fclose(fp);
im2 = gdImageWebpPtr(im1, &size);
gdTestAssert(im2 == NULL);
gdImageDestroy(im1);
return gdNumFailures();
} | 1 | C++ | CWE-415 | Double Free | The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. | https://cwe.mitre.org/data/definitions/415.html | safe |
TfLiteStatus SimpleOpEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, /*index=*/0, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, /*index=*/1, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, /*index=*/0, &output));
int32_t* output_data = output->data.i32;
*output_data = *(input1->data.i32) + *(input2->data.i32);
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
bool logToUSDT(const Array& bt) {
std::lock_guard<std::mutex> lock(usdt_mutex);
memset(&bt_slab, 0, sizeof(bt_slab));
int i = 0;
IterateVNoInc(
bt.get(),
[&](TypedValue tv) -> bool {
if (i >= strobelight::kMaxStackframes) {
return true;
}
assertx(isArrayLikeType(type(tv)));
ArrayData* bt_frame = val(tv).parr;
strobelight::backtrace_frame_t* frame = &bt_slab.frames[i];
auto const line = bt_frame->get(s_line.get());
if (line.is_init()) {
assertx(isIntType(type(line)));
frame->line = val(line).num;
}
auto const file_name = bt_frame->get(s_file.get());
if (file_name.is_init()) {
assertx(isStringType(type(file_name)));
strncpy(frame->file_name,
val(file_name).pstr->data(),
std::min(val(file_name).pstr->size(), strobelight::kFileNameMax));
frame->file_name[strobelight::kFileNameMax - 1] = '\0';
}
auto const class_name = bt_frame->get(s_class.get());
if (class_name.is_init()) {
assertx(isStringType(type(class_name)));
strncpy(frame->class_name,
val(class_name).pstr->data(),
std::min(val(class_name).pstr->size(), strobelight::kClassNameMax));
frame->class_name[strobelight::kClassNameMax - 1] = '\0';
}
auto const function_name = bt_frame->get(s_function.get());
if (function_name.is_init()) {
assertx(isStringType(type(function_name)));
strncpy(frame->function,
val(function_name).pstr->data(),
std::min(val(function_name).pstr->size(),
strobelight::kFunctionMax));
frame->function[strobelight::kFunctionMax - 1] = '\0';
}
i++;
return false;
}
);
bt_slab.len = i;
// Allow BPF to read the now-formatted stacktrace
FOLLY_SDT_WITH_SEMAPHORE(hhvm, hhvm_stack, &bt_slab);
return true;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix)
{
int stride;
U8 *buf;
int w, h, b;
Rect drect;
drect = r;
if (!drect.enclosed_by(getRect())) {
vlog.error("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d",
drect.width(), drect.height(), drect.tl.x, drect.tl.y, width_, height_);
drect = drect.intersect(getRect());
}
if (drect.is_empty())
return;
w = drect.width();
h = drect.height();
b = format.bpp/8;
if (h == 0)
return;
buf = getBufferRW(drect, &stride);
if (b == 1) {
while (h--) {
memset(buf, *(const U8*)pix, w);
buf += stride * b;
}
} else {
U8 *start;
int w1;
start = buf;
w1 = w;
while (w1--) {
memcpy(buf, pix, b);
buf += b;
}
buf += (stride - w) * b;
h--;
while (h--) {
memcpy(buf, start, w * b);
buf += stride * b;
}
}
commitBufferRW(drect);
} | 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 |
TfLiteRegistration AddOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.custom_name = "my_add";
reg.builtin_code = tflite::BuiltinOperator_CUSTOM;
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// Set output size to input size
const TfLiteTensor* input1 = GetInput(context, node, 0);
const TfLiteTensor* input2 = GetInput(context, node, 1);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_EQ(context, input1->dims->size, input2->dims->size);
for (int i = 0; i < input1->dims->size; ++i) {
TF_LITE_ENSURE_EQ(context, input1->dims->data[i], input2->dims->data[i]);
}
TF_LITE_ENSURE_STATUS(context->ResizeTensor(
context, output, TfLiteIntArrayCopy(input1->dims)));
return kTfLiteOk;
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
// Copy input data to output data.
const TfLiteTensor* a0 = GetInput(context, node, 0);
TF_LITE_ENSURE(context, a0);
TF_LITE_ENSURE(context, a0->data.f);
const TfLiteTensor* a1 = GetInput(context, node, 1);
TF_LITE_ENSURE(context, a1);
TF_LITE_ENSURE(context, a1->data.f);
TfLiteTensor* out = GetOutput(context, node, 0);
TF_LITE_ENSURE(context, out);
TF_LITE_ENSURE(context, out->data.f);
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
out->data.f[i] = a0->data.f[i] + a1->data.f[i];
}
return kTfLiteOk;
};
return reg;
} | 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_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (!se) {
return NULL;
}
se->tag = type;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = (ut16) value;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
/*if (bin->offset_sz == 4) {
se->info.uninit_offset = value;
} else {
se->info.uninit_offset = (ut16) value;
}*/
se->info.uninit_offset = (ut16) value;
}
return se;
} | 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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
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));
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;
} | 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 TfLitePackParams* data =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
return PackImpl<float>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteUInt8: {
return PackImpl<uint8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt8: {
return PackImpl<int8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt16: {
return PackImpl<int16_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt32: {
return PackImpl<int32_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt64: {
return PackImpl<int64_t>(context, node, output, data->values_count,
data->axis);
}
default: {
context->ReportError(context, "Type '%s' is not supported by pack.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | 0 | C++ | CWE-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 |
error_t ssiProcessExecCommand(HttpConnection *connection, const char_t *tag, size_t length)
{
char_t *separator;
char_t *attribute;
char_t *value;
//First, check whether CGI is supported by the server
if(connection->settings->cgiCallback == NULL)
return ERROR_INVALID_TAG;
//Discard invalid SSI directives
if(length < 4 || length >= HTTP_SERVER_BUFFER_SIZE)
return ERROR_INVALID_TAG;
//Skip the SSI exec command (4 bytes)
osMemcpy(connection->buffer, tag + 4, length - 4);
//Ensure the resulting string is NULL-terminated
connection->buffer[length - 4] = '\0';
//Check whether a separator is present
separator = strchr(connection->buffer, '=');
//Separator not found?
if(!separator)
return ERROR_INVALID_TAG;
//Split the tag
*separator = '\0';
//Get attribute name and value
attribute = strTrimWhitespace(connection->buffer);
value = strTrimWhitespace(separator + 1);
//Remove leading simple or double quote
if(value[0] == '\'' || value[0] == '\"')
value++;
//Get the length of the attribute value
length = osStrlen(value);
//Remove trailing simple or double quote
if(length > 0)
{
if(value[length - 1] == '\'' || value[length - 1] == '\"')
value[length - 1] = '\0';
}
//Enforce attribute name
if(osStrcasecmp(attribute, "cgi") && osStrcasecmp(attribute, "cmd") && osStrcasecmp(attribute, "cmd_argument"))
return ERROR_INVALID_TAG;
//Check the length of the CGI parameter
if(osStrlen(value) > HTTP_SERVER_CGI_PARAM_MAX_LEN)
return ERROR_INVALID_TAG;
//The scratch buffer may be altered by the user-defined callback.
//So the CGI parameter must be copied prior to function invocation
osStrcpy(connection->cgiParam, value);
//Invoke user-defined callback
return connection->settings->cgiCallback(connection, connection->cgiParam);
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static int intel_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
int bit, loops;
u64 status;
int handled;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This handler doesn't seem to have any issues with the unmasking
* so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
intel_pmu_disable_all();
handled = intel_pmu_drain_bts_buffer();
status = intel_pmu_get_status();
if (!status) {
intel_pmu_enable_all(0);
return handled;
}
loops = 0;
again:
intel_pmu_ack_status(status);
if (++loops > 100) {
WARN_ONCE(1, "perfevents: irq loop stuck!\n");
perf_event_print_debug();
intel_pmu_reset();
goto done;
}
inc_irq_stat(apic_perf_irqs);
intel_pmu_lbr_read();
/*
* PEBS overflow sets bit 62 in the global status register
*/
if (__test_and_clear_bit(62, (unsigned long *)&status)) {
handled++;
x86_pmu.drain_pebs(regs);
}
for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
struct perf_event *event = cpuc->events[bit];
handled++;
if (!test_bit(bit, cpuc->active_mask))
continue;
if (!intel_pmu_save_and_restart(event))
continue;
data.period = event->hw.last_period;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
/*
* Repeat if there is more work to be done:
*/
status = intel_pmu_get_status();
if (status)
goto again;
done:
intel_pmu_enable_all(0);
return handled;
} | 1 | C++ | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
inline TfLiteTensor* GetTensorAtIndex(const TfLiteContext* context,
int tensor_index) {
if (context->tensors != nullptr) {
return &context->tensors[tensor_index];
} else {
return context->GetTensor(context, tensor_index);
}
} | 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 |
HexOutStream::writeBuffer() {
U8* pos = start;
while (pos != ptr) {
out_stream.check(2);
U8* optr = out_stream.getptr();
U8* oend = out_stream.getend();
int length = min(ptr-pos, (oend-optr)/2);
for (int i=0; i<length; i++) {
optr[i*2] = intToHex((pos[i] >> 4) & 0xf);
optr[i*2+1] = intToHex(pos[i] & 0xf);
}
out_stream.setptr(optr + length*2);
pos += length;
}
offset += ptr - start;
ptr = start;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
int GetU8 (int nPos, bool *pbSuccess)
{
//*pbSuccess = true;
if ( nPos < 0 || nPos >= m_nLen )
{
*pbSuccess = false;
return 0;
}
return m_sFile[ nPos ];
} | 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 |
BinaryParameter::BinaryParameter(const char* name_, const char* desc_,
const void* v, int l, ConfigurationObject co)
: VoidParameter(name_, desc_, co), value(0), length(0), def_value((char*)v), def_length(l) {
if (l) {
value = new char[l];
length = l;
memcpy(value, v, l);
}
} | 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, node->inputs->size, 1);
TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
const TfLiteTensor* input_resource_id_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,
&input_resource_id_tensor));
TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputValue, &output));
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 |
write(Protocol_* iprot, const StructInfo& structInfo, const void* object) {
DCHECK(object);
size_t written = iprot->writeStructBegin(structInfo.name);
if (UNLIKELY(structInfo.unionExt != nullptr)) {
const FieldInfo* end = structInfo.fieldInfos + structInfo.numFields;
const auto& unionId =
activeUnionMemberId(object, structInfo.unionExt->unionTypeOffset);
const FieldInfo* found = std::lower_bound(
structInfo.fieldInfos,
end,
unionId,
[](const FieldInfo& lhs, FieldID rhs) { return lhs.id < rhs; });
if (found < end && found->id == unionId) {
const OptionalThriftValue value = getValue(*found->typeInfo, object);
if (value.hasValue()) {
written += writeField(iprot, *found, value.value());
} else if (found->typeInfo->type == protocol::TType::T_STRUCT) {
written += iprot->writeFieldBegin(
found->name, found->typeInfo->type, found->id);
written += iprot->writeStructBegin(found->name);
written += iprot->writeStructEnd();
written += iprot->writeFieldStop();
written += iprot->writeFieldEnd();
}
}
} else {
for (std::int16_t index = 0; index < structInfo.numFields; index++) {
const auto& fieldInfo = structInfo.fieldInfos[index];
if (fieldInfo.isUnqualified || fieldInfo.issetOffset == 0 ||
fieldIsSet(object, fieldInfo.issetOffset)) {
const OptionalThriftValue value =
getValue(*fieldInfo.typeInfo, getMember(fieldInfo, object));
if (value.hasValue()) {
written += writeField(iprot, fieldInfo, value.value());
}
}
}
}
written += iprot->writeFieldStop();
written += iprot->writeStructEnd();
return written;
} | 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 |
int64_t TensorByteSize(const TensorProto& t) {
// num_elements returns -1 if shape is not fully defined.
int64_t num_elems = TensorShape(t.tensor_shape()).num_elements();
return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());
} | 0 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | vulnerable |
static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
// handle a table switch condition
if (pos + 8 + 8 > len) {
return op->size;
}
const int min_val = (ut32)(UINT (data, pos + 4));
const int max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
//ut32 value = (ut32)(UINT (data, pos));
if (pos + 4 >= len) {
// switch is too big cant read further
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->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 |
CString CZNC::FixupEncoding(const CString& sEncoding) const {
if (!m_uiForceEncoding) {
return sEncoding;
}
if (sEncoding.empty()) {
return "UTF-8";
}
const char* sRealEncoding = sEncoding.c_str();
if (sEncoding[0] == '*' || sEncoding[0] == '^') {
sRealEncoding++;
}
if (!*sRealEncoding) {
return "UTF-8";
}
#ifdef HAVE_ICU
UErrorCode e = U_ZERO_ERROR;
UConverter* cnv = ucnv_open(sRealEncoding, &e);
if (cnv) {
ucnv_close(cnv);
}
if (U_FAILURE(e)) {
return "UTF-8";
}
#endif
return sEncoding;
} | 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 |
BGD_DECLARE(void *) gdImageWBMPPtr(gdImagePtr im, int *size, int fg)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) return NULL;
gdImageWBMPCtx(im, fg, out);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
} | 0 | C++ | CWE-415 | Double Free | The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. | https://cwe.mitre.org/data/definitions/415.html | vulnerable |
static void jsiDumpInstr(Jsi_Interp *interp, jsi_Pstate *ps, Jsi_Value *_this,
jsi_TryList *trylist, jsi_OpCode *ip, Jsi_OpCodes *opcodes)
{
int i;
char buf[200];
jsi_code_decode(interp, ip, ip - opcodes->codes, buf, sizeof(buf));
Jsi_Printf(interp, jsi_Stderr, "%p: %-30.200s : THIS=%s, STACK=[", ip, buf, jsi_evalprint(_this));
for (i = 0; i < interp->framePtr->Sp; ++i) {
Jsi_Printf(interp, jsi_Stderr, "%s%s", (i>0?", ":""), jsi_evalprint(_jsi_STACKIDX(i)));
}
Jsi_Printf(interp, jsi_Stderr, "]");
if (ip->fname) {
const char *fn = ip->fname, *cp = Jsi_Strrchr(fn, '/');
if (cp) fn = cp+1;
Jsi_Printf(interp, jsi_Stderr, ", %s:%d", fn, ip->Line);
}
Jsi_Printf(interp, jsi_Stderr, "\n");
jsi_TryList *tlt = trylist;
for (i = 0; tlt; tlt = tlt->next) i++;
if (ps->last_exception)
Jsi_Printf(interp, jsi_Stderr, "TL: %d, excpt: %s\n", i, jsi_evalprint(ps->last_exception));
} | 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 |
static String HHVM_FUNCTION(bcpow, const String& left, const String& right,
int64_t scale /* = -1 */) {
scale = adjust_scale(scale);
bc_num first, second, result;
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
SCOPE_EXIT {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
bc_raise(first, second, &result, scale);
if (result->n_scale > scale) {
result->n_scale = scale;
}
String ret(bc_num2str(result), AttachString);
return ret;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAnnotation *annotation = NULL;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | 0 | C++ | CWE-805 | Buffer Access with Incorrect Length Value | The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer. | https://cwe.mitre.org/data/definitions/805.html | vulnerable |
int CLASS ljpeg_start (struct jhead *jh, int info_only)
{
int c, tag, len;
uchar data[0x10000];
const uchar *dp;
memset (jh, 0, sizeof *jh);
jh->restart = INT_MAX;
fread (data, 2, 1, ifp);
if (data[1] != 0xd8) return 0;
do {
fread (data, 2, 2, ifp);
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00) return 0;
fread (data, 1, len, ifp);
switch (tag) {
case 0xffc3:
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc0:
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version) getc(ifp);
break;
case 0xffc4:
if (info_only) break;
for (dp = data; dp < data+len && (c = *dp++) < 4; )
jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
break;
case 0xffda:
jh->psv = data[1+data[0]*2];
jh->bits -= data[3+data[0]*2] & 15;
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (info_only) return 1;
FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
if (jh->sraw) {
FORC(4) jh->huff[2+c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
}
jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
merror (jh->row, "ljpeg_start()");
return zero_after_ff = 1;
} | 0 | C++ | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | https://cwe.mitre.org/data/definitions/189.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE(context, NumDimensions(input) <= 4);
TF_LITE_ENSURE(context, output->type == kTfLiteFloat32 ||
output->type == kTfLiteUInt8 ||
output->type == kTfLiteInt8);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.scale, (1. / 128.));
if (output->type == kTfLiteUInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 128);
}
if (output->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);
}
}
// TODO(ahentz): For some reason our implementations don't support
// activations.
TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->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 |
void ntlm_print_av_pair_list(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList)
{
UINT16 pair;
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
return;
WLog_INFO(TAG, "AV_PAIRs =");
while (pAvPair && ntlm_av_pair_get_id(pAvPair, cbAvPair, &pair) && (pair != MsvAvEOL))
{
size_t cbLen = 0;
ntlm_av_pair_get_len(pAvPair, cbAvPair, &cbLen);
WLog_INFO(TAG, "\t%s AvId: %" PRIu16 " AvLen: %" PRIu16 "", get_av_pair_string(pair), pair);
winpr_HexDump(TAG, WLOG_INFO, ntlm_av_pair_get_value_pointer(pAvPair), cbLen);
pAvPair = ntlm_av_pair_next(pAvPair, &cbAvPair);
}
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus NonMaxSuppressionMultiClass(TfLiteContext* context,
TfLiteNode* node, OpData* op_data) {
// Get the input tensors
const TfLiteTensor* input_box_encodings;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensorBoxEncodings,
&input_box_encodings));
const TfLiteTensor* input_class_predictions;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensorClassPredictions,
&input_class_predictions));
const int num_boxes = input_box_encodings->dims->data[1];
const int num_classes = op_data->num_classes;
TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[0],
kBatchSize);
TF_LITE_ENSURE_EQ(context, input_class_predictions->dims->data[1], num_boxes);
const int num_classes_with_background =
input_class_predictions->dims->data[2];
TF_LITE_ENSURE(context, (num_classes_with_background - num_classes <= 1));
TF_LITE_ENSURE(context, (num_classes_with_background >= num_classes));
const TfLiteTensor* scores;
switch (input_class_predictions->type) {
case kTfLiteUInt8: {
TfLiteTensor* temporary_scores = &context->tensors[op_data->scores_index];
DequantizeClassPredictions(input_class_predictions, num_boxes,
num_classes_with_background, temporary_scores);
scores = temporary_scores;
} break;
case kTfLiteFloat32:
scores = input_class_predictions;
break;
default:
// Unsupported type.
return kTfLiteError;
}
if (op_data->use_regular_non_max_suppression)
TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassRegularHelper(
context, node, op_data, GetTensorData<float>(scores)));
else
TF_LITE_ENSURE_STATUS(NonMaxSuppressionMultiClassFastHelper(
context, node, op_data, GetTensorData<float>(scores)));
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 EluPrepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// Use LUT to handle quantized elu path.
if (input->type == kTfLiteInt8) {
PopulateLookupTable<int8_t>(data, input, output, [](float value) {
return value < 0.0 ? std::exp(value) - 1.0f : value;
});
}
return GenericPrepare(context, node);
} | 1 | C++ | CWE-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 |
absl::Status IsSupported(const TfLiteContext* context,
const TfLiteNode* tflite_node,
const TfLiteRegistration* registration) final {
RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 3));
if (tflite_node->inputs->size != 2) {
return absl::UnimplementedError("MUL requires two input tensors.");
}
auto input0 = tflite::GetInput(context, tflite_node, 0);
auto input1 = tflite::GetInput(context, tflite_node, 1);
if (input0 == nullptr || input1 == nullptr) {
return absl::InvalidArgumentError("At least one input tensor is null");
}
if (input0->dims->size == input1->dims->size) {
// this code checks that at least one input of Mul not smaller in all
// dimensions. Sometimes Mul used for matrix-vector multiplication that we
// currently don't support. For example input0 HWC(1, 256, 1), input1
// HWC(1, 1, 256) -> output HWC (1, 256, 256). In this case it can be
// replaced with Convolution operation.
bool first_has_smaller_dim = false;
bool second_has_smaller_dim = false;
for (int i = 0; i < input0->dims->size; ++i) {
if (input0->dims->data[i] < input1->dims->data[i]) {
first_has_smaller_dim = true;
}
if (input1->dims->data[i] < input0->dims->data[i]) {
second_has_smaller_dim = true;
}
}
if (first_has_smaller_dim && second_has_smaller_dim) {
return absl::UnimplementedError(
"MUL requires one tensor that not less than second in all "
"dimensions.");
}
}
const TfLiteMulParams* tf_options;
RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options));
return IsActivationSupported(tf_options->activation);
} | 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 FormatConverter<T>::Populate(const T* src_data, std::vector<int> indices,
int level, int prev_idx, int* src_data_ptr,
T* dest_data) {
if (level == indices.size()) {
int orig_rank = dense_shape_.size();
std::vector<int> orig_idx;
orig_idx.resize(orig_rank);
int i = 0;
for (; i < orig_idx.size(); i++) {
int orig_dim = traversal_order_[i];
orig_idx[orig_dim] = indices[i];
}
for (; i < indices.size(); i++) {
const int block_idx = traversal_order_[i] - orig_rank;
const int orig_dim = block_map_[block_idx];
orig_idx[orig_dim] =
orig_idx[orig_dim] * block_size_[block_idx] + indices[i];
}
dest_data[GetFlattenedIndex(orig_idx, dense_shape_)] =
src_data[*src_data_ptr];
*src_data_ptr = *src_data_ptr + 1;
return;
}
const int metadata_idx = 2 * level;
const int shape_of_level = dim_metadata_[metadata_idx][0];
if (format_[level] == kTfLiteDimDense) {
for (int i = 0; i < shape_of_level; i++) {
indices[level] = i;
Populate(src_data, indices, level + 1, prev_idx * shape_of_level + i,
src_data_ptr, dest_data);
}
} else {
const auto& array_segments = dim_metadata_[metadata_idx];
const auto& array_indices = dim_metadata_[metadata_idx + 1];
for (int i = array_segments[prev_idx]; i < array_segments[prev_idx + 1];
i++) {
indices[level] = array_indices[i];
Populate(src_data, indices, level + 1, i, src_data_ptr, dest_data);
}
}
} | 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 int16_t decodeSample(ms_adpcm_state &state,
uint8_t code, const int16_t *coefficient, bool *ok=NULL)
{
int linearSample = (state.sample1 * coefficient[0] +
state.sample2 * coefficient[1]) >> 8;
int delta;
linearSample += ((code & 0x08) ? (code - 0x10) : code) * state.delta;
linearSample = clamp(linearSample, MIN_INT16, MAX_INT16);
if (multiplyCheckOverflow(state.delta, adaptationTable[code], &delta))
{
if (ok) *ok=false;
_af_error(AF_BAD_COMPRESSION, "Error decoding sample");
return 0;
}
delta >>= 8;
if (delta < 16)
delta = 16;
state.delta = delta;
state.sample2 = state.sample1;
state.sample1 = linearSample;
if (ok) *ok=true;
return static_cast<int16_t>(linearSample);
} | 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 ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,
TfLiteTensor* output, bool requires_broadcast) {
if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {
auto input1_offset = -input1->params.zero_point;
auto input2_offset = -input2->params.zero_point;
const int left_shift = 8;
int32 input1_multiplier;
int input1_shift;
QuantizeMultiplierSmallerThanOneExp(input1->params.scale,
&input1_multiplier, &input1_shift);
int32 input2_multiplier;
int input2_shift;
QuantizeMultiplierSmallerThanOneExp(input2->params.scale,
&input2_multiplier, &input2_shift);
ComparisonParams op_params;
op_params.left_shift = left_shift;
op_params.input1_offset = input1_offset;
op_params.input1_multiplier = input1_multiplier;
op_params.input1_shift = input1_shift;
op_params.input2_offset = input2_offset;
op_params.input2_multiplier = input2_multiplier;
op_params.input2_shift = input2_shift;
if (requires_broadcast) {
reference_ops::BroadcastComparison4DSlowWithScaling<input_dtype, opname>(
op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
GetTensorShape(input2), GetTensorData<input_dtype>(input2),
GetTensorShape(output), GetTensorData<bool>(output));
} else {
reference_ops::ComparisonWithScaling<input_dtype, opname>(
op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
GetTensorShape(input2), GetTensorData<input_dtype>(input2),
GetTensorShape(output), GetTensorData<bool>(output));
}
}
} | 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 |
inline int StringData::size() const { return m_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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
output->type = input->type;
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->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 |
void DCR_CLASS dcr_parse_riff(DCRAW* p)
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] =
{ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
struct tm t;
p->order = 0x4949;
dcr_fread(p->obj_, tag, 4, 1);
size = dcr_get4(p);
end = dcr_ftell(p->obj_) + size;
if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
dcr_get4(p);
while (dcr_ftell(p->obj_)+7 < (long)end)
dcr_parse_riff(p);
} else if (!memcmp(tag,"nctg",4)) {
while (dcr_ftell(p->obj_)+7 < (long)end) {
i = dcr_get2(p);
size = dcr_get2(p);
if ((i+1) >> 1 == 10 && size == 20)
dcr_get_timestamp(p,0);
else dcr_fseek(p->obj_, size, SEEK_CUR);
}
} else if (!memcmp(tag,"IDIT",4) && size < 64) {
dcr_fread(p->obj_, date, 64, 1);
date[size] = 0;
memset (&t, 0, sizeof t);
if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
p->timestamp = mktime(&t);
}
} else
dcr_fseek(p->obj_, size, SEEK_CUR);
}
| 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 |
ServerSecurityFeature::ServerSecurityFeature(application_features::ApplicationServer& server)
: ApplicationFeature(server, "ServerSecurity"),
_enableFoxxApi(true),
_enableFoxxStore(true),
_hardenedRestApi(false) {
setOptional(false);
startsAfter<application_features::GreetingsFeaturePhase>();
} | 0 | C++ | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | vulnerable |
inline bool CheckForOverflow<Eigen::half>(double as_double, Eigen::half* out) {
return (sizeof(Eigen::half) < sizeof(double) &&
Eigen::half_impl::isinf(*out) && std::isfinite(as_double));
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
TfLiteStatus ReluPrepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
ReluOpData* data = static_cast<ReluOpData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
if (input->type == kTfLiteInt8) {
CalculateReluOpData<int8_t>(input, output, data);
} else if (input->type == kTfLiteUInt8) {
CalculateReluOpData<uint8_t>(input, output, data);
}
return kTfLiteOk;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
Status InferenceContext::Multiply(DimensionHandle first,
DimensionOrConstant second,
DimensionHandle* out) {
const int64_t first_value = Value(first);
const int64_t second_value = Value(second);
// Special cases.
if (first_value == 0) {
*out = first;
} else if (second_value == 0) {
*out = MakeDim(second);
} else if (first_value == 1) {
*out = MakeDim(second);
} else if (second_value == 1) {
*out = first;
} else if (first_value == kUnknownDim || second_value == kUnknownDim) {
*out = UnknownDim();
} else {
// Invariant: Both values are known and greater than 1.
const int64_t product = MultiplyWithoutOverflow(first_value, second_value);
if (product < 0) {
return errors::InvalidArgument(
"Negative dimension size caused by overflow when multiplying ",
first_value, " and ", second_value);
}
*out = MakeDim(product);
}
return Status::OK();
} | 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 HTTPSession::onCertificate(uint16_t certId,
std::unique_ptr<IOBuf> authenticator) {
DestructorGuard dg(this);
VLOG(4) << "CERTIFICATE on" << *this << ", certId=" << certId;
if (!secondAuthManager_) {
return;
}
bool isValid = false;
auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
if (fizzBase) {
if (isUpstream()) {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::UPSTREAM,
certId,
std::move(authenticator));
} else {
isValid = secondAuthManager_->validateAuthenticator(
*fizzBase,
TransportDirection::DOWNSTREAM,
certId,
std::move(authenticator));
}
} else {
VLOG(4) << "Underlying transport does not support secondary "
"authentication.";
return;
}
if (isValid) {
VLOG(4) << "Successfully validated the authenticator provided by the peer.";
} else {
VLOG(4) << "Failed to validate the authenticator provided by the peer";
}
} | 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 ssize_t _hostsock_send(
oe_fd_t* sock_,
const 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 (oe_syscall_send_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 |
bool ZlibInStream::decompress(bool wait)
{
if (!underlying)
throw Exception("ZlibInStream overrun: no underlying stream");
zs->next_out = (U8*)end;
zs->avail_out = start + bufSize - end;
int n = underlying->check(1, 1, wait);
if (n == 0) return false;
zs->next_in = (U8*)underlying->getptr();
zs->avail_in = underlying->getend() - underlying->getptr();
if ((int)zs->avail_in > bytesIn)
zs->avail_in = bytesIn;
int rc = inflate(zs, Z_SYNC_FLUSH);
if (rc != Z_OK) {
throw Exception("ZlibInStream: inflate failed");
}
bytesIn -= zs->next_in - underlying->getptr();
end = zs->next_out;
underlying->setptr(zs->next_in);
return true;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void ZlibInStream::removeUnderlying()
{
ptr = end = start;
if (!underlying) return;
while (bytesIn > 0) {
decompress(true);
end = start; // throw away any data
}
underlying = 0;
} | 0 | C++ | CWE-672 | Operation on a Resource after Expiration or Release | The software uses, accesses, or otherwise operates on a resource after that resource has been expired, released, or revoked. | https://cwe.mitre.org/data/definitions/672.html | vulnerable |
void FdInStream::readBytes(void* data, int length)
{
if (length < MIN_BULK_SIZE) {
InStream::readBytes(data, length);
return;
}
U8* dataPtr = (U8*)data;
int n = end - ptr;
if (n > length) n = length;
memcpy(dataPtr, ptr, n);
dataPtr += n;
length -= n;
ptr += n;
while (length > 0) {
n = readWithTimeoutOrCallback(dataPtr, length);
dataPtr += n;
length -= n;
offset += n;
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {
TfLiteIntArray* output_shape = GetOutputShape(context, node);
std::unique_ptr<TfLiteIntArray, void (*)(TfLiteIntArray*)>
scoped_output_shape(output_shape, TfLiteIntArrayFree);
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));
// Tensorflow's Reshape allows one of the shape components to have the
// special -1 value, meaning it will be calculated automatically based on the
// input. Here we calculate what that dimension should be so that the number
// of output elements in the same as the number of input elements.
int num_input_elements = NumElements(input);
int num_output_elements = 1;
int stretch_dim = -1;
for (int i = 0; i < output_shape->size; ++i) {
int value = output_shape->data[i];
if (value == -1) {
TF_LITE_ENSURE_EQ(context, stretch_dim, -1);
stretch_dim = i;
} else {
num_output_elements *= value;
}
}
if (stretch_dim != -1) {
output_shape->data[stretch_dim] = num_input_elements / num_output_elements;
num_output_elements *= output_shape->data[stretch_dim];
}
TF_LITE_ENSURE_EQ(context, num_input_elements, num_output_elements);
return context->ResizeTensor(context, output, scoped_output_shape.release());
} | 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 CommandData::IsProcessFile(FileHeader &FileHead,bool *ExactMatch,int MatchType,
wchar *MatchedArg,uint MatchedArgSize)
{
if (MatchedArg!=NULL && MatchedArgSize>0)
*MatchedArg=0;
if (wcslen(FileHead.FileName)>=NM)
return 0;
bool Dir=FileHead.Dir;
if (ExclCheck(FileHead.FileName,Dir,false,true))
return 0;
#ifndef SFX_MODULE
if (TimeCheck(FileHead.mtime))
return 0;
if ((FileHead.FileAttr & ExclFileAttr)!=0 || InclAttrSet && (FileHead.FileAttr & InclFileAttr)==0)
return 0;
if (!Dir && SizeCheck(FileHead.UnpSize))
return 0;
#endif
wchar *ArgName;
FileArgs.Rewind();
for (int StringCount=1;(ArgName=FileArgs.GetString())!=NULL;StringCount++)
if (CmpName(ArgName,FileHead.FileName,MatchType))
{
if (ExactMatch!=NULL)
*ExactMatch=wcsicompc(ArgName,FileHead.FileName)==0;
if (MatchedArg!=NULL)
wcsncpyz(MatchedArg,ArgName,MatchedArgSize);
return StringCount;
}
return 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 |
Array HHVM_FUNCTION(compact,
const Variant& varname,
const Array& args /* = null array */) {
raise_disallowed_dynamic_call("compact should not be called dynamically");
Array ret = Array::attach(PackedArray::MakeReserve(args.size() + 1));
VarEnv* v = g_context->getOrCreateVarEnv();
if (v) {
PointerSet seen;
compact(seen, v, ret, varname);
if (!args.empty()) compact(seen, v, ret, args);
}
return ret;
} | 1 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const
{
ParaNdis_CheckSumVerifyFlat(IpHeader,
EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum,
__FUNCTION__);
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
int num_inputs = NumInputs(node);
TF_LITE_ENSURE(context, num_inputs >= 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
output->type = input1->type;
// Check that all input tensors have the same shape and type.
for (int i = kInputTensor1 + 1; i < num_inputs; ++i) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &input));
TF_LITE_ENSURE(context, HaveSameShapes(input1, input));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type);
}
// Use the first input node's dimension to be the dimension of the output
// node.
TfLiteIntArray* input1_dims = input1->dims;
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims);
return context->ResizeTensor(context, output, output_dims);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,
TfLiteTensor* output, bool requires_broadcast) {
if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {
auto input1_offset = -input1->params.zero_point;
auto input2_offset = -input2->params.zero_point;
const int left_shift = 8;
int32 input1_multiplier;
int32 input2_multiplier;
int input1_shift;
int input2_shift;
QuantizeMultiplier(input1->params.scale, &input1_multiplier, &input1_shift);
QuantizeMultiplier(input2->params.scale, &input2_multiplier, &input2_shift);
ComparisonParams op_params;
op_params.left_shift = left_shift;
op_params.input1_offset = input1_offset;
op_params.input1_multiplier = input1_multiplier;
op_params.input1_shift = input1_shift;
op_params.input2_offset = input2_offset;
op_params.input2_multiplier = input2_multiplier;
op_params.input2_shift = input2_shift;
if (requires_broadcast) {
reference_ops::BroadcastComparison4DSlowWithScaling<input_dtype, opname>(
op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
GetTensorShape(input2), GetTensorData<input_dtype>(input2),
GetTensorShape(output), GetTensorData<bool>(output));
} else {
reference_ops::ComparisonWithScaling<input_dtype, opname>(
op_params, GetTensorShape(input1), GetTensorData<input_dtype>(input1),
GetTensorShape(input2), GetTensorData<input_dtype>(input2),
GetTensorShape(output), GetTensorData<bool>(output));
}
}
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
TfLiteStatus Subgraph::CheckInputAndOutputForOverlap(const int* input_indices,
int num_inputs,
const int* output_indices,
int num_outputs) {
for (int i = 0; i < num_inputs; i++) {
for (int j = 0; j < num_outputs; j++) {
if (input_indices[i] == output_indices[j]) {
ReportError("Tensor %d is both input %d and output %d\n",
input_indices[i], i, j);
consistent_ = false;
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 |
inline bool ResolveAxis(const int num_dims, const int* axis,
const int64_t num_axis, int* out_axis,
int* out_num_axis) {
*out_num_axis = 0; // Just in case.
// Short-circuit axis resolution for scalars; the axis will go unused.
if (num_dims == 0) {
return true;
}
// o(n^2) is fine since out_num_axis should be really small, mostly <= 4
for (int64_t idx = 0; idx < num_axis; ++idx) {
// Handle negative index. A positive index 'p_idx' can be represented as a
// negative index 'n_idx' as: n_idx = p_idx-num_dims
// eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */
int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx];
TFLITE_DCHECK(current >= 0 && current < num_dims);
if (current < 0 || current >= num_dims) {
return false;
}
bool is_dup = false;
for (int j = 0; j < *out_num_axis; ++j) {
if (out_axis[j] == current) {
is_dup = true;
break;
}
}
if (!is_dup) {
out_axis[*out_num_axis] = current;
*out_num_axis += 1;
}
}
return true;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
absl::Status IsSupported(const TfLiteContext* context,
const TfLiteNode* tflite_node,
const TfLiteRegistration* registration) final {
if (mirror_pad_) {
const TfLiteMirrorPaddingParams* tf_options;
RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options));
if (tf_options->mode !=
TfLiteMirrorPaddingMode::kTfLiteMirrorPaddingReflect) {
return absl::InvalidArgumentError(
"Only Reflective padding is supported for Mirror Pad operation.");
}
}
RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 2));
RETURN_IF_ERROR(CheckInputsOutputs(context, tflite_node,
/*runtime_inputs=*/1, /*outputs=*/1));
RETURN_IF_ERROR(CheckTensorIsAvailable(context, tflite_node, 1));
const TfLiteTensor* pad_tensor = tflite::GetInput(context, tflite_node, 1);
if (pad_tensor == nullptr) {
return absl::InvalidArgumentError("Padding tensor was null");
}
if (pad_tensor->dims->size != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor dimension: expected 2 dim, got ",
pad_tensor->dims->size, " dim"));
}
bool supported =
pad_tensor->dims->data[0] == 3 || pad_tensor->dims->data[0] == 4;
if (!supported || pad_tensor->dims->data[1] != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor shape: expected 4x2 or 3x2, got ",
pad_tensor->dims->data[0], "x", pad_tensor->dims->data[1]));
}
return absl::OkStatus();
} | 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 ResizeOutputTensor(TfLiteContext* context,
SpaceToBatchNDContext* op_context) {
TfLiteIntArray* input_size = op_context->input->dims;
const int32* block_shape = GetTensorData<int32>(op_context->block_shape);
const int32* paddings_data = GetTensorData<int32>(op_context->paddings);
int spatial_dims_num = input_size->size - 2;
// Block_shape should be a 1D tensor with dimension [spatial_dims_num].
TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->block_shape), 1);
TF_LITE_ENSURE_EQ(context, op_context->block_shape->dims->data[0],
spatial_dims_num);
// Paddings should be a 2D tensor with dimension [spatial_dims_num, 2].
TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->paddings), 2);
TF_LITE_ENSURE_EQ(context, op_context->paddings->dims->data[0],
spatial_dims_num);
TF_LITE_ENSURE_EQ(context, op_context->paddings->dims->data[1], 2);
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input_size);
// Ensures the input height and width (with padding) is a multiple of block
// shape height and width.
int output_batch_size = input_size->data[0];
for (int dim = 0; dim < spatial_dims_num; ++dim) {
int final_dim_size = (input_size->data[dim + 1] + paddings_data[dim * 2] +
paddings_data[dim * 2 + 1]);
TF_LITE_ENSURE(context, block_shape[dim] != 0);
TF_LITE_ENSURE_EQ(context, final_dim_size % block_shape[dim], 0);
output_size->data[dim + 1] = final_dim_size / block_shape[dim];
output_batch_size *= block_shape[dim];
}
output_size->data[0] = output_batch_size;
output_size->data[input_size->size - 1] =
input_size->data[input_size->size - 1];
return context->ResizeTensor(context, op_context->output, output_size);
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
void CxImage::Startup(uint32_t imagetype)
{
//init pointers
pDib = pSelection = pAlpha = NULL;
ppLayers = ppFrames = NULL;
//init structures
memset(&head,0,sizeof(BITMAPINFOHEADER));
memset(&info,0,sizeof(CXIMAGEINFO));
//init default attributes
info.dwType = imagetype;
info.fQuality = 90.0f;
info.nAlphaMax = 255;
info.nBkgndIndex = -1;
info.bEnabled = true;
info.nJpegScale = 1;
SetXDPI(CXIMAGE_DEFAULT_DPI);
SetYDPI(CXIMAGE_DEFAULT_DPI);
int16_t test = 1;
info.bLittleEndianHost = (*((char *) &test) == 1);
}
| 0 | C++ | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
TF_LITE_ENSURE(context, input1 != nullptr);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TF_LITE_ENSURE(context, input2 != nullptr);
if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {
auto input1_offset = -input1->params.zero_point;
auto input2_offset = -input2->params.zero_point;
const int kLeftShift = 8;
int32_t input1_multiplier;
int input1_shift;
QuantizeMultiplierSmallerThanOneExp(
static_cast<double>(input1->params.scale), &input1_multiplier,
&input1_shift);
int32_t input2_multiplier;
int input2_shift;
QuantizeMultiplierSmallerThanOneExp(
static_cast<double>(input2->params.scale), &input2_multiplier,
&input2_shift);
data->params.left_shift = kLeftShift;
data->params.input1_offset = input1_offset;
data->params.input1_multiplier = input1_multiplier;
data->params.input1_shift = input1_shift;
data->params.input2_offset = input2_offset;
data->params.input2_multiplier = input2_multiplier;
data->params.input2_shift = input2_shift;
}
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 rpc_type_of_NPNVariable(int variable)
{
int type;
switch (variable) {
case NPNVjavascriptEnabledBool:
case NPNVasdEnabledBool:
case NPNVisOfflineBool:
case NPNVSupportsXEmbedBool:
case NPNVSupportsWindowless:
case NPNVprivateModeBool:
case NPNVsupportsAdvancedKeyHandling:
type = RPC_TYPE_BOOLEAN;
break;
case NPNVToolkit:
case NPNVnetscapeWindow:
type = RPC_TYPE_UINT32;
break;
case NPNVWindowNPObject:
case NPNVPluginElementNPObject:
type = RPC_TYPE_NP_OBJECT;
break;
default:
type = RPC_ERROR_GENERIC;
break;
}
return type;
} | 1 | C++ | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | https://cwe.mitre.org/data/definitions/264.html | safe |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
if (sz < 8) {
return NULL;
}
RBinJavaAnnotation *annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | 1 | C++ | CWE-805 | Buffer Access with Incorrect Length Value | The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer. | https://cwe.mitre.org/data/definitions/805.html | safe |
static inline bool isMountable(const RemoteFsDevice::Details &d)
{
return RemoteFsDevice::constSshfsProtocol==d.url.scheme();
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
String preg_quote(const String& str,
const String& delimiter /* = null_string */) {
const char* in_str = str.data();
const char* in_str_end = in_str + str.size();
/* Nothing to do if we got an empty string */
if (in_str == in_str_end) {
return str;
}
char delim_char = 0; /* Delimiter character to be quoted */
bool quote_delim = false; /* Whether to quote additional delim char */
if (!delimiter.empty()) {
delim_char = delimiter.charAt(0);
quote_delim = true;
}
/* Allocate enough memory so that even if each character
is quoted, we won't run out of room */
static_assert(
(StringData::MaxSize * 4 + 1) < std::numeric_limits<int64_t>::max()
);
String ret(4 * str.size() + 1, ReserveString);
char* out_str = ret.mutableData();
/* Go through the string and quote necessary characters */
const char* p;
char* q;
for (p = in_str, q = out_str; p != in_str_end; p++) {
char c = *p;
switch (c) {
case '.': case '\\': case '+': case '*': case '?':
case '[': case '^': case ']': case '$': case '(':
case ')': case '{': case '}': case '=': case '!':
case '>': case '<': case '|': case ':': case '-':
case '#':
*q++ = '\\';
*q++ = c;
break;
case '\0':
*q++ = '\\';
*q++ = '0';
*q++ = '0';
*q++ = '0';
break;
default:
if (quote_delim && c == delim_char)
*q++ = '\\';
*q++ = c;
break;
}
}
*q = '\0';
return ret.setSize(q - out_str);
} | 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 whenInputIs(const char *json, size_t len) {
memcpy(_jsonString, json, len);
_result = QuotedString::extractFrom(_jsonString, &_trailing);
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// TODO(b/140515557): Add cached dequant to improve hybrid model performance.
const TfLiteTensor* input = GetInput(context, node, 0);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE(context, input->type == kTfLiteUInt8 ||
input->type == kTfLiteInt8 ||
input->type == kTfLiteInt16);
TF_LITE_ENSURE(
context, output->type == kTfLiteFloat32 || output->type == kTfLiteInt32);
if (output->type == kTfLiteInt32) {
const double effective_output_scale =
static_cast<double>(input->params.scale) /
static_cast<double>(output->params.scale);
QuantizeMultiplier(effective_output_scale, &data->output_multiplier,
&data->output_shift);
}
data->quantization_params.zero_point = input->params.zero_point;
data->quantization_params.scale = static_cast<double>(input->params.scale);
data->output_zero_point = output->params.zero_point;
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 |
selReadStream(FILE *fp)
{
char *selname;
char linebuf[L_BUFSIZE];
l_int32 sy, sx, cy, cx, i, j, version, ignore;
SEL *sel;
PROCNAME("selReadStream");
if (!fp)
return (SEL *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, " Sel Version %d\n", &version) != 1)
return (SEL *)ERROR_PTR("not a sel file", procName, NULL);
if (version != SEL_VERSION_NUMBER)
return (SEL *)ERROR_PTR("invalid sel version", procName, NULL);
if (fgets(linebuf, L_BUFSIZE, fp) == NULL)
return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL);
selname = stringNew(linebuf);
sscanf(linebuf, " ------ %200s ------", selname);
if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n",
&sy, &sx, &cy, &cx) != 4) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("dimensions not read", procName, NULL);
}
if ((sel = selCreate(sy, sx, selname)) == NULL) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
}
selSetOrigin(sel, cy, cx);
for (i = 0; i < sy; i++) {
ignore = fscanf(fp, " ");
for (j = 0; j < sx; j++)
ignore = fscanf(fp, "%1d", &sel->data[i][j]);
ignore = fscanf(fp, "\n");
}
ignore = fscanf(fp, "\n");
LEPT_FREE(selname);
return sel;
} | 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 HardSwishPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_STATUS(GenericPrepare(context, node));
TfLiteTensor* output = GetOutput(context, node, 0);
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) {
HardSwishData* data = static_cast<HardSwishData*>(node->user_data);
HardSwishParams* params = &data->params;
const TfLiteTensor* input = GetInput(context, node, 0);
params->input_zero_point = input->params.zero_point;
params->output_zero_point = output->params.zero_point;
const float input_scale = input->params.scale;
const float hires_input_scale = (1.0f / 128.0f) * input_scale;
const float reluish_scale = 3.0f / 32768.0f;
const float output_scale = output->params.scale;
const float output_multiplier = hires_input_scale / output_scale;
int32_t output_multiplier_fixedpoint_int32;
QuantizeMultiplier(output_multiplier, &output_multiplier_fixedpoint_int32,
¶ms->output_multiplier_exponent);
DownScaleInt32ToInt16Multiplier(
output_multiplier_fixedpoint_int32,
¶ms->output_multiplier_fixedpoint_int16);
TF_LITE_ENSURE(context, params->output_multiplier_exponent <= 0);
const float reluish_multiplier = hires_input_scale / reluish_scale;
int32_t reluish_multiplier_fixedpoint_int32;
QuantizeMultiplier(reluish_multiplier, &reluish_multiplier_fixedpoint_int32,
¶ms->reluish_multiplier_exponent);
DownScaleInt32ToInt16Multiplier(
reluish_multiplier_fixedpoint_int32,
¶ms->reluish_multiplier_fixedpoint_int16);
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void ComputeAsync(OpKernelContext* c, DoneCallback done) override {
auto col_params = new CollectiveParams();
auto done_with_cleanup = [col_params, done = std::move(done)]() {
done();
col_params->Unref();
};
core::RefCountPtr<CollectiveGroupResource> resource;
OP_REQUIRES_OK_ASYNC(c, LookupResource(c, HandleFromInput(c, 1), &resource),
done);
Tensor group_assignment = c->input(2);
OP_REQUIRES_OK_ASYNC(
c,
FillCollectiveParams(col_params, group_assignment, REDUCTION_COLLECTIVE,
resource.get()),
done);
col_params->instance.shape = c->input(0).shape();
col_params->merge_op = merge_op_.get();
col_params->final_op = final_op_.get();
VLOG(1) << "CollectiveReduceV3 group_size " << col_params->group.group_size
<< " group_key " << col_params->group.group_key << " instance_key "
<< col_params->instance.instance_key;
// Allocate the output tensor, trying to reuse the input.
Tensor* output = nullptr;
OP_REQUIRES_OK_ASYNC(c,
c->forward_input_or_allocate_output(
{0}, 0, col_params->instance.shape, &output),
done_with_cleanup);
Run(c, col_params, std::move(done_with_cleanup));
} | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,
int index) {
if (index >= 0 && index < node->outputs->size) {
const int tensor_index = node->outputs->data[index];
if (tensor_index != kTfLiteOptionalTensor) {
if (context->tensors != nullptr) {
return &context->tensors[tensor_index];
} else {
return context->GetTensor(context, tensor_index);
}
}
}
return nullptr;
} | 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 Messageheader::Parser::checkHeaderspace(unsigned chars) const
{
if (headerdataPtr + chars >= header.rawdata + sizeof(header.rawdata))
{
header.rawdata[sizeof(header.rawdata) - 1] = '\0';
throw HttpError(HTTP_REQUEST_ENTITY_TOO_LARGE, "header too large");
}
} | 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 |
void readStructEnd() {
if (!nestedStructFieldIds_.empty()) {
lastFieldId_ = nestedStructFieldIds_.back();
nestedStructFieldIds_.pop_back();
}
} | 1 | C++ | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = offset;
return attr;
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,
TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// Make sure that the input is in uint8_t with at least 1 data entry.
const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);
if (input->type != kTfLiteUInt8) return kTfLiteError;
if (NumElements(input->dims) == 0) return kTfLiteError;
// Allocate a temporary buffer with the same size of input for sorting.
TF_LITE_ENSURE_STATUS(context->RequestScratchBufferInArena(
context, sizeof(uint8_t) * NumElements(input->dims),
&data->sorting_buffer));
// We can interleave scratch / persistent buffer allocation.
data->invoke_count = reinterpret_cast<int*>(
context->AllocatePersistentBuffer(context, sizeof(int)));
*data->invoke_count = 0;
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 |
int64_t OpLevelCostEstimator::CalculateOutputSize(const OpInfo& op_info,
bool* found_unknown_shapes) {
int64_t total_output_size = 0;
// Use float as default for calculations.
for (const auto& output : op_info.outputs()) {
DataType dt = output.dtype();
const auto& original_output_shape = output.shape();
int64_t output_size = DataTypeSize(BaseType(dt));
int num_dims = std::max(1, original_output_shape.dim_size());
auto output_shape = MaybeGetMinimumShape(original_output_shape, num_dims,
found_unknown_shapes);
for (const auto& dim : output_shape.dim()) {
int64_t new_output_size =
MultiplyWithoutOverflow(output_size, dim.size());
if (new_output_size < 0) {
VLOG(1) << "Overflow encountered when estimating cost, multiplying "
<< output_size << " with " << dim.size();
return -1;
}
output_size = new_output_size;
}
total_output_size += output_size;
VLOG(1) << "Output Size: " << output_size
<< " Total Output Size:" << total_output_size;
}
return total_output_size;
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.