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 |
---|---|---|---|---|---|---|---|
SSecurityTLS::~SSecurityTLS()
{
shutdown();
if (fis)
delete fis;
if (fos)
delete fos;
delete[] keyfile;
delete[] certfile;
gnutls_global_deinit();
} | 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 |
auto ReferenceHandle::New(Local<Value> value, MaybeLocal<Object> options) -> unique_ptr<ReferenceHandle> {
auto inherit = ReadOption<bool>(options, StringTable::Get().inheritUnsafe, false);
return std::make_unique<ReferenceHandle>(value, inherit);
} | 0 | C++ | CWE-913 | Improper Control of Dynamically-Managed Code Resources | The software does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements. | https://cwe.mitre.org/data/definitions/913.html | vulnerable |
TfLiteStatus InitializeTemporaries(TfLiteContext* context, TfLiteNode* node,
OpContext* op_context) {
// Creates a temp index to iterate through input data.
OpData* op_data = reinterpret_cast<OpData*>(node->user_data);
TfLiteIntArrayFree(node->temporaries);
node->temporaries = TfLiteIntArrayCreate(3);
node->temporaries->data[0] = op_data->scratch_tensor_index;
TfLiteTensor* scratch_tensor = GetTemporary(context, node, /*index=*/0);
scratch_tensor->type = kTfLiteInt32;
scratch_tensor->allocation_type = kTfLiteArenaRw;
TfLiteIntArray* index_size = TfLiteIntArrayCreate(1);
index_size->data[0] = NumDimensions(op_context->input);
TF_LITE_ENSURE_OK(context,
context->ResizeTensor(context, scratch_tensor, index_size));
// Creates a temp tensor to store resolved axis given input data.
node->temporaries->data[1] = op_data->scratch_tensor_index + 1;
TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1);
resolved_axis->type = kTfLiteInt32;
// Creates a temp tensor to store temp sums when calculating mean.
node->temporaries->data[2] = op_data->scratch_tensor_index + 2;
TfLiteTensor* temp_sum = GetTemporary(context, node, /*index=*/2);
switch (op_context->input->type) {
case kTfLiteFloat32:
temp_sum->type = kTfLiteFloat32;
break;
case kTfLiteInt32:
temp_sum->type = kTfLiteInt64;
break;
case kTfLiteInt64:
temp_sum->type = kTfLiteInt64;
break;
case kTfLiteUInt8:
case kTfLiteInt8:
case kTfLiteInt16:
temp_sum->type = kTfLiteInt32;
break;
case kTfLiteBool:
temp_sum->type = kTfLiteBool;
break;
default:
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | vulnerable |
void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,
int ystart, int xend, int yend)
{
jas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,
yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);
} | 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 |
inline void pad(int bytes) {
while (bytes-- > 0) writeU8(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 |
Variant HHVM_FUNCTION(apc_add,
const Variant& key_or_array,
const Variant& var /* = null */,
int64_t ttl /* = 0 */) {
if (!apcExtension::Enable) return false;
if (key_or_array.isArray()) {
Array valuesArr = key_or_array.toArray();
// errors stores all keys corresponding to entries that could not be cached
ArrayInit errors(valuesArr.size(), ArrayInit::Map{});
for (ArrayIter iter(valuesArr); iter; ++iter) {
Variant key = iter.first();
if (!key.isString()) {
throw_invalid_argument("apc key: (not a string)");
return false;
}
Variant v = iter.second();
auto const& strKey = key.toCStrRef();
if (isKeyInvalid(strKey)) {
throw_invalid_argument("apc key: (contains invalid characters)");
return false;
}
if (!apc_store().add(strKey, v, ttl)) {
errors.add(strKey, -1);
}
}
return errors.toVariant();
}
if (!key_or_array.isString()) {
throw_invalid_argument("apc key: (not a string)");
return false;
}
String strKey = key_or_array.toString();
if (isKeyInvalid(strKey)) {
throw_invalid_argument("apc key: (contains invalid characters)");
return false;
}
return apc_store().add(strKey, var, ttl);
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
static Status Compute(OpKernelContext* context,
const typename TTypes<T, 1>::ConstTensor& values,
const typename TTypes<T, 1>::ConstTensor& value_range,
int32_t nbins, typename TTypes<Tout, 1>::Tensor& out) {
const CPUDevice& d = context->eigen_device<CPUDevice>();
Tensor index_to_bin_tensor;
TF_RETURN_IF_ERROR(context->forward_input_or_allocate_temp(
{0}, DataTypeToEnum<int32>::value, TensorShape({values.size()}),
&index_to_bin_tensor));
auto index_to_bin = index_to_bin_tensor.flat<int32>();
const double step = static_cast<double>(value_range(1) - value_range(0)) /
static_cast<double>(nbins);
const double nbins_minus_1 = static_cast<double>(nbins - 1);
// We cannot handle NANs in the algorithm below (due to the case to int32)
const Eigen::Tensor<int32, 1, 1> nans_tensor =
values.isnan().template cast<int32>();
const Eigen::Tensor<int32, 0, 1> reduced_tensor = nans_tensor.sum();
const int num_nans = reduced_tensor(0);
if (num_nans > 0) {
return errors::InvalidArgument("Histogram values must not contain NaN");
}
// The calculation is done by finding the slot of each value in `values`.
// With [a, b]:
// step = (b - a) / nbins
// (x - a) / step
// , then the entries are mapped to output.
// Bug fix: Switch the order of cwiseMin and int32-casting to avoid
// producing a negative index when casting an big int64 number to int32
index_to_bin.device(d) =
((values.cwiseMax(value_range(0)) - values.constant(value_range(0)))
.template cast<double>() /
step)
.cwiseMin(nbins_minus_1)
.template cast<int32>();
out.setZero();
for (int32_t i = 0; i < index_to_bin.size(); i++) {
out(index_to_bin(i)) += Tout(1);
}
return Status::OK();
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
bool chopOff(string &domain)
{
if(domain.empty())
return false;
string::size_type fdot=domain.find('.');
if(fdot==string::npos)
domain="";
else {
string::size_type remain = domain.length() - (fdot + 1);
char tmp[remain];
memcpy(tmp, domain.c_str()+fdot+1, remain);
domain.assign(tmp, remain); // don't dare to do this w/o tmp holder :-)
}
return true;
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
void getReadBuffer(void** bufReturn, size_t* lenReturn) override {
*bufReturn = buf_.data();
*lenReturn = buf_.size();
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
TfLiteStatus GreaterEqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteFloat32:
Comparison<float, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::GreaterEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::GreaterEqualFn>(
input1, input2, output, requires_broadcast);
break;
default:
context->ReportError(context,
"Does not support type %d, requires float|int|uint8",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-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 chopOffDotted(string &domain)
{
if(domain.empty() || (domain.size()==1 && domain[0]=='.'))
return false;
string::size_type fdot=domain.find('.');
if(fdot == string::npos)
return false;
if(fdot==domain.size()-1)
domain=".";
else {
string::size_type remain = domain.length() - (fdot + 1);
char tmp[remain];
memcpy(tmp, domain.c_str()+fdot+1, remain);
domain.assign(tmp, remain);
}
return true;
} | 0 | C++ | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | https://cwe.mitre.org/data/definitions/399.html | vulnerable |
bool remoteComplete() const { return state_.remote_complete_; } | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
TfLiteStatus NotEqualEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteBool:
Comparison<bool, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteFloat32:
Comparison<float, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::NotEqualFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::NotEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::NotEqualFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteString:
ComparisonString(reference_ops::StringRefNotEqualFn, input1, input2,
output, requires_broadcast);
break;
default:
context->ReportError(
context,
"Does not support type %d, requires bool|float|int|uint8|string",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 0 | C++ | CWE-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 PrepareHashtable(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 0);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE(context, node->user_data != nullptr);
const auto* params =
reinterpret_cast<const TfLiteHashtableParams*>(node->user_data);
TF_LITE_ENSURE(context, !params->table_name.empty());
TF_LITE_ENSURE(context, (params->key_dtype == kTfLiteInt64 &&
params->value_dtype == kTfLiteString) ||
(params->key_dtype == kTfLiteString &&
params->value_dtype == kTfLiteInt64));
TfLiteTensor* resource_handle_tensor;
TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kResourceHandleTensor,
&resource_handle_tensor));
TF_LITE_ENSURE_EQ(context, resource_handle_tensor->type, kTfLiteInt32);
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);
outputSize->data[0] = 1;
return context->ResizeTensor(context, resource_handle_tensor, 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) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor1, &input1));
const TfLiteTensor* input2;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensor2, &input2));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
if (type != kTfLiteInt32 && type != kTfLiteFloat32) {
TF_LITE_KERNEL_LOG(context, "Unsupported data type %s.",
TfLiteTypeGetName(type));
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
const int num_elements = NumElements(input);
switch (input->type) {
case kTfLiteInt64:
memset(GetTensorData<int64_t>(output), 0, num_elements * sizeof(int64_t));
break;
case kTfLiteInt32:
memset(GetTensorData<int32_t>(output), 0, num_elements * sizeof(int32_t));
break;
case kTfLiteFloat32:
memset(GetTensorData<float>(output), 0, num_elements * sizeof(float));
break;
default:
context->ReportError(context,
"ZerosLike only currently supports int64, int32, "
"and float32, got %d.",
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 |
void Compute(OpKernelContext* ctx) override {
const Tensor& handle = ctx->input(0);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(handle.shape()),
errors::InvalidArgument("handle must be scalar"));
const string& name = handle.scalar<tstring>()();
Tensor val;
auto session_state = ctx->session_state();
OP_REQUIRES(ctx, session_state != nullptr,
errors::FailedPrecondition(
"GetSessionTensor called on null session state"));
OP_REQUIRES_OK(ctx, session_state->GetTensor(name, &val));
ctx->set_output(0, val);
} | 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 |
BigInt EC_Group::multiply_mod_order(const BigInt& x, const BigInt& y, const BigInt& z) const
{
return data().multiply_mod_order(x, y, z);
} | 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 |
Status ResourceHandle::BuildResourceHandle(const ResourceHandleProto& proto,
ResourceHandle* out) {
if (out == nullptr)
return errors::Internal(
"BuildResourceHandle() was called with nullptr for the output");
return out->FromProto(proto);
} | 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 |
void PrivateThreadPoolDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase* input,
DatasetBase** output) {
int64_t num_threads = 0;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64_t>(ctx, "num_threads", &num_threads));
OP_REQUIRES_OK(ctx, ValidateNumThreads(num_threads));
*output = new Dataset(ctx, input, num_threads);
} | 1 | C++ | CWE-770 | Allocation of Resources Without Limits or Throttling | The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->user_data != nullptr);
TFLITE_DCHECK(node->builtin_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const auto params =
static_cast<const TfLiteFullyConnectedParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
const TfLiteTensor* filter = GetInput(context, node, kWeightsTensor);
TF_LITE_ENSURE(context, filter != nullptr);
const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
TF_LITE_ENSURE_MSG(context, input->type == filter->type,
"Hybrid models are not supported on TFLite Micro.");
return CalculateOpData(context, params->activation, input->type, input,
filter, bias, output, data);
} | 1 | C++ | CWE-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 |
set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
lock_guard<std::recursive_mutex> guard(globalMutex);
string pipePath = endpoint.name();
if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
throw runtime_error("Tried to listen twice on the same path");
}
sockaddr_un local;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
FATAL_FAIL(fd);
initServerSocket(fd);
local.sun_family = AF_UNIX; /* local is declared before socket() ^ */
strcpy(local.sun_path, pipePath.c_str());
unlink(local.sun_path);
FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));
::listen(fd, 5);
#ifndef WIN32
FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));
#endif
pipeServerSockets[pipePath] = set<int>({fd});
return pipeServerSockets[pipePath];
} | 0 | C++ | CWE-120 | Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') | The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. | https://cwe.mitre.org/data/definitions/120.html | vulnerable |
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(i);
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-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 |
mptctl_eventreport (unsigned long arg)
{
struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventreport karg;
MPT_ADAPTER *ioc;
int iocnum;
int numBytes, maxEvents, max;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventreport - "
"Unable to read in mpt_ioctl_eventreport 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_eventreport() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventreport called.\n",
ioc->name));
numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);
max = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;
/* If fewer than 1 event is requested, there must have
* been some type of error.
*/
if ((max < 1) || !ioc->events)
return -ENODATA;
/* reset this flag so SIGIO can restart */
ioc->aen_event_read_flag=0;
/* Copy the data from kernel memory to user memory
*/
numBytes = max * sizeof(MPT_IOCTL_EVENTS);
if (copy_to_user(uarg->eventData, ioc->events, numBytes)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventreport - "
"Unable to write out mpt_ioctl_eventreport struct @ %p\n",
ioc->name, __FILE__, __LINE__, ioc->events);
return -EFAULT;
}
return 0;
} | 0 | C++ | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. | https://cwe.mitre.org/data/definitions/362.html | vulnerable |
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, kInput);
const TfLiteTensor* axis = GetInput(context, node, kAxis);
TfLiteTensor* output = GetOutput(context, node, 0);
output->type = input->type;
if (IsConstantTensor(axis)) {
int axis_value;
TF_LITE_ENSURE_OK(context,
GetAxisValueFromTensor(context, *axis, &axis_value));
return ExpandTensorDim(context, *input, axis_value, output);
}
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 |
void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const
{
if(tag->header()->majorVersion() < 4 &&
tag->frameList("TDRC").size() == 1 &&
tag->frameList("TDAT").size() == 1)
{
TextIdentificationFrame *tdrc =
static_cast<TextIdentificationFrame *>(tag->frameList("TDRC").front());
UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList("TDAT").front());
if(tdrc->fieldList().size() == 1 &&
tdrc->fieldList().front().size() == 4 &&
tdat->data().size() >= 5)
{
String date(tdat->data().mid(1), String::Type(tdat->data()[0]));
if(date.length() == 4) {
tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2));
if(tag->frameList("TIME").size() == 1) {
UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList("TIME").front());
if(timeframe->data().size() >= 5) {
String time(timeframe->data().mid(1), String::Type(timeframe->data()[0]));
if(time.length() == 4) {
tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2));
}
}
}
}
}
}
} | 0 | C++ | CWE-434 | Unrestricted Upload of File with Dangerous Type | The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. | https://cwe.mitre.org/data/definitions/434.html | vulnerable |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
return ReverseSequenceHelper<float>(context, node);
}
case kTfLiteUInt8: {
return ReverseSequenceHelper<uint8_t>(context, node);
}
case kTfLiteInt16: {
return ReverseSequenceHelper<int16_t>(context, node);
}
case kTfLiteInt32: {
return ReverseSequenceHelper<int32_t>(context, node);
}
case kTfLiteInt64: {
return ReverseSequenceHelper<int64_t>(context, node);
}
default: {
context->ReportError(context,
"Type '%s' is not supported by reverse_sequence.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} // namespace | 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 |
SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name = NULL;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
} | 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 |
ModuleSQL::~ModuleSQL()
{
if (Dispatcher)
{
Dispatcher->join();
Dispatcher->OnNotify();
delete Dispatcher;
}
for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
{
delete i->second;
}
mysql_library_end();
} | 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 |
inline int64_t StringData::size() const { return m_len; } | 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 ResourceHandle::FromProto(const ResourceHandleProto& proto) {
set_device(proto.device());
set_container(proto.container());
set_name(proto.name());
set_hash_code(proto.hash_code());
set_maybe_type_name(proto.maybe_type_name());
std::vector<DtypeAndPartialTensorShape> dtypes_and_shapes;
for (const auto& dtype_and_shape : proto.dtypes_and_shapes()) {
DataType dtype = dtype_and_shape.dtype();
PartialTensorShape shape(dtype_and_shape.shape());
dtypes_and_shapes.push_back(DtypeAndPartialTensorShape{dtype, shape});
}
dtypes_and_shapes_ = std::move(dtypes_and_shapes);
} | 0 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | vulnerable |
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
} | 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 Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
switch (input->type) {
case kTfLiteInt64:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int64_t>(input),
GetTensorShape(output), GetTensorData<int64_t>(output));
break;
case kTfLiteInt32:
reference_ops::Negate(
GetTensorShape(input), GetTensorData<int32_t>(input),
GetTensorShape(output), GetTensorData<int32_t>(output));
break;
case kTfLiteFloat32:
reference_ops::Negate(GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output),
GetTensorData<float>(output));
break;
default:
context->ReportError(
context,
"Neg only currently supports int64, int32, and float32, got %d.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | 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 |
PlayerGeneric::~PlayerGeneric()
{
if (mixer)
delete mixer;
if (player)
{
if (mixer->isActive() && !mixer->isDeviceRemoved(player))
mixer->removeDevice(player);
delete player;
}
delete[] audioDriverName;
delete listener;
} | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
TfLiteStatus ReverseSequenceHelper(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* seq_lengths_tensor =
GetInput(context, node, kSeqLengthsTensor);
switch (seq_lengths_tensor->type) {
case kTfLiteInt32: {
return ReverseSequenceImpl<T, int32_t>(context, node);
}
case kTfLiteInt64: {
return ReverseSequenceImpl<T, int64_t>(context, node);
}
default: {
context->ReportError(
context,
"Seq_lengths type '%s' is not supported by reverse_sequence.",
TfLiteTypeGetName(seq_lengths_tensor->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 |
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 |
std::string queueloader::get_filename(const std::string& str) {
std::string fn = ctrl->get_dlpath();
if (fn[fn.length()-1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char * base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t));
fn.append(lbuf);
} else {
fn.append(base);
}
return fn;
} | 0 | C++ | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | vulnerable |
void operator()(OpKernelContext* context, const Tensor& input_tensor,
Tensor& output_tensor, int n, bool reverse) {
const T* input = input_tensor.flat<T>().data();
T* output = output_tensor.flat<T>().data();
// Assume input_shape is [d1,d2,...dk], and output_shape is [d1,d2...dk-1],
// then num_rows = d1*d2...dk-1, last_dim = dk.
const int num_rows = output_tensor.NumElements();
const int last_dim = input_tensor.dim_size(input_tensor.dims() - 1);
// Allocate each row to different shard.
auto SubNthElement = [&, input, output, last_dim, n](int64 start,
int64 limit) {
// std::nth_element would rearrange the array, so we need a new buffer.
std::vector<T> buf(last_dim);
for (int b = start; b < limit; ++b) {
// Copy from one row of elements to buffer
const T* input_start = input + b * last_dim;
const T* input_end = input + (b + 1) * last_dim;
std::copy(input_start, input_end, buf.begin());
std::nth_element(buf.begin(), buf.begin() + n, buf.end());
// The element placed in the nth position is exactly the element that
// would occur in this position if the range was fully sorted.
output[b] = buf[n];
}
};
auto worker_threads = *(context->device()->tensorflow_cpu_worker_threads());
// The average time complexity of partition-based nth_element (BFPRT) is
// O(n), although the worst time complexity could be O(n^2). Here, 20 is a
// empirical factor of cost_per_unit.
Shard(worker_threads.num_threads, worker_threads.workers, num_rows,
20 * last_dim, SubNthElement);
} | 1 | C++ | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input1->type) {
case kTfLiteInt32: {
return EvalImpl<int32_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteFloat32: {
return EvalImpl<float>(context, data->requires_broadcast, input1, input2,
output);
}
default: {
context->ReportError(context, "Type '%s' is not supported by floor_div.",
TfLiteTypeGetName(input1->type));
return kTfLiteError;
}
}
} | 0 | C++ | CWE-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 |
mptctl_readtest (MPT_ADAPTER *ioc, unsigned long arg)
{
struct mpt_ioctl_test __user *uarg = (void __user *) arg;
struct mpt_ioctl_test karg;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - "
"Unable to read in mpt_ioctl_test struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
#ifdef MFCNT
karg.chip_type = ioc->mfcnt;
#else
karg.chip_type = ioc->pcidev->device;
#endif
strncpy (karg.name, ioc->name, MPT_MAX_NAME);
karg.name[MPT_MAX_NAME-1]='\0';
strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
karg.product[MPT_PRODUCT_LENGTH-1]='\0';
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - "
"Unable to write out mpt_ioctl_test struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
} | 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 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 |
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-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TFLITE_DCHECK(node->builtin_data != nullptr);
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
TFLITE_DCHECK(node->user_data != nullptr);
OpData* data = static_cast<OpData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, data));
if (input->type == kTfLiteFloat32) {
CalculateActivationRange(params->activation, &data->activation_min_f32,
&data->activation_max_f32);
} else if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8) {
CalculateActivationRangeQuantized(context, params->activation, output,
&data->activation_min,
&data->activation_max);
}
return kTfLiteOk;
} | 1 | C++ | CWE-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 |
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-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 ModuleSQL::init()
{
if (mysql_library_init(0, NULL, NULL))
throw ModuleException("Unable to initialise the MySQL library!");
Dispatcher = new DispatcherThread(this);
ServerInstance->Threads.Start(Dispatcher);
} | 1 | C++ | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
static int64_t HHVM_FUNCTION(bccomp, const String& left, const String& right,
int64_t scale /* = -1 */) {
scale = adjust_scale(scale);
bc_num first, second;
bc_init_num(&first);
bc_init_num(&second);
bc_str2num(&first, (char*)left.data(), scale);
bc_str2num(&second, (char*)right.data(), scale);
int64_t ret = bc_compare(first, second);
bc_free_num(&first);
bc_free_num(&second);
return ret;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
int IniParser::write()
{
int bugs = 0;
if (!inifile.isDirty())
{
y2debug ("File %s did not change. Not saving.", multiple_files ? files[0].c_str () : file.c_str ());
return 0;
}
if (read_only)
{
y2debug ("Attempt to write file %s that was mounted read-only. Not saving.", multiple_files ? files[0].c_str () : file.c_str ());
return 0;
}
UpdateIfModif ();
if (multiple_files)
{
IniIterator
ci = inifile.getContainerBegin (),
ce = inifile.getContainerEnd ();
for (;ci != ce; ++ci)
{
if (ci->t () == SECTION)
{
IniSection&s = ci->s ();
int wb = s.getRewriteBy (); // bug #19066
string filename = getFileName (s.getName (), wb);
// This is the only place where we unmark a
// section for deletion - when it is a file
// that got some data again. We can do it
// because we only erase the files afterwards.
deleted_sections.erase (filename);
if (!s.isDirty ()) {
y2debug ("Skipping file %s that was not changed.", filename.c_str());
continue;
}
s.initReadBy ();
bugs += write_file(filename, s);
}
else
{
y2error ("Value %s encountered at multifile top level",
ci->e ().getName ());
}
}
// FIXME: update time stamps of files...
// erase removed files...
for (set<string>::iterator i = deleted_sections.begin (); i!=deleted_sections.end();i++)
if (multi_files.find (*i) != multi_files.end ()) {
y2debug ("Removing file %s\n", (*i).c_str());
unlink ((*i).c_str());
}
}
else
{
bugs += write_file(file, inifile);
timestamp = getTimeStamp ();
}
return bugs ? -1 : 0;
} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteMfccParams*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input_wav;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensorWav, &input_wav));
const TfLiteTensor* input_rate;
TF_LITE_ENSURE_OK(context,
GetInputSafe(context, node, kInputTensorRate, &input_rate));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
TF_LITE_ENSURE_EQ(context, NumDimensions(input_wav), 3);
TF_LITE_ENSURE_EQ(context, NumElements(input_rate), 1);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
TF_LITE_ENSURE_TYPES_EQ(context, input_wav->type, output->type);
TF_LITE_ENSURE_TYPES_EQ(context, input_rate->type, kTfLiteInt32);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(3);
output_size->data[0] = input_wav->dims->data[0];
output_size->data[1] = input_wav->dims->data[1];
output_size->data[2] = params->dct_coefficient_count;
return context->ResizeTensor(context, output, output_size);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
int64_t length() const {
return m_str ? m_str->size() : 0;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
int size() 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 |
TfLiteStatus EvalHashtableFind(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
const TfLiteTensor* default_value_tensor =
GetInput(context, node, kDefaultValueTensor);
TfLiteTensor* output_tensor = GetOutput(context, node, 0);
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
TF_LITE_ENSURE_STATUS(
lookup->CheckKeyAndValueTypes(context, key_tensor, output_tensor));
auto result =
lookup->Lookup(context, key_tensor, output_tensor, default_value_tensor);
return result;
} | 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 inline bool IsGlobbingPattern(const std::string& pattern) {
return (pattern.find_first_of(kGlobbingChars) != std::string::npos);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
jas_matrix_t *jas_seq2d_input(FILE *in)
{
jas_matrix_t *matrix;
int i;
int j;
long x;
int numrows;
int numcols;
int xoff;
int yoff;
if (fscanf(in, "%d %d", &xoff, &yoff) != 2)
return 0;
if (fscanf(in, "%d %d", &numcols, &numrows) != 2)
return 0;
if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows)))
return 0;
if (jas_matrix_numrows(matrix) != numrows ||
jas_matrix_numcols(matrix) != numcols) {
abort();
}
/* Get matrix data. */
for (i = 0; i < jas_matrix_numrows(matrix); i++) {
for (j = 0; j < jas_matrix_numcols(matrix); j++) {
if (fscanf(in, "%ld", &x) != 1) {
jas_matrix_destroy(matrix);
return 0;
}
jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
}
}
return matrix;
} | 0 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | vulnerable |
TEST(BasicFlatBufferModel, TestHandleMalformedModel) {
const auto model_paths = {
// These models use the same tensor as both input and ouput of a node
"tensorflow/lite/testdata/add_shared_tensors.bin",
};
for (const auto& model_path : model_paths) {
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-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 |
String preg_quote(const String& str,
const String& delimiter /* = null_string */) {
const char* in_str = str.data();
const char* in_str_end = in_str + str.size();
/* Nothing to do if we got an empty string */
if (in_str == in_str_end) {
return str;
}
char delim_char = 0; /* Delimiter character to be quoted */
bool quote_delim = false; /* Whether to quote additional delim char */
if (!delimiter.empty()) {
delim_char = delimiter.charAt(0);
quote_delim = true;
}
/* Allocate enough memory so that even if each character
is quoted, we won't run out of room */
static_assert(
(StringData::MaxSize * 4 + 1) < std::numeric_limits<int64_t>::max()
);
String ret(4 * str.size() + 1, ReserveString);
char* out_str = ret.mutableData();
/* Go through the string and quote necessary characters */
const char* p;
char* q;
for (p = in_str, q = out_str; p != in_str_end; p++) {
char c = *p;
switch (c) {
case '.': case '\\': case '+': case '*': case '?':
case '[': case '^': case ']': case '$': case '(':
case ')': case '{': case '}': case '=': case '!':
case '>': case '<': case '|': case ':': case '-':
case '#':
*q++ = '\\';
*q++ = c;
break;
case '\0':
*q++ = '\\';
*q++ = '0';
*q++ = '0';
*q++ = '0';
break;
default:
if (quote_delim && c == delim_char)
*q++ = '\\';
*q++ = c;
break;
}
}
*q = '\0';
return ret.setSize(q - out_str);
} | 1 | C++ | CWE-787 | Out-of-bounds Write | The software writes data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/787.html | safe |
RemoteFsDevice::Details RemoteDevicePropertiesWidget::details()
{
int t=type->itemData(type->currentIndex()).toInt();
RemoteFsDevice::Details det;
det.name=name->text().trimmed();
switch (t) {
case Type_SshFs: {
det.url.setHost(sshHost->text().trimmed());
det.url.setUserName(sshUser->text().trimmed());
det.url.setPath(sshFolder->text().trimmed());
det.url.setPort(sshPort->value());
det.url.setScheme(RemoteFsDevice::constSshfsProtocol);
det.extraOptions=sshExtra->text().trimmed();
break;
}
case Type_File: {
QString path=fileFolder->text().trimmed();
if (path.isEmpty()) {
path="/";
}
det.url.setPath(path);
det.url.setScheme(RemoteFsDevice::constFileProtocol);
break;
}
}
return det;
} | 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 |
void Compute(OpKernelContext* ctx) override {
StagingMap<Ordered>* map = nullptr;
OP_REQUIRES_OK(ctx, GetStagingMap(ctx, def(), &map));
core::ScopedUnref scope(map);
typename StagingMap<Ordered>::OptionalTuple tuple;
const Tensor* key_tensor;
const Tensor* indices_tensor;
OpInputList values_tensor;
OP_REQUIRES_OK(ctx, ctx->input("key", &key_tensor));
OP_REQUIRES_OK(ctx, ctx->input("indices", &indices_tensor));
OP_REQUIRES_OK(ctx, ctx->input_list("values", &values_tensor));
OP_REQUIRES(ctx, key_tensor->NumElements() > 0,
errors::InvalidArgument("key must not be empty"));
OP_REQUIRES(ctx, key_tensor->NumElements() == 1,
errors::InvalidArgument(
"key must be an int64 scalar, got tensor with shape: ",
key_tensor->shape()));
// Create copy for insertion into Staging Area
Tensor key(*key_tensor);
// Create the tuple to store
for (std::size_t i = 0; i < values_tensor.size(); ++i) {
tuple.push_back(values_tensor[i]);
}
// Store the tuple in the map
OP_REQUIRES_OK(ctx, map->put(&key, indices_tensor, &tuple));
} | 1 | C++ | CWE-843 | Access of Resource Using Incompatible Type ('Type Confusion') | The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type. | https://cwe.mitre.org/data/definitions/843.html | safe |
MONGO_EXPORT int bson_iterator_int( const bson_iterator *i ) {
switch ( bson_iterator_type( i ) ) {
case BSON_INT:
return bson_iterator_int_raw( i );
case BSON_LONG:
return bson_iterator_long_raw( i );
case BSON_DOUBLE:
return bson_iterator_double_raw( i );
default:
return 0;
}
} | 0 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | vulnerable |
explicit DataFormatVecPermuteOp(OpKernelConstruction* context)
: OpKernel(context) {
string src_format;
OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format));
OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,
errors::InvalidArgument(
"Source format must be of length 4 or 5, received "
"src_format = ",
src_format));
string dst_format;
OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format));
OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,
errors::InvalidArgument("Destination format must be of length "
"4 or 5, received dst_format = ",
dst_format));
OP_REQUIRES(
context, IsValidPermutation(src_format, dst_format),
errors::InvalidArgument(
"Destination and source format must determine a permutation, got ",
src_format, " and ", dst_format));
src_format_ = src_format;
dst_format_ = dst_format;
} | 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 Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);
const TfLiteTensor* segment_ids =
GetInput(context, node, kInputSegmentIdsTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context,
data->type == kTfLiteInt32 || data->type == kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, segment_ids->type, kTfLiteInt32);
if (!IsConstantTensor(data) || !IsConstantTensor(segment_ids)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, data, segment_ids, output);
} | 0 | C++ | CWE-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 optional<Principal> parse_principal(CephContext* cct, TokenID t,
string&& s) {
// Wildcard!
if ((t == TokenID::AWS) && (s == "*")) {
return Principal::wildcard();
// Do nothing for now.
} else if (t == TokenID::CanonicalUser) {
// AWS ARNs
} else if (t == TokenID::AWS) {
auto a = ARN::parse(s);
if (!a) {
if (std::none_of(s.begin(), s.end(),
[](const char& c) {
return (c == ':') || (c == '/');
})) {
// Since tenants are simply prefixes, there's no really good
// way to see if one exists or not. So we return the thing and
// let them try to match against it.
return Principal::tenant(std::move(s));
}
}
if (a->resource == "root") {
return Principal::tenant(std::move(a->account));
}
static const char rx_str[] = "([^/]*)/(.*)";
static const regex rx(rx_str, sizeof(rx_str) - 1,
ECMAScript | optimize);
smatch match;
if (regex_match(a->resource, match, rx)) {
if (match.size() != 3) {
return boost::none;
}
if (match[1] == "user") {
return Principal::user(std::move(a->account),
match[2]);
}
if (match[1] == "role") {
return Principal::role(std::move(a->account),
match[2]);
}
}
}
ldout(cct, 0) << "Supplied principal is discarded: " << s << dendl;
return boost::none;
} | 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 int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
} | 1 | C++ | CWE-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 |
int TLSOutStream::writeTLS(const U8* data, int length)
{
int n;
n = gnutls_record_send(session, data, length);
if (n == GNUTLS_E_INTERRUPTED || n == GNUTLS_E_AGAIN)
return 0;
if (n < 0)
throw TLSException("writeTLS", 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 |
static Status ValidateSavedTensors(const GraphDef& graph_def) {
for (const auto& node : graph_def.node()) {
TF_RETURN_IF_ERROR(ValidateNode(node));
}
if (graph_def.has_library()) {
const FunctionDefLibrary& library = graph_def.library();
for (const auto& function : library.function()) {
for (const auto& node : function.node_def()) {
TF_RETURN_IF_ERROR(ValidateNode(node));
}
}
}
return Status::OK();
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
inline static bool jas_safe_intfast32_mul(int_fast32_t x, int_fast32_t y,
int_fast32_t *result)
{
if (x > 0) {
/* x is positive */
if (y > 0) {
/* x and y are positive */
if (x > INT_FAST32_MAX / y) {
return false;
}
} else {
/* x positive, y nonpositive */
if (y < INT_FAST32_MIN / x) {
return false;
}
}
} else {
/* x is nonpositive */
if (y > 0) {
/* x is nonpositive, y is positive */
if (x < INT_FAST32_MIN / y) {
return false;
}
} else { /* x and y are nonpositive */
if (x != 0 && y < INT_FAST32_MAX / x) {
return false;
}
}
}
if (result) {
*result = x * y;
}
return true;
} | 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 |
IniSection (const IniParser *p)
: IniBase (-1),
ip (p),
end_comment (), is_private(false), rewrite_by(-1),
container (), ivalues (), isections ()
{} | 1 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
assert(n >= 0);
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 >>= n;
*data = jas_seqent_asr(*data, n);
}
}
}
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,
TfLiteDepthwiseConvParams* params, int width,
int height, int filter_width, int filter_height,
const TfLiteType data_type, OpData* data) {
bool has_bias = node->inputs->size == 3;
// Check number of inputs/outputs
TF_LITE_ENSURE(context, has_bias || node->inputs->size == 2);
TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);
int unused_output_height, unused_output_width;
data->padding = ComputePaddingHeightWidth(
params->stride_height, params->stride_width, 1, 1, height, width,
filter_height, filter_width, params->padding, &unused_output_height,
&unused_output_width);
// Note that quantized inference requires that all tensors have their
// parameters set. This is usually done during quantized training.
if (data_type != kTfLiteFloat32) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TF_LITE_ENSURE(context, input != nullptr);
const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
TF_LITE_ENSURE(context, filter != nullptr);
const TfLiteTensor* bias =
GetOptionalInputTensor(context, node, kBiasTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output != nullptr);
int num_channels = filter->dims->data[kDepthwiseConvQuantizedDimension];
return tflite::PopulateConvolutionQuantizationParams(
context, input, filter, bias, output, params->activation,
&data->output_multiplier, &data->output_shift,
&data->output_activation_min, &data->output_activation_max,
data->per_channel_output_multiplier,
reinterpret_cast<int*>(data->per_channel_output_shift), num_channels);
}
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 |
Function *ESTreeIRGen::genGeneratorFunction(
Identifier originalName,
Variable *lazyClosureAlias,
ESTree::FunctionLikeNode *functionNode) {
assert(functionNode && "Function AST cannot be null");
// Build the outer function which creates the generator.
// Does not have an associated source range.
auto *outerFn = Builder.createGeneratorFunction(
originalName,
Function::DefinitionKind::ES5Function,
ESTree::isStrict(functionNode->strictness),
/* insertBefore */ nullptr);
auto *innerFn = genES5Function(
genAnonymousLabelName(originalName.isValid() ? originalName.str() : ""),
lazyClosureAlias,
functionNode,
true);
{
FunctionContext outerFnContext{this, outerFn, functionNode->getSemInfo()};
emitFunctionPrologue(
functionNode,
Builder.createBasicBlock(outerFn),
InitES5CaptureState::Yes,
DoEmitParameters::No);
// Create a generator function, which will store the arguments.
auto *gen = Builder.createCreateGeneratorInst(innerFn);
if (!hasSimpleParams(functionNode)) {
// If there are non-simple params, step the inner function once to
// initialize them.
Value *next = Builder.createLoadPropertyInst(gen, "next");
Builder.createCallInst(next, gen, {});
}
emitFunctionEpilogue(gen);
}
return outerFn;
} | 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 |
UnicodeString DecimalQuantity::toScientificString() const {
U_ASSERT(!isApproximate);
UnicodeString result;
if (isNegative()) {
result.append(u'-');
}
if (precision == 0) {
result.append(u"0E+0", -1);
return result;
}
// NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from
// rOptPos (aka -maxFrac) due to overflow.
int32_t upperPos = std::min(precision + scale, lOptPos) - scale - 1;
int32_t lowerPos = std::max(scale, rOptPos) - scale;
int32_t p = upperPos;
result.append(u'0' + getDigitPos(p));
if ((--p) >= lowerPos) {
result.append(u'.');
for (; p >= lowerPos; p--) {
result.append(u'0' + getDigitPos(p));
}
}
result.append(u'E');
int32_t _scale = upperPos + scale;
if (_scale == INT32_MIN) {
result.append({u"-2147483648", -1});
return result;
} else if (_scale < 0) {
_scale *= -1;
result.append(u'-');
} else {
result.append(u'+');
}
if (_scale == 0) {
result.append(u'0');
}
int32_t insertIndex = result.length();
while (_scale > 0) {
std::div_t res = std::div(_scale, 10);
result.insert(insertIndex, u'0' + res.rem);
_scale = res.quot;
}
return result;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
TEST_F(AutoParallelTest, SimpleParallelNoDequeue) {
tensorflow::Scope s = tensorflow::Scope::DisabledShapeInferenceScope();
Output constant_a = ops::Const(s.WithOpName("constant_a"), 1.0f, {1});
Output constant_c = ops::Const(s.WithOpName("constant_c"), 1.0f, {1});
Output constant_b = ops::Const(s.WithOpName("constant_b"), 1, {1});
Output var = ops::Variable(s.WithOpName("var"), {1}, DT_FLOAT);
Output assign = ops::Assign(s.WithOpName("assign"), {var}, {constant_a});
Output add = ops::AddN(s.WithOpName("add"), {constant_a, constant_c});
Output learning_rate = ops::Const(s.WithOpName("learning_rate"), 0.01f, {1});
Output apply_gradient = ops::ApplyGradientDescent(
s.WithOpName("apply_gradient"), {var}, {learning_rate}, {add});
GrapplerItem item;
item.init_ops.push_back("assign");
item.fetch.push_back("apply_gradient");
item.init_ops.push_back("assign");
TF_CHECK_OK(s.ToGraphDef(&item.graph));
AutoParallel parallel(2);
GraphDef output;
Status status = parallel.Optimize(nullptr, item, &output);
TF_EXPECT_OK(status);
} | 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 |
inline bool AveragePool(const uint8* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int filter_width, int filter_height,
int32 output_activation_min,
int32 output_activation_max, uint8* output_data,
const Dims<4>& output_dims) {
tflite::PoolParams params;
params.stride_height = stride_height;
params.stride_width = stride_width;
params.filter_height = filter_height;
params.filter_width = filter_width;
params.padding_values.height = pad_height;
params.padding_values.width = pad_width;
params.quantized_activation_min = output_activation_min;
params.quantized_activation_max = output_activation_max;
return AveragePool(params, DimsToShape(input_dims), input_data,
DimsToShape(output_dims), output_data);
} | 1 | C++ | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
void Phase2() final {
Local<Context> context_handle = Deref(context);
Context::Scope context_scope{context_handle};
Local<Value> key_inner = key->CopyInto();
Local<Object> object = Local<Object>::Cast(Deref(reference));
bool allow = [&]() {
if (!inherit) {
if (key_inner->IsName()) {
return Unmaybe(object->HasRealNamedProperty(context_handle, key_inner.As<Name>()));
} else if (key_inner->IsNumber()) {
return Unmaybe(object->HasRealIndexedProperty(context_handle, HandleCast<uint32_t>(key_inner)));
} else {
return false;
}
}
return true;
}();
Local<Value> value = allow ?
Unmaybe(object->Get(context_handle, key_inner)) :
Undefined(Isolate::GetCurrent()).As<Value>();
ret = TransferOut(value, options);
} | 0 | C++ | CWE-913 | Improper Control of Dynamically-Managed Code Resources | The software does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements. | https://cwe.mitre.org/data/definitions/913.html | vulnerable |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteAudioSpectrogramParams*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 2);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
TF_LITE_ENSURE(context, params->spectrogram->Initialize(params->window_size,
params->stride));
const int64_t sample_count = input->dims->data[0];
const int64_t length_minus_window = (sample_count - params->window_size);
if (length_minus_window < 0) {
params->output_height = 0;
} else {
params->output_height = 1 + (length_minus_window / params->stride);
}
TfLiteIntArray* output_size = TfLiteIntArrayCreate(3);
output_size->data[0] = input->dims->data[1];
output_size->data[1] = params->output_height;
output_size->data[2] = params->spectrogram->output_frequency_channels();
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 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* data = GetInput(context, node, kInputDataTensor);
const TfLiteTensor* segment_ids =
GetInput(context, node, kInputSegmentIdsTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context,
ResizeOutputTensor(context, data, segment_ids, output));
}
#define TF_LITE_SEGMENT_SUM(dtype) \
reference_ops::SegmentSum<dtype>( \
GetTensorShape(data), GetTensorData<dtype>(data), \
GetTensorShape(segment_ids), GetTensorData<int32_t>(segment_ids), \
GetTensorShape(output), GetTensorData<dtype>(output));
switch (data->type) {
case kTfLiteInt32:
TF_LITE_SEGMENT_SUM(int32_t);
break;
case kTfLiteFloat32:
TF_LITE_SEGMENT_SUM(float);
break;
default:
context->ReportError(context,
"Currently SegmentSum doesn't support type: %s",
TfLiteTypeGetName(data->type));
return kTfLiteError;
}
#undef TF_LITE_SEGMENT_SUM
return kTfLiteOk;
} | 0 | C++ | CWE-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 ResourceHandle::ParseFromString(const string& s) {
ResourceHandleProto proto;
const bool status = proto.ParseFromString(s);
if (status) FromProto(proto);
return status;
} | 0 | C++ | CWE-617 | Reachable Assertion | The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. | https://cwe.mitre.org/data/definitions/617.html | vulnerable |
void Compute(OpKernelContext* context) override {
const Tensor& tensor_in = context->input(0);
OP_REQUIRES(context, tensor_in.dims() == 4,
errors::InvalidArgument("tensor_in must be 4-dimensional (2)"));
OP_REQUIRES(context, tensor_in.NumElements() > 0,
errors::InvalidArgument("tensor_in must not be empty (2)"));
PoolParameters params{context,
ksize_,
stride_,
padding_,
/*explicit_paddings=*/{},
FORMAT_NHWC,
tensor_in.shape()};
if (!context->status().ok()) {
return;
}
TensorShape out_shape({params.tensor_in_batch, params.out_height,
params.out_width, params.depth});
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output));
Tensor* argmax = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, out_shape, &argmax));
LaunchMaxPoolingWithArgmax<Device, T, Targmax>::launch(
context, params, tensor_in, output, argmax, propagate_nans_,
include_batch_in_index_);
} | 1 | C++ | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
BGD_DECLARE(void *) gdImageWBMPPtr(gdImagePtr im, int *size, int fg)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) return NULL;
if (!_gdImageWBMPCtx(im, fg, out)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free(out);
return rv;
} | 1 | C++ | CWE-415 | Double Free | The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. | https://cwe.mitre.org/data/definitions/415.html | safe |
bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {
assertx(m_len != -1);
if (whence == SEEK_CUR) {
if (offset >= 0 && offset < bufferedLen()) {
setReadPosition(getReadPosition() + offset);
setPosition(getPosition() + offset);
return true;
}
offset += getPosition();
whence = SEEK_SET;
}
// invalidate the current buffer
setWritePosition(0);
setReadPosition(0);
if (whence == SEEK_SET) {
if (offset < 0) return false;
m_cursor = offset;
} else if (whence == SEEK_END) {
if (m_len + offset < 0) return false;
m_cursor = m_len + offset;
} else {
return false;
}
setPosition(m_cursor);
return true;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
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 = GetOutput(context, node, p);
TF_LITE_ENSURE_OK(context, Resize(context, {p_num, 2}, indices));
TfLiteTensor* values = GetOutput(context, node, p + top_paths);
TF_LITE_ENSURE_OK(context, Resize(context, {p_num}, values));
TfLiteTensor* decoded_shape = GetOutput(context, node, p + 2 * top_paths);
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;
} | 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);
const TfLiteTensor* axis = GetInput(context, node, kAxisTensor);
TF_LITE_ENSURE_EQ(context, NumDimensions(axis), 1);
TF_LITE_ENSURE(context, NumDimensions(input) >= NumElements(axis));
if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 &&
input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 &&
input->type != kTfLiteInt64 && input->type != kTfLiteBool) {
context->ReportError(context, "Type '%s' is not supported by reverse.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
if (axis->type != kTfLiteInt32) {
context->ReportError(context, "Axis Type '%s' is not supported by reverse.",
TfLiteTypeGetName(axis->type));
return kTfLiteError;
}
// TODO(renjieliu): support multi-axis case.
if (NumElements(axis) > 1) {
context->ReportError(context, "Current does not support more than 1 axis.");
}
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TfLiteIntArray* output_shape = TfLiteIntArrayCopy(input->dims);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, input->type);
return context->ResizeTensor(context, output, output_shape);
} | 0 | C++ | CWE-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 MultiplyAndCheckOverflow(size_t a, size_t b, size_t* product) {
// Multiplying a * b where a and b are size_t cannot result in overflow in a
// size_t accumulator if both numbers have no non-zero bits in their upper
// half.
constexpr size_t size_t_bits = 8 * sizeof(size_t);
constexpr size_t overflow_upper_half_bit_position = size_t_bits / 2;
*product = a * b;
// If neither integers have non-zero bits past 32 bits can't overflow.
// Otherwise check using slow devision.
if (TFLITE_EXPECT_FALSE((a | b) >> overflow_upper_half_bit_position != 0)) {
if (a != 0 && *product / a != b) return kTfLiteError;
}
return kTfLiteOk;
} | 1 | C++ | CWE-190 | Integer Overflow or Wraparound | The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* cond_tensor;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputConditionTensor,
&cond_tensor));
TfLiteTensor* output;
TF_LITE_ENSURE_OK(context,
GetOutputSafe(context, node, kOutputTensor, &output));
if (cond_tensor->type != kTfLiteBool) {
context->ReportError(context,
"Condition tensor must be of type bool, but saw '%s'.",
TfLiteTypeGetName(cond_tensor->type));
return kTfLiteError;
}
// As output will be a 2D tensor of indices, use int64 to be consistent with
// tensorflow.
output->type = kTfLiteInt64;
// Exit early if cond is a non-const tensor. Set output tensor to dynamic so
// output size can be determined in Eval.
if (!IsConstantTensor(cond_tensor)) {
SetTensorToDynamic(output);
return kTfLiteOk;
}
return ResizeOutputTensor(context, cond_tensor, output);
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void CleanupOutput(char *str)
{
char *s, *t;
int period = 0;
s = t = str;
// Collapse multiple white space (' ' and '\n') to one. Remove trailing space.
while ( *s ) {
if ( *s == '\n' ) {*s = ' '; }
if ( (*s == ' ') && ( s[1] == ' ' || s[1] == '\n' || s[1] == 0 ) ) { s++;}
else { *t++ = *s++; }
}
*t = 0;
// Optimize format of numbers:
s = t = str;
while ( *s ) {
if ( *s == '.' ) { period = 1; *t++ = *s++; }
else if ( isdigit(*s) ) { *t++ = *s++; }
else if ( period ) {
while ( t > str && t[-1] == '0' ) { t--; }
if ( t > str && t[-1] == '.' ) {
t--;
// Handle case that number is .000, not e.g. 9.000
if (t > str && ! isdigit(t[-1]) ) {
*t++ = '0';
}
}
period = 0; *t++ = *s++;
}
else {
period = 0; *t++ = *s++;
}
}
*t = 0;
// Collapse '-0' to '0'
s = t = str;
while ( *s ) {
if ( *s == '-' && s[1] == '0' && s[2] == ' ' ) { s++; }
else *t++ = *s++;
}
*t = 0;
} | 1 | C++ | NVD-CWE-noinfo | null | null | null | safe |
TfLiteStatus PrepareMeanOrSum(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_OK(context, PrepareSimple(context, node));
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// reduce_mean requires a buffer to store intermediate sum result.
OpContext op_context(context, node);
if (op_context.input->type == kTfLiteInt8 ||
op_context.input->type == kTfLiteUInt8 ||
op_context.input->type == kTfLiteInt16) {
const double real_multiplier =
static_cast<double>(op_context.input->params.scale) /
static_cast<double>(op_context.output->params.scale);
int exponent;
QuantizeMultiplier(real_multiplier, &data->multiplier, &exponent);
data->shift = exponent;
}
TfLiteTensor* temp_sum = GetTemporary(context, node, /*index=*/2);
if (!IsConstantTensor(op_context.axis)) {
SetTensorToDynamic(temp_sum);
return kTfLiteOk;
}
temp_sum->allocation_type = kTfLiteArenaRw;
return ResizeTempSum(context, &op_context, temp_sum);
} | 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 aligned_free(void* ptr) {
folly::detail::aligned_free(ptr);
} | 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 IsPadOpSupported(const TfLiteRegistration* registration,
const TfLiteNode* node, TfLiteContext* context) {
// padding is d x 2 tensor, where d is the dimension of input.
const TfLiteTensor* padding;
TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &padding));
if (!IsConstantTensor(padding)) {
TF_LITE_KERNEL_LOG(context,
"%s: Only constant padding is supported for PAD.",
padding->name);
return false;
}
if (padding->dims->data[0] != 4 || padding->dims->data[1] != 2) {
TF_LITE_KERNEL_LOG(context, "%s: Only 4D inputs are supported for PAD.",
padding->name);
return false;
}
const int32_t* padding_data = GetTensorData<int32_t>(padding);
if (!(padding_data[0] == 0 && padding_data[1] == 0)) {
TF_LITE_KERNEL_LOG(
context, "%s: Padding for batch dimension is not supported in PAD.",
padding->name);
return false;
}
if (!(padding_data[6] == 0 && padding_data[7] == 0)) {
TF_LITE_KERNEL_LOG(
context, "%s: Padding for channel dimension is not supported in PAD.",
padding->name);
return false;
}
return true;
} | 1 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
jas_seqent_t maxval)
{
int i;
int j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
int rowstep;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
} | 0 | C++ | CWE-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 |
std::string decodeBase64(
const std::string& encoded) {
if (encoded.size() == 0) {
// special case, to prevent an integer overflow down below.
return std::string();
}
int padding = 0;
for (auto it = encoded.rbegin();
padding < 2 && it != encoded.rend() && *it == '=';
++it) {
++padding;
}
return Base64::decode(encoded, padding);
} | 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 |
MONGO_EXPORT int bson_append_regex( bson *b, const char *name, const char *pattern, const char *opts ) {
const int plen = strlen( pattern )+1;
const int olen = strlen( opts )+1;
if ( bson_append_estart( b, BSON_REGEX, name, plen + olen ) == BSON_ERROR )
return BSON_ERROR;
if ( bson_check_string( b, pattern, plen - 1 ) == BSON_ERROR )
return BSON_ERROR;
bson_append( b , pattern , plen );
bson_append( b , opts , olen );
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 |
void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
QWriteLocker locker(&lock);
Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };
m_messages.push_back(temp);
if (m_messages.size() >= MAX_LOG_MESSAGES)
m_messages.pop_front();
emit newLogMessage(temp);
} | 1 | C++ | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
} | 0 | C++ | CWE-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 int em_fxrstor(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
if (rc != X86EMUL_CONTINUE)
return rc;
if (fx_state.mxcsr >> 16)
return emulate_gp(ctxt, 0);
ctxt->ops->get_fpu(ctxt);
if (ctxt->mode < X86EMUL_MODE_PROT64)
rc = fxrstor_fixup(ctxt, &fx_state);
if (rc == X86EMUL_CONTINUE)
rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
ctxt->ops->put_fpu(ctxt);
return rc;
} | 0 | C++ | CWE-416 | Use After Free | Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. | https://cwe.mitre.org/data/definitions/416.html | vulnerable |
R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR;
attr->info.constant_value_attr.constantvalue_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
}
// IFDBG r_bin_java_print_constant_value_attr_summary(attr);
return attr;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {
for (int i = 0; i < NumOutputs(node); ++i) {
SetTensorToDynamic(GetOutput(context, node, i));
}
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 SetGray(double grayscale,int par)
{
if ( par == STROKING ) {
outpos += sprintf(outpos," %12.3f G",grayscale);
}
else {
outpos += sprintf(outpos," %12.3f g",grayscale);
}
} | 0 | C++ | NVD-CWE-noinfo | null | null | null | vulnerable |
void AOClient::pktRemoveEvidence(AreaData* area, int argc, QStringList argv, AOPacket packet)
{
if (!checkEvidenceAccess(area))
return;
bool is_int = false;
int idx = argv[0].toInt(&is_int);
if (is_int && idx <= area->evidence().size() && idx >= 0) {
area->deleteEvidence(idx);
}
sendEvidenceList(area);
} | 0 | C++ | CWE-129 | Improper Validation of Array Index | The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. | https://cwe.mitre.org/data/definitions/129.html | vulnerable |
ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
BigInt m(msg, msg_len, m_group.get_order_bits());
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);
#else
const BigInt k = m_group.random_scalar(rng);
#endif
const BigInt k_inv = m_group.inverse_mod_order(k);
const BigInt r = m_group.mod_order(
m_group.blinded_base_point_multiply_x(k, rng, m_ws));
const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);
const BigInt s = m_group.multiply_mod_order(k_inv, xrm);
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("During ECDSA signature generated zero r/s");
return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());
} | 0 | C++ | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | vulnerable |
int ZlibInStream::overrun(int itemSize, int nItems, bool wait)
{
if (itemSize > bufSize)
throw Exception("ZlibInStream overrun: max itemSize exceeded");
if (!underlying)
throw Exception("ZlibInStream overrun: no underlying stream");
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-672 | Operation on a Resource after Expiration or Release | The software uses, accesses, or otherwise operates on a resource after that resource has been expired, released, or revoked. | https://cwe.mitre.org/data/definitions/672.html | vulnerable |
unsigned char *base64decode(const char *buf, size_t *size)
{
if (!buf || !size) return NULL;
size_t len = (*size > 0) ? *size : strlen(buf);
if (len <= 0) return NULL;
unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3);
const char *ptr = buf;
int p = 0;
size_t l = 0;
do {
ptr += strspn(ptr, "\r\n\t ");
if (*ptr == '\0' || ptr >= buf+len) {
break;
}
l = strcspn(ptr, "\r\n\t ");
if (l > 3 && ptr+l <= buf+len) {
p+=base64decode_block(outbuf+p, ptr, l);
ptr += l;
} else {
break;
}
} while (1);
outbuf[p] = 0;
*size = p;
return outbuf;
} | 0 | C++ | CWE-125 | Out-of-bounds Read | The software reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.