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 |
---|---|---|---|---|---|---|---|
jas_image_t *jas_image_create0()
{
jas_image_t *image;
if (!(image = jas_malloc(sizeof(jas_image_t)))) {
return 0;
}
image->tlx_ = 0;
image->tly_ = 0;
image->brx_ = 0;
image->bry_ = 0;
image->clrspc_ = JAS_CLRSPC_UNKNOWN;
image->numcmpts_ = 0;
image->maxcmpts_ = 0;
image->cmpts_ = 0;
// image->inmem_ = true;
image->cmprof_ = 0;
return image;
} | 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 |
KCleanup::expandVariables( const KFileInfo * item,
const QString & unexpanded ) const
{
QString expanded = unexpanded;
expanded.replace( QRegExp( "%p" ),
"'" + QString::fromLocal8Bit( item->url() ) + "'" );
expanded.replace( QRegExp( "%n" ),
"'" + QString::fromLocal8Bit( item->name() ) + "'" );
// if ( KDE::versionMajor() >= 3 && KDE::versionMinor() >= 4 )
expanded.replace( QRegExp( "%t" ), "trash:/" );
//else
//expanded.replace( QRegExp( "%t" ), KGlobalSettings::trashPath() );
return expanded;
} | 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 |
StatusOr<FullTypeDef> SpecializeType(const AttrSlice& attrs,
const OpDef& op_def) {
FullTypeDef ft;
ft.set_type_id(TFT_PRODUCT);
for (int i = 0; i < op_def.output_arg_size(); i++) {
auto* t = ft.add_args();
*t = op_def.output_arg(i).experimental_full_type();
// Resolve dependent types. The convention for op registrations is to use
// attributes as type variables.
// See https://www.tensorflow.org/guide/create_op#type_polymorphism.
// Once the op signature can be defined entirely in FullType, this
// convention can be deprecated.
//
// Note: While this code performs some basic verifications, it generally
// assumes consistent op defs and attributes. If more complete
// verifications are needed, they should be done by separately, and in a
// way that can be reused for type inference.
for (int j = 0; j < t->args_size(); j++) {
auto* arg = t->mutable_args(j);
if (arg->type_id() == TFT_VAR) {
const auto* attr = attrs.Find(arg->s());
if (attr == nullptr) {
return Status(
error::INVALID_ARGUMENT,
absl::StrCat("Could not find an attribute for key ", arg->s()));
}
if (attr->value_case() == AttrValue::kList) {
const auto& attr_list = attr->list();
arg->set_type_id(TFT_PRODUCT);
for (int i = 0; i < attr_list.type_size(); i++) {
map_dtype_to_tensor(attr_list.type(i), arg->add_args());
}
} else if (attr->value_case() == AttrValue::kType) {
map_dtype_to_tensor(attr->type(), arg);
} else {
return Status(error::UNIMPLEMENTED,
absl::StrCat("unknown attribute type",
attrs.DebugString(), " key=", arg->s()));
}
arg->clear_s();
}
}
}
return ft;
} | 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 UpdateDownloader::CleanLeftovers()
{
// Note: this is called at startup. Do not use wxWidgets from this code!
std::wstring tmpdir;
if ( !Settings::ReadConfigValue("UpdateTempDir", tmpdir) )
return;
// Check that the directory actually is a valid update temp dir, to prevent
// malicious users from forcing us into deleting arbitrary directories:
try
{
if (tmpdir.find(GetUniqueTempDirectoryPrefix()) != 0)
{
Settings::DeleteConfigValue("UpdateTempDir");
return;
}
}
catch (Win32Exception&) // cannot determine temp directory
{
return;
}
tmpdir.append(1, '\0'); // double NULL-terminate for SHFileOperation
SHFILEOPSTRUCT fos = {0};
fos.wFunc = FO_DELETE;
fos.pFrom = tmpdir.c_str();
fos.fFlags = FOF_NO_UI | // Vista+-only
FOF_SILENT |
FOF_NOCONFIRMATION |
FOF_NOERRORUI;
if ( SHFileOperation(&fos) == 0 )
{
Settings::DeleteConfigValue("UpdateTempDir");
}
// else: try another time, this is just a "soft" error
} | 1 | C++ | CWE-426 | Untrusted Search Path | The application searches for critical resources using an externally-supplied search path that can point to resources that are not under the application's direct control. | https://cwe.mitre.org/data/definitions/426.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-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
int bson_ensure_space( bson *b, const int bytesNeeded ) {
int pos = b->cur - b->data;
char *orig = b->data;
int new_size;
if ( pos + bytesNeeded <= b->dataSize )
return BSON_OK;
new_size = 1.5 * ( b->dataSize + bytesNeeded );
if( new_size < b->dataSize ) {
if( ( b->dataSize + bytesNeeded ) < INT_MAX )
new_size = INT_MAX;
else {
b->err = BSON_SIZE_OVERFLOW;
return BSON_ERROR;
}
}
b->data = bson_realloc( b->data, new_size );
if ( !b->data )
bson_fatal_msg( !!b->data, "realloc() failed" );
b->dataSize = new_size;
b->cur += b->data - orig;
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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const TfLiteTensor* multipliers;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kInputMultipliers, &multipliers));
// Only int32 and int64 multipliers type is supported.
if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {
context->ReportError(context,
"Multipliers of type '%s' are not supported by tile.",
TfLiteTypeGetName(multipliers->type));
return kTfLiteError;
}
if (IsConstantTensor(multipliers)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
TEST_F(QuantizedConv2DTest, Small32Bit) {
const int stride = 1;
TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D")
.Input(FakeInput(DT_QUINT8))
.Input(FakeInput(DT_QUINT8))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Input(FakeInput(DT_FLOAT))
.Attr("out_type", DataTypeToEnum<qint32>::v())
.Attr("strides", {1, stride, stride, 1})
.Attr("padding", "SAME")
.Finalize(node_def()));
TF_ASSERT_OK(InitOp());
const int depth = 1;
const int image_width = 4;
const int image_height = 3;
const int image_batch_count = 1;
AddInputFromArray<quint8>(
TensorShape({image_batch_count, image_height, image_width, depth}),
{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120});
const int filter_size = 3;
const int filter_count = 1;
AddInputFromArray<quint8>(
TensorShape({filter_size, filter_size, depth, filter_count}),
{10, 40, 70, 20, 50, 80, 30, 60, 90});
AddInputFromArray<float>(TensorShape({1}), {0});
AddInputFromArray<float>(TensorShape({1}), {255.0f});
AddInputFromArray<float>(TensorShape({1}), {0});
AddInputFromArray<float>(TensorShape({1}), {255.0f});
TF_ASSERT_OK(RunOpKernel());
const int expected_width = image_width;
const int expected_height = image_height * filter_count;
Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,
expected_width, filter_count}));
test::FillValues<qint32>(
&expected, {10500, 15000, 18300, 9500, 23500, 31200, 35700, 17800, 18700,
23400, 26100, 12100});
test::ExpectTensorEqual<qint32>(expected, *GetOutput(0));
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static ssize_t _consolefs_read(oe_fd_t* file_, void* buf, size_t count)
{
ssize_t ret = -1;
file_t* file = _cast_file(file_);
if (!file)
OE_RAISE_ERRNO(OE_EINVAL);
if (oe_syscall_read_ocall(&ret, file->host_fd, buf, count) != OE_OK)
OE_RAISE_ERRNO(OE_EINVAL);
done:
return ret;
} | 0 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | vulnerable |
void BinaryParameter::getData(void** data_, int* length_) const {
LOCK_CONFIG;
if (length_) *length_ = length;
if (data_) {
*data_ = new char[length];
memcpy(*data_, value, length);
}
} | 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 jas_matrix_divpow2(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = (*data >= 0) ? ((*data) >> n) :
(-((-(*data)) >> n));
}
}
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_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 |
bool is_print(char c) { return c >= 32 && c < 127; } | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
TfLiteStatus EvalHashtable(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE(context, node->user_data != nullptr);
const auto* params =
reinterpret_cast<const TfLiteHashtableParams*>(node->user_data);
// The resource id is generated based on the given table name.
const int resource_id = std::hash<std::string>{}(params->table_name);
TfLiteTensor* resource_handle_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kResourceHandleTensor,
&resource_handle_tensor));
auto* resource_handle_data =
GetTensorData<std::int32_t>(resource_handle_tensor);
resource_handle_data[0] = resource_id;
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
resource::CreateHashtableResourceIfNotAvailable(
&resources, resource_id, params->key_dtype, params->value_dtype);
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void Compute(OpKernelContext* context) override {
// Get the input Tensors.
OpInputList params_nested_splits_in;
OP_REQUIRES_OK(context, context->input_list("params_nested_splits",
¶ms_nested_splits_in));
const Tensor& params_dense_values_in =
context->input(params_nested_splits_in.size());
const Tensor& indices_in =
context->input(params_nested_splits_in.size() + 1);
DCHECK_GT(params_nested_splits_in.size(), 0); // Enforced by REGISTER_OP.
SPLITS_TYPE num_params = params_nested_splits_in[0].dim_size(0) - 1;
OP_REQUIRES_OK(context, ValidateIndices(indices_in, num_params));
OP_REQUIRES(context, params_dense_values_in.dims() > 0,
errors::InvalidArgument("params.rank must be nonzero"));
SPLITS_TYPE num_params_dense_values = params_dense_values_in.dim_size(0);
// Calculate the `splits`, and store the value slices that we need to
// copy in `value_slices`.
std::vector<std::pair<SPLITS_TYPE, SPLITS_TYPE>> value_slices;
SPLITS_TYPE num_values = 0;
std::vector<std::vector<SPLITS_TYPE>> out_splits;
OP_REQUIRES_OK(context, MakeSplits(indices_in, params_nested_splits_in,
num_params_dense_values, &out_splits,
&value_slices, &num_values));
// Write the output tensors.
OP_REQUIRES_OK(context, WriteSplits(out_splits, context));
OP_REQUIRES_OK(context,
WriteValues(params_dense_values_in, value_slices,
out_splits.size(), num_values, context));
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);
// Only int32 and int64 multipliers type is supported.
if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {
context->ReportError(context,
"Multipliers of type '%s' are not supported by tile.",
TfLiteTypeGetName(multipliers->type));
return kTfLiteError;
}
if (IsConstantTensor(multipliers)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)
{
auto* zei = entries.getUnchecked (index);
#if JUCE_WINDOWS
auto entryPath = zei->entry.filename;
#else
auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/');
#endif
if (entryPath.isEmpty())
return Result::ok();
auto targetFile = targetDirectory.getChildFile (entryPath);
if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\'))
return targetFile.createDirectory(); // (entry is a directory, not a file)
std::unique_ptr<InputStream> in (createStreamForEntry (index));
if (in == nullptr)
return Result::fail ("Failed to open the zip file for reading");
if (targetFile.exists())
{
if (! shouldOverwriteFiles)
return Result::ok();
if (! targetFile.deleteFile())
return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
}
if (! targetFile.getParentDirectory().createDirectory())
return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());
if (zei->entry.isSymbolicLink)
{
String originalFilePath (in->readEntireStreamAsString()
.replaceCharacter (L'/', File::getSeparatorChar()));
if (! File::createSymbolicLink (targetFile, originalFilePath, true))
return Result::fail ("Failed to create symbolic link: " + originalFilePath);
}
else
{
FileOutputStream out (targetFile);
if (out.failedToOpen())
return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
out << *in;
}
targetFile.setCreationTime (zei->entry.fileTime);
targetFile.setLastModificationTime (zei->entry.fileTime);
targetFile.setLastAccessTime (zei->entry.fileTime);
return Result::ok();
}
| 0 | C++ | CWE-59 | Improper Link Resolution Before File Access ('Link Following') | The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. | https://cwe.mitre.org/data/definitions/59.html | vulnerable |
Status ValidateInputsGenerateOutputs(
OpKernelContext* ctx, const Tensor** inputs, const Tensor** seq_len,
Tensor** log_prob, OpOutputList* decoded_indices,
OpOutputList* decoded_values, OpOutputList* decoded_shape) const {
Status status = ctx->input("inputs", inputs);
if (!status.ok()) return status;
status = ctx->input("sequence_length", seq_len);
if (!status.ok()) return status;
const TensorShape& inputs_shape = (*inputs)->shape();
if (inputs_shape.dims() != 3) {
return errors::InvalidArgument("inputs is not a 3-Tensor");
}
if (inputs_shape.num_elements() == 0) {
return errors::InvalidArgument("inputs must not be empty");
}
const int64 max_time = inputs_shape.dim_size(0);
const int64 batch_size = inputs_shape.dim_size(1);
if (max_time == 0) {
return errors::InvalidArgument("max_time is 0");
}
if (!TensorShapeUtils::IsVector((*seq_len)->shape())) {
return errors::InvalidArgument("sequence_length is not a vector");
}
if (!(batch_size == (*seq_len)->dim_size(0))) {
return errors::FailedPrecondition(
"len(sequence_length) != batch_size. ",
"len(sequence_length): ", (*seq_len)->dim_size(0),
" batch_size: ", batch_size);
}
auto seq_len_t = (*seq_len)->vec<int32>();
for (int b = 0; b < batch_size; ++b) {
if (!(seq_len_t(b) <= max_time)) {
return errors::FailedPrecondition("sequence_length(", b,
") <= ", max_time);
}
}
Status s = ctx->allocate_output(
"log_probability", TensorShape({batch_size, top_paths_}), log_prob);
if (!s.ok()) return s;
s = ctx->output_list("decoded_indices", decoded_indices);
if (!s.ok()) return s;
s = ctx->output_list("decoded_values", decoded_values);
if (!s.ok()) return s;
s = ctx->output_list("decoded_shape", decoded_shape);
if (!s.ok()) return s;
return Status::OK();
} | 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 |
static unsigned short get_tga_ushort(const unsigned char *data)
{
return data[0] | (data[1] << 8);
} | 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 FormatConverter<T>::InitSparseToDenseConverter(
std::vector<int> shape, std::vector<int> traversal_order,
std::vector<TfLiteDimensionType> format, std::vector<int> dense_size,
std::vector<std::vector<int>> segments,
std::vector<std::vector<int>> indices, std::vector<int> block_map) {
dense_shape_ = std::move(shape);
traversal_order_ = std::move(traversal_order);
block_map_ = std::move(block_map);
format_ = std::move(format);
dense_size_ = 1;
for (int i = 0; i < dense_shape_.size(); i++) {
dense_size_ *= dense_shape_[i];
}
dim_metadata_.resize(2 * format_.size());
for (int i = 0; i < format_.size(); i++) {
if (format_[i] == kTfLiteDimDense) {
dim_metadata_[2 * i] = {dense_size[i]};
} else {
dim_metadata_[2 * i] = std::move(segments[i]);
dim_metadata_[2 * i + 1] = std::move(indices[i]);
}
}
int original_rank = dense_shape_.size();
int block_dim = 0;
blocked_shape_.resize(original_rank);
block_size_.resize(block_map_.size());
for (int i = 0; i < original_rank; i++) {
if (block_dim < block_map_.size() && block_map_[block_dim] == i) {
int orig_dim = traversal_order_[original_rank + block_dim];
block_size_[block_dim] = dense_size[orig_dim];
blocked_shape_[i] = dense_shape_[i] / dense_size[orig_dim];
block_dim++;
} else {
blocked_shape_[i] = dense_shape_[i];
}
}
} | 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 AdminRequestHandler::handleDumpStaticStringsRequest(
const std::string& /*cmd*/, const std::string& filename) {
auto const& list = lookupDefinedStaticStrings();
std::ofstream out(filename.c_str());
SCOPE_EXIT { out.close(); };
for (auto item : list) {
out << formatStaticString(item);
if (RuntimeOption::EvalPerfDataMap) {
auto const len = std::min<size_t>(item->size(), 255);
std::string str(item->data(), len);
// Only print the first line (up to 255 characters). Since we want '\0' in
// the list of characters to avoid, we need to use the version of
// `find_first_of()' with explicit length.
auto cutOffPos = str.find_first_of("\r\n", 0, 3);
if (cutOffPos != std::string::npos) str.erase(cutOffPos);
Debug::DebugInfo::recordDataMap(item->mutableData(),
item->mutableData() + item->size(),
"Str-" + str);
}
}
return true;
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
static std::string PatchPattern(const std::string& pattern) {
const std::string fixed_prefix =
pattern.substr(0, pattern.find_first_of(kGlobbingChars));
// Patching is needed when there is no directory part in `prefix`
if (io::Dirname(fixed_prefix).empty()) {
return io::JoinPath(".", pattern);
}
// No patching needed
return pattern;
} | 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 TfLiteUnpackParams* data =
reinterpret_cast<TfLiteUnpackParams*>(node->builtin_data);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
switch (input->type) {
case kTfLiteFloat32: {
UnpackImpl<float>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt32: {
UnpackImpl<int32_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteUInt8: {
UnpackImpl<uint8_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt8: {
UnpackImpl<int8_t>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteBool: {
UnpackImpl<bool>(context, node, input, data->num, data->axis);
break;
}
case kTfLiteInt16: {
UnpackImpl<int16_t>(context, node, input, data->num, data->axis);
break;
}
default: {
context->ReportError(context, "Type '%s' is not supported by unpack.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | 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 |
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
} | 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 |
lazy_entry* lazy_entry::dict_find(std::string const& name)
{
TORRENT_ASSERT(m_type == dict_t);
for (int i = 0; i < int(m_size); ++i)
{
lazy_dict_entry& e = m_data.dict[i];
if (name.size() != e.val.m_begin - e.name) continue;
if (std::equal(name.begin(), name.end(), e.name))
return &e.val;
}
return 0;
} | 1 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLitePackParams* data =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
switch (output->type) {
case kTfLiteFloat32: {
return PackImpl<float>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteUInt8: {
return PackImpl<uint8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt8: {
return PackImpl<int8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt16: {
return PackImpl<int16_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt32: {
return PackImpl<int32_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt64: {
return PackImpl<int64_t>(context, node, output, data->values_count,
data->axis);
}
default: {
context->ReportError(context, "Type '%s' is not supported by pack.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TEST(AsyncSSLSocketTest, EarlyCloseNotify) {
WriteOnEofReadCallback readCallback(nullptr);
HandshakeCallback handshakeCallback(&readCallback);
SSLServerAcceptCallback acceptCallback(&handshakeCallback);
TestSSLServer server(&acceptCallback);
EventBase eventBase;
CloseNotifyConnector cnc(&eventBase, server.getAddress());
eventBase.loop();
} | 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 (%d) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, true);
} | 0 | C++ | CWE-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 TfLiteRegistration DelegateRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// If tensors are resized, the runtime should propagate shapes
// automatically if correct flag is set. Ensure values are correct.
// Output 0 should be dynamic.
TfLiteTensor* output0 = GetOutput(context, node, 0);
TF_LITE_ENSURE(context, IsDynamicTensor(output0));
// Output 1 has the same shape as input.
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output1 = GetOutput(context, node, 1);
TF_LITE_ENSURE(context, input->dims->size == output1->dims->size);
TF_LITE_ENSURE(context, input->dims->data[0] == output1->dims->data[0]);
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 |
inline void StringData::setSize(int64_t len) {
assertx(!isImmutable() && !hasMultipleRefs());
assertx(len >= 0 && len <= capacity());
mutableData()[len] = 0;
m_lenAndHash = len;
assertx(m_hash == 0);
assertx(checkSane());
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
bool Archive::Open(const wchar *Name,uint Mode)
{
#ifdef USE_QOPEN
// Important if we reuse Archive object and it has virtual QOpen
// file position not matching real. For example, for 'l -v volname'.
QOpen.Unload();
#endif
#ifdef USE_ARCMEM
if (Cmd->ArcInMem)
{
wcsncpyz(FileName,Name,ASIZE(FileName));
ArcMem.Load(Cmd->ArcMemData,Cmd->ArcMemSize);
Cmd->SetArcInMem(NULL,0); // Return in memory data for first volume only, not for next volumes.
return true;
}
#endif
return File::Open(Name,Mode);
} | 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 TfLiteIntArray* GetOutputShapeFromTensor(TfLiteContext* context,
TfLiteNode* node) {
const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);
if (shape == nullptr) return nullptr;
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(shape->dims->data[0]);
for (int i = 0; i < output_shape->size; ++i) {
output_shape->data[i] = shape->data.i32[i];
}
return 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 |
TEST_F(ZNCTest, StatusEchoMessage) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = LoginClient();
client.Write("CAP REQ :echo-message");
client.Write("PRIVMSG *status :blah");
client.ReadUntil(":[email protected] PRIVMSG *status :blah");
client.ReadUntil(":*[email protected] PRIVMSG nick :Unknown command");
} | 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 TLSInStream::readTLS(U8* buf, int len, bool wait)
{
int n;
n = in->check(1, 1, wait);
if (n == 0)
return 0;
n = gnutls_record_recv(session, (void *) buf, len);
if (n == GNUTLS_E_INTERRUPTED || n == GNUTLS_E_AGAIN)
return 0;
if (n < 0) throw TLSException("readTLS", n);
return n;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteDepthToSpaceParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
auto data_type = output->type;
TF_LITE_ENSURE(context,
data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
data_type == kTfLiteInt64);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const int block_size = params->block_size;
TF_LITE_ENSURE(context, block_size > 0);
const int input_height = input->dims->data[1];
const int input_width = input->dims->data[2];
const int input_channels = input->dims->data[3];
int output_height = input_height * block_size;
int output_width = input_width * block_size;
int output_channels = input_channels / block_size / block_size;
TF_LITE_ENSURE_EQ(context, input_height, output_height / block_size);
TF_LITE_ENSURE_EQ(context, input_width, output_width / block_size);
TF_LITE_ENSURE_EQ(context, input_channels,
output_channels * block_size * block_size);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
output_size->data[0] = input->dims->data[0];
output_size->data[1] = output_height;
output_size->data[2] = output_width;
output_size->data[3] = output_channels;
return context->ResizeTensor(context, output, output_size);
} | 1 | C++ | CWE-369 | Divide By Zero | The product divides a value by zero. | https://cwe.mitre.org/data/definitions/369.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
output->type = input->type;
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
int length() const {
return m_str ? m_str->size() : 0;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
MpdCantataMounterInterface * RemoteFsDevice::mounter()
{
if (!mounterIface) {
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {
QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());
}
mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),
"/Mounter", QDBusConnection::systemBus(), this);
connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));
connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));
}
return mounterIface;
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
TfLiteStatus Resize(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteLSHProjectionParams*>(node->builtin_data);
TF_LITE_ENSURE(context, NumInputs(node) == 2 || NumInputs(node) == 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* hash;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &hash));
TF_LITE_ENSURE_EQ(context, NumDimensions(hash), 2);
// Support up to 32 bits.
TF_LITE_ENSURE(context, SizeOfDimension(hash, 1) <= 32);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &input));
TF_LITE_ENSURE(context, NumDimensions(input) >= 1);
if (NumInputs(node) == 3) {
const TfLiteTensor* weight;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 2, &weight));
TF_LITE_ENSURE_EQ(context, NumDimensions(weight), 1);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(weight, 0),
SizeOfDimension(input, 0));
}
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);
switch (params->type) {
case kTfLiteLshProjectionSparse:
outputSize->data[0] = SizeOfDimension(hash, 0);
break;
case kTfLiteLshProjectionDense:
outputSize->data[0] = SizeOfDimension(hash, 0) * SizeOfDimension(hash, 1);
break;
default:
return kTfLiteError;
}
return context->ResizeTensor(context, output, outputSize);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, NumDimensions(input) <= 4);
TF_LITE_ENSURE(context, output->type == kTfLiteFloat32 ||
output->type == kTfLiteUInt8 ||
output->type == kTfLiteInt8);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.scale, (1. / 128.));
if (output->type == kTfLiteUInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 128);
}
if (output->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0);
}
}
// TODO(ahentz): For some reason our implementations don't support
// activations.
TF_LITE_ENSURE_EQ(context, params->activation, kTfLiteActNone);
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_size);
} | 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 bool couldRecur(const Variant& v, const ArrayData* arr) {
return v.isReferenced() ||
arr->kind() == ArrayData::kGlobalsKind ||
arr->kind() == ArrayData::kProxyKind;
} | 1 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
void* IOBuf::operator new(size_t size) {
if (size > kMaxIOBufSize) {
throw_exception<std::bad_alloc>();
}
size_t fullSize = offsetof(HeapStorage, buf) + size;
auto storage = static_cast<HeapStorage*>(checkedMalloc(fullSize));
new (&storage->prefix) HeapPrefix(kIOBufInUse, fullSize);
if (io_buf_alloc_cb) {
io_buf_alloc_cb(storage, fullSize);
}
return &(storage->buf);
} | 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 |
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
} | 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 |
TfLiteRegistration OkOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
// Set output size to the input size in OkOp::Prepare(). Code exists to have
// a framework in Prepare. The input and output tensors are not used.
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* in_tensor = GetInput(context, node, 0);
TfLiteTensor* out_tensor = GetOutput(context, node, 0);
TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);
return context->ResizeTensor(context, out_tensor, new_size);
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
return kTfLiteOk;
};
return reg;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
vector <string> genECDSAKey() {
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
vector <uint8_t> encr_pr_key(BUF_LEN, 0);
vector<char> pub_key_x(BUF_LEN, 0);
vector<char> pub_key_y(BUF_LEN, 0);
uint32_t enc_len = 0;
sgx_status_t status = trustedGenerateEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
vector <string> keys(3);
vector<char> hexEncrKey(BUF_LEN * 2, 0);
carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data(),
BUF_LEN * 2);
keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer);
vector<char> rand_str(BUF_LEN, 0);
carray2Hex(randBuffer.data(), 32, rand_str.data(), BUF_LEN);
keys.at(2) = rand_str.data();
CHECK_STATE(keys.at(2).size() == 64);
return keys;
} | 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 RepeatedAttrDefEqual(
const protobuf::RepeatedPtrField<OpDef::AttrDef>& a1,
const protobuf::RepeatedPtrField<OpDef::AttrDef>& a2) {
std::unordered_map<string, const OpDef::AttrDef*> a1_set;
for (const OpDef::AttrDef& def : a1) {
if (a1_set.find(def.name()) != a1_set.end()) {
LOG(ERROR) << "AttrDef names must be unique, but '" << def.name()
<< "' appears more than once";
}
a1_set[def.name()] = &def;
}
for (const OpDef::AttrDef& def : a2) {
auto iter = a1_set.find(def.name());
if (iter == a1_set.end()) return false;
if (!AttrDefEqual(*iter->second, def)) return false;
a1_set.erase(iter);
}
if (!a1_set.empty()) return false;
return true;
} | 1 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
TfLiteStatus EvalHashtableSize(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
int resource_id = input_resource_id_tensor->data.i32[0];
TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);
auto* output_data = GetTensorData<std::int64_t>(output_tensor);
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
output_data[0] = lookup->Size();
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 |
int TLSOutStream::length()
{
return offset + ptr - start;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
YCPBoolean IniAgent::Write(const YCPPath &path, const YCPValue& value, const YCPValue& arg)
{
if (!parser.isStarted())
{
y2warning("Can't execute Write before being mounted.");
return YCPBoolean (false);
}
// no need to update if modified, we are changing value
bool ok = false; // is the _path_ ok?
// return value
YCPBoolean b (true);
if (0 == path->length ())
{
if (value->isString() && value->asString()->value() == "force")
parser.inifile.setDirty();
else if (value->isString () && value->asString()->value() == "clean")
parser.inifile.clean ();
if (0 != parser.write ())
b = false;
ok = true;
}
else
{
if (( parser.repeatNames () && value->isList ()) ||
(!parser.repeatNames () && (value->isString () || value->isBoolean() || value->isInteger())) ||
path->component_str(0) == "all"
)
{
ok = true;
if (parser.inifile.Write (path, value, parser.HaveRewrites ()))
b = false;
}
else if (value->isVoid ())
{
int wb = -1;
string del_sec = "";
ok = true;
if (2 == path->length ())
{
string pc = path->component_str(0);
if ("s" == pc || "section" == pc)
{ // request to delete section. Find the file name
del_sec = path->component_str (1);
wb = parser.inifile.getSubSectionRewriteBy (del_sec.c_str());
}
}
if (parser.inifile.Delete (path))
b = false;
else if (del_sec != "")
{
parser.deleted_sections.insert (parser.getFileName (del_sec, wb));
}
}
else
{
ycp2error ("Wrong value for path %s: %s", path->toString ().c_str (), value->toString ().c_str ());
b = false;
}
}
if (!ok)
{
ycp2error ( "Wrong path '%s' in Write().", path->toString().c_str () );
}
return b;
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
static const char* ConvertScalar(PyObject* v, Eigen::half* out) {
// NOTE(nareshmodi): Is there a way to convert to C double without the
// intermediate Python double? This will help with ConvertOneFloat as well.
Safe_PyObjectPtr as_float = make_safe(PyNumber_Float(v));
double v_double = PyFloat_AS_DOUBLE(as_float.get());
*out = Eigen::half(v_double);
return nullptr;
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
void RegKey::getBinary(const TCHAR* valname, void** data, int* length) const {
TCharArray hex(getRepresentation(valname));
if (!rdr::HexInStream::hexStrToBin(CStr(hex.buf), (char**)data, length))
throw rdr::Exception("getBinary failed");
} | 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 DecodeResourceHandleList(std::unique_ptr<port::StringListDecoder> d,
ResourceHandle* ps, int64_t n) {
std::vector<uint32> sizes(n);
if (!d->ReadSizes(&sizes)) return false;
ResourceHandleProto proto;
for (int i = 0; i < n; ++i) {
if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {
return false;
}
ps[i].FromProto(proto);
}
return true;
} | 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 |
mptctl_mpt_command (unsigned long arg)
{
struct mpt_ioctl_command __user *uarg = (void __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *ioc;
int iocnum;
int rc;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_mpt_command - "
"Unable to read in mpt_ioctl_command struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_mpt_command() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
rc = mptctl_do_mpt_command (karg, &uarg->MF);
return rc;
} | 0 | C++ | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | vulnerable |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
if (sz < 8) {
return NULL;
}
RBinJavaAnnotation *annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | 1 | C++ | CWE-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 |
ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
{
std::string ctcpname;
bool is_ctcp = details.IsCTCP(ctcpname) && !irc::equals(ctcpname, "ACTION");
SilenceEntry::SilenceFlags flag = SilenceEntry::SF_NONE;
if (target.type == MessageTarget::TYPE_CHANNEL)
{
if (is_ctcp)
flag = SilenceEntry::SF_CTCP_CHANNEL;
else if (details.type == MSG_NOTICE)
flag = SilenceEntry::SF_NOTICE_CHANNEL;
else if (details.type == MSG_PRIVMSG)
flag = SilenceEntry::SF_PRIVMSG_CHANNEL;
return BuildChannelExempts(user, target.Get<Channel>(), flag, details.exemptions);
}
if (target.type == MessageTarget::TYPE_USER)
{
if (is_ctcp)
flag = SilenceEntry::SF_CTCP_USER;
else if (details.type == MSG_NOTICE)
flag = SilenceEntry::SF_NOTICE_USER;
else if (details.type == MSG_PRIVMSG)
flag = SilenceEntry::SF_PRIVMSG_USER;
if (!CanReceiveMessage(user, target.Get<User>(), flag))
{
details.echo_original = true;
return MOD_RES_DENY;
}
}
return MOD_RES_PASSTHRU;
} | 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 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* start = GetInput(context, node, kStartTensor);
const TfLiteTensor* limit = GetInput(context, node, kLimitTensor);
const TfLiteTensor* delta = GetInput(context, node, kDeltaTensor);
// Make sure all the inputs are scalars.
TF_LITE_ENSURE_EQ(context, NumDimensions(start), 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(limit), 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(delta), 0);
// Currently only supports int32 and float.
// TODO(b/117912892): Support quantization as well.
const auto dtype = start->type;
if (dtype != kTfLiteFloat32 && dtype != kTfLiteInt32) {
context->ReportError(context, "Unknown index output data type: %s",
TfLiteTypeGetName(dtype));
return kTfLiteError;
}
TF_LITE_ENSURE_TYPES_EQ(context, limit->type, dtype);
TF_LITE_ENSURE_TYPES_EQ(context, delta->type, dtype);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
output->type = dtype;
if (IsConstantTensor(start) && IsConstantTensor(limit) &&
IsConstantTensor(delta)) {
return ResizeOutput(context, start, limit, delta, output);
}
SetTensorToDynamic(output);
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void CtcpParser::query(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message)
{
QList<QByteArray> params;
params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message)));
static const char *splitter = " .,-!?";
int maxSplitPos = message.count();
int splitPos = maxSplitPos;
int overrun = net->userInputHandler()->lastParamOverrun("PRIVMSG", params);
if (overrun) {
maxSplitPos = message.count() - overrun -2;
splitPos = -1;
for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {
splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line
}
if (splitPos <= 0 || splitPos > maxSplitPos)
splitPos = maxSplitPos;
params = params.mid(0, 1) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message.left(splitPos))));
}
net->putCmd("PRIVMSG", params);
if (splitPos < message.count())
query(net, bufname, ctcpTag, message.mid(splitPos));
} | 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 Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
output->type = input->type;
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_size);
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
int64_t TensorByteSize(const TensorProto& t) {
// num_elements returns -1 if shape is not fully defined.
int64_t num_elems = PartialTensorShape(t.tensor_shape()).num_elements();
return num_elems < 0 ? -1 : num_elems * DataTypeSize(t.dtype());
} | 1 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | safe |
static bool extractFileTo(zip* zip, const std::string &file, std::string& to,
char* buf, size_t len) {
auto sep = file.rfind('/');
if (sep != std::string::npos) {
auto path = to + file.substr(0, sep);
if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {
return false;
}
if (sep == file.length() - 1) {
return true;
}
}
to.append(file);
struct zip_stat zipStat;
if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {
return false;
}
auto zipFile = zip_fopen_index(zip, zipStat.index, 0);
FAIL_IF_INVALID_PTR(zipFile);
auto outFile = fopen(to.c_str(), "wb");
if (outFile == nullptr) {
zip_fclose(zipFile);
return false;
}
for (auto n = zip_fread(zipFile, buf, len); n != 0;
n = zip_fread(zipFile, buf, len)) {
if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {
zip_fclose(zipFile);
fclose(outFile);
remove(to.c_str());
return false;
}
}
zip_fclose(zipFile);
if (fclose(outFile) != 0) {
return false;
}
return true;
} | 0 | C++ | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | vulnerable |
string PacketReader::getLabel(unsigned int recurs)
{
string ret;
ret.reserve(40);
getLabelFromContent(d_content, d_pos, ret, recurs++);
return ret;
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
int size() const {
return m_str ? m_str->size() : 0;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAnnotation *annotation = NULL;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_fw_xfer32 kfw32;
struct mpt_fw_xfer kfw;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = kfw32.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mptfwxfer_ioctl() called\n",
iocp->name));
kfw.iocnum = iocnum;
kfw.fwlen = kfw32.fwlen;
kfw.bufp = compat_ptr(kfw32.bufp);
ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
} | 0 | C++ | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | vulnerable |
TypedValue HHVM_FUNCTION(substr_compare,
const String& main_str,
const String& str,
int offset,
int length /* = INT_MAX */,
bool case_insensitivity /* = false */) {
int s1_len = main_str.size();
int s2_len = str.size();
if (length <= 0) {
raise_warning("The length must be greater than zero");
return make_tv<KindOfBoolean>(false);
}
if (offset < 0) {
offset = s1_len + offset;
if (offset < 0) offset = 0;
}
if (offset >= s1_len) {
raise_warning("The start position cannot exceed initial string length");
return make_tv<KindOfBoolean>(false);
}
auto const cmp_len = std::min(s1_len - offset, std::min(s2_len, length));
auto const ret = [&] {
const char *s1 = main_str.data();
if (case_insensitivity) {
return bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len);
}
return string_ncmp(s1 + offset, str.data(), cmp_len);
}();
if (ret == 0) {
auto const m1 = std::min(s1_len - offset, length);
auto const m2 = std::min(s2_len, length);
if (m1 > m2) return tvReturn(1);
if (m1 < m2) return tvReturn(-1);
return tvReturn(0);
}
return tvReturn(ret);
} | 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) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input1->type) {
case kTfLiteInt32: {
return EvalImpl<int32_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteInt64: {
return EvalImpl<int64_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteFloat32: {
return EvalImpl<float>(context, data->requires_broadcast, input1, input2,
output);
}
default: {
context->ReportError(context, "Type '%s' is not supported by floor_mod.",
TfLiteTypeGetName(input1->type));
return kTfLiteError;
}
}
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void LibRaw::exp_bef(float shift, float smooth)
{
// params limits
if(shift>8) shift = 8;
if(shift<0.25) shift = 0.25;
if(smooth < 0.0) smooth = 0.0;
if(smooth > 1.0) smooth = 1.0;
unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short));
if(shift <=1.0)
{
for(int i=0;i<=TBLN;i++)
lut[i] = (unsigned short)((float)i*shift);
}
else
{
float x1,x2,y1,y2;
float cstops = log(shift)/log(2.0f);
float room = cstops*2;
float roomlin = powf(2.0f,room);
x2 = (float)TBLN;
x1 = (x2+1)/roomlin-1;
y1 = x1*shift;
y2 = x2*(1+(1-smooth)*(shift-1));
float sq3x=powf(x1*x1*x2,1.0f/3.0f);
float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x);
float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f);
float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2;
for(int i=0;i<=TBLN;i++)
{
float X = (float)i;
float Y = A*powf(X,1.0f/3.0f)+B*X+CC;
if(i<x1)
lut[i] = (unsigned short)((float)i*shift);
else
lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y));
}
}
for(int i=0; i< S.height*S.width; i++)
{
imgdata.image[i][0] = lut[imgdata.image[i][0]];
imgdata.image[i][1] = lut[imgdata.image[i][1]];
imgdata.image[i][2] = lut[imgdata.image[i][2]];
imgdata.image[i][3] = lut[imgdata.image[i][3]];
}
C.data_maximum = lut[C.data_maximum];
C.maximum = lut[C.maximum];
// no need to adjust the minumum, black is already subtracted
free(lut);
} | 0 | C++ | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. | https://cwe.mitre.org/data/definitions/119.html | vulnerable |
KCleanup::expandVariables( const KFileInfo * item,
const QString & unexpanded ) const
{
QString expanded = unexpanded;
QString url = QString::fromLocal8Bit( item->url() ).replace("'", "'\\''");
expanded.replace( QRegExp( "%p" ), "'" + url + "'" );
QString name = QString::fromLocal8Bit( item->name() ).replace("'", "'\\''");
expanded.replace( QRegExp( "%n" ), "'" + name + "'" );
// if ( KDE::versionMajor() >= 3 && KDE::versionMinor() >= 4 )
expanded.replace( QRegExp( "%t" ), "trash:/" );
//else
//expanded.replace( QRegExp( "%t" ), KGlobalSettings::trashPath() );
return expanded;
} | 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 |
TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg,
TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits,
TPM2B_MAX_BUFFER *resultKey )
{
TPM2B_DIGEST tmpResult;
TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2;
UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0];
UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0];
TPM2B_DIGEST *bufferList[8];
UINT32 bitsSwizzled, i_Swizzled;
TPM_RC rval;
int i, j;
UINT16 bytes = bits / 8;
resultKey->t .size = 0;
tpm2b_i_2.t.size = 4;
tpm2bBits.t.size = 4;
bitsSwizzled = string_bytes_endian_convert_32( bits );
*(UINT32 *)tpm2bBitsPtr = bitsSwizzled;
for(i = 0; label[i] != 0 ;i++ );
tpm2bLabel.t.size = i+1;
for( i = 0; i < tpm2bLabel.t.size; i++ )
{
tpm2bLabel.t.buffer[i] = label[i];
}
resultKey->t.size = 0;
i = 1;
while( resultKey->t.size < bytes )
{
// Inner loop
i_Swizzled = string_bytes_endian_convert_32( i );
*(UINT32 *)tpm2b_i_2Ptr = i_Swizzled;
j = 0;
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b);
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b);
bufferList[j++] = (TPM2B_DIGEST *)contextU;
bufferList[j++] = (TPM2B_DIGEST *)contextV;
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b);
bufferList[j++] = (TPM2B_DIGEST *)0;
rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult );
if( rval != TPM_RC_SUCCESS )
{
return( rval );
}
bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b));
if (!res) {
return TSS2_SYS_RC_BAD_VALUE;
}
}
// Truncate the result to the desired size.
resultKey->t.size = bytes;
return TPM_RC_SUCCESS;
} | 0 | C++ | CWE-522 | Insufficiently Protected Credentials | The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval. | https://cwe.mitre.org/data/definitions/522.html | vulnerable |
void RemoteDevicePropertiesWidget::setType()
{
if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) {
sshPort->setValue(22);
}
if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) {
smbPort->setValue(445);
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)
{
char *colon;
char *host = NULL;
#ifdef HAVE_IPV6
char *p;
if (*(str) == '[' && str_len > 1) {
/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */
p = memchr(str + 1, ']', str_len - 2);
if (!p || *(p + 1) != ':') {
if (get_err) {
*err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str);
}
return NULL;
}
*portno = atoi(p + 2);
return estrndup(str + 1, p - str - 1);
}
#endif
if (str_len) {
colon = memchr(str, ':', str_len - 1);
} else {
colon = NULL;
}
if (colon) {
*portno = atoi(colon + 1);
host = estrndup(str, colon - str);
} else {
if (get_err) {
*err = strpprintf(0, "Failed to parse address \"%s\"", str);
}
return NULL;
}
return host;
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
QWriteLocker locker(&lock);
Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };
m_messages.push_back(temp);
if (m_messages.size() >= MAX_LOG_MESSAGES)
m_messages.pop_front();
emit newLogMessage(temp);
} | 0 | C++ | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
void Context::onDelete() {
if (wasm_->onDelete_) {
wasm_->onDelete_(this, id_);
}
} | 0 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
const TfLiteTensor* seq_lengths;
TF_LITE_ENSURE_OK(
context, GetInputSafe(context, node, kSeqLengthsTensor, &seq_lengths));
TF_LITE_ENSURE_EQ(context, NumDimensions(seq_lengths), 1);
if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 &&
input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 &&
input->type != kTfLiteInt64) {
context->ReportError(context,
"Type '%s' is not supported by reverse_sequence.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
if (seq_lengths->type != kTfLiteInt32 && seq_lengths->type != kTfLiteInt64) {
context->ReportError(
context, "Seq_lengths type '%s' is not supported by reverse_sequence.",
TfLiteTypeGetName(seq_lengths->type));
return kTfLiteError;
}
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);
return context->ResizeTensor(context, output, output_shape);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
inline typename V::VariantType FBUnserializer<V>::unserialize(
folly::StringPiece serialized) {
FBUnserializer<V> unserializer(serialized);
return unserializer.unserializeThing(0);
} | 1 | C++ | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion which takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | safe |
void UTFstring::UpdateFromUTF8()
{
delete [] _Data;
// find the size of the final UCS-2 string
size_t i;
for (_Length=0, i=0; i<UTF8string.length(); _Length++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80)
i++;
else if ((lead >> 5) == 0x6)
i += 2;
else if ((lead >> 4) == 0xe)
i += 3;
else if ((lead >> 3) == 0x1e)
i += 4;
else
// Invalid size?
break;
}
_Data = new wchar_t[_Length+1];
size_t j;
for (j=0, i=0; i<UTF8string.length(); j++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80) {
_Data[j] = lead;
i++;
} else if ((lead >> 5) == 0x6) {
_Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);
i += 2;
} else if ((lead >> 4) == 0xe) {
_Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);
i += 3;
} else if ((lead >> 3) == 0x1e) {
_Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);
i += 4;
} else
// Invalid char?
break;
}
_Data[j] = 0;
} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
TfLiteStatus LessEqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteFloat32:
Comparison<float, reference_ops::LessEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::LessEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::LessEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::LessEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::LessEqualFn>(
input1, input2, output, requires_broadcast);
break;
default:
context->ReportError(context,
"Does not support type %d, requires float|int|uint8",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
void RequestContext::AddInstanceIdentityToken() {
if (!method()) {
return;
}
const auto &audience = method()->backend_jwt_audience();
if (!audience.empty()) {
auto &token = service_context()
->global_context()
->GetInstanceIdentityToken(audience)
->GetAuthToken();
if (!token.empty()) {
std::string origin_auth_header;
if (request()->FindHeader(kAuthorizationHeader, &origin_auth_header)) {
Status status = request()->AddHeaderToBackend(
kXForwardedAuthorizationHeader, origin_auth_header);
if (!status.ok()) {
service_context()->env()->LogError(
"Failed to set X-Forwarded-Authorization header to backend.");
}
}
Status status = request()->AddHeaderToBackend(kAuthorizationHeader,
kBearerPrefix + token);
if (!status.ok()) {
service_context()->env()->LogError(
"Failed to set authorization header to backend.");
}
}
}
} | 0 | C++ | CWE-290 | Authentication Bypass by Spoofing | This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks. | https://cwe.mitre.org/data/definitions/290.html | vulnerable |
int length() const {
return m_str ? m_str->size() : 0;
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, 0);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
if (!IsSupportedType(input->type)) {
TF_LITE_KERNEL_LOG(context, "Input data type %s (%d) is not supported.",
TfLiteTypeGetName(input->type), input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
R_API ut8 *r_bin_java_get_attr_buf(RBinJavaObj *bin, ut64 sz, const ut64 offset, const ut8 *buf, const ut64 len) {
// XXX this pending is wrong and too expensive
int pending = len - offset;
const ut8 *a_buf = offset + buf;
ut8 *attr_buf = (ut8 *) calloc (pending + 1, 1);
if (!attr_buf) {
eprintf ("Unable to allocate enough bytes (0x%04"PFMT64x
") to read in the attribute.\n", sz);
return attr_buf;
}
memcpy (attr_buf, a_buf, pending); // sz+1);
return attr_buf;
} | 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 test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
} | 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 |
TfLiteStatus L2Eval(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:
L2EvalFloat<kernel_type>(context, node, params, data, input, output);
break;
case kTfLiteUInt8:
// We don't have a quantized implementation, so just fall through to the
// 'default' case.
default:
context->ReportError(context, "Type %d not currently supported.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
void RequestContext::StartBackendSpanAndSetTraceContext() {
backend_span_.reset(CreateSpan(cloud_trace_.get(), "Backend"));
// TODO: A better logic would be to send for GRPC backends the grpc-trace-bin
// header, and for http/https backends the X-Cloud-Trace-Context header.
std::string trace_context_header = cloud_trace()->ToTraceContextHeader(
backend_span_->trace_span()->span_id());
// Set trace context header to backend.
Status status = request()->AddHeaderToBackend(
cloud_trace()->header_type() == HeaderType::CLOUD_TRACE_CONTEXT
? kCloudTraceContextHeader
: kGRpcTraceContextHeader,
trace_context_header);
if (!status.ok()) {
service_context()->env()->LogError(
"Failed to set trace context header to backend.");
}
} | 0 | C++ | CWE-290 | Authentication Bypass by Spoofing | This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks. | https://cwe.mitre.org/data/definitions/290.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE(context, NumInputs(node) == 1 || NumInputs(node) == 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Always postpone sizing string tensors, even if we could in principle
// calculate their shapes now. String tensors don't benefit from having their
// shapes precalculated because the actual memory can only be allocated after
// we know all the content.
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type != kTfLiteString) {
if (NumInputs(node) == 1 ||
IsConstantTensor(GetInput(context, node, kShapeTensor))) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
} else {
SetTensorToDynamic(output);
}
}
return kTfLiteOk;
} | 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 |
ModResult OnUserPreTagMessage(User* user, const MessageTarget& target, CTCTags::TagMessageDetails& details) CXX11_OVERRIDE
{
if (target.type == MessageTarget::TYPE_CHANNEL)
return BuildChannelExempts(user, target.Get<Channel>(), SilenceEntry::SF_TAGMSG_CHANNEL, details.exemptions);
if (target.type == MessageTarget::TYPE_USER && !CanReceiveMessage(user, target.Get<User>(), SilenceEntry::SF_TAGMSG_USER))
{
details.echo_original = true;
return MOD_RES_DENY;
}
return MOD_RES_PASSTHRU;
} | 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 |
int ZlibInStream::overrun(int itemSize, int nItems, bool wait)
{
if (itemSize > bufSize)
throw Exception("ZlibInStream overrun: max itemSize exceeded");
if (end - ptr != 0)
memmove(start, ptr, end - ptr);
offset += ptr - start;
end -= ptr - start;
ptr = start;
while (end - ptr < itemSize) {
if (!decompress(wait))
return 0;
}
if (itemSize * nItems > end - ptr)
nItems = (end - ptr) / itemSize;
return nItems;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void CConfig::Write(CFile& File, unsigned int iIndentation) {
CString sIndentation = CString(iIndentation, '\t');
for (const auto& it : m_ConfigEntries) {
for (const CString& sValue : it.second) {
File.Write(sIndentation + it.first + " = " + sValue + "\n");
}
}
for (const auto& it : m_SubConfigs) {
for (const auto& it2 : it.second) {
File.Write("\n");
File.Write(sIndentation + "<" + it.first + " " + it2.first + ">\n");
it2.second.m_pSubConfig->Write(File, iIndentation + 1);
File.Write(sIndentation + "</" + it.first + ">\n");
}
}
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
void HeaderMapImpl::addCopy(const LowerCaseString& key, uint64_t value) {
auto* entry = getExistingInline(key.get());
if (entry != nullptr) {
char buf[32];
StringUtil::itoa(buf, sizeof(buf), value);
appendToHeader(entry->value(), buf);
return;
}
HeaderString new_key;
new_key.setCopy(key.get().c_str(), key.get().size());
HeaderString new_value;
new_value.setInteger(value);
insertByKey(std::move(new_key), std::move(new_value));
ASSERT(new_key.empty()); // NOLINT(bugprone-use-after-move)
ASSERT(new_value.empty()); // NOLINT(bugprone-use-after-move)
} | 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 |
mptctl_mpt_command (MPT_ADAPTER *ioc, unsigned long arg)
{
struct mpt_ioctl_command __user *uarg = (void __user *) arg;
struct mpt_ioctl_command karg;
int rc;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_mpt_command - "
"Unable to read in mpt_ioctl_command struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
rc = mptctl_do_mpt_command (ioc, karg, &uarg->MF);
return rc;
} | 1 | C++ | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | safe |
void CalculateOutputIndexRowSplit(
const RowPartitionTensor& row_split,
const vector<INDEX_TYPE>& parent_output_index,
INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,
vector<INDEX_TYPE>* result) {
INDEX_TYPE row_split_size = row_split.size();
if (row_split_size > 0) {
result->reserve(row_split(row_split_size - 1));
}
for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) {
INDEX_TYPE row_length = row_split(i + 1) - row_split(i);
INDEX_TYPE real_length = std::min(output_size, row_length);
INDEX_TYPE parent_output_index_current = parent_output_index[i];
if (parent_output_index_current == -1) {
real_length = 0;
}
for (INDEX_TYPE j = 0; j < real_length; ++j) {
result->push_back(parent_output_index_current);
parent_output_index_current += output_index_multiplier;
}
for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) {
result->push_back(-1);
}
}
if (row_split_size > 0) {
DCHECK_EQ(result->size(), row_split(row_split_size - 1));
}
} | 0 | C++ | CWE-131 | Incorrect Calculation of Buffer Size | The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow. | https://cwe.mitre.org/data/definitions/131.html | vulnerable |
inline TfLiteTensor* GetMutableInput(const TfLiteContext* context,
const TfLiteNode* node, int index) {
const int tensor_index = ValidateTensorIndexing(
context, index, node->inputs->size, node->inputs->data);
if (tensor_index < 0) {
return nullptr;
}
return GetTensorAtIndex(context, tensor_index);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
bool Router::MatchView(const std::string& method, const std::string& url,
bool* stream) {
assert(stream != nullptr);
*stream = false;
for (auto& route : routes_) {
if (std::find(route.methods.begin(), route.methods.end(), method) ==
route.methods.end()) {
continue;
}
if (route.url.empty()) {
std::smatch match;
if (std::regex_match(url, match, route.url_regex)) {
*stream = route.view->Stream(method);
return true;
}
} else {
if (boost::iequals(route.url, url)) {
*stream = route.view->Stream(method);
return true;
}
}
}
return false;
} | 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 RemoteDevicePropertiesWidget::update(const RemoteFsDevice::Details &d, bool create, bool isConnected)
{
int t=d.isLocalFile() ? Type_File : Type_SshFs;
setEnabled(d.isLocalFile() || !isConnected);
infoLabel->setVisible(create);
orig=d;
name->setText(d.name);
sshPort->setValue(22);
connectionNote->setVisible(!d.isLocalFile() && isConnected);
sshFolder->setText(QString());
sshHost->setText(QString());
sshUser->setText(QString());
fileFolder->setText(QString());
switch (t) {
case Type_SshFs: {
sshFolder->setText(d.url.path());
if (0!=d.url.port()) {
sshPort->setValue(d.url.port());
}
sshHost->setText(d.url.host());
sshUser->setText(d.url.userName());
sshExtra->setText(d.extraOptions);
break;
}
case Type_File:
fileFolder->setText(d.url.path());
break;
}
name->setEnabled(d.isLocalFile() || !isConnected);
connect(type, SIGNAL(currentIndexChanged(int)), this, SLOT(setType()));
for (int i=1; i<type->count(); ++i) {
if (type->itemData(i).toInt()==t) {
type->setCurrentIndex(i);
stackedWidget->setCurrentIndex(i);
break;
}
}
connect(name, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
connect(sshHost, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
connect(sshUser, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
connect(sshFolder, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
connect(sshPort, SIGNAL(valueChanged(int)), this, SLOT(checkSaveable()));
connect(sshExtra, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
connect(fileFolder, SIGNAL(textChanged(const QString &)), this, SLOT(checkSaveable()));
modified=false;
setType();
checkSaveable();
} | 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 StoreAllDecodedSequences(
TfLiteContext* context,
const std::vector<std::vector<std::vector<int>>>& sequences,
TfLiteNode* node, int top_paths) {
const int32_t batch_size = sequences.size();
std::vector<int32_t> num_entries(top_paths, 0);
// Calculate num_entries per path
for (const auto& batch_s : sequences) {
TF_LITE_ENSURE_EQ(context, batch_s.size(), top_paths);
for (int p = 0; p < top_paths; ++p) {
num_entries[p] += batch_s[p].size();
}
}
for (int p = 0; p < top_paths; ++p) {
const int32_t p_num = num_entries[p];
// Resize the decoded outputs.
TfLiteTensor* indices;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, p, &indices));
TF_LITE_ENSURE_OK(context, Resize(context, {p_num, 2}, indices));
TfLiteTensor* values;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, p + top_paths, &values));
TF_LITE_ENSURE_OK(context, Resize(context, {p_num}, values));
TfLiteTensor* decoded_shape;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, p + 2 * top_paths,
&decoded_shape));
TF_LITE_ENSURE_OK(context, Resize(context, {2}, decoded_shape));
int32_t max_decoded = 0;
int32_t offset = 0;
int32_t* indices_data = GetTensorData<int32_t>(indices);
int32_t* values_data = GetTensorData<int32_t>(values);
int32_t* decoded_shape_data = GetTensorData<int32_t>(decoded_shape);
for (int b = 0; b < batch_size; ++b) {
auto& p_batch = sequences[b][p];
int32_t num_decoded = p_batch.size();
max_decoded = std::max(max_decoded, num_decoded);
std::copy_n(p_batch.begin(), num_decoded, values_data + offset);
for (int32_t t = 0; t < num_decoded; ++t, ++offset) {
indices_data[offset * 2] = b;
indices_data[offset * 2 + 1] = t;
}
}
decoded_shape_data[0] = batch_size;
decoded_shape_data[1] = max_decoded;
}
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 |
TEST(BasicFlatBufferModel, TestHandleMalformedModelReuseTensor) {
const auto model_path =
"tensorflow/lite/testdata/add_shared_tensors.bin";
std::unique_ptr<tflite::FlatBufferModel> model =
FlatBufferModel::BuildFromFile(model_path);
ASSERT_NE(model, nullptr);
tflite::ops::builtin::BuiltinOpResolver resolver;
InterpreterBuilder builder(*model, resolver);
std::unique_ptr<Interpreter> interpreter;
ASSERT_EQ(builder(&interpreter), kTfLiteOk);
ASSERT_NE(interpreter, nullptr);
ASSERT_NE(interpreter->AllocateTensors(), kTfLiteOk);
} | 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 |
unsigned int bounded_iostream::write_no_buffer(const void *from, size_t bytes_to_write) {
//return iostream::write(from,tpsize,dtsize);
std::pair<unsigned int, Sirikata::JpegError> retval;
if (byte_bound != 0 && byte_position + bytes_to_write > byte_bound) {
size_t real_bytes_to_write = byte_bound - byte_position;
byte_position += real_bytes_to_write;
retval = parent->Write(reinterpret_cast<const unsigned char*>(from), real_bytes_to_write);
if (retval.first < real_bytes_to_write) {
err = retval.second;
return retval.first;
}
return bytes_to_write; // pretend we wrote it all
}
size_t total = bytes_to_write;
retval = parent->Write(reinterpret_cast<const unsigned char*>(from), total);
unsigned int written = retval.first;
byte_position += written;
if (written < total ) {
err = retval.second;
return written;
}
return bytes_to_write;
} | 0 | C++ | CWE-1187 | DEPRECATED: Use of Uninitialized Resource | This entry has been deprecated because it was a duplicate of CWE-908. All content has been transferred to CWE-908. | https://cwe.mitre.org/data/definitions/1187.html | vulnerable |
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg)
{
u8 cpl = ctxt->ops->cpl(ctxt);
/*
* None of MOV, POP and LSS can load a NULL selector in CPL=3, but
* they can load it at CPL<3 (Intel's manual says only LSS can,
* but it's wrong).
*
* However, the Intel manual says that putting IST=1/DPL=3 in
* an interrupt gate will result in SS=3 (the AMD manual instead
* says it doesn't), so allow SS=3 in __load_segment_descriptor
* and only forbid it here.
*/
if (seg == VCPU_SREG_SS && selector == 3 &&
ctxt->mode == X86EMUL_MODE_PROT64)
return emulate_exception(ctxt, GP_VECTOR, 0, true);
return __load_segment_descriptor(ctxt, selector, seg, cpl,
X86_TRANSFER_NONE, NULL);
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
int64_t MemFile::readImpl(char *buffer, int64_t length) {
assertx(m_len != -1);
assertx(length > 0);
int64_t remaining = m_len - m_cursor;
if (remaining < length) length = remaining;
if (length > 0) {
memcpy(buffer, (const void *)(m_data + m_cursor), length);
}
m_cursor += length;
return length;
} | 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 DependencyOptimizer::SafeToRemoveIdentity(const NodeDef& node) const {
if (!IsIdentity(node) && !IsIdentityN(node)) {
return true;
}
if (nodes_to_preserve_.find(node.name()) != nodes_to_preserve_.end()) {
return false;
}
if (!fetch_nodes_known_) {
// The output values of this node may be needed.
return false;
}
if (node.input_size() < 1) {
// Node lacks input, is invalid
return false;
}
const NodeDef* input = node_map_->GetNode(NodeName(node.input(0)));
CHECK(input != nullptr) << "node = " << node.name()
<< " input = " << node.input(0);
// Don't remove Identity nodes corresponding to Variable reads or following
// Recv.
if (IsVariable(*input) || IsRecv(*input)) {
return false;
}
for (const auto& consumer : node_map_->GetOutputs(node.name())) {
if (node.input_size() > 1 && (IsRetval(*consumer) || IsMerge(*consumer))) {
return false;
}
if (IsSwitch(*input)) {
for (const string& consumer_input : consumer->input()) {
if (consumer_input == AsControlDependency(node.name())) {
return false;
}
}
}
}
return true;
} | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.