code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDepthToSpaceParams*>(node->builtin_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); auto data_type = output->type; TF_LITE_ENSURE(context, data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 || data_type == kTfLiteInt8 || data_type == kTfLiteInt32 || data_type == kTfLiteInt64); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); const int block_size = params->block_size; const int input_height = input->dims->data[1]; const int input_width = input->dims->data[2]; const int input_channels = input->dims->data[3]; int output_height = input_height * block_size; int output_width = input_width * block_size; int output_channels = input_channels / block_size / block_size; TF_LITE_ENSURE_EQ(context, input_height, output_height / block_size); TF_LITE_ENSURE_EQ(context, input_width, output_width / block_size); TF_LITE_ENSURE_EQ(context, input_channels, output_channels * block_size * block_size); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = output_height; output_size->data[2] = output_width; output_size->data[3] = output_channels; return context->ResizeTensor(context, output, output_size); }
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 QuickOpen::Load(uint64 BlockPos) { if (!Loaded) { // If loading for the first time, perform additional intialization. SeekPos=Arc->Tell(); UnsyncSeekPos=false; SaveFilePos SavePos(*Arc); Arc->Seek(BlockPos,SEEK_SET); // If BlockPos points to original main header, we'll have the infinite // recursion, because ReadHeader() for main header will attempt to load // QOpen and call QuickOpen::Load again. If BlockPos points to long chain // of other main headers, we'll have multiple recursive calls of this // function wasting resources. So we prohibit QOpen temporarily to // prevent this. ReadHeader() calls QOpen.Init and sets MainHead Locator // and QOpenOffset fields, so we cannot use them to prohibit QOpen. Arc->SetProhibitQOpen(true); size_t ReadSize=Arc->ReadHeader(); Arc->SetProhibitQOpen(false); if (ReadSize==0 || Arc->GetHeaderType()!=HEAD_SERVICE || !Arc->SubHead.CmpName(SUBHEAD_TYPE_QOPEN)) return; QLHeaderPos=Arc->CurBlockPos; RawDataStart=Arc->Tell(); RawDataSize=Arc->SubHead.UnpSize; Loaded=true; // Set only after all file processing calls like Tell, Seek, ReadHeader. } if (Arc->SubHead.Encrypted) { RAROptions *Cmd=Arc->GetRAROptions(); #ifndef RAR_NOCRYPT if (Cmd->Password.IsSet()) Crypt.SetCryptKeys(false,CRYPT_RAR50,&Cmd->Password,Arc->SubHead.Salt, Arc->SubHead.InitV,Arc->SubHead.Lg2Count, Arc->SubHead.HashKey,Arc->SubHead.PswCheck); else #endif return; } RawDataPos=0; ReadBufSize=0; ReadBufPos=0; LastReadHeader.Reset(); LastReadHeaderPos=0; ReadBuffer(); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
bool IsFullyConnectedOpSupported(const TfLiteRegistration* registration, const TfLiteNode* node, TfLiteContext* context) { if (node->builtin_data == nullptr) return false; const auto* fc_params = reinterpret_cast<const TfLiteFullyConnectedParams*>(node->builtin_data); const int kInput = 0; const int kWeights = 1; const int kBias = 2; if (fc_params->weights_format != kTfLiteFullyConnectedWeightsFormatDefault) { return false; } const TfLiteTensor* input = GetInput(context, node, kInput); const TfLiteTensor* weights = GetInput(context, node, kWeights); if (!IsFloatType(input->type)) { return false; } if (!IsFloatType(weights->type) || !IsConstantTensor(weights)) { return false; } // Core ML 2 only supports single-batch fully connected layer, thus dimensions // except the last one should be 1. if (input->dims->data[input->dims->size - 1] != NumElements(input)) { return false; } if (node->inputs->size > 2) { const TfLiteTensor* bias = GetInput(context, node, kBias); if (!IsFloatType(bias->type) || !IsConstantTensor(bias)) { return false; } } TfLiteFusedActivation activation = fc_params->activation; if (activation == kTfLiteActSignBit) { return false; } return true; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); const TfLiteTensor* size; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kSizeTensor, &size)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); // TODO(ahentz): Our current implementations rely on the inputs being 4D. TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, NumDimensions(size), 1); TF_LITE_ENSURE_EQ(context, size->type, kTfLiteInt32); // ResizeBilinear creates a float tensor even when the input is made of // integers. output->type = input->type; if (!IsConstantTensor(size)) { SetTensorToDynamic(output); return kTfLiteOk; } // Ensure params are valid. auto* params = reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data); if (params->half_pixel_centers && params->align_corners) { context->ReportError( context, "If half_pixel_centers is True, align_corners must be False."); return kTfLiteError; } return ResizeOutputTensor(context, input, size, output); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
check_owner_password_V4(std::string& user_password, std::string const& owner_password, QPDF::EncryptionData const& data) { // Algorithm 3.7 from the PDF 1.7 Reference Manual unsigned char key[OU_key_bytes_V4]; compute_O_rc4_key(user_password, owner_password, data, key); unsigned char O_data[key_bytes]; memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes); iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(), (data.getR() >= 3) ? 20 : 1, true); std::string new_user_password = std::string(reinterpret_cast<char*>(O_data), key_bytes); bool result = false; if (check_user_password(new_user_password, data)) { result = true; user_password = new_user_password; } return result; }
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 do_change_user(int afdt_fd) { std::string uname; lwp_read(afdt_fd, uname); if (!uname.length()) return; auto buf = PasswdBuffer{}; struct passwd *pw; if (getpwnam_r(uname.c_str(), &buf.ent, buf.data.get(), buf.size, &pw)) { // TODO(alexeyt) should we log something and/or fail to start? return; } if (!pw) { // TODO(alexeyt) should we log something and/or fail to start? return; } if (pw->pw_gid) { initgroups(pw->pw_name, pw->pw_gid); setgid(pw->pw_gid); } if (pw->pw_uid) { setuid(pw->pw_uid); } }
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* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); const TfLiteTensor* multipliers; TF_LITE_ENSURE_OK( context, GetInputSafe(context, node, kInputMultipliers, &multipliers)); if (IsDynamicTensor(output)) { TF_LITE_ENSURE_OK(context, ResizeOutput(context, node)); } switch (output->type) { case kTfLiteFloat32: Tile<float>(*(input->dims), input, multipliers, output); break; case kTfLiteUInt8: Tile<uint8_t>(*(input->dims), input, multipliers, output); break; case kTfLiteInt32: Tile<int32_t>(*(input->dims), input, multipliers, output); break; case kTfLiteInt64: Tile<int64_t>(*(input->dims), input, multipliers, output); break; case kTfLiteString: { DynamicBuffer buffer; TileString(*(input->dims), input, multipliers, &buffer, output); buffer.WriteToTensor(output, /*new_shape=*/nullptr); break; } case kTfLiteBool: Tile<bool>(*(input->dims), input, multipliers, output); break; default: context->ReportError(context, "Type '%s' is not supported by tile.", TfLiteTypeGetName(output->type)); return kTfLiteError; } return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
int LibRaw::subtract_black() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if(!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3])) { #define BAYERC(row,col,c) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][c] int cblk[4],i; for(i=0;i<4;i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define CLIP(x) LIM(x,0,65535) int dmax = 0; for(i=0; i< size*4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if(dmax < val) dmax = val; } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort*)imgdata.image; int dmax = 0; for(idx=0;idx<S.iheight*S.iwidth*4;idx++) if(dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } }
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
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength); PrintOutParsingResult(res, 1, caller); return res; }
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 CUser::SetClientEncoding(const CString& s) { m_sClientEncoding = CZNC::Get().FixupEncoding(s); for (CClient* pClient : GetAllClients()) { pClient->SetEncoding(m_sClientEncoding); } }
1
C++
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
static TfLiteRegistration DynamicCopyOpRegistration() { TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr}; reg.prepare = [](TfLiteContext* context, TfLiteNode* node) { // Output 0 is dynamic TfLiteTensor* output0 = GetOutput(context, node, 0); SetTensorToDynamic(output0); // Output 1 has the same shape as input. const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output1 = GetOutput(context, node, 1); TF_LITE_ENSURE_STATUS(context->ResizeTensor( context, output1, TfLiteIntArrayCopy(input->dims))); return kTfLiteOk; }; reg.invoke = [](TfLiteContext* context, TfLiteNode* node) { // Not implemented since this isn't required in testing. return kTfLiteOk; }; return reg; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; }
0
C++
CWE-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
bool ValidateInput<Variant>(const Tensor& updates) { return true; }
1
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNegative) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {-1, 0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); }
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
static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; // The first field at the start of a level 3 header is supposed to // indicate word size, with the idea being that the header format // can be extended beyond 32-bit words in the future. In practise, // nothing supports anything other than 32-bit (4 bytes), and neither // do we. if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } // Read the full header. if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } // Read the header length field (including extended headers), and // extend to this full length. Because this is a 32-bit value, // we must place a sensible limit on the amount of data that will // be read, to avoid possibly allocating gigabytes of memory. header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN || header_len < RAW_DATA_LEN(header)) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } // Compression method: memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; // File lengths: (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); // Unix-style timestamp. (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); // CRC. (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); // OS type: (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotTheRightCardinality) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {2}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); }
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
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-908
Use of Uninitialized Resource
The software uses or accesses a resource that has not been initialized.
https://cwe.mitre.org/data/definitions/908.html
vulnerable
void fx_DataView(txMachine* the) { txSlot* slot; txBoolean flag = 0; txInteger offset, size; txSlot* info; txSlot* instance; txSlot* view; txSlot* buffer; if (mxIsUndefined(mxTarget)) mxTypeError("call: DataView"); if ((mxArgc > 0) && (mxArgv(0)->kind == XS_REFERENCE_KIND)) { slot = mxArgv(0)->value.reference->next; if (slot && ((slot->kind == XS_ARRAY_BUFFER_KIND) || (slot->kind == XS_HOST_KIND))) { flag = 1; } } if (!flag) mxTypeError("buffer is no ArrayBuffer instance"); offset = fxArgToByteLength(the, 1, 0); info = fxGetBufferInfo(the, mxArgv(0)); if (info->value.bufferInfo.length < offset) mxRangeError("out of range byteOffset %ld", offset); size = fxArgToByteLength(the, 2, -1); if (size >= 0) { if (info->value.bufferInfo.length < (offset + size)) mxRangeError("out of range byteLength %ld", size); } else { if (info->value.bufferInfo.maxLength < 0) size = info->value.bufferInfo.length - offset; } mxPushSlot(mxTarget); fxGetPrototypeFromConstructor(the, &mxDataViewPrototype); instance = fxNewDataViewInstance(the); mxPullSlot(mxResult); view = instance->next; buffer = view->next; buffer->kind = XS_REFERENCE_KIND; buffer->value.reference = mxArgv(0)->value.reference; info = fxGetBufferInfo(the, buffer); if (info->value.bufferInfo.maxLength >= 0) { if (info->value.bufferInfo.length < offset) mxRangeError("out of range byteOffset %ld", offset); else if (size >= 0) { if (info->value.bufferInfo.length < (offset + size)) mxRangeError("out of range byteLength %ld", size); } } view->value.dataView.offset = offset; view->value.dataView.size = size; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
Variant HHVM_METHOD(XMLReader, expand, const Variant& basenode /* = null */) { auto* data = Native::data<XMLReader>(this_); req::ptr<XMLDocumentData> doc; xmlDocPtr docp = nullptr; SYNC_VM_REGS_SCOPED(); if (!basenode.isNull()) { auto dombasenode = Native::data<DOMNode>(basenode.toObject()); doc = dombasenode->doc(); docp = doc->docp(); if (docp == nullptr) { raise_warning("Invalid State Error"); return false; } } if (data->m_ptr) { xmlNodePtr node = xmlTextReaderExpand(data->m_ptr); if (node == nullptr) { raise_warning("An Error Occurred while expanding"); return false; } else { xmlNodePtr nodec = xmlDocCopyNode(node, docp, 1); if (nodec == nullptr) { raise_notice("Cannot expand this node type"); return false; } else { return php_dom_create_object(nodec, doc); } } } raise_warning("Load Data before trying to read"); return false; }
0
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
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-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
bool ResourceHandle::ParseFromString(const string& s) { ResourceHandleProto proto; return proto.ParseFromString(s) && FromProto(proto).ok(); }
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
QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly) { QString mount_point = mountPoint(device); if (!mount_point.isEmpty()) return mount_point; mount_point = "%1/.%2/mount/%3"; const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation); mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()).arg(qApp->applicationName()).arg(name); if (!QDir::current().mkpath(mount_point)) { dCError("mkpath \"%s\" failed", qPrintable(mount_point)); return QString(); } if (!mountDevice(device, mount_point, readonly)) { dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point)); return QString(); } return mount_point; }
0
C++
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
ALWAYS_INLINE String serialize_impl(const Variant& value, const SerializeOptions& opts) { switch (value.getType()) { case KindOfClass: case KindOfLazyClass: case KindOfPersistentString: case KindOfString: { auto const str = isStringType(value.getType()) ? value.getStringData() : isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) : lazyClassToStringHelper(value.toLazyClassVal()); auto const size = str->size(); if (size >= RuntimeOption::MaxSerializedStringSize) { throw Exception("Size of serialized string (%ld) exceeds max", size); } StringBuffer sb; sb.append("s:"); sb.append(size); sb.append(":\""); sb.append(str->data(), size); sb.append("\";"); return sb.detach(); } case KindOfResource: return s_Res; case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfFunc: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfDouble: case KindOfObject: case KindOfClsMeth: case KindOfRClsMeth: case KindOfRFunc: case KindOfRecord: break; } VariableSerializer vs(VariableSerializer::Type::Serialize); if (opts.keepDVArrays) vs.keepDVArrays(); if (opts.forcePHPArrays) vs.setForcePHPArrays(); if (opts.warnOnHackArrays) vs.setHackWarn(); if (opts.warnOnPHPArrays) vs.setPHPWarn(); if (opts.ignoreLateInit) vs.setIgnoreLateInit(); if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy(); // Keep the count so recursive calls to serialize() embed references properly. return vs.serialize(value, true, true); }
1
C++
CWE-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) { int num_inputs = NumInputs(node); TF_LITE_ENSURE(context, num_inputs >= 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = input1->type; // Check that all input tensors have the same shape and type. for (int i = kInputTensor1 + 1; i < num_inputs; ++i) { const TfLiteTensor* input = GetInput(context, node, i); TF_LITE_ENSURE(context, HaveSameShapes(input1, input)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type); } // Use the first input node's dimension to be the dimension of the output // node. TfLiteIntArray* input1_dims = input1->dims; TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims); return context->ResizeTensor(context, output, output_dims); }
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 AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS")); t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS")); t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*)); if (t->Data == NULL) { SynError(it8, "AllocateDataSet: Unable to allocate data array"); } }
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
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { int pkt_len; char line[COSINE_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) return FALSE; if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Parse the header */ pkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data */ return parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err, err_info); }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
void Compute(OpKernelContext* context) override { INDEX_TYPE first_dimension; const Tensor first_partition_tensor = context->input(kFirstPartitionInputIndex); OP_REQUIRES(context, first_partition_tensor.NumElements() > 0, errors::InvalidArgument("Invalid first partition input. Tensor " "requires at least one element.")); OP_REQUIRES_OK(context, GetFirstDimensionSize(context, &first_dimension)); vector<INDEX_TYPE> output_size; OP_REQUIRES_OK(context, CalculateOutputSize(first_dimension, context, &output_size)); vector<INDEX_TYPE> multiplier; multiplier.resize(ragged_rank_ + 1); multiplier[multiplier.size() - 1] = 1; for (int i = multiplier.size() - 2; i >= 0; --i) { multiplier[i] = multiplier[i + 1] * output_size[i + 1]; } // Full size of the tensor. TensorShape output_shape; OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(output_size, &output_shape)); Tensor* output_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor)); const INDEX_TYPE full_size = multiplier[0] * output_size[0]; if (full_size > 0) { vector<INDEX_TYPE> output_index, new_output_index; int nvals = context->input(kValueInputIndex).shape().dim_size(0); output_index.reserve(nvals); new_output_index.reserve(nvals); CalculateFirstParentOutputIndex(first_dimension, multiplier[0], output_size[0], &output_index); for (int i = 1; i <= ragged_rank_; ++i) { OP_REQUIRES_OK(context, CalculateOutputIndex( context, i - 1, output_index, multiplier[i], output_size[i], &new_output_index)); output_index.swap(new_output_index); new_output_index.clear(); } SetOutput(context, ragged_rank_, output_index, output_tensor); } }
1
C++
CWE-131
Incorrect Calculation of Buffer Size
The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
https://cwe.mitre.org/data/definitions/131.html
safe
static inline bool isValid(const RemoteFsDevice::Details &d) { return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() || RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme(); }
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(SegmentSumOpModelTest, TestFailIfSegmentsAreNotSorted) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 3, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = input->type; return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
inline int StringData::size() const { return m_len; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
TfLiteStatus 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; }
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 operator()(OpKernelContext* ctx, const Index num_segments, const TensorShape& segment_ids_shape, typename TTypes<Index>::ConstFlat segment_ids, const Index data_size, const T* data, typename TTypes<T, 2>::Tensor output) { output.setConstant(InitialValueF()()); if (data_size == 0) { return; } const int64 N = segment_ids.dimension(0); ReductionF reduction; auto data_flat = typename TTypes<T, 2>::ConstTensor(data, N, data_size / N); for (int64 i = 0; i < N; ++i) { Index j = internal::SubtleMustCopy(segment_ids(i)); if (j < 0) { continue; } OP_REQUIRES(ctx, FastBoundsCheck(j, num_segments), errors::InvalidArgument( "segment_ids", SliceDebugString(segment_ids_shape, i), " = ", j, " is out of range [0, ", num_segments, ")")); reduction(data_flat.template chip<0>(i), output.template chip<0>(j)); } }
0
C++
CWE-681
Incorrect Conversion between Numeric Types
When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.
https://cwe.mitre.org/data/definitions/681.html
vulnerable
void pcre_dump_cache(const std::string& filename) { s_pcreCache.dump(filename); }
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
const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst, socklen_t size) { if (!src || !dst) { errno = EFAULT; return nullptr; } size_t src_size = 0; if (af == AF_INET) { src_size = sizeof(struct in_addr); } else if (af == AF_INET6) { src_size = sizeof(struct in6_addr); } else { errno = EAFNOSUPPORT; return nullptr; } MessageWriter input; input.Push<int>(TokLinuxAfFamily(af)); input.PushByReference(Extent{reinterpret_cast<const char *>(src), src_size}); input.Push(size); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kInetNtopHandler, &input, &output); CheckStatusAndParamCount(status, output, "enc_untrusted_inet_ntop", 2); auto result = output.next(); int klinux_errno = output.next<int>(); if (result.empty()) { errno = FromkLinuxErrorNumber(klinux_errno); return nullptr; } memcpy(dst, result.data(), std::min(static_cast<size_t>(size), static_cast<size_t>(INET6_ADDRSTRLEN))); return dst; }
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), 0); OpData* op_data = reinterpret_cast<OpData*>(node->user_data); OpContext op_context(context, node); TF_LITE_ENSURE(context, op_context.input->type == kTfLiteUInt8 || op_context.input->type == kTfLiteInt8 || op_context.input->type == kTfLiteInt16 || op_context.input->type == kTfLiteFloat16); TF_LITE_ENSURE(context, op_context.ref->type == kTfLiteFloat32); op_data->max_diff = op_data->tolerance * op_context.input->params.scale; switch (op_context.input->type) { case kTfLiteUInt8: case kTfLiteInt8: op_data->max_diff *= (1 << 8); break; case kTfLiteInt16: op_data->max_diff *= (1 << 16); break; default: break; } // Allocate tensor to store the dequantized inputs. if (op_data->cache_tensor_id == kTensorNotAllocated) { TF_LITE_ENSURE_OK( context, context->AddTensors(context, 1, &op_data->cache_tensor_id)); } TfLiteIntArrayFree(node->temporaries); node->temporaries = TfLiteIntArrayCreate(1); node->temporaries->data[0] = op_data->cache_tensor_id; TfLiteTensor* dequantized; TF_LITE_ENSURE_OK(context, GetTemporarySafe(context, node, /*index=*/0, &dequantized)); dequantized->type = op_context.ref->type; dequantized->allocation_type = kTfLiteDynamic; TF_LITE_ENSURE_OK(context, context->ResizeTensor( context, dequantized, TfLiteIntArrayCopy(op_context.input->dims))); return kTfLiteOk; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
int GetS32BE (int nPos, bool *pbSuccess) { //*pbSuccess = true; if ( nPos < 0 || nPos + 3 >= m_nLen ) { *pbSuccess = false; return 0; } int nRes = m_sFile[ nPos ]; nRes = (nRes << 8) + m_sFile[nPos + 1]; nRes = (nRes << 8) + m_sFile[nPos + 2]; nRes = (nRes << 8) + m_sFile[nPos + 3]; if ( nRes & 0x80000000 ) nRes |= ~0xffffffff; return nRes; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) { if (sz < 8) { return NULL; } RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset); if (!attr) { return NULL; } attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR; attr->size = 6; return attr; }
1
C++
CWE-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
error_t coapServerInitResponse(CoapServerContext *context) { CoapMessageHeader *requestHeader; CoapMessageHeader *responseHeader; //Point to the CoAP request header requestHeader = (CoapMessageHeader *) context->request.buffer; //Point to the CoAP response header responseHeader = (CoapMessageHeader *) context->response.buffer; //Format message header responseHeader->version = COAP_VERSION_1; responseHeader->tokenLen = requestHeader->tokenLen; responseHeader->code = COAP_CODE_INTERNAL_SERVER; responseHeader->mid = requestHeader->mid; //If immediately available, the response to a request carried in a //Confirmable message is carried in an Acknowledgement (ACK) message if(requestHeader->type == COAP_TYPE_CON) { responseHeader->type = COAP_TYPE_ACK; } else { responseHeader->type = COAP_TYPE_NON; } //The token is used to match a response with a request osMemcpy(responseHeader->token, requestHeader->token, requestHeader->tokenLen); //Set the length of the CoAP message context->response.length = sizeof(CoapMessageHeader) + responseHeader->tokenLen; context->response.pos = 0; //Sucessful processing return NO_ERROR; }
0
C++
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
void AverageEvalQuantizedInt16(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { int32_t activation_min; int32_t activation_max; CalculateActivationRangeQuantized(context, params->activation, output, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.quantized_activation_min = activation_min; \ op_params.quantized_activation_max = activation_max; \ type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<int16_t>(input), GetTensorShape(output), \ GetTensorData<int16_t>(output)) TF_LITE_AVERAGE_POOL(reference_integer_ops); #undef TF_LITE_AVERAGE_POOL }
0
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type); output->type = input2->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); } if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized( context, params->activation, output, &data->output_activation_min, &data->output_activation_max)); const double real_multiplier = input1->params.scale / (input2->params.scale * output->params.scale); QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } return context->ResizeTensor(context, output, output_size); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) { RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj); if (!se) { return NULL; } se->tag = type; if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) { se->info.obj_val_cp_idx = (ut16) value; } else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) { /*if (bin->offset_sz == 4) { se->info.uninit_offset = value; } else { se->info.uninit_offset = (ut16) value; }*/ se->info.uninit_offset = (ut16) value; } return se; }
0
C++
CWE-788
Access of Memory Location After End of Buffer
The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.
https://cwe.mitre.org/data/definitions/788.html
vulnerable
void ValidateOpDimensionsFromInputs(const int n, const int h, const int w, const int c, const int kx, const int ky, const int sx, const int sy, const string& data_format, const string& padding) { OpContext op_context; int ho; int wo; if (data_format == "NHWC") { op_context = DescribePoolingOp("MaxPool", {n, h, w, c}, {1, kx, ky, 1}, {1, sx, sy, 1}, "NHWC", padding); ho = op_context.op_info.outputs(0).shape().dim(1).size(); wo = op_context.op_info.outputs(0).shape().dim(2).size(); } else { op_context = DescribePoolingOp("MaxPool", {n, c, h, w}, {1, 1, kx, ky}, {1, 1, sx, sy}, "NCHW", padding); ho = op_context.op_info.outputs(0).shape().dim(2).size(); wo = op_context.op_info.outputs(0).shape().dim(3).size(); } bool found_unknown_shapes; auto dims = OpLevelCostEstimator::OpDimensionsFromInputs( op_context.op_info.inputs(0).shape(), op_context.op_info, &found_unknown_shapes); Padding padding_enum; if (padding == "VALID") { padding_enum = Padding::VALID; } else { padding_enum = Padding::SAME; } EXPECT_EQ(n, dims.batch); EXPECT_EQ(h, dims.ix); EXPECT_EQ(w, dims.iy); EXPECT_EQ(c, dims.iz); EXPECT_EQ(kx, dims.kx); EXPECT_EQ(ky, dims.ky); EXPECT_EQ(sx, dims.sx); EXPECT_EQ(sy, dims.sy); EXPECT_EQ(ho, dims.ox); EXPECT_EQ(wo, dims.oy); EXPECT_EQ(c, dims.oz); EXPECT_EQ(padding_enum, dims.padding); }
0
C++
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
vulnerable
void AverageEvalFloat(TfLiteContext* context, TfLiteNode* node, TfLitePoolParams* params, OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { float activation_min, activation_max; CalculateActivationRange(params->activation, &activation_min, &activation_max); #define TF_LITE_AVERAGE_POOL(type) \ tflite::PoolParams op_params; \ op_params.stride_height = params->stride_height; \ op_params.stride_width = params->stride_width; \ op_params.filter_height = params->filter_height; \ op_params.filter_width = params->filter_width; \ op_params.padding_values.height = data->padding.height; \ op_params.padding_values.width = data->padding.width; \ op_params.float_activation_min = activation_min; \ op_params.float_activation_max = activation_max; \ type::AveragePool(op_params, GetTensorShape(input), \ GetTensorData<float>(input), GetTensorShape(output), \ GetTensorData<float>(output)) if (kernel_type == kReference) { TF_LITE_AVERAGE_POOL(reference_ops); } else { TF_LITE_AVERAGE_POOL(optimized_ops); } #undef TF_LITE_AVERAGE_POOL }
0
C++
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
folly::Optional<DumpFile> dump_file(const char* name) { auto const path = folly::sformat("{}/{}", RO::AdminDumpPath, name); // mkdir -p the directory prefix of `path` if (FileUtil::mkdir(path) != 0) return folly::none; // If remove fails because of a permissions issue, then we won't be // able to open the file for exclusive write below. remove(path.c_str()); // Create the file, failing if it already exists. Doing so ensures // that we have write access to the file and that no other user does. auto const fd = open(path.c_str(), O_CREAT|O_EXCL|O_RDWR, 0666); if (fd < 0) return folly::none; return DumpFile{path, folly::File(fd, /*owns=*/true)}; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
int LibarchivePlugin::extractionFlags() const { int result = ARCHIVE_EXTRACT_TIME; result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT; // TODO: Don't use arksettings here /*if ( ArkSettings::preservePerms() ) { result &= ARCHIVE_EXTRACT_PERM; } if ( !ArkSettings::extractOverwrite() ) { result &= ARCHIVE_EXTRACT_NO_OVERWRITE; }*/ return result; }
0
C++
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
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)); // Delete key before transferring in, potentially freeing up some v8 heap Unmaybe(object->Delete(context_handle, key_inner)); Local<Value> val_inner = val->TransferIn(); did_set = Unmaybe(object->Set(context_handle, key_inner, val_inner)); }
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
int64_t MemFile::readImpl(char *buffer, int64_t length) { assertx(m_len != -1); assertx(length > 0); int64_t remaining = m_len - m_cursor; if (remaining < length) length = remaining; if (length > 0) { memcpy(buffer, (const void *)(m_data + m_cursor), length); } m_cursor += length; return length; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
bool ArcMemory::Unload() { if (!Loaded) return false; Loaded=false; return true; }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
void FileBody::Dump(std::ostream& os, const std::string& prefix) const { os << prefix << "<file: " << path_.string() << ">" << std::endl; }
0
C++
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
void Magick::Image::read(MagickCore::Image *image, MagickCore::ExceptionInfo *exceptionInfo) { // Ensure that multiple image frames were not read. if (image != (MagickCore::Image *) NULL && image->next != (MagickCore::Image *) NULL) { MagickCore::Image *next; // Destroy any extra image frames next=image->next; image->next=(MagickCore::Image *) NULL; next->previous=(MagickCore::Image *) NULL; DestroyImageList(next); } replaceImage(image); if (exceptionInfo->severity == MagickCore::UndefinedException && image == (MagickCore::Image *) NULL) { (void) MagickCore::DestroyExceptionInfo(exceptionInfo); if (!quiet()) throwExceptionExplicit(MagickCore::ImageWarning, "No image was loaded."); return; } ThrowImageException; }
1
C++
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* seq_lengths = GetInput(context, node, kSeqLengthsTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(seq_lengths), 1); if (input->type != kTfLiteInt32 && input->type != kTfLiteFloat32 && input->type != kTfLiteUInt8 && input->type != kTfLiteInt16 && input->type != kTfLiteInt64) { context->ReportError(context, "Type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(input->type)); return kTfLiteError; } if (seq_lengths->type != kTfLiteInt32 && seq_lengths->type != kTfLiteInt64) { context->ReportError( context, "Seq_lengths type '%s' is not supported by reverse_sequence.", TfLiteTypeGetName(seq_lengths->type)); return kTfLiteError; } TfLiteTensor* output = 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
TEST_P(SslSocketTest, Ipv6San) { const std::string client_ctx_yaml = R"EOF( common_tls_context: validation_context: trusted_ca: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamcacert.pem" match_subject_alt_names: exact: "::1" )EOF"; const std::string server_ctx_yaml = R"EOF( common_tls_context: tls_certificates: certificate_chain: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamlocalhostcert.pem" private_key: filename: "{{ test_rundir }}/test/config/integration/certs/upstreamlocalhostkey.pem" )EOF"; TestUtilOptions test_options(client_ctx_yaml, server_ctx_yaml, true, GetParam()); testUtil(test_options); }
0
C++
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) { for (int i = 0; i < NumOutputs(node); ++i) { SetTensorToDynamic(GetOutput(context, node, i)); } return kTfLiteOk; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static char *pool_strdup(const char *s) { char *r = pool_alloc(strlen(s) + 1); strcpy(r, s); return r; }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
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 r = m_group.mod_order( m_group.blinded_base_point_multiply_x(k, rng, m_ws)); const BigInt k_inv = m_group.inverse_mod_order(k); /* * Blind the input message and compute x*r+m as (x*r*b + m*b)/b */ m_b = m_group.square_mod_order(m_b); m_b_inv = m_group.square_mod_order(m_b_inv); m = m_group.multiply_mod_order(m_b, m); const BigInt xr = m_group.multiply_mod_order(m_x, m_b, r); const BigInt s = m_group.multiply_mod_order(k_inv, xr + m, m_b_inv); // 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()); }
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
AP4_DataAtom::AP4_DataAtom(AP4_UI32 size, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_DATA, size) { if (size < AP4_ATOM_HEADER_SIZE+8) return; AP4_UI32 i; stream.ReadUI32(i); m_DataType = (DataType)i; stream.ReadUI32(i); m_DataLang = (DataLang)i; // the stream for the data is a substream of this source AP4_Position data_offset; stream.Tell(data_offset); AP4_Size data_size = size-AP4_ATOM_HEADER_SIZE-8; m_Source = new AP4_SubStream(stream, data_offset, data_size); }
0
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); FillDiagHelper(input, 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
std::string decodeBase64( const std::string& encoded) { if (encoded.size() == 0) { // special case, to prevent an integer overflow down below. return ""; } using namespace boost::archive::iterators; using b64it = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>; std::string decoded = std::string(b64it(std::begin(encoded)), b64it(std::end(encoded))); uint32_t numPadding = std::count(encoded.begin(), encoded.end(), '='); decoded.erase(decoded.end() - numPadding, decoded.end()); return decoded; }
0
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static int putint(jas_stream_t *out, int sgnd, int prec, long val) { int n; int c; bool s; jas_ulong tmp; assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); if (sgnd) { val = encode_twos_comp(val, prec); } assert(val >= 0); val &= (1 << prec) - 1; n = (prec + 7) / 8; while (--n >= 0) { c = (val >> (n * 8)) & 0xff; if (jas_stream_putc(out, c) != c) return -1; } return 0; }
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 AOClient::pktEditEvidence(AreaData* area, int argc, QStringList argv, AOPacket packet) { if (!checkEvidenceAccess(area)) return; bool is_int = false; int idx = argv[0].toInt(&is_int); AreaData::Evidence evi = {argv[1], argv[2], argv[3]}; if (is_int && idx <= area->evidence().size() && idx >= 0) { area->replaceEvidence(idx, evi); } 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
TfLiteStatus Relu6Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); ReluOpData* data = reinterpret_cast<ReluOpData*>(node->user_data); switch (input->type) { case kTfLiteFloat32: { size_t elements = input->bytes / sizeof(float); const float* in = GetTensorData<float>(input); const float* in_end = in + elements; float* out = GetTensorData<float>(output); for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f); return kTfLiteOk; } break; case kTfLiteUInt8: QuantizedReluX<uint8_t>(0.0f, 6.0f, input, output, data); return kTfLiteOk; case kTfLiteInt8: { QuantizedReluX<int8_t>(0.0f, 6.0f, input, output, data); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, "Only float32, uint8 and int8 are supported currently, got %s.", TfLiteTypeGetName(input->type)); return kTfLiteError; } }
0
C++
CWE-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
containsNonAlphaNumDash(const LString &s) { const LString::Part *part = s.start; while (part != NULL) { for (unsigned int i = 0; i < part->size; i++) { const char start = part->data[i]; if (start != '-' && !isAlphaNum(start)) { return true; } } part = part->next; } return false; }
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
int64_t OutputFile::readImpl(char* /*buffer*/, int64_t /*length*/) { raise_warning("cannot read from a php://output stream"); return 0; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
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) { m_cursor = offset; } else { assertx(whence == SEEK_END); m_cursor = m_len + offset; } setPosition(m_cursor); return true; }
0
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
inline int64_t StringData::size() const { return m_len; }
1
C++
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) { EvalDiv<kernel_type>(context, node, params, data, input1, input2, output); } else if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_OK( context, EvalQuantized<kernel_type>(context, node, params, data, input1, input2, output)); } else { context->ReportError( context, "Div only supports FLOAT32, INT32 and quantized UINT8 now, got %d.", output->type); return kTfLiteError; } return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
void connectSuccess() noexcept override { ssl_->writeChain(nullptr, IOBuf::copyBuffer("hi")); auto ssl = const_cast<SSL*>(ssl_->getSSL()); SSL_shutdown(ssl); auto fd = ssl_->detachNetworkSocket(); tcp_.reset(new AsyncSocket(evb_, fd), AsyncSocket::Destructor()); evb_->runAfterDelay( [this]() { perLoopReads_.setSocket(tcp_.get()); tcp_->setReadCB(&perLoopReads_); evb_->runAfterDelay([this]() { tcp_->closeNow(); }, 10); }, 100); }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
static int64 getnum(cchar *value) { char *junk; int64 num; value = ssplit(slower(value), " \t", &junk); if (sends(value, "kb") || sends(value, "k")) { num = stoi(value) * 1024; } else if (sends(value, "mb") || sends(value, "m")) { num = stoi(value) * 1024 * 1024; } else if (sends(value, "gb") || sends(value, "g")) { num = stoi(value) * 1024 * 1024 * 1024; } else if (sends(value, "byte") || sends(value, "bytes")) { num = stoi(value); } else { num = stoi(value); } if (num == 0) { num = MAXINT; } return num; }
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
unique_ptr<IOBuf> IOBuf::takeOwnership( void* buf, std::size_t capacity, std::size_t offset, std::size_t length, FreeFunction freeFn, void* userData, bool freeOnError, TakeOwnershipOption option) { if (capacity > kMaxIOBufSize) { throw_exception<std::bad_alloc>(); } // do not allow only user data without a freeFn // since we use that for folly::sizedFree DCHECK( !userData || (userData && freeFn) || (userData && !freeFn && (option == TakeOwnershipOption::STORE_SIZE))); HeapFullStorage* storage = nullptr; auto rollback = makeGuard([&] { if (storage) { free(storage); } takeOwnershipError(freeOnError, buf, freeFn, userData); }); size_t requiredStorage = sizeof(HeapFullStorage); size_t mallocSize = goodMallocSize(requiredStorage); storage = static_cast<HeapFullStorage*>(checkedMalloc(mallocSize)); new (&storage->hs.prefix) HeapPrefix(kIOBufInUse | kSharedInfoInUse, mallocSize); new (&storage->shared) SharedInfo(freeFn, userData, true /*useHeapFullStorage*/); auto result = unique_ptr<IOBuf>(new (&storage->hs.buf) IOBuf( InternalConstructor(), packFlagsAndSharedInfo(0, &storage->shared), static_cast<uint8_t*>(buf), capacity, static_cast<uint8_t*>(buf) + offset, length)); rollback.dismiss(); if (io_buf_alloc_cb) { io_buf_alloc_cb(storage, mallocSize); if (userData && !freeFn && (option == TakeOwnershipOption::STORE_SIZE)) { // Even though we did not allocate the buffer, call io_buf_alloc_cb() // since we will call io_buf_free_cb() on destruction, and we want these // calls to be 1:1. io_buf_alloc_cb(buf, capacity); } } return result; }
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& input = ctx->input(0); OP_REQUIRES(ctx, ctx->input(1).NumElements() > 0, errors::InvalidArgument("Input min must not be empty.")); OP_REQUIRES(ctx, ctx->input(2).NumElements() > 0, errors::InvalidArgument("Input max must not be empty.")); const float input_min_float = ctx->input(1).flat<float>()(0); const float input_max_float = ctx->input(2).flat<float>()(0); Tensor* output_min = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output_min)); Tensor* output_max = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(1, TensorShape({}), &output_max)); qint32 used_min_quantized; qint32 used_max_quantized; CalculateUsedRange(input, &used_min_quantized, &used_max_quantized); // We want to make sure that the minimum is no larger than zero, so that the // convolution operation can run efficiently. const float used_min_float = std::min( 0.0f, QuantizedToFloat(used_min_quantized, input_min_float, input_max_float)); const float used_max_float = QuantizedToFloat(used_max_quantized, input_min_float, input_max_float); output_min->flat<float>().setConstant(used_min_float); output_max->flat<float>().setConstant(used_max_float); }
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
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input if ((temp.length() % 12) != 0) return cipherText; temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) { // Sanity check if ((temp2.length() % 8) != 0) return cipherText; temp2 = byteToB64(temp2); } return temp2; }
1
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
inline TfLiteStatus EvalImpl(TfLiteContext* context, TfLiteNode* node, std::function<T(T)> func, TfLiteType expected_type) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, expected_type); const int64_t num_elements = NumElements(input); const T* in_data = GetTensorData<T>(input); T* out_data = GetTensorData<T>(output); for (int64_t i = 0; i < num_elements; ++i) { out_data[i] = func(in_data[i]); } 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 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](int start, int 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); }
0
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
static int crossOriginDirective(MaState *state, cchar *key, cchar *value) { HttpRoute *route; char *option, *ovalue, *tok; route = state->route; tok = sclone(value); while ((option = maGetNextArg(tok, &tok)) != 0) { option = stok(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (scaselessmatch(option, "origin")) { route->corsOrigin = sclone(ovalue); } else if (scaselessmatch(option, "credentials")) { route->corsCredentials = httpGetBoolToken(ovalue); } else if (scaselessmatch(option, "headers")) { route->corsHeaders = sclone(ovalue); } else if (scaselessmatch(option, "age")) { route->corsAge = atoi(ovalue); } else { mprLog("error appweb config", 0, "Unknown CrossOrigin option %s", option); return MPR_ERR_BAD_SYNTAX; } } #if KEEP if (smatch(route->corsOrigin, "*") && route->corsCredentials) { mprLog("error appweb config", 0, "CrossOrigin: Cannot use wildcard Origin if allowing credentials"); return MPR_ERR_BAD_STATE; } #endif /* Need the options method for pre-flight requests */ httpAddRouteMethods(route, "OPTIONS"); route->flags |= HTTP_ROUTE_CORS; return 0; }
0
C++
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-key]") { int errStatus = 0; vector<char> errMsg(BUF_LEN, 0); vector <uint8_t> encPrivKey(BUF_LEN, 0); vector<char> pubKeyX(BUF_LEN, 0); vector<char> pubKeyY(BUF_LEN, 0); uint32_t encLen = 0; PRINT_SRC_LINE auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(), pubKeyY.data()); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); vector<char> receivedPubKeyX(BUF_LEN, 0); vector<char> receivedPubKeyY(BUF_LEN, 0); PRINT_SRC_LINE status = trustedGetPublicEcdsaKeyAES(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, receivedPubKeyX.data(), receivedPubKeyY.data()); REQUIRE(status == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS); }
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 TfLiteUnpackParams* data = reinterpret_cast<TfLiteUnpackParams*>(node->builtin_data); const TfLiteTensor* input = GetInput(context, node, kInputTensor); switch (input->type) { case kTfLiteFloat32: { UnpackImpl<float>(context, node, input, data->num, data->axis); break; } case kTfLiteInt32: { UnpackImpl<int32_t>(context, node, input, data->num, data->axis); break; } case kTfLiteUInt8: { UnpackImpl<uint8_t>(context, node, input, data->num, data->axis); break; } case kTfLiteInt8: { UnpackImpl<int8_t>(context, node, input, data->num, data->axis); break; } case kTfLiteBool: { UnpackImpl<bool>(context, node, input, data->num, data->axis); break; } case kTfLiteInt16: { UnpackImpl<int16_t>(context, node, input, data->num, data->axis); break; } default: { context->ReportError(context, "Type '%s' is not supported by unpack.", TfLiteTypeGetName(input->type)); return kTfLiteError; } } return kTfLiteOk; }
0
C++
CWE-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 char *getDirective(char *line, char **valuep) { char *key, *value; ssize len; assert(line); assert(valuep); *valuep = 0; /* Use stok instead of ssplit to skip leading white space */ if ((key = stok(line, " \t", &value)) == 0) { return 0; } key = strim(key, " \t\r\n>", MPR_TRIM_END); if (value) { value = strim(value, " \t\r\n>", MPR_TRIM_END); /* Trim quotes if wrapping the entire value and no spaces. Preserve embedded quotes and leading/trailing "" etc. */ len = slen(value); if (*value == '\"' && value[len - 1] == '"' && len > 2 && value[1] != '\"' && !strpbrk(value, " \t")) { /* Cannot strip quotes if multiple args are quoted, only if one single arg is quoted */ if (schr(&value[1], '"') == &value[len - 1]) { value = snclone(&value[1], len - 2); } } *valuep = value; } return key; }
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
set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers) { char *startCur = ciphers; int algCount = 0; static ALG_ID algIds[45]; /*There are 45 listed in the MS headers*/ while(startCur && (0 != *startCur) && (algCount < 45)) { long alg = strtol(startCur, 0, 0); if(!alg) alg = get_alg_id_by_name(startCur); if(alg) algIds[algCount++] = alg; else if(!strncmp(startCur, "USE_STRONG_CRYPTO", sizeof("USE_STRONG_CRYPTO") - 1) || !strncmp(startCur, "SCH_USE_STRONG_CRYPTO", sizeof("SCH_USE_STRONG_CRYPTO") - 1)) schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO; else return CURLE_SSL_CIPHER; startCur = strchr(startCur, ':'); if(startCur) startCur++; } schannel_cred->palgSupportedAlgs = algIds; schannel_cred->cSupportedAlgs = algCount; return CURLE_OK; }
0
C++
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
vulnerable
virtual ~CxFile() { };
0
C++
CWE-770
Allocation of Resources Without Limits or Throttling
The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
vulnerable
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDivParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); const TfLiteTensor* input2; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor2, &input2)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type); output->type = input2->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); } if (output->type == kTfLiteUInt8) { TF_LITE_ENSURE_STATUS(CalculateActivationRangeQuantized( context, params->activation, output, &data->output_activation_min, &data->output_activation_max)); const double real_multiplier = input1->params.scale / (input2->params.scale * output->params.scale); QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } return context->ResizeTensor(context, output, output_size); }
1
C++
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
static int 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-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1) { int i; int j; if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ != mat1->numcols_) { return 1; } for (i = 0; i < mat0->numrows_; i++) { for (j = 0; j < mat0->numcols_; j++) { if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) { return 1; } } } return 0; }
0
C++
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { return channelEncode(target, message); }; #ifdef HAVE_QCA2 putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc, network()->cipher(bufferInfo.bufferName())); #else putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc); #endif emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); }
1
C++
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
https://cwe.mitre.org/data/definitions/399.html
safe
static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests) { // Written using Wikipedia: // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test ASSERT(!(n < 4)); auto predecessor = n.minus({ 1 }); auto d = predecessor; size_t r = 0; { auto div_result = d.divided_by(2); while (div_result.remainder == 0) { d = div_result.quotient; div_result = d.divided_by(2); ++r; } } if (r == 0) { // n - 1 is odd, so n was even. But there is only one even prime: return n == 2; } for (auto a : tests) { // Technically: ASSERT(2 <= a && a <= n - 2) ASSERT(a < n); auto x = ModularPower(a, d, n); if (x == 1 || x == predecessor) continue; bool skip_this_witness = false; // r − 1 iterations. for (size_t i = 0; i < r - 1; ++i) { x = ModularPower(x, 2, n); if (x == predecessor) { skip_this_witness = true; break; } } if (skip_this_witness) continue; return false; // "composite" } return true; // "probably prime" }
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
void ImapModelOpenConnectionTest::testPreauthWithStartTlsWanted() { cleanup(); init(true); // yuck, but I can't come up with anything better... cEmpty(); cServer("* PREAUTH hi there\r\n"); QCOMPARE(failedSpy->size(), 1); QVERIFY(completedSpy->isEmpty()); QVERIFY(authSpy->isEmpty()); QVERIFY(startTlsUpgradeSpy->isEmpty()); }
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 Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* axis_tensor = GetInput(context, node, kAxisTensor); int axis = GetTensorData<int32_t>(axis_tensor)[0]; const int rank = NumDimensions(input); if (axis < 0) { axis += rank; } TF_LITE_ENSURE(context, axis >= 0 && axis < rank); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); switch (output->type) { case kTfLiteFloat32: { reference_ops::Reverse<float>( axis, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<float>(output)); break; } case kTfLiteUInt8: { reference_ops::Reverse<uint8_t>( axis, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); break; } case kTfLiteInt16: { reference_ops::Reverse<int16_t>( axis, GetTensorShape(input), GetTensorData<int16_t>(input), GetTensorShape(output), GetTensorData<int16_t>(output)); break; } case kTfLiteInt32: { reference_ops::Reverse<int32_t>( axis, GetTensorShape(input), GetTensorData<int32_t>(input), GetTensorShape(output), GetTensorData<int32_t>(output)); break; } case kTfLiteInt64: { reference_ops::Reverse<int64_t>( axis, GetTensorShape(input), GetTensorData<int64_t>(input), GetTensorShape(output), GetTensorData<int64_t>(output)); break; } case kTfLiteBool: { reference_ops::Reverse<bool>( axis, GetTensorShape(input), GetTensorData<bool>(input), GetTensorShape(output), GetTensorData<bool>(output)); break; } default: { context->ReportError(context, "Type '%s' is not supported by reverse.", TfLiteTypeGetName(output->type)); return kTfLiteError; } } return kTfLiteOk; }
0
C++
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
void readEOF() noexcept override { LOG(INFO) << "Got EOF"; auto chain = IOBuf::create(0); for (size_t i = 0; i < 1000 * 1000; i++) { auto buf = IOBuf::create(10); buf->append(10); memset(buf->writableData(), 'x', 10); chain->prependChain(std::move(buf)); } socket_->writeChain(&writeCallback_, std::move(chain)); }
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
QInt8() : value(0) {}
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
void CalculateOutputIndexValueRowID( OpKernelContext* context, const RowPartitionTensor& value_rowids, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { const INDEX_TYPE index_size = value_rowids.size(); result->reserve(index_size); if (index_size == 0) { return; } INDEX_TYPE current_output_column = 0; INDEX_TYPE current_value_rowid = value_rowids(0); DCHECK_LT(current_value_rowid, parent_output_index.size()); INDEX_TYPE current_output_index = parent_output_index[current_value_rowid]; result->push_back(current_output_index); for (INDEX_TYPE i = 1; i < index_size; ++i) { INDEX_TYPE next_value_rowid = value_rowids(i); if (next_value_rowid == current_value_rowid) { if (current_output_index >= 0) { ++current_output_column; if (current_output_column < output_size) { current_output_index += output_index_multiplier; } else { current_output_index = -1; } } } else { current_output_column = 0; current_value_rowid = next_value_rowid; DCHECK_LT(next_value_rowid, parent_output_index.size()); current_output_index = parent_output_index[next_value_rowid]; } result->push_back(current_output_index); } OP_REQUIRES(context, result->size() == value_rowids.size(), errors::InvalidArgument("Invalid row ids.")); }
1
C++
CWE-131
Incorrect Calculation of Buffer Size
The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
https://cwe.mitre.org/data/definitions/131.html
safe
__global__ void UnsortedSegmentCustomKernel(const int64 input_outer_dim_size, const int64 inner_dim_size, const int64 output_outer_dim_size, const Index* segment_ids, const T* input, T* output) { const int64 input_total_size = input_outer_dim_size * inner_dim_size; for (int64 input_index : GpuGridRangeX(input_total_size)) { const int64 input_segment_index = input_index / inner_dim_size; const int64 segment_offset = input_index % inner_dim_size; const Index output_segment_index = segment_ids[input_segment_index]; if (output_segment_index < 0 || output_segment_index >= output_outer_dim_size) { continue; } const int64 output_index = output_segment_index * inner_dim_size + segment_offset; KernelReductionFunctor()(output + output_index, ldg(input + input_index)); } }
1
C++
CWE-681
Incorrect Conversion between Numeric Types
When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.
https://cwe.mitre.org/data/definitions/681.html
safe
void CommandData::ParseArg(wchar *Arg) { if (IsSwitch(*Arg) && !NoMoreSwitches) if (Arg[1]=='-' && Arg[2]==0) NoMoreSwitches=true; else ProcessSwitch(Arg+1); else if (*Command==0) { wcsncpy(Command,Arg,ASIZE(Command)); *Command=toupperw(*Command); // 'I' and 'S' commands can contain case sensitive strings after // the first character, so we must not modify their case. // 'S' can contain SFX name, which case is important in Unix. if (*Command!='I' && *Command!='S') wcsupper(Command); } else if (*ArcName==0) wcsncpyz(ArcName,Arg,ASIZE(ArcName)); else { // Check if last character is the path separator. size_t Length=wcslen(Arg); wchar EndChar=Length==0 ? 0:Arg[Length-1]; bool EndSeparator=IsDriveDiv(EndChar) || IsPathDiv(EndChar); wchar CmdChar=toupperw(*Command); bool Add=wcschr(L"AFUM",CmdChar)!=NULL; bool Extract=CmdChar=='X' || CmdChar=='E'; if (EndSeparator && !Add) wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); else if ((Add || CmdChar=='T') && (*Arg!='@' || ListMode==RCLM_REJECT_LISTS)) FileArgs.AddString(Arg); else { FindData FileData; bool Found=FindFile::FastFind(Arg,&FileData); if ((!Found || ListMode==RCLM_ACCEPT_LISTS) && ListMode!=RCLM_REJECT_LISTS && *Arg=='@' && !IsWildcard(Arg)) { FileLists=true; ReadTextFile(Arg+1,&FileArgs,false,true,FilelistCharset,true,true,true); } else if (Found && FileData.IsDir && Extract && *ExtrPath==0) { wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); AddEndSlash(ExtrPath,ASIZE(ExtrPath)); } else FileArgs.AddString(Arg); } } }
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
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); if (name_size == 0) return; char* name = new char[name_size+1]; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if (name[0] == name_size-1) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; }
0
C++
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
void ImplPolygon::ImplSplit( sal_uInt16 nPos, sal_uInt16 nSpace, ImplPolygon const * pInitPoly ) { //Can't fit this in :-(, throw ? if (mnPoints + nSpace > USHRT_MAX) return; const sal_uInt16 nNewSize = mnPoints + nSpace; const std::size_t nSpaceSize = static_cast<std::size_t>(nSpace) * sizeof(Point); if( nPos >= mnPoints ) { // Append at the back nPos = mnPoints; ImplSetSize( nNewSize ); if( pInitPoly ) { memcpy( mpPointAry + nPos, pInitPoly->mpPointAry, nSpaceSize ); if( pInitPoly->mpFlagAry ) memcpy( mpFlagAry + nPos, pInitPoly->mpFlagAry, nSpace ); } } else { const sal_uInt16 nSecPos = nPos + nSpace; const sal_uInt16 nRest = mnPoints - nPos; Point* pNewAry = reinterpret_cast<Point*>(new char[ static_cast<std::size_t>(nNewSize) * sizeof(Point) ]); memcpy( pNewAry, mpPointAry, nPos * sizeof( Point ) ); if( pInitPoly ) memcpy( pNewAry + nPos, pInitPoly->mpPointAry, nSpaceSize ); else memset( pNewAry + nPos, 0, nSpaceSize ); memcpy( pNewAry + nSecPos, mpPointAry + nPos, nRest * sizeof( Point ) ); delete[] reinterpret_cast<char*>(mpPointAry); // consider FlagArray if( mpFlagAry ) { PolyFlags* pNewFlagAry = new PolyFlags[ nNewSize ]; memcpy( pNewFlagAry, mpFlagAry, nPos ); if( pInitPoly && pInitPoly->mpFlagAry ) memcpy( pNewFlagAry + nPos, pInitPoly->mpFlagAry, nSpace ); else memset( pNewFlagAry + nPos, 0, nSpace ); memcpy( pNewFlagAry + nSecPos, mpFlagAry + nPos, nRest ); delete[] mpFlagAry; mpFlagAry = pNewFlagAry; } mpPointAry = pNewAry; mnPoints = nNewSize; } }
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 operator()(OpKernelContext* ctx, const Index num_segments, const TensorShape& segment_ids_shape, typename TTypes<Index>::ConstFlat segment_ids, const Index data_size, const T* data, typename TTypes<T, 2>::Tensor output) { if (output.size() == 0) { return; } // Set 'output' to initial value. GPUDevice d = ctx->template eigen_device<GPUDevice>(); GpuLaunchConfig config = GetGpuLaunchConfig(output.size(), d); TF_CHECK_OK(GpuLaunchKernel( SetToValue<T>, config.block_count, config.thread_per_block, 0, d.stream(), output.size(), output.data(), InitialValueF()())); if (data_size == 0 || segment_ids_shape.num_elements() == 0) { return; } // Launch kernel to compute unsorted segment reduction. // Notes: // *) 'data_size' is the total number of elements to process. // *) 'segment_ids.shape' is a prefix of data's shape. // *) 'input_outer_dim_size' is the total number of segments to process. const Index input_outer_dim_size = segment_ids.dimension(0); const Index input_inner_dim_size = data_size / input_outer_dim_size; config = GetGpuLaunchConfig(data_size, d); TF_CHECK_OK( GpuLaunchKernel(UnsortedSegmentCustomKernel<T, Index, ReductionF>, config.block_count, config.thread_per_block, 0, d.stream(), input_outer_dim_size, input_inner_dim_size, num_segments, segment_ids.data(), data, output.data())); }
0
C++
CWE-681
Incorrect Conversion between Numeric Types
When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur.
https://cwe.mitre.org/data/definitions/681.html
vulnerable
ALWAYS_INLINE String serialize_impl(const Variant& value, const SerializeOptions& opts) { switch (value.getType()) { case KindOfClass: case KindOfLazyClass: case KindOfPersistentString: case KindOfString: { auto const str = isStringType(value.getType()) ? value.getStringData() : isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) : lazyClassToStringHelper(value.toLazyClassVal()); auto const size = str->size(); if (size >= RuntimeOption::MaxSerializedStringSize) { throw Exception("Size of serialized string (%d) exceeds max", size); } StringBuffer sb; sb.append("s:"); sb.append(size); sb.append(":\""); sb.append(str->data(), size); sb.append("\";"); return sb.detach(); } case KindOfResource: return s_Res; case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfFunc: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfDouble: case KindOfObject: case KindOfClsMeth: case KindOfRClsMeth: case KindOfRFunc: case KindOfRecord: break; } VariableSerializer vs(VariableSerializer::Type::Serialize); if (opts.keepDVArrays) vs.keepDVArrays(); if (opts.forcePHPArrays) vs.setForcePHPArrays(); if (opts.warnOnHackArrays) vs.setHackWarn(); if (opts.warnOnPHPArrays) vs.setPHPWarn(); if (opts.ignoreLateInit) vs.setIgnoreLateInit(); if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy(); // Keep the count so recursive calls to serialize() embed references properly. return vs.serialize(value, true, true); }
0
C++
CWE-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
CAMLprim value caml_bitvect_test(value bv, value n) { int pos = Int_val(n); return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7))); }
0
C++
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
vulnerable
inline TfLiteTensor* GetTensorAtIndex(const TfLiteContext* context, int tensor_index) { if (context->tensors != nullptr) { return &context->tensors[tensor_index]; } else { return context->GetTensor(context, tensor_index); } }
1
C++
CWE-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 lcdSetPixels_ArrayBuffer_flat(JsGraphics *gfx, short x, short y, short pixelCount, unsigned int col) { unsigned char *ptr = (unsigned char*)gfx->backendData; unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,pixelCount); ptr += idx>>3; unsigned int whiteMask = (1U<<gfx->data.bpp)-1; bool shortCut = (col==0 || (col&whiteMask)==whiteMask) && (!(gfx->data.flags&JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)); // simple black or white fill while (pixelCount--) { // writing individual bits if (gfx->data.bpp&7/*not a multiple of one byte*/) { idx = idx & 7; if (shortCut && idx==0) { // Basically, if we're aligned and we're filling all 0 or all 1 // then we can go really quickly and can just fill int wholeBytes = (gfx->data.bpp*(pixelCount+1)) >> 3; if (wholeBytes) { char c = (char)(col?0xFF:0); pixelCount = (short)(pixelCount+1 - (wholeBytes*8/gfx->data.bpp)); while (wholeBytes--) { *ptr = c; ptr++; } continue; } } unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1; unsigned int existing = (unsigned int)*ptr; unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx; assert(ptr>=gfx->backendData && ptr<((char*)gfx->backendData + graphicsGetMemoryRequired(gfx))); *ptr = (char)((existing&~(mask<<bitIdx)) | ((col&mask)<<bitIdx)); if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE) { ptr++; } else { idx += gfx->data.bpp; if (idx>=8) ptr++; } } else { // we're writing whole bytes int i; for (i=0;i<gfx->data.bpp;i+=8) { *ptr = (char)(col >> i); ptr++; } } } }
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