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 |
---|---|---|---|---|---|---|---|
TfLiteStatus ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
// Segment ids should be of same cardinality as first input dimension and they
// should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)
const int segment_id_size = segment_ids->dims->data[0];
TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);
int previous_segment_id = -1;
for (int i = 0; i < segment_id_size; i++) {
const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i];
if (i == 0) {
TF_LITE_ENSURE_EQ(context, current_segment_id, 0);
} else {
int delta = current_segment_id - previous_segment_id;
TF_LITE_ENSURE(context, delta == 0 || delta == 1);
}
previous_segment_id = current_segment_id;
}
const int max_index = previous_segment_id;
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
jas_matrix_t *jas_seq2d_input(FILE *in)
{
jas_matrix_t *matrix;
jas_matind_t i;
jas_matind_t j;
long x;
jas_matind_t numrows;
jas_matind_t numcols;
jas_matind_t xoff;
jas_matind_t yoff;
long tmp_xoff;
long tmp_yoff;
long tmp_numrows;
long tmp_numcols;
if (fscanf(in, "%ld %ld", &tmp_xoff, &tmp_yoff) != 2) {
return 0;
}
xoff = tmp_xoff;
yoff = tmp_yoff;
if (fscanf(in, "%ld %ld", &tmp_numcols, &tmp_numrows) != 2) {
return 0;
}
numrows = tmp_numrows;
numcols = tmp_numcols;
if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols,
yoff + numrows))) {
return 0;
}
if (jas_matrix_numrows(matrix) != numrows ||
jas_matrix_numcols(matrix) != numcols) {
abort();
}
/* Get matrix data. */
for (i = 0; i < jas_matrix_numrows(matrix); i++) {
for (j = 0; j < jas_matrix_numcols(matrix); j++) {
if (fscanf(in, "%ld", &x) != 1) {
jas_matrix_destroy(matrix);
return 0;
}
jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
}
}
return matrix;
} | 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 Relu1Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data);
switch (input->type) {
case kTfLiteFloat32: {
optimized_ops::Relu1(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output),
GetTensorData<float>(output));
return kTfLiteOk;
} break;
case kTfLiteUInt8: {
QuantizedReluX<uint8_t>(-1.0f, 1.0f, input, output, data);
return kTfLiteOk;
} break;
case kTfLiteInt8: {
QuantizedReluX<int8_t>(-1, 1, input, output, data);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(context,
"Only float32, uint8, int8 supported "
"currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | 1 | C++ | CWE-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 |
LiteralString(std::string &&s, bool ignore_case)
: lit_(s), ignore_case_(ignore_case),
is_word_(false) {} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
} | 0 | C++ | CWE-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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output_index_tensor = GetOutput(context, node, 1);
TF_LITE_ENSURE_EQ(context, NumElements(output_index_tensor),
NumElements(input));
switch (input->type) {
case kTfLiteInt8:
TF_LITE_ENSURE_STATUS(EvalImpl<int8_t>(context, input, node));
break;
case kTfLiteInt16:
TF_LITE_ENSURE_STATUS(EvalImpl<int16_t>(context, input, node));
break;
case kTfLiteInt32:
TF_LITE_ENSURE_STATUS(EvalImpl<int32_t>(context, input, node));
break;
case kTfLiteInt64:
TF_LITE_ENSURE_STATUS(EvalImpl<int64_t>(context, input, node));
break;
case kTfLiteFloat32:
TF_LITE_ENSURE_STATUS(EvalImpl<float>(context, input, node));
break;
case kTfLiteUInt8:
TF_LITE_ENSURE_STATUS(EvalImpl<uint8_t>(context, input, node));
break;
default:
context->ReportError(context, "Currently Unique doesn't support type: %s",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
setSanMatchers(std::vector<envoy::type::matcher::v3::StringMatcher> san_matchers) {
san_matchers_ = san_matchers;
return *this;
} | 0 | C++ | CWE-295 | Improper Certificate Validation | The software does not validate, or incorrectly validates, a certificate. | https://cwe.mitre.org/data/definitions/295.html | vulnerable |
TfLiteRegistration CopyOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// Set output size to input size
const TfLiteTensor* tensor0 = GetInput(context, node, 0);
TfLiteTensor* tensor1 = GetOutput(context, node, 0);
TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);
return context->ResizeTensor(context, tensor1, newSize);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
CallReporting* call_reporting =
static_cast<CallReporting*>(node->builtin_data);
// Copy input data to output data.
const TfLiteTensor* a0 = GetInput(context, node, 0);
TfLiteTensor* a1 = GetOutput(context, node, 0);
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
a1->data.f[i] = a0->data.f[i];
}
call_reporting->Record();
return kTfLiteOk;
};
return reg;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
int64_t OutputFile::readImpl(char* /*buffer*/, int64_t /*length*/) {
raise_warning("cannot read from a php://output stream");
return -1;
} | 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 |
_forceinline void Unpack::CopyString(uint Length,uint Distance)
{
size_t SrcPtr=UnpPtr-Distance;
if (SrcPtr<MaxWinSize-MAX_LZ_MATCH && UnpPtr<MaxWinSize-MAX_LZ_MATCH)
{
// If we are not close to end of window, we do not need to waste time
// to "& MaxWinMask" pointer protection.
byte *Src=Window+SrcPtr;
byte *Dest=Window+UnpPtr;
UnpPtr+=Length;
#ifdef FAST_MEMCPY
if (Distance<Length) // Overlapping strings
#endif
while (Length>=8)
{
Dest[0]=Src[0];
Dest[1]=Src[1];
Dest[2]=Src[2];
Dest[3]=Src[3];
Dest[4]=Src[4];
Dest[5]=Src[5];
Dest[6]=Src[6];
Dest[7]=Src[7];
Src+=8;
Dest+=8;
Length-=8;
}
#ifdef FAST_MEMCPY
else
while (Length>=8)
{
// In theory we still could overlap here.
// Supposing Distance == MaxWinSize - 1 we have memcpy(Src, Src + 1, 8).
// But for real RAR archives Distance <= MaxWinSize - MAX_LZ_MATCH
// always, so overlap here is impossible.
// This memcpy expanded inline by MSVC. We could also use uint64
// assignment, which seems to provide about the same speed.
memcpy(Dest,Src,8);
Src+=8;
Dest+=8;
Length-=8;
}
#endif
// Unroll the loop for 0 - 7 bytes left. Note that we use nested "if"s.
if (Length>0) { Dest[0]=Src[0];
if (Length>1) { Dest[1]=Src[1];
if (Length>2) { Dest[2]=Src[2];
if (Length>3) { Dest[3]=Src[3];
if (Length>4) { Dest[4]=Src[4];
if (Length>5) { Dest[5]=Src[5];
if (Length>6) { Dest[6]=Src[6]; } } } } } } } // Close all nested "if"s.
}
else
while (Length-- > 0) // Slow copying with all possible precautions.
{
Window[UnpPtr]=Window[SrcPtr++ & MaxWinMask];
// We need to have masked UnpPtr after quit from loop, so it must not
// be replaced with 'Window[UnpPtr++ & MaxWinMask]'
UnpPtr=(UnpPtr+1) & MaxWinMask;
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
true, NULL);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) :
AP4_Atom(AP4_ATOM_TYPE_AVCC, size)
{
// make a copy of our configuration bytes
unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE;
m_RawBytes.SetData(payload, payload_size);
// parse the payload
m_ConfigurationVersion = payload[0];
m_Profile = payload[1];
m_ProfileCompatibility = payload[2];
m_Level = payload[3];
m_NaluLengthSize = 1+(payload[4]&3);
AP4_UI08 num_seq_params = payload[5]&31;
m_SequenceParameters.EnsureCapacity(num_seq_params);
unsigned int cursor = 6;
for (unsigned int i=0; i<num_seq_params; i++) {
if (cursor+2 <= payload_size) {
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
cursor += 2;
if (cursor + param_length < payload_size) {
m_SequenceParameters.Append(AP4_DataBuffer());
m_SequenceParameters[i].SetData(&payload[cursor], param_length);
cursor += param_length;
}
}
}
AP4_UI08 num_pic_params = payload[cursor++];
m_PictureParameters.EnsureCapacity(num_pic_params);
for (unsigned int i=0; i<num_pic_params; i++) {
if (cursor+2 <= payload_size) {
AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]);
cursor += 2;
if (cursor + param_length < payload_size) {
m_PictureParameters.Append(AP4_DataBuffer());
m_PictureParameters[i].SetData(&payload[cursor], param_length);
cursor += param_length;
}
}
}
} | 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 |
QString Utils::String::toHtmlEscaped(const QString &str)
{
#ifdef QBT_USES_QT5
return str.toHtmlEscaped();
#else
return Qt::escape(str);
#endif
} | 1 | C++ | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* data =
reinterpret_cast<TfLiteAudioMicrofrontendParams*>(node->user_data);
FrontendReset(data->state);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (data->out_float) {
GenerateFeatures<float>(data, input, output);
} else {
GenerateFeatures<int32>(data, input, output);
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TEST_F(HttpConnectionManagerImplTest, OverlyLongHeadersRejected) {
setup(false, "");
std::string response_code;
std::string response_body;
EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> void {
StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_);
HeaderMapPtr headers{
new TestHeaderMapImpl{{":authority", "host"}, {":path", "/"}, {":method", "GET"}}};
headers->addCopy(LowerCaseString("Foo"), std::string(60 * 1024, 'a'));
EXPECT_CALL(response_encoder_, encodeHeaders(_, true))
.WillOnce(Invoke([&response_code](const HeaderMap& headers, bool) -> void {
response_code = std::string(headers.Status()->value().getStringView());
}));
decoder->decodeHeaders(std::move(headers), true);
conn_manager_->newStream(response_encoder_);
}));
Buffer::OwnedImpl fake_input("1234");
conn_manager_->onData(fake_input, false); // kick off request
EXPECT_EQ("431", response_code);
EXPECT_EQ("", response_body);
} | 0 | C++ | CWE-400 | Uncontrolled Resource Consumption | The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaBootStrapMethod *bsm = NULL;
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR;
if (offset + 8 > sz) {
free (attr);
return NULL;
}
attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);
for (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) {
// bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur);
if (offset >= sz) {
break;
}
bsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset);
if (bsm) {
offset += bsm->size;
r_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
attr->size = offset;
}
return attr;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
bool chopOff(string &domain)
{
if(domain.empty())
return false;
string::size_type fdot=domain.find('.');
if(fdot==string::npos)
domain="";
else {
string::size_type remain = domain.length() - (fdot + 1);
char tmp[remain];
memcpy(tmp, domain.c_str()+fdot+1, remain);
domain.assign(tmp, remain); // don't dare to do this w/o tmp holder :-)
}
return true;
} | 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 |
TfLiteStatus ResizeOutputTensors(TfLiteContext* context, TfLiteNode* node,
const TfLiteTensor* axis,
const TfLiteTensor* input, int num_splits) {
int axis_value = GetTensorData<int>(axis)[0];
if (axis_value < 0) {
axis_value += NumDimensions(input);
}
TF_LITE_ENSURE(context, axis_value >= 0);
TF_LITE_ENSURE(context, axis_value < NumDimensions(input));
const int input_size = SizeOfDimension(input, axis_value);
TF_LITE_ENSURE_MSG(context, input_size % num_splits == 0,
"Not an even split");
const int slice_size = input_size / num_splits;
for (int i = 0; i < NumOutputs(node); ++i) {
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);
output_dims->data[axis_value] = slice_size;
TfLiteTensor* output = GetOutput(context, node, i);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_dims));
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
} | 0 | C++ | CWE-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 RemoteDevicePropertiesWidget::checkSaveable()
{
RemoteFsDevice::Details det=details();
modified=det!=orig;
saveable=!det.isEmpty();
if (saveable && Type_SambaAvahi==type->itemData(type->currentIndex()).toInt()) {
saveable=!smbAvahiName->text().trimmed().isEmpty();
}
emit updated();
} | 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 AverageEval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));
switch (input->type) { // Already know in/out types are same.
case kTfLiteFloat32:
AverageEvalFloat<kernel_type>(context, node, params, data, input, output);
break;
case kTfLiteUInt8:
AverageEvalQuantizedUint8<kernel_type>(context, node, params, data, input,
output);
break;
case kTfLiteInt8:
AverageEvalQuantizedInt8<kernel_type>(context, node, params, data, input,
output);
break;
case kTfLiteInt16:
AverageEvalQuantizedInt16<kernel_type>(context, node, params, data, input,
output);
break;
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers,
int *algIds)
{
char *startCur = ciphers;
int algCount = 0;
while(startCur && (0 != *startCur) && (algCount < NUMOF_CIPHERS)) {
long alg = strtol(startCur, 0, 0);
if(!alg)
alg = get_alg_id_by_name(startCur);
if(alg)
algIds[algCount++] = alg;
else if(!strncmp(startCur, "USE_STRONG_CRYPTO",
sizeof("USE_STRONG_CRYPTO") - 1) ||
!strncmp(startCur, "SCH_USE_STRONG_CRYPTO",
sizeof("SCH_USE_STRONG_CRYPTO") - 1))
schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO;
else
return CURLE_SSL_CIPHER;
startCur = strchr(startCur, ':');
if(startCur)
startCur++;
}
schannel_cred->palgSupportedAlgs = algIds;
schannel_cred->cSupportedAlgs = algCount;
return CURLE_OK;
} | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* axis = GetInput(context, node, kAxisTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(axis), 1);
TF_LITE_ENSURE(context, NumDimensions(input) >= NumElements(axis));
if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 &&
input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 &&
input->type != kTfLiteInt64 && input->type != kTfLiteBool) {
context->ReportError(context, "Type '%s' is not supported by reverse.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
if (axis->type != kTfLiteInt32) {
context->ReportError(context, "Axis Type '%s' is not supported by reverse.",
TfLiteTypeGetName(axis->type));
return kTfLiteError;
}
// TODO(renjieliu): support multi-axis case.
if (NumElements(axis) > 1) {
context->ReportError(context, "Current does not support more than 1 axis.");
}
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);
return context->ResizeTensor(context, output, output_shape);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
static void compact(PointerSet& seen,
VarEnv* v, Array &ret, const Variant& var) {
if (var.isArray()) {
auto adata = var.getArrayData();
auto check = couldRecur(var, adata);
if (check && !seen.insert(adata).second) {
raise_warning("compact(): recursion detected");
return;
}
for (ArrayIter iter(adata); iter; ++iter) {
compact(seen, v, ret, iter.secondRef());
}
if (check) seen.erase(adata);
} else {
String varname = var.toString();
if (!varname.empty() && v->lookup(varname.get()) != NULL) {
ret.set(varname, *reinterpret_cast<Variant*>(v->lookup(varname.get())));
}
}
} | 1 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
TfLiteStatus Subgraph::AllocateTensors() {
TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "AllocateTensors");
if (!consistent_) {
ReportError("AllocateTensors() called on inconsistent model.");
return kTfLiteError;
}
// Restore delegation state if applicable.
TF_LITE_ENSURE_STATUS(RedoAllDelegates());
// Explicit (re)allocation is necessary if nodes have been changed or tensors
// have been resized. For inputs marked as dynamic, we can't short-circuit the
// allocation as the client may have done the resize manually.
if (state_ != kStateUninvokable &&
!HasDynamicTensorImpl(context_, inputs())) {
if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {
// If the only change was the release of non-persistent memory via
// ReleaseNonPersistentMemory(), just re-allocate it. For any other type
// of memory-planning change (for eg, ResizeInputTensor), the state would
// be kStateUninvokable.
memory_planner_->AcquireNonPersistentMemory();
}
return kTfLiteOk;
}
// Note `AllocateTensors` sometimes calls itself recursively above
// for delegates. Therefore only the logic below need to be guarded
// by `SubgraphGuard`.
SubgraphGuard guard(&context_, &is_subgraph_in_use_);
TF_LITE_ENSURE_OK(&context_, guard.status());
next_execution_plan_index_to_prepare_ = 0;
next_execution_plan_index_to_plan_allocation_ = 0;
next_original_execution_plan_index_to_prepare_ = 0;
if (memory_planner_) {
TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations());
}
TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());
state_ = kStateInvokable;
// Reset the variable tensors to zero after (re)allocating the tensors.
// Developers shouldn't rely on the side effect of this function to reset
// variable tensors. They should call `ResetVariableTensors` directly
// instead.
ResetVariableTensors();
return kTfLiteOk;
} | 1 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);
const TfLiteTensor* segment_ids =
GetInput(context, node, kInputSegmentIdsTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context,
data->type == kTfLiteInt32 || data->type == kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, segment_ids->type, kTfLiteInt32);
if (!IsConstantTensor(data) || !IsConstantTensor(segment_ids)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, data, segment_ids, output);
} | 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 =
GetInput(context, node, kInputVariableId);
TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);
TfLiteTensor* output = GetOutput(context, node, kOutputValue);
SetTensorToDynamic(output);
return kTfLiteOk;
} | 0 | C++ | CWE-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 ParseAttrValueHelper_TensorNestsUnderLimit(int limit, string to_parse) {
int nests = 0;
int maxed_out = to_parse.length();
int open_curly = to_parse.find('{');
int open_bracket = to_parse.find('<');
int close_curly = to_parse.find('}');
int close_bracket = to_parse.find('>');
if (open_curly == -1) {
open_curly = maxed_out;
}
if (open_bracket == -1) {
open_bracket = maxed_out;
}
int min = std::min(open_curly, open_bracket);
do {
if (open_curly == maxed_out && open_bracket == maxed_out) {
return true;
}
if (min == open_curly) {
nests += 1;
open_curly = to_parse.find('{', open_curly + 1);
if (open_curly == -1) {
open_curly = maxed_out;
}
} else if (min == open_bracket) {
nests += 1;
open_bracket = to_parse.find('<', open_bracket + 1);
if (open_bracket == -1) {
open_bracket = maxed_out;
}
} else if (min == close_curly) {
nests -= 1;
close_curly = to_parse.find('}', close_curly + 1);
if (close_curly == -1) {
close_curly = maxed_out;
}
} else if (min == close_bracket) {
nests -= 1;
close_bracket = to_parse.find('>', close_bracket + 1);
if (close_bracket == -1) {
close_bracket = maxed_out;
}
}
min = std::min({open_curly, open_bracket, close_curly, close_bracket});
} while (nests < 100);
return false;
} | 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 |
int multiplyCheckOverflow(int a, int b, int *result)
{
#if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow))
return __builtin_mul_overflow(a, b, result);
#else
if (firstBitSet(a)+firstBitSet(b)>31) // int is signed, so we can't use 32 bits
return true;
*result = a * b;
return false;
#endif
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input->type) {
case kTfLiteInt64:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int64_t>(input),
GetTensorShape(output), GetTensorData<int64_t>(output));
break;
case kTfLiteInt32:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int32_t>(input),
GetTensorShape(output), GetTensorData<int32_t>(output));
break;
case kTfLiteFloat32:
reference_ops::Negate(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output),
GetTensorData<float>(output));
break;
default:
context->ReportError(
context,
"Neg only currently supports int64, int32, and float32, got %d.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
old_cs = get_segment_selector(ctxt, VCPU_SREG_CS);
old_eip = ctxt->_eip;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
if (load_segment_descriptor(ctxt, sel, VCPU_SREG_CS))
return X86EMUL_CONTINUE;
ctxt->_eip = 0;
memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes);
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = old_eip;
return em_push(ctxt);
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
TEST(CudnnRNNOpsTest, ForwardLstm_ShapeFn) {
int seq_length = 2;
int batch_size = 3;
int num_units = 4;
int num_layers = 5;
int dir_count = 1;
std::vector<int> input_shape = {seq_length, batch_size, num_units};
std::vector<int> input_h_shape = {num_layers * dir_count, batch_size,
num_units};
std::vector<int> output_shape = {seq_length, batch_size,
num_units * dir_count};
auto shape_to_str = [](const std::vector<int>& v) {
return strings::StrCat("[", absl::StrJoin(v, ","), "]");
};
string input_shapes_desc = strings::StrCat(
shape_to_str(input_shape), ";", shape_to_str(input_h_shape), ";",
shape_to_str(input_h_shape), ";", "[?]");
string output_shapes_desc = "[d0_0,d0_1,d1_2];in1;in1;?";
ShapeInferenceTestOp op("CudnnRNN");
TF_ASSERT_OK(NodeDefBuilder("test", "CudnnRNN")
.Input({"input", 0, DT_FLOAT})
.Input({"input_h", 0, DT_FLOAT})
.Input({"input_c", 0, DT_FLOAT})
.Input({"params", 0, DT_FLOAT})
.Attr("rnn_mode", "lstm")
.Attr("input_mode", "auto_select")
.Attr("direction", "unidirectional")
.Finalize(&op.node_def));
INFER_OK(op, input_shapes_desc, output_shapes_desc);
INFER_ERROR("Shape must be rank 3 ", op, "[];[?,?,?];[?,?,?];[?]");
INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[];[?,?,?];[?]");
// Disabled because the kernel does not check shape of input_c.
// INFER_ERROR("Shape must be rank 3 ", op, "[?,?,?];[?,?,?];[?];[?]");
INFER_ERROR("Shape must be rank 1 ", op, "[?,?,?];[?,?,?];[?,?,?];[]");
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
jas_seqent_t maxval)
{
int i;
int j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
int rowstep;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
} | 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 |
AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)
{
inspector.AddField("Configuration Version", m_ConfigurationVersion);
const char* profile_name = GetProfileName(m_Profile);
if (profile_name) {
inspector.AddField("Profile", profile_name);
} else {
inspector.AddField("Profile", m_Profile);
}
inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX);
inspector.AddField("Level", m_Level);
inspector.AddField("NALU Length Size", m_NaluLengthSize);
for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) {
inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize());
}
for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) {
inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize());
}
return AP4_SUCCESS;
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
void AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return; // Already allocated
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)
{
SynError(it8, "AllocateDataSet: too much data");
}
else {
t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
}
} | 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 AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride,
int pad_width, int pad_height, int filter_width,
int filter_height, int32 output_activation_min,
int32 output_activation_max, uint8* output_data,
const Dims<4>& output_dims) {
AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height,
filter_width, filter_height, output_activation_min,
output_activation_max, output_data, output_dims);
} | 0 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Reinterprete the opaque data provided by user.
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
if (type != kTfLiteBool) {
context->ReportError(context, "Logical ops only support bool type.");
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-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 RBinJavaAttrInfo *r_bin_java_enclosing_methods_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 || sz < 10) {
free (attr);
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_ENCLOSING_METHOD_ATTR;
attr->info.enclosing_method_attr.class_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.enclosing_method_attr.method_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.enclosing_method_attr.class_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.class_idx);
if (attr->info.enclosing_method_attr.class_name == NULL) {
eprintf ("Could not resolve enclosing class name for the enclosed method.\n");
}
attr->info.enclosing_method_attr.method_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);
if (attr->info.enclosing_method_attr.class_name == NULL) {
eprintf ("Could not resolve method descriptor for the enclosed method.\n");
}
attr->info.enclosing_method_attr.method_descriptor = r_bin_java_get_desc_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);
if (attr->info.enclosing_method_attr.method_name == NULL) {
eprintf ("Could not resolve method name for the enclosed method.\n");
}
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 |
TEST(TensorSliceReaderTest, MissingTensorType) {
const string fname = io::JoinPath(testing::TmpDir(), "invalid_checkpoint");
TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder);
const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
TensorShape shape({4, 5});
TensorSlice slice = TensorSlice::ParseOrDie("0,2:-");
TF_CHECK_OK(writer.Add("test", shape, slice, data));
TF_CHECK_OK(writer.Finish());
MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) {
if (sts.has_meta()) {
for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) {
tensor.clear_type();
}
}
return sts.SerializeAsString();
});
TensorSliceReader reader(fname, OpenTableTensorSliceReader);
TF_CHECK_OK(reader.status());
// The tensor should be present, but loading it should fail due to the
// unset (invalid) type.
EXPECT_TRUE(reader.HasTensor("test", nullptr, nullptr));
std::unique_ptr<Tensor> tensor;
EXPECT_FALSE(reader.GetTensor("test", &tensor).ok());
} | 1 | C++ | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
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;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
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;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (sz < 8) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = 6;
return attr;
} | 1 | C++ | CWE-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 float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
} | 0 | C++ | CWE-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 chopOffDotted(string &domain)
{
if(domain.empty() || (domain.size()==1 && domain[0]=='.'))
return false;
bool escaped = false;
const string::size_type domainLen = domain.length();
for (size_t fdot = 0; fdot < domainLen; fdot++)
{
if (domain[fdot] == '.' && !escaped) {
if (fdot==domain.size()-1) {
domain=".";
}
else {
string::size_type remain = domainLen - (fdot + 1);
char tmp[remain];
memcpy(tmp, domain.c_str()+fdot+1, remain);
domain.assign(tmp, remain); // don't dare to do this w/o tmp holder :-)
}
return true;
}
else if (domain[fdot] == '\\' && !escaped) {
escaped = true;
}
else {
escaped = false;
}
}
return false;
} | 1 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | safe |
friend H AbslHashValue(H h, const TensorKey& k) {
if (DataTypeCanUseMemcpy(k.dtype())) {
return H::combine(std::move(h), k.tensor_data());
} else if (k.dtype() == DT_STRING) {
const auto strs = k.unaligned_flat<tstring>();
for (int64_t i = 0, n = k.NumElements(); i < n; ++i) {
h = H::combine(std::move(h), strs(i));
}
return h;
} else {
DCHECK(false) << "Unimplemented dtype " << DataTypeString(k.dtype())
<< std::endl;
}
return h;
} | 1 | 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 | safe |
TfLiteRegistration CopyOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// Set output size to input size
const TfLiteTensor* tensor0;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));
TfLiteTensor* tensor1;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));
TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);
return context->ResizeTensor(context, tensor1, newSize);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
CallReporting* call_reporting =
static_cast<CallReporting*>(node->builtin_data);
// Copy input data to output data.
const TfLiteTensor* a0;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));
TfLiteTensor* a1;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
a1->data.f[i] = a0->data.f[i];
}
call_reporting->Record();
return kTfLiteOk;
};
return reg;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void CharToWideMap(const char *Src,wchar *Dest,size_t DestSize,bool &Success)
{
// Map inconvertible characters to private use Unicode area 0xE000.
// Mark such string by placing special non-character code before
// first inconvertible character.
Success=false;
bool MarkAdded=false;
uint SrcPos=0,DestPos=0;
while (DestPos<DestSize)
{
if (Src[SrcPos]==0)
{
Success=true;
break;
}
mbstate_t ps;
memset(&ps,0,sizeof(ps));
if (mbrtowc(Dest+DestPos,Src+SrcPos,MB_CUR_MAX,&ps)==-1)
{
// For security reasons we do not want to map low ASCII characters,
// so we do not have additional .. and path separator codes.
if (byte(Src[SrcPos])>=0x80)
{
if (!MarkAdded)
{
Dest[DestPos++]=MappedStringMark;
MarkAdded=true;
if (DestPos>=DestSize)
break;
}
Dest[DestPos++]=byte(Src[SrcPos++])+MapAreaStart;
}
else
break;
}
else
{
memset(&ps,0,sizeof(ps));
int Length=mbrlen(Src+SrcPos,MB_CUR_MAX,&ps);
SrcPos+=Max(Length,1);
DestPos++;
}
}
Dest[Min(DestPos,DestSize-1)]=0;
} | 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 TfLiteTensor* GetMutableInput(const TfLiteContext* context,
const TfLiteNode* node, int index) {
if (context->tensors != nullptr) {
return &context->tensors[node->inputs->data[index]];
} else {
return context->GetTensor(context, node->inputs->data[index]);
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {
const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);
if (!r)
return BadHdr;
return *r;
} | 0 | C++ | CWE-116 | Improper Encoding or Escaping of Output | The software prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved. | https://cwe.mitre.org/data/definitions/116.html | vulnerable |
inline int ValidateTensorIndexing(const TfLiteContext* context, int index,
int max_size, const int* tensor_indices) {
if (index >= 0 && index < max_size) {
const int tensor_index = tensor_indices[index];
if (tensor_index != kTfLiteOptionalTensor) {
return tensor_index;
}
}
return -1;
} | 1 | C++ | CWE-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 |
jas_matrix_t *jas_seq2d_create(jas_matind_t xstart, jas_matind_t ystart,
jas_matind_t xend, jas_matind_t yend)
{
jas_matrix_t *matrix;
assert(xstart <= xend && ystart <= yend);
if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {
return 0;
}
matrix->xstart_ = xstart;
matrix->ystart_ = ystart;
matrix->xend_ = xend;
matrix->yend_ = yend;
return matrix;
} | 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 |
bool PackLinuxElf32::calls_crt1(Elf32_Rel const *rel, int sz)
{
if (!dynsym || !dynstr) {
return false;
}
for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf32_Rel)), ++rel, ++relnum) {
unsigned const symnum = get_te32(&rel->r_info) >> 8;
char const *const symnam = get_dynsym_name(symnum, relnum);
if (0==strcmp(symnam, "__libc_start_main") // glibc
|| 0==strcmp(symnam, "__libc_init") // Android
|| 0==strcmp(symnam, "__uClibc_main")
|| 0==strcmp(symnam, "__uClibc_start_main"))
return true;
}
return false;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
static void nodeConstruct(struct SaveNode* node, tr_variant const* v, bool sort_dicts)
{
node->isVisited = false;
node->childIndex = 0;
if (sort_dicts && tr_variantIsDict(v))
{
/* make node->sorted a sorted version of this dictionary */
size_t const n = v->val.l.count;
struct KeyIndex* tmp = tr_new(struct KeyIndex, n);
for (size_t i = 0; i < n; i++)
{
tmp[i].val = v->val.l.vals + i;
tmp[i].keystr = tr_quark_get_string(tmp[i].val->key, NULL);
}
qsort(tmp, n, sizeof(struct KeyIndex), compareKeyIndex);
node->sorted = tr_new(tr_variant, 1);
tr_variantInitDict(node->sorted, n);
for (size_t i = 0; i < n; ++i)
{
node->sorted->val.l.vals[i] = *tmp[i].val;
}
node->sorted->val.l.count = n;
tr_free(tmp);
v = node->sorted;
}
else
{
node->sorted = NULL;
}
node->v = v;
} | 1 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | safe |
bool VerifySparsity(const RuntimeShape& weights_shape,
const RuntimeShape& input_shape,
const RuntimeShape& output_shape,
const TfLiteSparsity* sparsity) {
const int weights_dims_count = weights_shape.DimensionsCount();
const int output_dims_count = output_shape.DimensionsCount();
const int w0_size = sparsity->dim_metadata[0].dense_size;
const int accum_depth = weights_shape.Dims(weights_dims_count - 1);
const int output_elements = output_shape.FlatSize();
const int input_elements = input_shape.FlatSize();
const int batches = FlatSizeSkipDim(output_shape, output_dims_count - 1);
const int output_depth = MatchingDim(weights_shape, weights_dims_count - 2,
output_shape, output_dims_count - 1);
const int max_batch_index = batches - 1;
const int max_output = max_batch_index * output_depth + w0_size;
const int max_batch_depth = accum_depth * max_batch_index;
// Verify output size is enough.
if (output_elements < max_output) return false;
// Verify index from sparse in input is valid.
for (int i = 0; i < sparsity->dim_metadata[1].array_indices->size; ++i) {
if (input_elements <=
max_batch_depth + sparsity->dim_metadata[1].array_indices->data[i])
return false;
}
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 |
static int em_sysenter(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
ops->get_msr(ctxt, MSR_EFER, &efer);
/* inject #GP if in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL)
return emulate_gp(ctxt, 0);
/*
* Not recognized on AMD in compat mode (but is recognized in legacy
* mode).
*/
if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA)
&& !vendor_intel(ctxt))
return emulate_ud(ctxt);
/* sysenter/sysexit have not been tested in 64bit mode. */
if (ctxt->mode == X86EMUL_MODE_PROT64)
return X86EMUL_UNHANDLEABLE;
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
switch (ctxt->mode) {
case X86EMUL_MODE_PROT32:
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
break;
case X86EMUL_MODE_PROT64:
if (msr_data == 0x0)
return emulate_gp(ctxt, 0);
break;
default:
break;
}
ctxt->eflags &= ~(EFLG_VM | EFLG_IF);
cs_sel = (u16)msr_data;
cs_sel &= ~SELECTOR_RPL_MASK;
ss_sel = cs_sel + 8;
ss_sel &= ~SELECTOR_RPL_MASK;
if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
*reg_write(ctxt, VCPU_REGS_RSP) = msr_data;
return X86EMUL_CONTINUE;
} | 0 | C++ | CWE-269 | Improper Privilege Management | The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. | https://cwe.mitre.org/data/definitions/269.html | vulnerable |
static int closeVirtualHostDirective(MaState *state, cchar *key, cchar *value)
{
HttpEndpoint *endpoint;
char *address, *ip, *addresses, *tok;
int port;
if (state->enabled) {
if (state->endpoints && *state->endpoints) {
addresses = state->endpoints;
while ((address = stok(addresses, " \t,", &tok)) != 0) {
addresses = 0;
mprParseSocketAddress(address, &ip, &port, NULL, -1);
if ((endpoint = httpLookupEndpoint(ip, port)) == 0) {
mprLog("error appweb config", 0, "Cannot find listen directive for virtual host %s", address);
return MPR_ERR_BAD_SYNTAX;
} else {
httpAddHostToEndpoint(endpoint, state->host);
}
}
} else {
httpAddHostToEndpoints(state->host);
}
}
closeDirective(state, key, value);
return 0;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
// Check that the inputs and outputs have the right sizes and types.
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output_values;
TF_LITE_ENSURE_OK(
context, GetOutputSafe(context, node, kOutputValues, &output_values));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output_values->type);
const TfLiteTensor* top_k;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTopK, &top_k));
TF_LITE_ENSURE_TYPES_EQ(context, top_k->type, kTfLiteInt32);
// Set output dynamic if the input is not const.
if (IsConstantTensor(top_k)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
TfLiteTensor* output_indexes;
TF_LITE_ENSURE_OK(
context, GetOutputSafe(context, node, kOutputIndexes, &output_indexes));
TfLiteTensor* output_values;
TF_LITE_ENSURE_OK(
context, GetOutputSafe(context, node, kOutputValues, &output_values));
SetTensorToDynamic(output_indexes);
SetTensorToDynamic(output_values);
}
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 |
ALWAYS_INLINE String serialize_impl(const Variant& value,
const SerializeOptions& opts) {
switch (value.getType()) {
case KindOfClass:
case KindOfLazyClass:
case KindOfPersistentString:
case KindOfString: {
auto const str =
isStringType(value.getType()) ? value.getStringData() :
isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :
lazyClassToStringHelper(value.toLazyClassVal());
auto const size = str->size();
if (size >= RuntimeOption::MaxSerializedStringSize) {
throw Exception("Size of serialized string (%ld) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, true);
} | 1 | C++ | CWE-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 int64_t StringData::size() const { return m_len; } | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
switch (input->type) { // Already know in/out types are same.
case kTfLiteFloat32:
return EvalImpl<kernel_type, kTfLiteFloat32>(context, node);
case kTfLiteUInt8:
return EvalImpl<kernel_type, kTfLiteUInt8>(context, node);
case kTfLiteInt8:
return EvalImpl<kernel_type, kTfLiteInt8>(context, node);
case kTfLiteInt16:
return EvalImpl<kernel_type, kTfLiteInt16>(context, node);
default:
context->ReportError(context, "Type %d not currently supported.",
input->type);
return kTfLiteError;
}
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
bool ArcMemory::Tell(int64 *Pos)
{
if (!Loaded)
return false;
*Pos=SeekPos;
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 |
size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf,
StreamID stream,
const HTTPHeaders& trailers) {
VLOG(4) << "generating TRAILERS for stream=" << stream;
std::vector<compress::Header> allHeaders;
CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE);
HTTPHeaderSize size;
auto out = encodeHeaders(trailers, allHeaders, &size);
IOBufQueue queue(IOBufQueue::cacheChainLength());
queue.append(std::move(out));
auto maxFrameSize = maxSendFrameSize();
if (queue.chainLength() > 0) {
folly::Optional<http2::PriorityUpdate> pri;
auto remainingFrameSize = maxFrameSize;
auto chunk = queue.split(std::min(remainingFrameSize, queue.chainLength()));
bool endHeaders = queue.chainLength() == 0;
generateHeaderCallbackWrapper(stream,
http2::FrameType::HEADERS,
http2::writeHeaders(writeBuf,
std::move(chunk),
stream,
pri,
http2::kNoPadding,
true /*eom*/,
endHeaders));
if (!endHeaders) {
generateContinuation(writeBuf, queue, stream, maxFrameSize);
}
}
return size.compressed;
} | 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 |
R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64 sz, st64 buf_offset) {
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
ut16 name_idx;
st64 nsz;
if (!buffer || ((int) sz) < 4 || buf_offset < 0) {
eprintf ("r_bin_Java_read_next_attr_from_buffer: invalid buffer size %d\n", (int) sz);
return NULL;
}
name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
nsz = R_BIN_JAVA_UINT (buffer, offset);
offset += 4;
char *name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);
if (!name) {
name = strdup ("unknown");
}
IFDBG eprintf("r_bin_java_read_next_attr: name_idx = %d is %s\n", name_idx, name);
RBinJavaAttrMetas *type_info = r_bin_java_get_attr_type_by_name (name);
if (type_info) {
IFDBG eprintf("Typeinfo: %s, was %s\n", type_info->name, name);
// printf ("SZ %d %d %d\n", nsz, sz, buf_offset);
if (nsz > sz) {
free (name);
return NULL;
}
if ((attr = type_info->allocs->new_obj (buffer, nsz, buf_offset))) {
attr->metas->ord = (R_BIN_JAVA_GLOBAL_BIN->attr_idx++);
}
} else {
eprintf ("r_bin_java_read_next_attr_from_buffer: Cannot find type_info for %s\n", name);
}
free (name);
return attr;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void TestJlCompress::extractDir_data()
{
QTest::addColumn<QString>("zipName");
QTest::addColumn<QStringList>("fileNames");
QTest::newRow("simple") << "jlextdir.zip" << (
QStringList() << "test0.txt" << "testdir1/test1.txt"
<< "testdir2/test2.txt" << "testdir2/subdir/test2sub.txt");
QTest::newRow("separate dir") << "sepdir.zip" << (
QStringList() << "laj/" << "laj/lajfile.txt");
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
void Polygon::Insert( sal_uInt16 nPos, const Point& rPt )
{
ImplMakeUnique();
if( nPos >= mpImplPolygon->mnPoints )
nPos = mpImplPolygon->mnPoints;
mpImplPolygon->ImplSplit( nPos, 1 );
mpImplPolygon->mpPointAry[ nPos ] = rPt;
} | 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 SetLineWidth(double w) {
outpos +=
sprintf(outpos," %12.3f w",w);
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
} | 1 | C++ | CWE-908 | Use of Uninitialized Resource | The software uses or accesses a resource that has not been initialized. | https://cwe.mitre.org/data/definitions/908.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* data =
reinterpret_cast<TfLiteAudioMicrofrontendParams*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 1);
TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt16);
output->type = kTfLiteInt32;
if (data->out_float) {
output->type = kTfLiteFloat32;
}
TfLiteIntArray* output_size = TfLiteIntArrayCreate(2);
int num_frames = 0;
if (input->dims->data[0] >= data->state->window.size) {
num_frames = (input->dims->data[0] - data->state->window.size) /
data->state->window.step / data->frame_stride +
1;
}
output_size->data[0] = num_frames;
output_size->data[1] = data->state->filterbank.num_channels *
(1 + data->left_context + data->right_context);
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Reinterprete the opaque data provided by user.
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
switch (type) {
case kTfLiteFloat32:
case kTfLiteInt32:
break;
default:
context->ReportError(context, "Type '%s' is not supported by floor_div.",
TfLiteTypeGetName(type));
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 1 | C++ | CWE-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 pcre_dump_cache(const std::string& filename) {
s_pcreCache.dump(filename);
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
int64_t length() const {
return m_str ? m_str->size() : 0;
} | 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 PrepareSimple(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
OpContext op_context(context, node);
TF_LITE_ENSURE_TYPES_EQ(context, op_context.axis->type, kTfLiteInt32);
TF_LITE_ENSURE_OK(context, InitializeTemporaries(context, node, &op_context));
TfLiteTensor* resolved_axis;
TF_LITE_ENSURE_OK(
context, GetTemporarySafe(context, node, /*index=*/1, &resolved_axis));
// Leaves work to Eval if axis is not constant; else resizes output.
if (!IsConstantTensor(op_context.axis)) {
SetTensorToDynamic(op_context.output);
SetTensorToDynamic(resolved_axis);
return kTfLiteOk;
}
resolved_axis->allocation_type = kTfLiteArenaRw;
TF_LITE_ENSURE_OK(context,
ResizeTempAxis(context, &op_context, resolved_axis));
TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, &op_context));
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 jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
jas_seqent_t maxval)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
jas_matind_t rowstep;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
} | 1 | C++ | CWE-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 |
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) {
ut64 sz = 2;
if (evp && evp->value) {
// evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);
// evp->value = r_bin_java_element_value_new (bin, offset+2);
sz += r_bin_java_element_value_calc_size (evp->value);
}
return sz;
} | 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 |
MONGO_EXPORT int bson_append_binary( bson *b, const char *name, char type, const char *str, int len ) {
if ( type == BSON_BIN_BINARY_OLD ) {
int subtwolen = len + 4;
if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+4+len ) == BSON_ERROR )
return BSON_ERROR;
bson_append32( b, &subtwolen );
bson_append_byte( b, type );
bson_append32( b, &len );
bson_append( b, str, len );
}
else {
if ( bson_append_estart( b, BSON_BINDATA, name, 4+1+len ) == BSON_ERROR )
return BSON_ERROR;
bson_append32( b, &len );
bson_append_byte( b, type );
bson_append( b, str, len );
}
return BSON_OK;
} | 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 |
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
if (sz < 8) {
return NULL;
}
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr && sz >= offset) {
attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;
attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);
if (attr->info.annotation_default_attr.default_value) {
offset += attr->info.annotation_default_attr.default_value->size;
}
}
r_bin_java_print_annotation_default_attr_summary (attr);
return attr;
} | 1 | C++ | CWE-788 | Access of Memory Location After End of Buffer | The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer. | https://cwe.mitre.org/data/definitions/788.html | safe |
static char *getDirective(char *line, char **valuep)
{
char *key, *value;
ssize len;
assert(line);
assert(valuep);
*valuep = 0;
key = stok(line, " \t", &value);
key = strim(key, " \t\r\n>", MPR_TRIM_END);
if (value) {
value = strim(value, " \t\r\n>", MPR_TRIM_END);
/*
Trim quotes if wrapping the entire value and no spaces. Preserve embedded quotes and leading/trailing "" etc.
*/
len = slen(value);
if (*value == '\"' && value[len - 1] == '"' && len > 2 && value[1] != '\"' && !strpbrk(value, " \t")) {
/*
Cannot strip quotes if multiple args are quoted, only if one single arg is quoted
*/
if (schr(&value[1], '"') == &value[len - 1]) {
value = snclone(&value[1], len - 2);
}
}
*valuep = value;
}
return key;
} | 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 CanReceiveMessage(User* source, User* target, SilenceEntry::SilenceFlags flag)
{
// Servers handle their own clients.
if (!IS_LOCAL(target))
return true;
if (exemptuline && source->server->IsULine())
return true;
SilenceList* list = cmd.ext.get(target);
if (!list)
return true;
for (SilenceList::iterator iter = list->begin(); iter != list->end(); ++iter)
{
if (!(iter->flags & flag))
continue;
if (InspIRCd::Match(source->GetFullHost(), iter->mask))
return iter->flags & SilenceEntry::SF_EXEMPT;
}
return true;
} | 1 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | safe |
uint64 ReadCodedSizeValue(const binary * InBuffer, uint32 & BufferSize, uint64 & SizeUnknown)
{
binary SizeBitMask = 1 << 7;
uint64 Result = 0x7F;
unsigned int SizeIdx, PossibleSizeLength = 0;
binary PossibleSize[8];
memset(PossibleSize, 0, 8);
SizeUnknown = 0x7F; // the last bit is discarded when computing the size
for (SizeIdx = 0; SizeIdx < BufferSize && SizeIdx < 8; SizeIdx++) {
if (InBuffer[0] & (SizeBitMask >> SizeIdx)) {
// ID found
PossibleSizeLength = SizeIdx + 1;
SizeBitMask >>= SizeIdx;
// Guard against invalid memory accesses with incomplete IDs.
if (PossibleSizeLength > BufferSize)
break;
for (SizeIdx = 0; SizeIdx < PossibleSizeLength; SizeIdx++) {
PossibleSize[SizeIdx] = InBuffer[SizeIdx];
}
for (SizeIdx = 0; SizeIdx < PossibleSizeLength - 1; SizeIdx++) {
Result <<= 7;
Result |= 0xFF;
}
Result = 0;
Result |= PossibleSize[0] & ~SizeBitMask;
for (unsigned int i = 1; i<PossibleSizeLength; i++) {
Result <<= 8;
Result |= PossibleSize[i];
}
BufferSize = PossibleSizeLength;
return Result;
}
SizeUnknown <<= 7;
SizeUnknown |= 0xFF;
}
BufferSize = 0;
return 0;
} | 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 |
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) {
ut64 sz = 2;
if (evp && evp->value) {
// evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);
// evp->value = r_bin_java_element_value_new (bin, offset+2);
sz += r_bin_java_element_value_calc_size (evp->value);
}
return sz;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
bool 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-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
void SetDashSize(double dashsize,double phase) {
if ( dashsize ) {
sprintf(outputbuffer," [%12.3f] %12.3f d",dashsize,phase);
sendClean(outputbuffer);
}
else send(" [] 0 d");
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
MONGO_EXPORT bson_type bson_iterator_next( bson_iterator *i ) {
int ds;
if ( i->first ) {
i->first = 0;
return ( bson_type )( *i->cur );
}
switch ( bson_iterator_type( i ) ) {
case BSON_EOO:
return BSON_EOO; /* don't advance */
case BSON_UNDEFINED:
case BSON_NULL:
ds = 0;
break;
case BSON_BOOL:
ds = 1;
break;
case BSON_INT:
ds = 4;
break;
case BSON_LONG:
case BSON_DOUBLE:
case BSON_TIMESTAMP:
case BSON_DATE:
ds = 8;
break;
case BSON_OID:
ds = 12;
break;
case BSON_STRING:
case BSON_SYMBOL:
case BSON_CODE:
ds = 4 + bson_iterator_int_raw( i );
break;
case BSON_BINDATA:
ds = 5 + bson_iterator_int_raw( i );
break;
case BSON_OBJECT:
case BSON_ARRAY:
case BSON_CODEWSCOPE:
ds = bson_iterator_int_raw( i );
break;
case BSON_DBREF:
ds = 4+12 + bson_iterator_int_raw( i );
break;
case BSON_REGEX: {
const char *s = bson_iterator_value( i );
const char *p = s;
p += strlen( p )+1;
p += strlen( p )+1;
ds = p-s;
break;
}
default: {
char msg[] = "unknown type: 000000000000";
bson_numstr( msg+14, ( unsigned )( i->cur[0] ) );
bson_fatal_msg( 0, msg );
return 0;
}
}
i->cur += 1 + strlen( i->cur + 1 ) + 1 + ds;
return ( bson_type )( *i->cur );
} | 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 |
Status TensorSlice::BuildTensorSlice(const TensorSliceProto& proto,
TensorSlice* output) {
output->Clear();
output->starts_.reserve(proto.extent_size());
output->lengths_.reserve(proto.extent_size());
for (const auto& e : proto.extent()) {
int64_t l = GetExtentLength(e);
if (e.start() != 0 || l != kFullExtent) {
if (e.start() < 0 || l <= 0) {
return errors::InvalidArgument(
"Expected non-negative start and positive length but got start = ",
e.start(), ", length = ", l, ": extent = ", e.ShortDebugString());
}
// Calculating the extent end must not cause signed integer overflow.
if (static_cast<uint64_t>(e.start()) + static_cast<uint64_t>(e.length()) >
std::numeric_limits<int64_t>::max()) {
return errors::InvalidArgument(
"Extent end exceeds the maximum possible size: extent = ",
e.ShortDebugString());
}
}
output->starts_.push_back(e.start());
output->lengths_.push_back(l);
}
return Status::OK();
} | 1 | C++ | CWE-345 | Insufficient Verification of Data Authenticity | The software does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. | https://cwe.mitre.org/data/definitions/345.html | safe |
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y]);
}
}
} | 0 | C++ | CWE-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 * alloc_top(size_t size, size_t align)
{loop:
top -= size;
align_top(align);
if (top < bottom) {new_chunk(); goto loop;}
return top;
} | 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 Relu6Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data);
switch (input->type) {
case kTfLiteFloat32: {
size_t elements = input->bytes / sizeof(float);
const float* in = GetTensorData<float>(input);
const float* in_end = in + elements;
float* out = GetTensorData<float>(output);
for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f);
return kTfLiteOk;
} break;
case kTfLiteUInt8:
QuantizedReluX<uint8_t>(0.0f, 6.0f, input, output, data);
return kTfLiteOk;
case kTfLiteInt8: {
QuantizedReluX<int8_t>(0.0f, 6.0f, input, output, data);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context,
"Only float32, uint8 and int8 are supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | 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 MaxEval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* output = GetOutput(context, node, 0);
const TfLiteTensor* input = GetInput(context, node, 0);
switch (input->type) { // Already know in/out types are same.
case kTfLiteFloat32:
MaxEvalFloat<kernel_type>(context, node, params, data, input, output);
break;
case kTfLiteUInt8:
MaxEvalQuantizedUInt8<kernel_type>(context, node, params, data, input,
output);
break;
case kTfLiteInt8:
MaxEvalQuantizedInt8<kernel_type>(context, node, params, data, input,
output);
break;
case kTfLiteInt16:
MaxEvalQuantizedInt16<kernel_type>(context, node, params, data, input,
output);
break;
default:
TF_LITE_KERNEL_LOG(context, "Type %s not currently supported.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
return kTfLiteOk;
} | 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 RemoteFsDevice::load()
{
if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {
// Start Avahi listener...
Avahi::self();
QUrlQuery q(details.url);
if (q.hasQueryItem(constServiceNameQuery)) {
details.serviceName=q.queryItemValue(constServiceNameQuery);
}
if (!details.serviceName.isEmpty()) {
AvahiService *srv=Avahi::self()->getService(details.serviceName);
if (!srv || srv->getHost().isEmpty()) {
sub=tr("Not Available");
} else {
sub=tr("Available");
}
}
connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));
connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));
}
if (isConnected()) {
setAudioFolder();
readOpts(settingsFileName(), opts, true);
rescan(false); // Read from cache if we have it!
}
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;
AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
char* name = new char[name_size+1];
if (name == NULL) return;
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData,
UINT32* pDstSize, UINT32 flags)
{
int status = -1;
BYTE descriptor;
wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize);
if (!stream)
return -1;
if (Stream_GetRemainingLength(stream) < 1)
goto fail;
Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */
if (descriptor == ZGFX_SEGMENTED_SINGLE)
{
if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream)))
goto fail;
*ppDstData = NULL;
if (zgfx->OutputCount > 0)
*ppDstData = (BYTE*) malloc(zgfx->OutputCount);
if (!*ppDstData)
goto fail;
*pDstSize = zgfx->OutputCount;
CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount);
}
else if (descriptor == ZGFX_SEGMENTED_MULTIPART)
{
UINT32 segmentSize;
UINT16 segmentNumber;
UINT16 segmentCount;
UINT32 uncompressedSize;
BYTE* pConcatenated;
if (Stream_GetRemainingLength(stream) < 6)
goto fail;
Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */
Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */
if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32))
goto fail;
pConcatenated = (BYTE*) malloc(uncompressedSize);
if (!pConcatenated)
goto fail;
*ppDstData = pConcatenated;
*pDstSize = uncompressedSize;
for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++)
{
if (Stream_GetRemainingLength(stream) < sizeof(UINT32))
goto fail;
Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */
if (!zgfx_decompress_segment(zgfx, stream, segmentSize))
goto fail;
CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount);
pConcatenated += zgfx->OutputCount;
}
}
else
{
goto fail;
}
status = 1;
fail:
Stream_Free(stream, FALSE);
return status;
} | 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 LogicalImpl(TfLiteContext* context, TfLiteNode* node,
bool (*func)(bool, bool)) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (data->requires_broadcast) {
reference_ops::BroadcastBinaryFunction4DSlow<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
} else {
reference_ops::BinaryFunction<bool, bool, bool>(
GetTensorShape(input1), GetTensorData<bool>(input1),
GetTensorShape(input2), GetTensorData<bool>(input2),
GetTensorShape(output), GetTensorData<bool>(output), func);
}
return kTfLiteOk;
} | 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 SimpleStatefulOp::Invoke(TfLiteContext* context,
TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
*data->invoke_count += 1;
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const uint8_t* input_data = GetTensorData<uint8_t>(input);
int size = NumElements(input->dims);
uint8_t* sorting_buffer = reinterpret_cast<uint8_t*>(
context->GetScratchBuffer(context, data->sorting_buffer));
// Copy inputs data to the sorting buffer. We don't want to mutate the input
// tensor as it might be used by a another node.
for (int i = 0; i < size; i++) {
sorting_buffer[i] = input_data[i];
}
// In place insertion sort on `sorting_buffer`.
for (int i = 1; i < size; i++) {
for (int j = i; j > 0 && sorting_buffer[j] < sorting_buffer[j - 1]; j--) {
std::swap(sorting_buffer[j], sorting_buffer[j - 1]);
}
}
TfLiteTensor* median = GetOutput(context, node, kMedianTensor);
uint8_t* median_data = GetTensorData<uint8_t>(median);
TfLiteTensor* invoke_count = GetOutput(context, node, kInvokeCount);
int32_t* invoke_count_data = GetTensorData<int32_t>(invoke_count);
median_data[0] = sorting_buffer[size / 2];
invoke_count_data[0] = *data->invoke_count;
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
static inline int checkSettingSecurity(lua_State* L, const std::string &name)
{
if (ScriptApiSecurity::isSecure(L) && name.compare(0, 7, "secure.") == 0)
throw LuaError("Attempt to set secure setting.");
bool is_mainmenu = false;
#ifndef SERVER
is_mainmenu = ModApiBase::getGuiEngine(L) != nullptr;
#endif
if (!is_mainmenu && (name == "mg_name" || name == "mg_flags")) {
errorstream << "Tried to set global setting " << name << ", ignoring. "
"minetest.set_mapgen_setting() should be used instead." << std::endl;
infostream << script_get_backtrace(L) << std::endl;
return -1;
}
return 0;
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | 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) {
if (max_seq_length <= 0) {
return port::Status(port::error::INVALID_ARGUMENT, "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));
} | 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 ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
int max_index = -1;
const int segment_id_size = segment_ids->dims->data[0];
if (segment_id_size > 0) {
max_index = segment_ids->data.i32[segment_id_size - 1];
}
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | 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 IsReshapeOpSupported(const TfLiteRegistration* registration,
const TfLiteNode* node, TfLiteContext* context,
int coreml_version) {
if (coreml_version >= 3) {
return false;
}
if (node->inputs->size == 1) {
const auto* params =
reinterpret_cast<TfLiteReshapeParams*>(node->builtin_data);
return params->num_dimensions == 3 || params->num_dimensions == 4;
}
const int kShapeTensor = 1;
const TfLiteTensor* shape;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kShapeTensor, &shape));
if (shape->allocation_type != kTfLiteMmapRo) {
TF_LITE_KERNEL_LOG(context, "Reshape has non-const shape.");
return false;
}
const bool is_shape_tensor =
shape->dims->size == 1 && shape->type == kTfLiteInt32;
return is_shape_tensor &&
(shape->dims->data[0] == 3 || shape->dims->data[0] == 4);
} | 1 | C++ | CWE-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 readBytes(void* data, int length) {
U8* dataPtr = (U8*)data;
U8* dataEnd = dataPtr + length;
while (dataPtr < dataEnd) {
int n = check(1, dataEnd - dataPtr);
memcpy(dataPtr, ptr, n);
ptr += n;
dataPtr += 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 |
void* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) {
const Tensor* tensor = GetTensorFromHandle(h, status);
TF_DataType data_type = static_cast<TF_DataType>(tensor->dtype());
TensorReference tensor_ref(*tensor); // This will call buf_->Ref()
auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref);
tf_dlm_tensor_ctx->reference = tensor_ref;
DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor;
dlm_tensor->manager_ctx = tf_dlm_tensor_ctx;
dlm_tensor->deleter = &DLManagedTensorDeleter;
dlm_tensor->dl_tensor.ctx = GetDlContext(h, status);
int ndim = tensor->dims();
dlm_tensor->dl_tensor.ndim = ndim;
dlm_tensor->dl_tensor.data = TFE_TensorHandleDevicePointer(h, status);
dlm_tensor->dl_tensor.dtype = GetDlDataType(data_type, status);
std::vector<int64_t>* shape_arr = &tf_dlm_tensor_ctx->shape;
std::vector<int64_t>* stride_arr = &tf_dlm_tensor_ctx->strides;
shape_arr->resize(ndim);
stride_arr->resize(ndim, 1);
for (int i = 0; i < ndim; i++) {
(*shape_arr)[i] = tensor->dim_size(i);
}
for (int i = ndim - 2; i >= 0; --i) {
(*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1];
}
dlm_tensor->dl_tensor.shape = &(*shape_arr)[0];
// There are two ways to represent compact row-major data
// 1) nullptr indicates tensor is compact and row-majored.
// 2) fill in the strides array as the real case for compact row-major data.
// Here we choose option 2, since some frameworks didn't handle the strides
// argument properly.
dlm_tensor->dl_tensor.strides = &(*stride_arr)[0];
dlm_tensor->dl_tensor.byte_offset =
0; // TF doesn't handle the strides and byte_offsets here
return static_cast<void*>(dlm_tensor);
} | 0 | C++ | CWE-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 EluEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
switch (input->type) {
case kTfLiteFloat32: {
optimized_ops::Elu(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
return kTfLiteOk;
} break;
case kTfLiteInt8: {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
EvalUsingLookupTable(data, input, output);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context, "Only float32 and int8 is supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.