project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
ImageMagick
|
cc4ac341f29fa368da6ef01c207deaf8c61f6a2e
| 1 |
static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y,
ExceptionInfo *exception)
{
size_t bit; ssize_t x;
register Quantum *q;
Quantum index;
index=0;
switch (depth)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) >= 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) >= 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
(void) SyncAuthenticPixels(image,exception);
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
p++;
q+=GetPixelChannels(image);
}
(void) SyncAuthenticPixels(image,exception);
break;
}
}
}
|
CWE-787
| 182,214 | 3,558 |
248821212902523869130037279765368477375
| null | null | null |
ImageMagick
|
256825d4eb33dc301496710d15cf5a7ae924088b
| 1 |
static MagickBooleanType TIFFWritePhotoshopLayers(Image* image,
const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception)
{
BlobInfo
*blob;
CustomStreamInfo
*custom_stream;
Image
*base_image,
*next;
ImageInfo
*clone_info;
MagickBooleanType
status;
PhotoshopProfile
profile;
PSDInfo
info;
StringInfo
*layers;
base_image=CloneImage(image,0,0,MagickFalse,exception);
if (base_image == (Image *) NULL)
return(MagickTrue);
clone_info=CloneImageInfo(image_info);
if (clone_info == (ImageInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
profile.offset=0;
profile.quantum=MagickMinBlobExtent;
layers=AcquireStringInfo(profile.quantum);
if (layers == (StringInfo *) NULL)
{
clone_info=DestroyImageInfo(clone_info);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
profile.data=layers;
profile.extent=layers->length;
custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception);
if (custom_stream == (CustomStreamInfo *) NULL)
{
clone_info=DestroyImageInfo(clone_info);
layers=DestroyStringInfo(layers);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
blob=CloneBlobInfo((BlobInfo *) NULL);
if (blob == (BlobInfo *) NULL)
{
clone_info=DestroyImageInfo(clone_info);
layers=DestroyStringInfo(layers);
custom_stream=DestroyCustomStreamInfo(custom_stream);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
DestroyBlob(base_image);
base_image->blob=blob;
next=base_image;
while (next != (Image *) NULL)
next=SyncNextImageInList(next);
AttachCustomStream(base_image->blob,custom_stream);
InitPSDInfo(image,&info);
base_image->endian=endian;
WriteBlobString(base_image,"Adobe Photoshop Document Data Block");
WriteBlobByte(base_image,0);
WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" :
"8BIMLayr");
status=WritePSDLayers(base_image,clone_info,&info,exception);
if (status != MagickFalse)
{
SetStringInfoLength(layers,(size_t) profile.offset);
status=SetImageProfile(image,"tiff:37724",layers,exception);
}
next=base_image;
while (next != (Image *) NULL)
{
CloseBlob(next);
next=next->next;
}
layers=DestroyStringInfo(layers);
clone_info=DestroyImageInfo(clone_info);
custom_stream=DestroyCustomStreamInfo(custom_stream);
return(status);
}
|
CWE-772
| 182,215 | 3,559 |
24688139327807033971357432907251742784
| null | null | null |
Little-CMS
|
768f70ca405cd3159d990e962d54456773bb8cf8
| 1 |
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");
}
}
|
CWE-190
| 182,217 | 3,560 |
130867891295494081529324063578808735740
| null | null | null |
OpenSC
|
03628449b75a93787eb2359412a3980365dda49b#diff-f8c0128e14031ed9307d47f10f601b54
| 1 |
iasecc_select_file(struct sc_card *card, const struct sc_path *path,
struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_path lpath;
int cache_valid = card->cache.valid, df_from_cache = 0;
int rv, ii;
LOG_FUNC_CALLED(ctx);
memcpy(&lpath, path, sizeof(struct sc_path));
if (file_out)
*file_out = NULL;
sc_log(ctx,
"iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u",
card, path->len, path->type, path->aid.len);
sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path));
sc_print_cache(card);
if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : "");
rv = iasecc_select_mf(card, file_out);
LOG_TEST_RET(ctx, rv, "MF selection error");
if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);
lpath.len -= 2;
}
}
if (lpath.aid.len) {
struct sc_file *file = NULL;
struct sc_path ppath;
sc_log(ctx,
"iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u",
lpath.aid.value, lpath.aid.len);
sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len));
memset(&ppath, 0, sizeof(ppath));
memcpy(ppath.value, lpath.aid.value, lpath.aid.len);
ppath.len = lpath.aid.len;
ppath.type = SC_PATH_TYPE_DF_NAME;
if (card->cache.valid && card->cache.current_df
&& card->cache.current_df->path.len == lpath.aid.len
&& !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len))
df_from_cache = 1;
rv = iasecc_select_file(card, &ppath, &file);
LOG_TEST_RET(ctx, rv, "select AID path failed");
if (file_out)
*file_out = file;
else
sc_file_free(file);
if (lpath.type == SC_PATH_TYPE_DF_NAME)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
}
if (lpath.type == SC_PATH_TYPE_PATH)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
if (!lpath.len)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
sc_print_cache(card);
if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_df->path.len == lpath.len
&& !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) {
sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path));
if (file_out) {
sc_file_free(*file_out);
sc_file_dup(file_out, card->cache.current_df);
}
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
do {
struct sc_apdu apdu;
struct sc_file *file = NULL;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int pathlen = lpath.len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
if (card->type != SC_CARD_TYPE_IASECC_GEMALTO
&& card->type != SC_CARD_TYPE_IASECC_OBERTHUR
&& card->type != SC_CARD_TYPE_IASECC_SAGEM
&& card->type != SC_CARD_TYPE_IASECC_AMOS
&& card->type != SC_CARD_TYPE_IASECC_MI
&& card->type != SC_CARD_TYPE_IASECC_MI2)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card");
if (lpath.type == SC_PATH_TYPE_FILE_ID) {
apdu.p1 = 0x02;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) {
apdu.p1 = 0x01;
apdu.p2 = 0x04;
}
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {
apdu.p1 = 0x09;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_PARENT) {
apdu.p1 = 0x03;
pathlen = 0;
apdu.cse = SC_APDU_CASE_2_SHORT;
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
apdu.p1 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else {
sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type);
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type");
}
for (ii=0; ii<2; ii++) {
apdu.lc = pathlen;
apdu.data = lpath.value;
apdu.datalen = pathlen;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv == SC_ERROR_INCORRECT_PARAMETERS &&
lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) {
apdu.p2 = 0x0C;
continue;
}
if (ii) {
/* 'SELECT AID' do not returned FCP. Try to emulate. */
apdu.resplen = sizeof(rbuf);
rv = iasecc_emulate_fcp(ctx, &apdu);
LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP");
}
break;
}
/*
* Using of the cached DF and EF can cause problems in the multi-thread environment.
* FIXME: introduce config. option that invalidates this cache outside the locked card session,
* (or invent something else)
*/
if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) {
sc_invalidate_cache(card);
sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF");
if (file_out) {
sc_file_free(*file_out);
*file_out = NULL;
}
rv = iasecc_select_file(card, path, file_out);
LOG_FUNC_RETURN(ctx, rv);
}
LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed");
sc_log(ctx,
"iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen) {
sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]);
switch (apdu.resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = lpath;
rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen);
if (rv)
LOG_FUNC_RETURN(ctx, rv);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
sc_log(ctx, "FileType %i", file->type);
if (file->type == SC_FILE_TYPE_DF) {
if (card->cache.valid)
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_df, file);
card->cache.valid = 1;
}
else {
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out) {
sc_file_free(*file_out);
*file_out = file;
}
else {
sc_file_free(file);
}
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
} while(0);
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
|
CWE-674
| 182,242 | 3,581 |
15095566280526776776269335754345672863
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, priv->cac_id_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
|
CWE-415
| 182,243 | 3,582 |
62749081203659249018214962126394821434
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
|
CWE-415
| 182,244 | 3,583 |
242799205298628294550760024967209106704
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
muscle_private_t* priv = MUSCLE_DATA(card);
mscfs_t *fs = priv->fs;
int x;
int count = 0;
mscfs_check_cache(priv->fs);
for(x = 0; x < fs->cache.size; x++) {
u8* oid= fs->cache.array[x].objectId.id;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"FILE: %02X%02X%02X%02X\n",
oid[0],oid[1],oid[2],oid[3]);
if(0 == memcmp(fs->currentPath, oid, 2)) {
buf[0] = oid[2];
buf[1] = oid[3];
if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
buf += 2;
count+=2;
}
}
return count;
}
|
CWE-415
| 182,246 | 3,585 |
276035595384972056131068100242925685950
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
|
CWE-415
| 182,247 | 3,586 |
206419591839581679226999968799892402944
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
|
CWE-415
| 182,248 | 3,587 |
178422683966294863742660011441876893503
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
|
CWE-415
| 182,249 | 3,588 |
173755131876834833795325765211579338885
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
|
CWE-415
| 182,250 | 3,589 |
292005769458856392686741125201527966464
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
|
CWE-415
| 182,251 | 3,590 |
200304011778260893193709657108490213768
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
|
CWE-415
| 182,253 | 3,592 |
161354385550546095544370264755350412662
| null | null | null |
OpenSC
|
360e95d45ac4123255a4c796db96337f332160ad#diff-d643a0fa169471dbf2912f4866dc49c5
| 1 |
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
|
CWE-415
| 182,255 | 3,593 |
104691721202525009386928572846417114598
| null | null | null |
linux
|
f1e255d60ae66a9f672ff9a207ee6cd8e33d2679
| 1 |
static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_yurex *dev;
int retval = 0;
int bytes_read = 0;
char in_buffer[20];
unsigned long flags;
dev = file->private_data;
mutex_lock(&dev->io_mutex);
if (!dev->interface) { /* already disconnected */
retval = -ENODEV;
goto exit;
}
spin_lock_irqsave(&dev->lock, flags);
bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu);
spin_unlock_irqrestore(&dev->lock, flags);
if (*ppos < bytes_read) {
if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos))
retval = -EFAULT;
else {
retval = bytes_read - *ppos;
*ppos += bytes_read;
}
}
exit:
mutex_unlock(&dev->io_mutex);
return retval;
}
|
CWE-20
| 182,256 | 3,594 |
31187263457320153580212902653113504557
| null | null | null |
axtls-8266
|
5efe2947ab45e81d84b5f707c51d1c64be52f36c
| 1 |
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len,
bigint *modulus, bigint *pub_exp)
{
int i, size;
bigint *decrypted_bi, *dat_bi;
bigint *bir = NULL;
uint8_t *block = (uint8_t *)malloc(sig_len);
/* decrypt */
dat_bi = bi_import(ctx, sig, sig_len);
ctx->mod_offset = BIGINT_M_OFFSET;
/* convert to a normal block */
decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp);
bi_export(ctx, decrypted_bi, block, sig_len);
ctx->mod_offset = BIGINT_M_OFFSET;
i = 10; /* start at the first possible non-padded byte */
while (block[i++] && i < sig_len);
size = sig_len - i;
/* get only the bit we want */
if (size > 0)
{
int len;
const uint8_t *sig_ptr = get_signature(&block[i], &len);
if (sig_ptr)
{
bir = bi_import(ctx, sig_ptr, len);
}
}
free(block);
/* save a few bytes of memory */
bi_clear_cache(ctx);
return bir;
}
|
CWE-347
| 182,258 | 3,595 |
270479850159638358028621980964298565491
| null | null | null |
libxkbcommon
|
96df3106d49438e442510c59acad306e94f3db4d
| 1 |
ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
}
|
CWE-476
| 182,260 | 3,597 |
322677027855373449927249713272969016000
| null | null | null |
libxkbcommon
|
bb4909d2d8fa6b08155e449986a478101e2b2634
| 1 |
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
|
CWE-476
| 182,263 | 3,598 |
31784033323607915525184000174581244874
| null | null | null |
libxkbcommon
|
badb428e63387140720f22486b3acbd3d738859f
| 1 |
CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
{
AliasInfo *alias;
unsigned i, num_key_aliases;
struct xkb_key_alias *key_aliases;
/*
* Do some sanity checking on the aliases. We can't do it before
* because keys and their aliases may be added out-of-order.
*/
num_key_aliases = 0;
darray_foreach(alias, info->aliases) {
/* Check that ->real is a key. */
if (!XkbKeyByName(keymap, alias->real, false)) {
log_vrb(info->ctx, 5,
"Attempt to alias %s to non-existent key %s; Ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
/* Check that ->alias is not a key. */
if (XkbKeyByName(keymap, alias->alias, false)) {
log_vrb(info->ctx, 5,
"Attempt to create alias with the name of a real key; "
"Alias \"%s = %s\" ignored\n",
KeyNameText(info->ctx, alias->alias),
KeyNameText(info->ctx, alias->real));
alias->real = XKB_ATOM_NONE;
continue;
}
num_key_aliases++;
}
/* Copy key aliases. */
key_aliases = NULL;
if (num_key_aliases > 0) {
key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));
if (!key_aliases)
return false;
}
i = 0;
darray_foreach(alias, info->aliases) {
if (alias->real != XKB_ATOM_NONE) {
key_aliases[i].alias = alias->alias;
key_aliases[i].real = alias->real;
i++;
}
}
keymap->num_key_aliases = num_key_aliases;
keymap->key_aliases = key_aliases;
return true;
}
|
CWE-476
| 182,264 | 3,599 |
36688546490544028666146865390249559367
| null | null | null |
libxkbcommon
|
c1e5ac16e77a21f87bdf3bc4dea61b037a17dddb
| 1 |
ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
unsigned numEntries = darray_size(append->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, numEntries);
darray_concat(expr->keysym_list.syms, append->keysym_list.syms);
FreeStmt((ParseCommon *) &append);
return expr;
}
|
CWE-416
| 182,265 | 3,600 |
50655231442243782136237033048286386578
| null | null | null |
libxkbcommon
|
842e4351c2c97de6051cab6ce36b4a81e709a0e1
| 1 |
lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
|
CWE-835
| 182,266 | 3,601 |
100560431963326217117985635138796471406
| null | null | null |
libxkbcommon
|
917636b1d0d70205a13f89062b95e3a0fc31d4ff
| 1 |
CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
}
|
CWE-476
| 182,267 | 3,602 |
188930561233461655328681105362065949927
| null | null | null |
libxkbcommon
|
1f9d1248c07cda8aaff762429c0dce146de8632a
| 1 |
ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr,
bool *set_rtrn)
{
bool ok = false;
const char *ident;
switch (expr->expr.op) {
case EXPR_VALUE:
if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) {
log_err(ctx,
"Found constant of type %s where boolean was expected\n",
expr_value_type_to_string(expr->expr.value_type));
return false;
}
*set_rtrn = expr->boolean.set;
return true;
case EXPR_IDENT:
ident = xkb_atom_text(ctx, expr->ident.ident);
if (ident) {
if (istreq(ident, "true") ||
istreq(ident, "yes") ||
istreq(ident, "on")) {
*set_rtrn = true;
return true;
}
else if (istreq(ident, "false") ||
istreq(ident, "no") ||
istreq(ident, "off")) {
*set_rtrn = false;
return true;
}
}
log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident);
return false;
case EXPR_FIELD_REF:
log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n",
xkb_atom_text(ctx, expr->field_ref.element),
xkb_atom_text(ctx, expr->field_ref.field));
return false;
case EXPR_INVERT:
case EXPR_NOT:
ok = ExprResolveBoolean(ctx, expr, set_rtrn);
if (ok)
*set_rtrn = !*set_rtrn;
return ok;
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_DIVIDE:
case EXPR_ASSIGN:
case EXPR_NEGATE:
case EXPR_UNARY_PLUS:
log_err(ctx, "%s of boolean values not permitted\n",
expr_op_type_to_string(expr->expr.op));
break;
default:
log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n",
expr->expr.op);
break;
}
return false;
}
|
CWE-400
| 182,268 | 3,603 |
335781184501352737004882175421538747794
| null | null | null |
Openswan
|
9eaa6c2a823c1d2b58913506a15f9474bf857a3d
| 1 |
err_t verify_signed_hash(const struct RSA_public_key *k
, u_char *s, unsigned int s_max_octets
, u_char **psig
, size_t hash_len
, const u_char *sig_val, size_t sig_len)
{
unsigned int padlen;
/* actual exponentiation; see PKCS#1 v2.0 5.1 */
{
chunk_t temp_s;
MP_INT c;
n_to_mpz(&c, sig_val, sig_len);
oswcrypto.mod_exp(&c, &c, &k->e, &k->n);
temp_s = mpz_to_n(&c, sig_len); /* back to octets */
if(s_max_octets < sig_len) {
return "2""exponentiation failed; too many octets";
}
memcpy(s, temp_s.ptr, sig_len);
pfree(temp_s.ptr);
mpz_clear(&c);
}
/* check signature contents */
/* verify padding (not including any DER digest info! */
padlen = sig_len - 3 - hash_len;
/* now check padding */
DBG(DBG_CRYPT,
DBG_dump("verify_sh decrypted SIG1:", s, sig_len));
DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len));
/* skip padding */
if(s[0] != 0x00
|| s[1] != 0x01
|| s[padlen+2] != 0x00) {
return "3""SIG padding does not check out";
}
s += padlen + 3;
(*psig) = s;
/* return SUCCESS */
return NULL;
}
|
CWE-347
| 182,269 | 3,604 |
27311431029886652870018573217320389980
| null | null | null |
linux
|
fdf82a7856b32d905c39afc85e34364491e46346
| 1 |
static void __init spectre_v2_select_mitigation(void)
{
enum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline();
enum spectre_v2_mitigation mode = SPECTRE_V2_NONE;
/*
* If the CPU is not affected and the command line mode is NONE or AUTO
* then nothing to do.
*/
if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) &&
(cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO))
return;
switch (cmd) {
case SPECTRE_V2_CMD_NONE:
return;
case SPECTRE_V2_CMD_FORCE:
case SPECTRE_V2_CMD_AUTO:
if (IS_ENABLED(CONFIG_RETPOLINE))
goto retpoline_auto;
break;
case SPECTRE_V2_CMD_RETPOLINE_AMD:
if (IS_ENABLED(CONFIG_RETPOLINE))
goto retpoline_amd;
break;
case SPECTRE_V2_CMD_RETPOLINE_GENERIC:
if (IS_ENABLED(CONFIG_RETPOLINE))
goto retpoline_generic;
break;
case SPECTRE_V2_CMD_RETPOLINE:
if (IS_ENABLED(CONFIG_RETPOLINE))
goto retpoline_auto;
break;
}
pr_err("Spectre mitigation: kernel not compiled with retpoline; no mitigation available!");
return;
retpoline_auto:
if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) {
retpoline_amd:
if (!boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) {
pr_err("Spectre mitigation: LFENCE not serializing, switching to generic retpoline\n");
goto retpoline_generic;
}
mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_AMD :
SPECTRE_V2_RETPOLINE_MINIMAL_AMD;
setup_force_cpu_cap(X86_FEATURE_RETPOLINE_AMD);
setup_force_cpu_cap(X86_FEATURE_RETPOLINE);
} else {
retpoline_generic:
mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_GENERIC :
SPECTRE_V2_RETPOLINE_MINIMAL;
setup_force_cpu_cap(X86_FEATURE_RETPOLINE);
}
spectre_v2_enabled = mode;
pr_info("%s\n", spectre_v2_strings[mode]);
/*
* If neither SMEP nor PTI are available, there is a risk of
* hitting userspace addresses in the RSB after a context switch
* from a shallow call stack to a deeper one. To prevent this fill
* the entire RSB, even when using IBRS.
*
* Skylake era CPUs have a separate issue with *underflow* of the
* RSB, when they will predict 'ret' targets from the generic BTB.
* The proper mitigation for this is IBRS. If IBRS is not supported
* or deactivated in favour of retpolines the RSB fill on context
* switch is required.
*/
if ((!boot_cpu_has(X86_FEATURE_PTI) &&
!boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) {
setup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);
pr_info("Spectre v2 mitigation: Filling RSB on context switch\n");
}
/* Initialize Indirect Branch Prediction Barrier if supported */
if (boot_cpu_has(X86_FEATURE_IBPB)) {
setup_force_cpu_cap(X86_FEATURE_USE_IBPB);
pr_info("Spectre v2 mitigation: Enabling Indirect Branch Prediction Barrier\n");
}
/*
* Retpoline means the kernel is safe because it has no indirect
* branches. But firmware isn't, so use IBRS to protect that.
*/
if (boot_cpu_has(X86_FEATURE_IBRS)) {
setup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW);
pr_info("Enabling Restricted Speculation for firmware calls\n");
}
}
| 182,274 | 3,607 |
315846410972680352605090430258640904725
| null | null | null |
|
libgit2
|
1f9a8510e1d2f20ed7334eeeddb92c4dd8e7c649
| 1 |
static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
line += 3; /* skip "ng " */
if (!(ptr = strchr(line, ' ')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
line = ptr + 1;
if (!(ptr = strchr(line, '\n')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
|
CWE-125
| 182,275 | 3,608 |
104719273059594508887568049490589894150
| null | null | null |
src
|
779974d35b4859c07bc3cb8a12c74b43b0a7d1e0
| 1 |
userauth_hostbased(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *cuser, *chost;
u_char *pkblob, *sig;
size_t alen, blen, slen;
int r, pktype, authenticated = 0;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
/* XXX use sshkey_froms() */
if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
(r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
(r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
fatal("%s: packet parsing: %s", __func__, ssh_err(r));
debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
debug("signature:");
sshbuf_dump_data(sig, siglen, stderr);
#endif
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
logit("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: key_from_blob: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
error("Refusing RSA key because peer uses unsafe "
"signature format");
goto done;
}
if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
__func__, sshkey_type(key));
goto done;
}
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
/* reconstruct packet */
if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
(r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
(r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
(r = sshbuf_put_cstring(b, chost)) != 0 ||
(r = sshbuf_put_cstring(b, cuser)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
auth2_record_info(authctxt,
"client user \"%.100s\", client host \"%.100s\"", cuser, chost);
/* test for allowed key and correct signature */
authenticated = 0;
if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
authenticated = 1;
auth2_record_key(authctxt, authenticated, key);
sshbuf_free(b);
done:
debug2("%s: authenticated %d", __func__, authenticated);
sshkey_free(key);
free(pkalg);
free(pkblob);
free(cuser);
free(chost);
free(sig);
return authenticated;
}
|
CWE-200
| 182,277 | 3,609 |
163718903000687192933922548105907006843
| null | null | null |
src
|
779974d35b4859c07bc3cb8a12c74b43b0a7d1e0
| 1 |
userauth_pubkey(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct passwd *pw = authctxt->pw;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
u_char *pkblob, *sig, have_sig;
size_t blen, slen;
int r, pktype;
int authenticated = 0;
struct sshauthopt *authopts = NULL;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
(r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
fatal("%s: parse request failed: %s", __func__, ssh_err(r));
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
verbose("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: could not parse key: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
logit("Refusing RSA key because client uses unsafe "
"signature scheme");
goto done;
}
if (auth2_key_already_used(authctxt, key)) {
logit("refusing previously-used %s key", sshkey_type(key));
goto done;
}
if (match_pattern_list(pkalg, options.pubkey_key_types, 0) != 1) {
logit("%s: key type %s not in PubkeyAcceptedKeyTypes",
__func__, sshkey_ssh_name(key));
goto done;
}
key_s = format_key(key);
if (sshkey_is_cert(key))
ca_s = format_key(key->cert->signature_key);
if (have_sig) {
debug3("%s: have %s signature for %s%s%s",
__func__, pkalg, key_s,
ca_s == NULL ? "" : " CA ",
ca_s == NULL ? "" : ca_s);
if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
(r = sshpkt_get_end(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
if (ssh->compat & SSH_OLD_SESSIONID) {
if ((r = sshbuf_put(b, session_id2,
session_id2_len)) != 0)
fatal("%s: sshbuf_put session id: %s",
__func__, ssh_err(r));
} else {
if ((r = sshbuf_put_string(b, session_id2,
session_id2_len)) != 0)
fatal("%s: sshbuf_put_string session id: %s",
__func__, ssh_err(r));
}
/* reconstruct packet */
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, userstyle)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "publickey")) != 0 ||
(r = sshbuf_put_u8(b, have_sig)) != 0 ||
(r = sshbuf_put_cstring(b, pkalg) != 0) ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0)
fatal("%s: build packet failed: %s",
__func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
/* test for correct signature */
authenticated = 0;
if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b),
(ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
ssh->compat)) == 0) {
authenticated = 1;
}
sshbuf_free(b);
free(sig);
auth2_record_key(authctxt, authenticated, key);
} else {
debug("%s: test pkalg %s pkblob %s%s%s",
__func__, pkalg, key_s,
ca_s == NULL ? "" : " CA ",
ca_s == NULL ? "" : ca_s);
if ((r = sshpkt_get_end(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
/* XXX fake reply and always send PK_OK ? */
/*
* XXX this allows testing whether a user is allowed
* to login: if you happen to have a valid pubkey this
* message is sent. the message is NEVER sent at all
* if a user is not allowed to login. is this an
* issue? -markus
*/
if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
!= 0 ||
(r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
(r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
(r = sshpkt_send(ssh)) != 0 ||
(r = ssh_packet_write_wait(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
authctxt->postponed = 1;
}
}
done:
if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
debug("%s: key options inconsistent with existing", __func__);
authenticated = 0;
}
debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg);
sshauthopt_free(authopts);
sshkey_free(key);
free(userstyle);
free(pkalg);
free(pkblob);
free(key_s);
free(ca_s);
return authenticated;
}
|
CWE-200
| 182,278 | 3,610 |
267521840593734708823447266775181016108
| null | null | null |
php-src
|
f151e048ed27f6f4eef729f3310d053ab5da71d4
| 1 |
PHP_FUNCTION(linkinfo)
{
char *link;
size_t link_len;
zend_stat_t sb;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) {
return;
}
ret = VCWD_STAT(link, &sb);
if (ret == -1) {
php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
RETURN_LONG(Z_L(-1));
}
RETURN_LONG((zend_long) sb.st_dev);
}
|
CWE-200
| 182,279 | 3,611 |
81678671678671031951396685687937160593
| null | null | null |
pango
|
71aaeaf020340412b8d012fe23a556c0420eda5f
| 1 |
_pango_emoji_iter_next (PangoEmojiIter *iter)
{
PangoEmojiType current_emoji_type = PANGO_EMOJI_TYPE_INVALID;
if (iter->end == iter->text_end)
return FALSE;
iter->start = iter->end;
for (; iter->end < iter->text_end; iter->end = g_utf8_next_char (iter->end))
{
gunichar ch = g_utf8_get_char (iter->end);
/* Except at the beginning, ZWJ just carries over the emoji or neutral
* text type, VS15 & VS16 we just carry over as well, since we already
* resolved those through lookahead. Also, don't downgrade to text
* presentation for emoji that are part of a ZWJ sequence, example
* U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech
* bubble, see below. */
if ((!(ch == kZeroWidthJoinerCharacter && !iter->is_emoji) &&
ch != kVariationSelector15Character &&
ch != kVariationSelector16Character &&
ch != kCombiningEnclosingCircleBackslashCharacter &&
!_pango_Is_Regional_Indicator(ch) &&
!((ch == kLeftSpeechBubbleCharacter ||
ch == kRainbowCharacter ||
ch == kMaleSignCharacter ||
ch == kFemaleSignCharacter ||
ch == kStaffOfAesculapiusCharacter) &&
!iter->is_emoji)) ||
current_emoji_type == PANGO_EMOJI_TYPE_INVALID) {
current_emoji_type = _pango_get_emoji_type (ch);
}
if (g_utf8_next_char (iter->end) < iter->text_end) /* Optimize. */
{
gunichar peek_char = g_utf8_get_char (g_utf8_next_char (iter->end));
/* Variation Selectors */
if (current_emoji_type ==
PANGO_EMOJI_TYPE_EMOJI_EMOJI &&
peek_char == kVariationSelector15Character) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_TEXT;
}
if ((current_emoji_type ==
PANGO_EMOJI_TYPE_EMOJI_TEXT ||
_pango_Is_Emoji_Keycap_Base(ch)) &&
peek_char == kVariationSelector16Character) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
/* Combining characters Keycap... */
if (_pango_Is_Emoji_Keycap_Base(ch) &&
peek_char == kCombiningEnclosingKeycapCharacter) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
};
/* Regional indicators */
if (_pango_Is_Regional_Indicator(ch) &&
_pango_Is_Regional_Indicator(peek_char)) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
/* Upgrade text presentation emoji to emoji presentation when followed by
* ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble. */
if ((ch == kEyeCharacter ||
ch == kWavingWhiteFlagCharacter) &&
peek_char == kZeroWidthJoinerCharacter) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
}
if (iter->is_emoji == (gboolean) 2)
iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
if (iter->is_emoji == PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type))
{
iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
return TRUE;
}
}
iter->is_emoji = PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
return TRUE;
}
|
CWE-119
| 182,280 | 3,612 |
267323365278579827581036352280243518405
| null | null | null |
libmspack
|
0b0ef9344255ff5acfac6b7af09198ac9c9756c8
| 1 |
static int kwajd_read_headers(struct mspack_system *sys,
struct mspack_file *fh,
struct mskwajd_header *hdr)
{
unsigned char buf[16];
int i;
/* read in the header */
if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check for "KWAJ" signature */
if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) ||
((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088))
{
return MSPACK_ERR_SIGNATURE;
}
/* basic header fields */
hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]);
hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]);
hdr->headers = EndGetI16(&buf[kwajh_Flags]);
hdr->length = 0;
hdr->filename = NULL;
hdr->extra = NULL;
hdr->extra_length = 0;
/* optional headers */
/* 4 bytes: length of unpacked file */
if (hdr->headers & MSKWAJ_HDR_HASLENGTH) {
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
hdr->length = EndGetI32(&buf[0]);
}
/* 2 bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
}
/* 2 bytes: length of section, then [length] bytes: unknown purpose */
if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK;
}
/* filename and extension */
if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) {
off_t pos = sys->tell(fh);
char *fn = (char *) sys->alloc(sys, (size_t) 13);
/* allocate memory for maximum length filename */
if (! fn) return MSPACK_ERR_NOMEMORY;
hdr->filename = fn;
/* copy filename if present */
if (hdr->headers & MSKWAJ_HDR_HASFILENAME) {
if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ;
for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break;
pos += (i < 9) ? i+1 : 9;
if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))
return MSPACK_ERR_SEEK;
}
/* copy extension if present */
if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) {
*fn++ = '.';
if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ;
for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break;
pos += (i < 4) ? i+1 : 4;
if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START))
return MSPACK_ERR_SEEK;
}
*fn = '\0';
}
/* 2 bytes: extra text length then [length] bytes of extra text data */
if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) {
if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ;
i = EndGetI16(&buf[0]);
hdr->extra = (char *) sys->alloc(sys, (size_t)i+1);
if (! hdr->extra) return MSPACK_ERR_NOMEMORY;
if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ;
hdr->extra[i] = '\0';
hdr->extra_length = i;
}
return MSPACK_ERR_OK;
}
|
CWE-787
| 182,283 | 3,614 |
276727971155017355009787888662582740870
| null | null | null |
FFmpeg
|
fa19fbcf712a6a6cc5a5cfdc3254a97b9bce6582
| 1 |
static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int version = 0;
uint32_t tag = track->tag;
if (track->mode == MODE_MOV) {
if (track->timescale > UINT16_MAX) {
if (mov_get_lpcm_flags(track->par->codec_id))
tag = AV_RL32("lpcm");
version = 2;
} else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id) ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2) {
version = 1;
}
}
avio_wb32(pb, 0); /* size */
if (mov->encryption_scheme != MOV_ENC_NONE) {
ffio_wfourcc(pb, "enca");
} else {
avio_wl32(pb, tag); // store it byteswapped
}
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
/* SoundDescription */
avio_wb16(pb, version); /* Version */
avio_wb16(pb, 0); /* Revision level */
avio_wb32(pb, 0); /* Reserved */
if (version == 2) {
avio_wb16(pb, 3);
avio_wb16(pb, 16);
avio_wb16(pb, 0xfffe);
avio_wb16(pb, 0);
avio_wb32(pb, 0x00010000);
avio_wb32(pb, 72);
avio_wb64(pb, av_double2int(track->par->sample_rate));
avio_wb32(pb, track->par->channels);
avio_wb32(pb, 0x7F000000);
avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
avio_wb32(pb, track->sample_size);
avio_wb32(pb, get_samples_per_packet(track));
} else {
if (track->mode == MODE_MOV) {
avio_wb16(pb, track->par->channels);
if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
track->par->codec_id == AV_CODEC_ID_PCM_S8)
avio_wb16(pb, 8); /* bits per sample */
else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
avio_wb16(pb, track->par->bits_per_coded_sample);
else
avio_wb16(pb, 16);
avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
} else { /* reserved for mp4/3gp */
if (track->par->codec_id == AV_CODEC_ID_FLAC ||
track->par->codec_id == AV_CODEC_ID_OPUS) {
avio_wb16(pb, track->par->channels);
} else {
avio_wb16(pb, 2);
}
if (track->par->codec_id == AV_CODEC_ID_FLAC) {
avio_wb16(pb, track->par->bits_per_raw_sample);
} else {
avio_wb16(pb, 16);
}
avio_wb16(pb, 0);
}
avio_wb16(pb, 0); /* packet size (= 0) */
if (track->par->codec_id == AV_CODEC_ID_OPUS)
avio_wb16(pb, 48000);
else
avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
track->par->sample_rate : 0);
avio_wb16(pb, 0); /* Reserved */
}
if (version == 1) { /* SoundDescription V1 extended info */
if (mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id))
avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
else
avio_wb32(pb, track->par->frame_size); /* Samples per packet */
avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
avio_wb32(pb, track->sample_size); /* Bytes per frame */
avio_wb32(pb, 2); /* Bytes per sample */
}
if (track->mode == MODE_MOV &&
(track->par->codec_id == AV_CODEC_ID_AAC ||
track->par->codec_id == AV_CODEC_ID_AC3 ||
track->par->codec_id == AV_CODEC_ID_EAC3 ||
track->par->codec_id == AV_CODEC_ID_AMR_NB ||
track->par->codec_id == AV_CODEC_ID_ALAC ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2 ||
(mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
(mov_pcm_be_gt16(track->par->codec_id) && version==1)))
mov_write_wave_tag(s, pb, track);
else if (track->tag == MKTAG('m','p','4','a'))
mov_write_esds_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
mov_write_amr_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AC3)
mov_write_ac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_EAC3)
mov_write_eac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_ALAC)
mov_write_extradata_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
mov_write_wfex_tag(s, pb, track);
else if (track->par->codec_id == AV_CODEC_ID_FLAC)
mov_write_dfla_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_OPUS)
mov_write_dops_tag(pb, track);
else if (track->vos_len > 0)
mov_write_glbl_tag(pb, track);
if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_chan_tag(s, pb, track);
if (mov->encryption_scheme != MOV_ENC_NONE) {
ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
}
return update_size(pb, pos);
}
|
CWE-369
| 182,289 | 3,620 |
170281166197927188066678313471492319523
| null | null | null |
FFmpeg
|
3a2d21bc5f97aa0161db3ae731fc2732be6108b8
| 1 |
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
unsigned int samples_in_chunk = 0;
int size = pkt->size, ret = 0;
uint8_t *reformatted_data = NULL;
ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret;
if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
if (mov->frag_interleave && mov->fragments > 0) {
if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
return ret;
}
}
if (!trk->mdat_buf) {
if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
return ret;
}
pb = trk->mdat_buf;
} else {
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
pb = mov->mdat_buf;
}
}
if (par->codec_id == AV_CODEC_ID_AMR_NB) {
/* We must find out how many AMR blocks there are in one packet */
static const uint16_t packed_size[16] =
{13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
int len = 0;
while (len < size && samples_in_chunk < 100) {
len += packed_size[(pkt->data[len] >> 3) & 0x0F];
samples_in_chunk++;
}
if (samples_in_chunk > 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
return -1;
}
} else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
samples_in_chunk = trk->par->frame_size;
} else if (trk->sample_size)
samples_in_chunk = size / trk->sample_size;
else
samples_in_chunk = 1;
/* copy extradata if it exists */
if (trk->vos_len == 0 && par->extradata_size > 0 &&
!TAG_IS_AVCI(trk->tag) &&
(par->codec_id != AV_CODEC_ID_DNXHD)) {
trk->vos_len = par->extradata_size;
trk->vos_data = av_malloc(trk->vos_len);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, par->extradata, trk->vos_len);
}
if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
(AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
if (!s->streams[pkt->stream_index]->nb_frames) {
av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
"use the audio bitstream filter 'aac_adtstoasc' to fix it "
"('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
return -1;
}
av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
}
if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
/* from x264 or from bytestream H.264 */
/* NAL reformatting needed */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
&size);
avio_write(pb, reformatted_data, size);
} else {
if (trk->cenc.aes_ctr) {
size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
if (size < 0) {
ret = size;
goto err;
}
} else {
size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
}
}
} else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
(AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
/* extradata is Annex B, assume the bitstream is too and convert it */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
avio_write(pb, reformatted_data, size);
} else {
size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
}
#if CONFIG_AC3_PARSER
} else if (par->codec_id == AV_CODEC_ID_EAC3) {
size = handle_eac3(mov, pkt, trk);
if (size < 0)
return size;
else if (!size)
goto end;
avio_write(pb, pkt->data, size);
#endif
} else {
if (trk->cenc.aes_ctr) {
if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
int nal_size_length = (par->extradata[4] & 0x3) + 1;
ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
} else {
ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
}
if (ret) {
goto err;
}
} else {
avio_write(pb, pkt->data, size);
}
}
if ((par->codec_id == AV_CODEC_ID_DNXHD ||
par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
/* copy frame to create needed atoms */
trk->vos_len = size;
trk->vos_data = av_malloc(size);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, pkt->data, size);
}
if (trk->entry >= trk->cluster_capacity) {
unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
if (av_reallocp_array(&trk->cluster, new_capacity,
sizeof(*trk->cluster))) {
ret = AVERROR(ENOMEM);
goto err;
}
trk->cluster_capacity = new_capacity;
}
trk->cluster[trk->entry].pos = avio_tell(pb) - size;
trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
trk->cluster[trk->entry].chunkNum = 0;
trk->cluster[trk->entry].size = size;
trk->cluster[trk->entry].entries = samples_in_chunk;
trk->cluster[trk->entry].dts = pkt->dts;
trk->cluster[trk->entry].pts = pkt->pts;
if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
if (!trk->frag_discont) {
/* First packet of a new fragment. We already wrote the duration
* of the last packet of the previous fragment based on track_duration,
* which might not exactly match our dts. Therefore adjust the dts
* of this packet to be what the previous packets duration implies. */
trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
/* We also may have written the pts and the corresponding duration
* in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
* the next fragment. This means the cts of the first sample must
* be the same in all fragments, unless end_pts was updated by
* the packet causing the fragment to be written. */
if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
mov->mode == MODE_ISM)
pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
} else {
/* New fragment, but discontinuous from previous fragments.
* Pretend the duration sum of the earlier fragments is
* pkt->dts - trk->start_dts. */
trk->frag_start = pkt->dts - trk->start_dts;
trk->end_pts = AV_NOPTS_VALUE;
trk->frag_discont = 0;
}
}
if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
/* Not using edit lists and shifting the first track to start from zero.
* If the other streams start from a later timestamp, we won't be able
* to signal the difference in starting time without an edit list.
* Thus move the timestamp for this first sample to 0, increasing
* its duration instead. */
trk->cluster[trk->entry].dts = trk->start_dts = 0;
}
if (trk->start_dts == AV_NOPTS_VALUE) {
trk->start_dts = pkt->dts;
if (trk->frag_discont) {
if (mov->use_editlist) {
/* Pretend the whole stream started at pts=0, with earlier fragments
* already written. If the stream started at pts=0, the duration sum
* of earlier fragments would have been pkt->pts. */
trk->frag_start = pkt->pts;
trk->start_dts = pkt->dts - pkt->pts;
} else {
/* Pretend the whole stream started at dts=0, with earlier fragments
* already written, with a duration summing up to pkt->dts. */
trk->frag_start = pkt->dts;
trk->start_dts = 0;
}
trk->frag_discont = 0;
} else if (pkt->dts && mov->moov_written)
av_log(s, AV_LOG_WARNING,
"Track %d starts with a nonzero dts %"PRId64", while the moov "
"already has been written. Set the delay_moov flag to handle "
"this case.\n",
pkt->stream_index, pkt->dts);
}
trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
trk->last_sample_is_subtitle_end = 0;
if (pkt->pts == AV_NOPTS_VALUE) {
av_log(s, AV_LOG_WARNING, "pts has no value\n");
pkt->pts = pkt->dts;
}
if (pkt->dts != pkt->pts)
trk->flags |= MOV_TRACK_CTTS;
trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
trk->cluster[trk->entry].flags = 0;
if (trk->start_cts == AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
if (trk->end_pts == AV_NOPTS_VALUE)
trk->end_pts = trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts + pkt->duration;
else
trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts +
pkt->duration);
if (par->codec_id == AV_CODEC_ID_VC1) {
mov_parse_vc1_frame(pkt, trk);
} else if (pkt->flags & AV_PKT_FLAG_KEY) {
if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
trk->entry > 0) { // force sync sample for the first key frame
mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
trk->flags |= MOV_TRACK_STPS;
} else {
trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
}
if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
trk->has_keyframes++;
}
if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
trk->has_disposable++;
}
trk->entry++;
trk->sample_count += samples_in_chunk;
mov->mdat_size += size;
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
reformatted_data, size);
end:
err:
av_free(reformatted_data);
return ret;
}
|
CWE-369
| 182,290 | 3,621 |
329834679352203602616111071978951770215
| null | null | null |
neomutt
|
9bfab35522301794483f8f9ed60820bdec9be59e
| 1 |
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)
{
return snprintf(dest, destlen, "%s.hcache", path);
}
|
CWE-22
| 182,291 | 3,622 |
226490900771100710599864485841947948772
| null | null | null |
neomutt
|
6296f7153f0c9d5e5cd3aaf08f9731e56621bdd3
| 1 |
int nntp_add_group(char *line, void *data)
{
struct NntpServer *nserv = data;
struct NntpData *nntp_data = NULL;
char group[LONG_STRING];
char desc[HUGE_STRING] = "";
char mod;
anum_t first, last;
if (!nserv || !line)
return 0;
if (sscanf(line, "%s " ANUM " " ANUM " %c %[^\n]", group, &last, &first, &mod, desc) < 4)
return 0;
nntp_data = nntp_data_find(nserv, group);
nntp_data->deleted = false;
nntp_data->first_message = first;
nntp_data->last_message = last;
nntp_data->allowed = (mod == 'y') || (mod == 'm');
mutt_str_replace(&nntp_data->desc, desc);
if (nntp_data->newsrc_ent || nntp_data->last_cached)
nntp_group_unread_stat(nntp_data);
else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message)
nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1;
else
nntp_data->unread = 0;
return 0;
}
|
CWE-119
| 182,297 | 3,626 |
119568824275084946196753086815434177044
| null | null | null |
neomutt
|
1b0f0d0988e6df4e32e9f4bf8780846ea95d4485
| 1 |
static int msg_parse_fetch(struct ImapHeader *h, char *s)
{
char tmp[SHORT_STRING];
char *ptmp = NULL;
if (!s)
return -1;
while (*s)
{
SKIPWS(s);
if (mutt_str_strncasecmp("FLAGS", s, 5) == 0)
{
s = msg_parse_flags(h, s);
if (!s)
return -1;
}
else if (mutt_str_strncasecmp("UID", s, 3) == 0)
{
s += 3;
SKIPWS(s);
if (mutt_str_atoui(s, &h->data->uid) < 0)
return -1;
s = imap_next_word(s);
}
else if (mutt_str_strncasecmp("INTERNALDATE", s, 12) == 0)
{
s += 12;
SKIPWS(s);
if (*s != '\"')
{
mutt_debug(1, "bogus INTERNALDATE entry: %s\n", s);
return -1;
}
s++;
ptmp = tmp;
while (*s && *s != '\"')
*ptmp++ = *s++;
if (*s != '\"')
return -1;
s++; /* skip past the trailing " */
*ptmp = '\0';
h->received = mutt_date_parse_imap(tmp);
}
else if (mutt_str_strncasecmp("RFC822.SIZE", s, 11) == 0)
{
s += 11;
SKIPWS(s);
ptmp = tmp;
while (isdigit((unsigned char) *s))
*ptmp++ = *s++;
*ptmp = '\0';
if (mutt_str_atol(tmp, &h->content_length) < 0)
return -1;
}
else if ((mutt_str_strncasecmp("BODY", s, 4) == 0) ||
(mutt_str_strncasecmp("RFC822.HEADER", s, 13) == 0))
{
/* handle above, in msg_fetch_header */
return -2;
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
/* got something i don't understand */
imap_error("msg_parse_fetch", s);
return -1;
}
}
return 0;
}
|
CWE-119
| 182,304 | 3,633 |
8085076253557074134241166954403737208
| null | null | null |
neomutt
|
93b8ac558752d09e1c56d4f1bc82631316fa9c82
| 1 |
static int fetch_uidl(char *line, void *data)
{
int i, index;
struct Context *ctx = (struct Context *) data;
struct PopData *pop_data = (struct PopData *) ctx->data;
char *endp = NULL;
errno = 0;
index = strtol(line, &endp, 10);
if (errno)
return -1;
while (*endp == ' ')
endp++;
memmove(line, endp, strlen(endp) + 1);
for (i = 0; i < ctx->msgcount; i++)
if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0)
break;
if (i == ctx->msgcount)
{
mutt_debug(1, "new header %d %s\n", index, line);
if (i >= ctx->hdrmax)
mx_alloc_memory(ctx);
ctx->msgcount++;
ctx->hdrs[i] = mutt_header_new();
ctx->hdrs[i]->data = mutt_str_strdup(line);
}
else if (ctx->hdrs[i]->index != index - 1)
pop_data->clear_cache = true;
ctx->hdrs[i]->refno = index;
ctx->hdrs[i]->index = index - 1;
return 0;
}
|
CWE-824
| 182,308 | 3,637 |
91378846021011035290207044324269515482
| null | null | null |
neomutt
|
95e80bf9ff10f68cb6443f760b85df4117cb15eb
| 1 |
int imap_subscribe(char *path, bool subscribe)
{
struct ImapData *idata = NULL;
char buf[LONG_STRING];
char mbox[LONG_STRING];
char errstr[STRING];
struct Buffer err, token;
struct ImapMbox mx;
if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox)
{
mutt_error(_("Bad mailbox name"));
return -1;
}
idata = imap_conn_find(&(mx.account), 0);
if (!idata)
goto fail;
imap_fix_path(idata, mx.mbox, buf, sizeof(buf));
if (!*buf)
mutt_str_strfcpy(buf, "INBOX", sizeof(buf));
if (ImapCheckSubscribed)
{
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path);
if (mutt_parse_rc_line(mbox, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
if (subscribe)
mutt_message(_("Subscribing to %s..."), buf);
else
mutt_message(_("Unsubscribing from %s..."), buf);
imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);
snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);
if (imap_exec(idata, buf, 0) < 0)
goto fail;
imap_unmunge_mbox_name(idata, mx.mbox);
if (subscribe)
mutt_message(_("Subscribed to %s"), mx.mbox);
else
mutt_message(_("Unsubscribed from %s"), mx.mbox);
FREE(&mx.mbox);
return 0;
fail:
FREE(&mx.mbox);
return -1;
}
|
CWE-77
| 182,309 | 3,638 |
336804774773163748774354919633472432056
| null | null | null |
neomutt
|
3c49c44be9b459d9c616bcaef6eb5d51298c1741
| 1 |
static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
|
CWE-20
| 182,310 | 3,639 |
255835415023365775655101037103928065385
| null | null | null |
neomutt
|
36a29280448097f34ce9c94606195f2ac643fed1
| 1 |
static int cmd_handle_untagged(struct ImapData *idata)
{
unsigned int count = 0;
char *s = imap_next_word(idata->buf);
char *pn = imap_next_word(s);
if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
pn = s;
s = imap_next_word(s);
/* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
* connection, so update that one.
*/
if (mutt_str_strncasecmp("EXISTS", s, 6) == 0)
{
mutt_debug(2, "Handling EXISTS\n");
/* new mail arrived */
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(1, "Malformed EXISTS: '%s'\n", pn);
}
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(1, "Message count is out of sync\n");
return 0;
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == idata->max_msn)
mutt_debug(3, "superfluous EXISTS message.\n");
else
{
if (!(idata->reopen & IMAP_EXPUNGE_PENDING))
{
mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count);
idata->reopen |= IMAP_NEWMAIL_PENDING;
}
idata->new_mail_count = count;
}
}
/* pn vs. s: need initial seqno */
else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0)
cmd_parse_expunge(idata, pn);
else if (mutt_str_strncasecmp("FETCH", s, 5) == 0)
cmd_parse_fetch(idata, pn);
}
else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0)
cmd_parse_capability(idata, s);
else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0)
cmd_parse_capability(idata, pn);
else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0)
cmd_parse_capability(idata, imap_next_word(pn));
else if (mutt_str_strncasecmp("LIST", s, 4) == 0)
cmd_parse_list(idata, s);
else if (mutt_str_strncasecmp("LSUB", s, 4) == 0)
cmd_parse_lsub(idata, s);
else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0)
cmd_parse_myrights(idata, s);
else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0)
cmd_parse_search(idata, s);
else if (mutt_str_strncasecmp("STATUS", s, 6) == 0)
cmd_parse_status(idata, s);
else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0)
cmd_parse_enabled(idata, s);
else if (mutt_str_strncasecmp("BYE", s, 3) == 0)
{
mutt_debug(2, "Handling BYE\n");
/* check if we're logging out */
if (idata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(idata);
return -1;
}
else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0))
{
mutt_debug(2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 3);
}
return 0;
}
|
CWE-20
| 182,311 | 3,640 |
183539949140153252586790194417694283770
| null | null | null |
radare2
|
40b021ba29c8f90ccf7c879fde2580bc73a17e8e
| 1 |
static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {
int i;
ut8 *directory_base;
struct minidump_directory *entry;
directory_base = obj->b->buf + obj->hdr->stream_directory_rva;
sdb_num_set (obj->kv, "mdmp_directory.offset",
obj->hdr->stream_directory_rva, 0);
sdb_set (obj->kv, "mdmp_directory.format", "[4]E? "
"(mdmp_stream_type)StreamType "
"(mdmp_location_descriptor)Location", 0);
/* Parse each entry in the directory */
for (i = 0; i < (int)obj->hdr->number_of_streams; i++) {
entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory)));
r_bin_mdmp_init_directory_entry (obj, entry);
}
return true;
}
|
CWE-125
| 182,320 | 3,649 |
275785464801853410853950886418673142388
| null | null | null |
libpng
|
8a05766cb74af05c04c53e6c9d60c13fc4d59bf2
| 1 |
png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length)
{
png_alloc_size_t limit = PNG_UINT_31_MAX;
# ifdef PNG_SET_USER_LIMITS_SUPPORTED
if (png_ptr->user_chunk_malloc_max > 0 &&
png_ptr->user_chunk_malloc_max < limit)
limit = png_ptr->user_chunk_malloc_max;
# elif PNG_USER_CHUNK_MALLOC_MAX > 0
if (PNG_USER_CHUNK_MALLOC_MAX < limit)
limit = PNG_USER_CHUNK_MALLOC_MAX;
# endif
if (png_ptr->chunk_name == png_IDAT)
{
png_alloc_size_t idat_limit = PNG_UINT_31_MAX;
size_t row_factor =
(png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1)
+ 1 + (png_ptr->interlaced? 6: 0));
if (png_ptr->height > PNG_UINT_32_MAX/row_factor)
idat_limit=PNG_UINT_31_MAX;
else
idat_limit = png_ptr->height * row_factor;
row_factor = row_factor > 32566? 32566 : row_factor;
idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */
idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX;
limit = limit < idat_limit? idat_limit : limit;
}
if (length > limit)
{
png_debug2(0," length = %lu, limit = %lu",
(unsigned long)length,(unsigned long)limit);
png_chunk_error(png_ptr, "chunk data is too large");
}
}
|
CWE-190
| 182,323 | 3,651 |
110259438980219466803745405748439794300
| null | null | null |
linux
|
9f645bcc566a1e9f921bdae7528a01ced5bc3713
| 1 |
static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct uvesafb_pal_entry *entries;
int shift = 16 - dac_width;
int i, err = 0;
if (info->var.bits_per_pixel == 8) {
if (cmap->start + cmap->len > info->cmap.start +
info->cmap.len || cmap->start < info->cmap.start)
return -EINVAL;
entries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);
if (!entries)
return -ENOMEM;
for (i = 0; i < cmap->len; i++) {
entries[i].red = cmap->red[i] >> shift;
entries[i].green = cmap->green[i] >> shift;
entries[i].blue = cmap->blue[i] >> shift;
entries[i].pad = 0;
}
err = uvesafb_setpalette(entries, cmap->len, cmap->start, info);
kfree(entries);
} else {
/*
* For modes with bpp > 8, we only set the pseudo palette in
* the fb_info struct. We rely on uvesafb_setcolreg to do all
* sanity checking.
*/
for (i = 0; i < cmap->len; i++) {
err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],
cmap->green[i], cmap->blue[i],
0, info);
}
}
return err;
}
|
CWE-190
| 182,324 | 3,652 |
129461505887171658800573294043167777219
| null | null | null |
linux
|
0fa3ecd87848c9c93c2c828ef4c3a8ca36ce46c7
| 1 |
void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
if (S_ISDIR(mode))
mode |= S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
|
CWE-269
| 182,325 | 3,653 |
215180090082961614700747700660177257303
| null | null | null |
FFmpeg
|
00e8181bd97c834fe60751b0c511d4bb97875f78
| 1 |
int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
|
CWE-476
| 182,330 | 3,654 |
236477656578978815652862952555526055291
| null | null | null |
FFmpeg
|
2aa9047486dbff12d9e040f917e5f799ed2fd78b
| 1 |
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
mpeg4_decode_profile_level(s, gb);
if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(s->avctx->level > 0 && s->avctx->level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
}
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
|
CWE-476
| 182,332 | 3,655 |
328896097922084939468247711509143770713
| null | null | null |
linux
|
23fcb3340d033d9f081e21e6c12c2db7eaa541d3
| 1 |
xfs_dinode_verify(
struct xfs_mount *mp,
xfs_ino_t ino,
struct xfs_dinode *dip)
{
xfs_failaddr_t fa;
uint16_t mode;
uint16_t flags;
uint64_t flags2;
uint64_t di_size;
if (dip->di_magic != cpu_to_be16(XFS_DINODE_MAGIC))
return __this_address;
/* Verify v3 integrity information first */
if (dip->di_version >= 3) {
if (!xfs_sb_version_hascrc(&mp->m_sb))
return __this_address;
if (!xfs_verify_cksum((char *)dip, mp->m_sb.sb_inodesize,
XFS_DINODE_CRC_OFF))
return __this_address;
if (be64_to_cpu(dip->di_ino) != ino)
return __this_address;
if (!uuid_equal(&dip->di_uuid, &mp->m_sb.sb_meta_uuid))
return __this_address;
}
/* don't allow invalid i_size */
di_size = be64_to_cpu(dip->di_size);
if (di_size & (1ULL << 63))
return __this_address;
mode = be16_to_cpu(dip->di_mode);
if (mode && xfs_mode_to_ftype(mode) == XFS_DIR3_FT_UNKNOWN)
return __this_address;
/* No zero-length symlinks/dirs. */
if ((S_ISLNK(mode) || S_ISDIR(mode)) && di_size == 0)
return __this_address;
/* Fork checks carried over from xfs_iformat_fork */
if (mode &&
be32_to_cpu(dip->di_nextents) + be16_to_cpu(dip->di_anextents) >
be64_to_cpu(dip->di_nblocks))
return __this_address;
if (mode && XFS_DFORK_BOFF(dip) > mp->m_sb.sb_inodesize)
return __this_address;
flags = be16_to_cpu(dip->di_flags);
if (mode && (flags & XFS_DIFLAG_REALTIME) && !mp->m_rtdev_targp)
return __this_address;
/* Do we have appropriate data fork formats for the mode? */
switch (mode & S_IFMT) {
case S_IFIFO:
case S_IFCHR:
case S_IFBLK:
case S_IFSOCK:
if (dip->di_format != XFS_DINODE_FMT_DEV)
return __this_address;
break;
case S_IFREG:
case S_IFLNK:
case S_IFDIR:
switch (dip->di_format) {
case XFS_DINODE_FMT_LOCAL:
/*
* no local regular files yet
*/
if (S_ISREG(mode))
return __this_address;
if (di_size > XFS_DFORK_DSIZE(dip, mp))
return __this_address;
if (dip->di_nextents)
return __this_address;
/* fall through */
case XFS_DINODE_FMT_EXTENTS:
case XFS_DINODE_FMT_BTREE:
break;
default:
return __this_address;
}
break;
case 0:
/* Uninitialized inode ok. */
break;
default:
return __this_address;
}
if (XFS_DFORK_Q(dip)) {
switch (dip->di_aformat) {
case XFS_DINODE_FMT_LOCAL:
if (dip->di_anextents)
return __this_address;
/* fall through */
case XFS_DINODE_FMT_EXTENTS:
case XFS_DINODE_FMT_BTREE:
break;
default:
return __this_address;
}
} else {
/*
* If there is no fork offset, this may be a freshly-made inode
* in a new disk cluster, in which case di_aformat is zeroed.
* Otherwise, such an inode must be in EXTENTS format; this goes
* for freed inodes as well.
*/
switch (dip->di_aformat) {
case 0:
case XFS_DINODE_FMT_EXTENTS:
break;
default:
return __this_address;
}
if (dip->di_anextents)
return __this_address;
}
/* extent size hint validation */
fa = xfs_inode_validate_extsize(mp, be32_to_cpu(dip->di_extsize),
mode, flags);
if (fa)
return fa;
/* only version 3 or greater inodes are extensively verified here */
if (dip->di_version < 3)
return NULL;
flags2 = be64_to_cpu(dip->di_flags2);
/* don't allow reflink/cowextsize if we don't have reflink */
if ((flags2 & (XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE)) &&
!xfs_sb_version_hasreflink(&mp->m_sb))
return __this_address;
/* only regular files get reflink */
if ((flags2 & XFS_DIFLAG2_REFLINK) && (mode & S_IFMT) != S_IFREG)
return __this_address;
/* don't let reflink and realtime mix */
if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags & XFS_DIFLAG_REALTIME))
return __this_address;
/* don't let reflink and dax mix */
if ((flags2 & XFS_DIFLAG2_REFLINK) && (flags2 & XFS_DIFLAG2_DAX))
return __this_address;
/* COW extent size hint validation */
fa = xfs_inode_validate_cowextsize(mp, be32_to_cpu(dip->di_cowextsize),
mode, flags, flags2);
if (fa)
return fa;
return NULL;
}
|
CWE-476
| 182,335 | 3,657 |
274742324962726912323034600420334859223
| null | null | null |
linux
|
bb3d48dcf86a97dc25fe9fc2c11938e19cb4399a
| 1 |
xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
}
|
CWE-476
| 182,336 | 3,658 |
255451512913000986368397354024036501857
| null | null | null |
gpac
|
bceb03fd2be95097a7b409ea59914f332fb6bc86
| 1 |
GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
|
CWE-125
| 182,340 | 3,662 |
20155211497845733229569258641571509246
| null | null | null |
linux
|
81f9c4e4177d31ced6f52a89bb70e93bfb77ca03
| 1 |
predicate_parse(const char *str, int nr_parens, int nr_preds,
parse_pred_fn parse_pred, void *data,
struct filter_parse_error *pe)
{
struct prog_entry *prog_stack;
struct prog_entry *prog;
const char *ptr = str;
char *inverts = NULL;
int *op_stack;
int *top;
int invert = 0;
int ret = -ENOMEM;
int len;
int N = 0;
int i;
nr_preds += 2; /* For TRUE and FALSE */
op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
if (!op_stack)
return ERR_PTR(-ENOMEM);
prog_stack = kmalloc_array(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
if (!prog_stack) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
if (!inverts) {
parse_error(pe, -ENOMEM, 0);
goto out_free;
}
top = op_stack;
prog = prog_stack;
*top = 0;
/* First pass */
while (*ptr) { /* #1 */
const char *next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case '(': /* #2 */
if (top - op_stack > nr_parens)
return ERR_PTR(-EINVAL);
*(++top) = invert;
continue;
case '!': /* #3 */
if (!is_not(next))
break;
invert = !invert;
continue;
}
if (N >= nr_preds) {
parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
goto out_free;
}
inverts[N] = invert; /* #4 */
prog[N].target = N-1;
len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
if (len < 0) {
ret = len;
goto out_free;
}
ptr = next + len;
N++;
ret = -1;
while (1) { /* #5 */
next = ptr++;
if (isspace(*next))
continue;
switch (*next) {
case ')':
case '\0':
break;
case '&':
case '|':
if (next[1] == next[0]) {
ptr++;
break;
}
default:
parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
next - str);
goto out_free;
}
invert = *top & INVERT;
if (*top & PROCESS_AND) { /* #7 */
update_preds(prog, N - 1, invert);
*top &= ~PROCESS_AND;
}
if (*next == '&') { /* #8 */
*top |= PROCESS_AND;
break;
}
if (*top & PROCESS_OR) { /* #9 */
update_preds(prog, N - 1, !invert);
*top &= ~PROCESS_OR;
}
if (*next == '|') { /* #10 */
*top |= PROCESS_OR;
break;
}
if (!*next) /* #11 */
goto out;
if (top == op_stack) {
ret = -1;
/* Too few '(' */
parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
goto out_free;
}
top--; /* #12 */
}
}
out:
if (top != op_stack) {
/* Too many '(' */
parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
goto out_free;
}
prog[N].pred = NULL; /* #13 */
prog[N].target = 1; /* TRUE */
prog[N+1].pred = NULL;
prog[N+1].target = 0; /* FALSE */
prog[N-1].target = N;
prog[N-1].when_to_branch = false;
/* Second Pass */
for (i = N-1 ; i--; ) {
int target = prog[i].target;
if (prog[i].when_to_branch == prog[target].when_to_branch)
prog[i].target = prog[target].target;
}
/* Third Pass */
for (i = 0; i < N; i++) {
invert = inverts[i] ^ prog[i].when_to_branch;
prog[i].when_to_branch = invert;
/* Make sure the program always moves forward */
if (WARN_ON(prog[i].target <= i)) {
ret = -EINVAL;
goto out_free;
}
}
return prog;
out_free:
kfree(op_stack);
kfree(prog_stack);
kfree(inverts);
return ERR_PTR(ret);
}
|
CWE-787
| 182,358 | 3,679 |
269743203244690440960250715941704526620
| null | null | null |
linux
|
bd23a7269834dc7c1f93e83535d16ebc44b75eba
| 1 |
static long vbg_misc_device_ioctl(struct file *filp, unsigned int req,
unsigned long arg)
{
struct vbg_session *session = filp->private_data;
size_t returned_size, size;
struct vbg_ioctl_hdr hdr;
bool is_vmmdev_req;
int ret = 0;
void *buf;
if (copy_from_user(&hdr, (void *)arg, sizeof(hdr)))
return -EFAULT;
if (hdr.version != VBG_IOCTL_HDR_VERSION)
return -EINVAL;
if (hdr.size_in < sizeof(hdr) ||
(hdr.size_out && hdr.size_out < sizeof(hdr)))
return -EINVAL;
size = max(hdr.size_in, hdr.size_out);
if (_IOC_SIZE(req) && _IOC_SIZE(req) != size)
return -EINVAL;
if (size > SZ_16M)
return -E2BIG;
/*
* IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid
* the need for a bounce-buffer and another copy later on.
*/
is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) ||
req == VBG_IOCTL_VMMDEV_REQUEST_BIG;
if (is_vmmdev_req)
buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT);
else
buf = kmalloc(size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (copy_from_user(buf, (void *)arg, hdr.size_in)) {
ret = -EFAULT;
goto out;
}
if (hdr.size_in < size)
memset(buf + hdr.size_in, 0, size - hdr.size_in);
ret = vbg_core_ioctl(session, req, buf);
if (ret)
goto out;
returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out;
if (returned_size > size) {
vbg_debug("%s: too much output data %zu > %zu\n",
__func__, returned_size, size);
returned_size = size;
}
if (copy_to_user((void *)arg, buf, returned_size) != 0)
ret = -EFAULT;
out:
if (is_vmmdev_req)
vbg_req_free(buf, size);
else
kfree(buf);
return ret;
}
|
CWE-362
| 182,360 | 3,680 |
3708566526586698345873749560471863148
| null | null | null |
FFmpeg
|
b3332a182f8ba33a34542e4a0370f38b914ccf7d
| 1 |
av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
|
CWE-476
| 182,361 | 3,681 |
258201715643119116608213935146888282511
| null | null | null |
FFmpeg
|
b3332a182f8ba33a34542e4a0370f38b914ccf7d
| 1 |
av_cold void ff_mpv_idct_init(MpegEncContext *s)
{
ff_idctdsp_init(&s->idsp, s->avctx);
/* load & permutate scantables
* note: only wmv uses different ones
*/
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
}
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
|
CWE-476
| 182,362 | 3,682 |
214617330672650499784244762882956448165
| null | null | null |
FFmpeg
|
2fc108f60f98cd00813418a8754a46476b404a3c
| 1 |
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
mpeg4_decode_profile_level(s, gb);
if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(s->avctx->level > 0 && s->avctx->level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
}
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
|
CWE-20
| 182,363 | 3,683 |
20215823895074910769238460496652532466
| null | null | null |
FFmpeg
|
e1182fac1afba92a4975917823a5f644bee7e6e8
| 1 |
static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
|
CWE-20
| 182,364 | 3,684 |
141072668666883984160767024230368732990
| null | null | null |
radare2
|
90b71c017a7fa9732fe45fd21b245ee051b1f548
| 1 |
R_API void r_anal_bb_free(RAnalBlock *bb) {
if (!bb) {
return;
}
r_anal_cond_free (bb->cond);
R_FREE (bb->fingerprint);
r_anal_diff_free (bb->diff);
bb->diff = NULL;
R_FREE (bb->op_bytes);
r_anal_switch_op_free (bb->switch_op);
bb->switch_op = NULL;
bb->fingerprint = NULL;
bb->cond = NULL;
R_FREE (bb->label);
R_FREE (bb->op_pos);
R_FREE (bb->parent_reg_arena);
if (bb->prev) {
if (bb->prev->jumpbb == bb) {
bb->prev->jumpbb = NULL;
}
if (bb->prev->failbb == bb) {
bb->prev->failbb = NULL;
}
bb->prev = NULL;
}
if (bb->jumpbb) {
bb->jumpbb->prev = NULL;
bb->jumpbb = NULL;
}
if (bb->failbb) {
bb->failbb->prev = NULL;
bb->failbb = NULL;
}
R_FREE (bb);
}
|
CWE-416
| 182,371 | 3,687 |
33807903809090474830802850779995266307
| null | null | null |
mruby
|
faa4eaf6803bd11669bc324b4c34e7162286bfa3
| 1 |
mrb_class_real(struct RClass* cl)
{
if (cl == 0)
return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
}
return cl;
}
|
CWE-476
| 182,372 | 3,688 |
120395878351176819060032359026014788669
| null | null | null |
mruby
|
778500563a9f7ceba996937dc886bd8cde29b42b
| 1 |
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
{
struct mrb_context *c = fiber_check(mrb, self);
struct mrb_context *old_c = mrb->c;
mrb_value value;
fiber_check_cfunc(mrb, c);
if (resume && c->status == MRB_FIBER_TRANSFERRED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
}
if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {
mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)");
}
if (c->status == MRB_FIBER_TERMINATED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
}
mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
if (c->status == MRB_FIBER_CREATED) {
mrb_value *b, *e;
if (len >= c->stend - c->stack) {
mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber");
}
b = c->stack+1;
e = b + len;
while (b<e) {
*b++ = *a++;
}
c->cibase->argc = (int)len;
value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];
}
else {
value = fiber_result(mrb, a, len);
}
fiber_switch_context(mrb, c);
if (vmexec) {
c->vmexec = TRUE;
value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);
mrb->c = old_c;
}
else {
MARK_CONTEXT_MODIFY(c);
}
return value;
}
|
CWE-125
| 182,373 | 3,689 |
148482836348799476480970672962208608736
| null | null | null |
mruby
|
55edae0226409de25e59922807cb09acb45731a2
| 1 |
mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags = mrb_obj_ptr(self)->flags;
return clone;
}
|
CWE-476
| 182,374 | 3,690 |
229363253371945332954669988513029782012
| null | null | null |
linux
|
6d8c50dcb029872b298eea68cc6209c866fd3e14
| 1 |
static int sock_close(struct inode *inode, struct file *filp)
{
sock_release(SOCKET_I(inode));
return 0;
}
|
CWE-362
| 182,375 | 3,691 |
84494788491717659517723317594552502652
| null | null | null |
mruby
|
b64ce17852b180dfeea81cf458660be41a78974d
| 1 |
init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
|
CWE-824
| 182,378 | 3,693 |
180805267474604722868794255457277270966
| null | null | null |
Espruino
|
ce1924193862d58cb43d3d4d9dada710a8361b89
| 1 |
size_t jsvGetString(const JsVar *v, char *str, size_t len) {
assert(len>0);
const char *s = jsvGetConstString(v);
if (s) {
/* don't use strncpy here because we don't
* want to pad the entire buffer with zeros */
len--;
int l = 0;
while (*s && l<len) {
str[l] = s[l];
l++;
}
str[l] = 0;
return l;
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
str[0] = 0;
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
|
CWE-119
| 182,382 | 3,696 |
159195423267930791337159210665299377372
| null | null | null |
Espruino
|
8a44b04b584b3d3ab1cb68fed410f7ecb165e50e
| 1 |
JsVar *jswrap_graphics_createArrayBuffer(int width, int height, int bpp, JsVar *options) {
if (width<=0 || height<=0 || width>32767 || height>32767) {
jsExceptionHere(JSET_ERROR, "Invalid Size");
return 0;
}
if (!isValidBPP(bpp)) {
jsExceptionHere(JSET_ERROR, "Invalid BPP");
return 0;
}
JsVar *parent = jspNewObject(0, "Graphics");
if (!parent) return 0; // low memory
JsGraphics gfx;
graphicsStructInit(&gfx);
gfx.data.type = JSGRAPHICSTYPE_ARRAYBUFFER;
gfx.data.flags = JSGRAPHICSFLAGS_NONE;
gfx.graphicsVar = parent;
gfx.data.width = (unsigned short)width;
gfx.data.height = (unsigned short)height;
gfx.data.bpp = (unsigned char)bpp;
if (jsvIsObject(options)) {
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "zigzag", 0)))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG);
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "msb", 0)))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_MSB);
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "vertical_byte", 0))) {
if (gfx.data.bpp==1)
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE);
else
jsWarn("vertical_byte only works for 1bpp ArrayBuffers\n");
}
JsVar *colorv = jsvObjectGetChild(options, "color_order", 0);
if (colorv) {
if (jsvIsStringEqual(colorv, "rgb")) ; // The default
else if (!jsvIsStringEqual(colorv, "brg"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BRG);
else if (!jsvIsStringEqual(colorv, "bgr"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BGR);
else if (!jsvIsStringEqual(colorv, "gbr"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GBR);
else if (!jsvIsStringEqual(colorv, "grb"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GRB);
else if (!jsvIsStringEqual(colorv, "rbg"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_RBG);
else
jsWarn("color_order must be 3 characters");
jsvUnLock(colorv);
}
}
lcdInit_ArrayBuffer(&gfx);
graphicsSetVar(&gfx);
return parent;
}
|
CWE-125
| 182,388 | 3,699 |
250096056660193641454945811382560551519
| null | null | null |
Espruino
|
b6d362f6a1f2de0b3e7604848116efb509196bf4
| 1 |
void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
|
CWE-476
| 182,389 | 3,700 |
53958977605870524294019929096202127921
| null | null | null |
linux
|
0a0b98734479aa5b3c671d5190e86273372cab95
| 1 |
int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)
{
struct compat_timex tx32;
if (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))
return -EFAULT;
txc->modes = tx32.modes;
txc->offset = tx32.offset;
txc->freq = tx32.freq;
txc->maxerror = tx32.maxerror;
txc->esterror = tx32.esterror;
txc->status = tx32.status;
txc->constant = tx32.constant;
txc->precision = tx32.precision;
txc->tolerance = tx32.tolerance;
txc->time.tv_sec = tx32.time.tv_sec;
txc->time.tv_usec = tx32.time.tv_usec;
txc->tick = tx32.tick;
txc->ppsfreq = tx32.ppsfreq;
txc->jitter = tx32.jitter;
txc->shift = tx32.shift;
txc->stabil = tx32.stabil;
txc->jitcnt = tx32.jitcnt;
txc->calcnt = tx32.calcnt;
txc->errcnt = tx32.errcnt;
txc->stbcnt = tx32.stbcnt;
return 0;
}
|
CWE-200
| 182,391 | 3,701 |
24540572475707357747624380791273635108
| null | null | null |
radare2
|
77c47cf873dd55b396da60baa2ca83bbd39e4add
| 1 |
static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data)
return 0;
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
}
|
CWE-125
| 182,393 | 3,702 |
249622554086958552832101360272773835516
| null | null | null |
radare2
|
d04c78773f6959bcb427453f8e5b9824d5ba9eff
| 1 |
INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
|
CWE-125
| 182,395 | 3,703 |
145404004174958071732437188449141060878
| null | null | null |
radare2
|
3fcf41ed96ffa25b38029449520c8d0a198745f3
| 1 |
static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
ut8 *buf = calloc (to - from, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, to - from);
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
|
CWE-125
| 182,396 | 3,704 |
227698591978418271254349870679402257144
| null | null | null |
radare2
|
60208765887f5f008b3b9a883f3addc8bdb9c134
| 1 |
static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)
if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {
sym = j;
break;
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
|
CWE-125
| 182,399 | 3,707 |
318868786944603373289699355796067858255
| null | null | null |
radare2
|
4e1cf0d3e6f6fe2552a269def0af1cd2403e266c
| 1 |
static int get_debug_info(struct PE_(r_bin_pe_obj_t)* bin, PE_(image_debug_directory_entry)* dbg_dir_entry, ut8* dbg_data, int dbg_data_len, SDebugInfo* res) {
#define SIZEOF_FILE_NAME 255
int i = 0;
const char* basename;
if (!dbg_data) {
return 0;
}
switch (dbg_dir_entry->Type) {
case IMAGE_DEBUG_TYPE_CODEVIEW:
if (!strncmp ((char*) dbg_data, "RSDS", 4)) {
SCV_RSDS_HEADER rsds_hdr;
init_rsdr_hdr (&rsds_hdr);
if (!get_rsds (dbg_data, dbg_data_len, &rsds_hdr)) {
bprintf ("Warning: Cannot read PE debug info\n");
return 0;
}
snprintf (res->guidstr, GUIDSTR_LEN,
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x%x",
rsds_hdr.guid.data1,
rsds_hdr.guid.data2,
rsds_hdr.guid.data3,
rsds_hdr.guid.data4[0],
rsds_hdr.guid.data4[1],
rsds_hdr.guid.data4[2],
rsds_hdr.guid.data4[3],
rsds_hdr.guid.data4[4],
rsds_hdr.guid.data4[5],
rsds_hdr.guid.data4[6],
rsds_hdr.guid.data4[7],
rsds_hdr.age);
basename = r_file_basename ((char*) rsds_hdr.file_name);
strncpy (res->file_name, (const char*)
basename, sizeof (res->file_name));
res->file_name[sizeof (res->file_name) - 1] = 0;
rsds_hdr.free ((struct SCV_RSDS_HEADER*) &rsds_hdr);
} else if (strncmp ((const char*) dbg_data, "NB10", 4) == 0) {
SCV_NB10_HEADER nb10_hdr;
init_cv_nb10_header (&nb10_hdr);
get_nb10 (dbg_data, &nb10_hdr);
snprintf (res->guidstr, sizeof (res->guidstr),
"%x%x", nb10_hdr.timestamp, nb10_hdr.age);
strncpy (res->file_name, (const char*)
nb10_hdr.file_name, sizeof(res->file_name) - 1);
res->file_name[sizeof (res->file_name) - 1] = 0;
nb10_hdr.free ((struct SCV_NB10_HEADER*) &nb10_hdr);
} else {
bprintf ("CodeView section not NB10 or RSDS\n");
return 0;
}
break;
default:
return 0;
}
while (i < 33) {
res->guidstr[i] = toupper ((int) res->guidstr[i]);
i++;
}
return 1;
}
|
CWE-125
| 182,400 | 3,708 |
38287125071570593044246613241784423157
| null | null | null |
radare2
|
25a3703ef2e015bbe1d1f16f6b2f63bb10dd34f4
| 1 |
INST_HANDLER (sbrx) { // SBRC Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
|
CWE-125
| 182,403 | 3,710 |
117498818528294228480754336319360415158
| null | null | null |
radare2
|
041e53cab7ca33481ae45ecd65ad596976d78e68
| 1 |
INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
|
CWE-125
| 182,406 | 3,713 |
293018390461922754162542553874259203272
| null | null | null |
linux
|
f09444639099584bc4784dfcd85ada67c6f33e0f
| 1 |
static void *etm_setup_aux(int event_cpu, void **pages,
int nr_pages, bool overwrite)
{
int cpu;
cpumask_t *mask;
struct coresight_device *sink;
struct etm_event_data *event_data = NULL;
event_data = alloc_event_data(event_cpu);
if (!event_data)
return NULL;
/*
* In theory nothing prevent tracers in a trace session from being
* associated with different sinks, nor having a sink per tracer. But
* until we have HW with this kind of topology we need to assume tracers
* in a trace session are using the same sink. Therefore go through
* the coresight bus and pick the first enabled sink.
*
* When operated from sysFS users are responsible to enable the sink
* while from perf, the perf tools will do it based on the choice made
* on the cmd line. As such the "enable_sink" flag in sysFS is reset.
*/
sink = coresight_get_enabled_sink(true);
if (!sink)
goto err;
INIT_WORK(&event_data->work, free_event_data);
mask = &event_data->mask;
/* Setup the path for each CPU in a trace session */
for_each_cpu(cpu, mask) {
struct coresight_device *csdev;
csdev = per_cpu(csdev_src, cpu);
if (!csdev)
goto err;
/*
* Building a path doesn't enable it, it simply builds a
* list of devices from source to sink that can be
* referenced later when the path is actually needed.
*/
event_data->path[cpu] = coresight_build_path(csdev, sink);
if (IS_ERR(event_data->path[cpu]))
goto err;
}
if (!sink_ops(sink)->alloc_buffer)
goto err;
/* Get the AUX specific data from the sink buffer */
event_data->snk_config =
sink_ops(sink)->alloc_buffer(sink, cpu, pages,
nr_pages, overwrite);
if (!event_data->snk_config)
goto err;
out:
return event_data;
err:
etm_free_aux(event_data);
event_data = NULL;
goto out;
}
|
CWE-20
| 182,408 | 3,714 |
116152585108812734867606932032521246634
| null | null | null |
linux
|
9de4ee40547fd315d4a0ed1dd15a2fa3559ad707
| 1 |
static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,
unsigned long arg)
{
struct cdrom_changer_info *info;
int ret;
cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n");
if (!CDROM_CAN(CDC_MEDIA_CHANGED))
return -ENOSYS;
/* cannot select disc or select current disc */
if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)
return media_changed(cdi, 1);
if ((unsigned int)arg >= cdi->capacity)
return -EINVAL;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
ret = cdrom_read_mech_status(cdi, info);
if (!ret)
ret = info->slots[arg].change;
kfree(info);
return ret;
}
|
CWE-119
| 182,415 | 3,715 |
336721753792307097791762765764818291734
| null | null | null |
libgit2
|
9844d38bed10e9ff17174434b3421b227ae710f3
| 1 |
int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
if (cmd & 0x01) off = *delta++;
if (cmd & 0x02) off |= *delta++ << 8UL;
if (cmd & 0x04) off |= *delta++ << 16UL;
if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL);
if (cmd & 0x10) len = *delta++;
if (cmd & 0x20) len |= *delta++ << 8UL;
if (cmd & 0x40) len |= *delta++ << 16UL;
if (!len) len = 0x10000;
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
|
CWE-125
| 182,416 | 3,716 |
129712746807172529945615606837622916216
| null | null | null |
libgit2
|
c1577110467b701dcbcf9439ac225ea851b47d22
| 1 |
int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }
if (cmd & 0x01) ADD_DELTA(off, 0UL);
if (cmd & 0x02) ADD_DELTA(off, 8UL);
if (cmd & 0x04) ADD_DELTA(off, 16UL);
if (cmd & 0x08) ADD_DELTA(off, 24UL);
if (cmd & 0x10) ADD_DELTA(len, 0UL);
if (cmd & 0x20) ADD_DELTA(len, 8UL);
if (cmd & 0x40) ADD_DELTA(len, 16UL);
if (!len) len = 0x10000;
#undef ADD_DELTA
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
|
CWE-125
| 182,417 | 3,717 |
228984589945149856757342211749769930425
| null | null | null |
ngiflib
|
cf429e0a2fe26b5f01ce0c8e9b79432e94509b6e
| 1 |
static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
|
CWE-119
| 182,418 | 3,718 |
208688875586295621212827610786487999880
| null | null | null |
ngiflib
|
b588a2249c7abbfc52173e32ee11d6facef82f89
| 1 |
static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
|
CWE-119
| 182,419 | 3,719 |
284105126342844775400312315715063783216
| null | null | null |
linux
|
73223e4e2e3867ebf033a5a8eb2e5df0158ccc99
| 1 |
static long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
err = lookup_node(addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = next_node_in(current->il_prev, pol->v.nodes);
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
if (vma) {
up_read(¤t->mm->mmap_sem);
vma = NULL;
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(¤t->mm->mmap_sem);
return err;
}
|
CWE-416
| 182,420 | 3,720 |
152269556434917934062798078757331326818
| null | null | null |
file
|
a642587a9c9e2dd7feacdf513c3643ce26ad3c22
| 1 |
do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
CAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
|
CWE-125
| 182,426 | 3,721 |
272730783674373486565961769977123106769
| null | null | null |
mruby
|
b51b21fc63c9805862322551387d9036f2b63433
| 1 |
mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)
{
mrb_value orig;
mrb_value buf;
struct mrb_io *fptr_copy;
struct mrb_io *fptr_orig;
mrb_bool failed = TRUE;
mrb_get_args(mrb, "o", &orig);
fptr_copy = (struct mrb_io *)DATA_PTR(copy);
if (fptr_copy != NULL) {
fptr_finalize(mrb, fptr_copy, FALSE);
mrb_free(mrb, fptr_copy);
}
fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);
fptr_orig = io_get_open_fptr(mrb, orig);
DATA_TYPE(copy) = &mrb_io_type;
DATA_PTR(copy) = fptr_copy;
buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf"));
mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf);
fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);
if (failed) {
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd);
if (fptr_orig->fd2 != -1) {
fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);
if (failed) {
close(fptr_copy->fd);
mrb_sys_fail(mrb, 0);
}
mrb_fd_cloexec(mrb, fptr_copy->fd2);
}
fptr_copy->pid = fptr_orig->pid;
fptr_copy->readable = fptr_orig->readable;
fptr_copy->writable = fptr_orig->writable;
fptr_copy->sync = fptr_orig->sync;
fptr_copy->is_socket = fptr_orig->is_socket;
return copy;
}
|
CWE-416
| 182,427 | 3,722 |
150634863447224435072251929801425738408
| null | null | null |
mruby
|
1905091634a6a2925c911484434448e568330626
| 1 |
mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc)
{
/* mrb_assert(mrb_proc_cfunc_p(proc)) */
mrb_irep *irep = proc->body.irep;
mrb_value *pool = irep->pool;
mrb_sym *syms = irep->syms;
mrb_code i;
int ai = mrb_gc_arena_save(mrb);
struct mrb_jmpbuf *prev_jmp = mrb->jmp;
struct mrb_jmpbuf c_jmp;
#ifdef DIRECT_THREADED
static void *optable[] = {
&&L_OP_NOP, &&L_OP_MOVE,
&&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL,
&&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF,
&&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL,
&&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV,
&&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST,
&&L_OP_GETUPVAR, &&L_OP_SETUPVAR,
&&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT,
&&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP,
&&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND,
&&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER,
&&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH,
&&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV,
&&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE,
&&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST,
&&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH,
&&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS,
&&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC,
&&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS,
&&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR,
};
#endif
mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:
MRB_TRY(&c_jmp) {
if (exc_catched) {
exc_catched = FALSE;
if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
goto L_BREAK;
goto L_RAISE;
}
mrb->jmp = &c_jmp;
mrb->c->ci->proc = proc;
mrb->c->ci->nregs = irep->nregs;
#define regs (mrb->c->stack)
INIT_DISPATCH {
CASE(OP_NOP) {
/* do nothing */
NEXT;
}
CASE(OP_MOVE) {
/* A B R(A) := R(B) */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = regs[b];
NEXT;
}
CASE(OP_LOADL) {
/* A Bx R(A) := Pool(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
#ifdef MRB_WORD_BOXING
mrb_value val = pool[bx];
#ifndef MRB_WITHOUT_FLOAT
if (mrb_float_p(val)) {
val = mrb_float_value(mrb, mrb_float(val));
}
#endif
regs[a] = val;
#else
regs[a] = pool[bx];
#endif
NEXT;
}
CASE(OP_LOADI) {
/* A sBx R(A) := sBx */
int a = GETARG_A(i);
mrb_int bx = GETARG_sBx(i);
SET_INT_VALUE(regs[a], bx);
NEXT;
}
CASE(OP_LOADSYM) {
/* A Bx R(A) := Syms(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
SET_SYM_VALUE(regs[a], syms[bx]);
NEXT;
}
CASE(OP_LOADSELF) {
/* A R(A) := self */
int a = GETARG_A(i);
regs[a] = regs[0];
NEXT;
}
CASE(OP_LOADT) {
/* A R(A) := true */
int a = GETARG_A(i);
SET_TRUE_VALUE(regs[a]);
NEXT;
}
CASE(OP_LOADF) {
/* A R(A) := false */
int a = GETARG_A(i);
SET_FALSE_VALUE(regs[a]);
NEXT;
}
CASE(OP_GETGLOBAL) {
/* A Bx R(A) := getglobal(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_gv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETGLOBAL) {
/* A Bx setglobal(Syms(Bx), R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_gv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETSPECIAL) {
/* A Bx R(A) := Special[Bx] */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_special_get(mrb, bx);
regs[a] = val;
NEXT;
}
CASE(OP_SETSPECIAL) {
/* A Bx Special[Bx] := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_special_set(mrb, bx, regs[a]);
NEXT;
}
CASE(OP_GETIV) {
/* A Bx R(A) := ivget(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_iv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETIV) {
/* A Bx ivset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_iv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCV) {
/* A Bx R(A) := cvget(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val;
ERR_PC_SET(mrb, pc);
val = mrb_vm_cv_get(mrb, syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCV) {
/* A Bx cvset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_cv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCONST) {
/* A Bx R(A) := constget(Syms(Bx)) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_sym sym = syms[bx];
ERR_PC_SET(mrb, pc);
val = mrb_vm_const_get(mrb, sym);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCONST) {
/* A Bx constset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_const_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETMCNST) {
/* A Bx R(A) := R(A)::Syms(Bx) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
ERR_PC_SET(mrb, pc);
val = mrb_const_get(mrb, regs[a], syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETMCNST) {
/* A Bx R(A+1)::Syms(Bx) := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETUPVAR) {
/* A B C R(A) := uvget(B,C) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value *regs_a = regs + a;
struct REnv *e = uvenv(mrb, c);
if (!e) {
*regs_a = mrb_nil_value();
}
else {
*regs_a = e->stack[b];
}
NEXT;
}
CASE(OP_SETUPVAR) {
/* A B C uvset(B,C,R(A)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
struct REnv *e = uvenv(mrb, c);
if (e) {
mrb_value *regs_a = regs + a;
if (b < MRB_ENV_STACK_LEN(e)) {
e->stack[b] = *regs_a;
mrb_write_barrier(mrb, (struct RBasic*)e);
}
}
NEXT;
}
CASE(OP_JMP) {
/* sBx pc+=sBx */
int sbx = GETARG_sBx(i);
pc += sbx;
JUMP;
}
CASE(OP_JMPIF) {
/* A sBx if R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_JMPNOT) {
/* A sBx if !R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (!mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_ONERR) {
/* sBx pc+=sBx on exception */
int sbx = GETARG_sBx(i);
if (mrb->c->rsize <= mrb->c->ci->ridx) {
if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE;
else mrb->c->rsize *= 2;
mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize);
}
mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx;
NEXT;
}
CASE(OP_RESCUE) {
/* A B R(A) := exc; clear(exc); R(B) := matched (bool) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value exc;
if (c == 0) {
exc = mrb_obj_value(mrb->exc);
mrb->exc = 0;
}
else { /* continued; exc taken from R(A) */
exc = regs[a];
}
if (b != 0) {
mrb_value e = regs[b];
struct RClass *ec;
switch (mrb_type(e)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
break;
default:
{
mrb_value exc;
exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"class or module required for rescue clause");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
ec = mrb_class_ptr(e);
regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
}
if (a != 0 && c == 0) {
regs[a] = exc;
}
NEXT;
}
CASE(OP_POPERR) {
/* A A.times{rescue_pop()} */
int a = GETARG_A(i);
mrb->c->ci->ridx -= a;
NEXT;
}
CASE(OP_RAISE) {
/* A raise(R(A)) */
int a = GETARG_A(i);
mrb_exc_set(mrb, regs[a]);
goto L_RAISE;
}
CASE(OP_EPUSH) {
/* Bx ensure_push(SEQ[Bx]) */
int bx = GETARG_Bx(i);
struct RProc *p;
p = mrb_closure_new(mrb, irep->reps[bx]);
/* push ensure_stack */
if (mrb->c->esize <= mrb->c->eidx+1) {
if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE;
else mrb->c->esize *= 2;
mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize);
}
mrb->c->ensure[mrb->c->eidx++] = p;
mrb->c->ensure[mrb->c->eidx] = NULL;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EPOP) {
/* A A.times{ensure_pop().call} */
int a = GETARG_A(i);
mrb_callinfo *ci = mrb->c->ci;
int n, epos = ci->epos;
mrb_value self = regs[0];
struct RClass *target_class = ci->target_class;
if (mrb->c->eidx <= epos) {
NEXT;
}
if (a > mrb->c->eidx - epos)
a = mrb->c->eidx - epos;
pc = pc + 1;
for (n=0; n<a; n++) {
proc = mrb->c->ensure[epos+n];
mrb->c->ensure[epos+n] = NULL;
if (proc == NULL) continue;
irep = proc->body.irep;
ci = cipush(mrb);
ci->mid = ci[-1].mid;
ci->argc = 0;
ci->proc = proc;
ci->stackent = mrb->c->stack;
ci->nregs = irep->nregs;
ci->target_class = target_class;
ci->pc = pc;
ci->acc = ci[-1].nregs;
mrb->c->stack += ci->acc;
stack_extend(mrb, ci->nregs);
regs[0] = self;
pc = irep->iseq;
}
pool = irep->pool;
syms = irep->syms;
mrb->c->eidx = epos;
JUMP;
}
CASE(OP_LOADNIL) {
/* A R(A) := nil */
int a = GETARG_A(i);
SET_NIL_VALUE(regs[a]);
NEXT;
}
CASE(OP_SENDB) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/
/* fall through */
};
L_SEND:
CASE(OP_SEND) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = syms[GETARG_B(i)];
mrb_assert(bidx < ci->nregs);
recv = regs[a];
if (GET_OPCODE(i) != OP_SENDB) {
SET_NIL_VALUE(regs[bidx]);
blk = regs[bidx];
}
else {
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack might have been reallocated during mrb_convert_type(),
see #3622 */
regs[bidx] = blk;
}
}
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
if (argc >= 0) {
if (a+2 >= irep->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid));
mid = missing;
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->argc = argc;
ci->pc = pc + 1;
ci->acc = a;
/* prepare stack */
mrb->c->stack += a;
if (MRB_METHOD_CFUNC_P(m)) {
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
struct RProc *p = MRB_METHOD_PROC(m);
ci->proc = p;
recv = p->body.func(mrb, recv);
}
else {
recv = MRB_METHOD_FUNC(m)(mrb, recv);
}
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (GET_OPCODE(i) == OP_SENDB) {
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return recv;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = recv;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_FSEND) {
/* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */
/* not implemented yet */
NEXT;
}
CASE(OP_CALL) {
/* A R(A) := self.call(frame.argc, frame.argv) */
mrb_callinfo *ci;
mrb_value recv = mrb->c->stack[0];
struct RProc *m = mrb_proc_ptr(recv);
/* replace callinfo */
ci = mrb->c->ci;
ci->target_class = MRB_PROC_TARGET_CLASS(m);
ci->proc = m;
if (MRB_PROC_ENV_P(m)) {
mrb_sym mid;
struct REnv *e = MRB_PROC_ENV(m);
mid = e->mid;
if (mid) ci->mid = mid;
if (!e->stack) {
e->stack = mrb->c->stack;
}
}
/* prepare stack */
if (MRB_PROC_CFUNC_P(m)) {
recv = MRB_PROC_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
/* pop stackpos */
ci = mrb->c->ci;
mrb->c->stack = ci->stackent;
regs[ci->acc] = recv;
pc = ci->pc;
cipop(mrb);
irep = mrb->c->ci->proc->body.irep;
pool = irep->pool;
syms = irep->syms;
JUMP;
}
else {
/* setup environment for calling method */
proc = m;
irep = m->body.irep;
if (!irep) {
mrb->c->stack[0] = mrb_nil_value();
goto L_RETURN;
}
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
if (ci->argc < 0) {
if (irep->nregs > 3) {
stack_clear(regs+3, irep->nregs-3);
}
}
else if (ci->argc+2 < irep->nregs) {
stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2);
}
if (MRB_PROC_ENV_P(m)) {
regs[0] = MRB_PROC_ENV(m)->stack[0];
}
pc = irep->iseq;
JUMP;
}
}
CASE(OP_SUPER) {
/* A C R(A) := super(R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = ci->mid;
struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc);
mrb_assert(bidx < ci->nregs);
if (mid == 0 || !target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (target_class->tt == MRB_TT_MODULE) {
target_class = ci->target_class;
if (target_class->tt != MRB_TT_ICLASS) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "superclass info lost [mruby limitations]");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
recv = regs[0];
if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"self has wrong type to call super in this context");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack or ci stack might have been reallocated during
mrb_convert_type(), see #3622 and #3784 */
regs[bidx] = blk;
ci = mrb->c->ci;
}
c = target_class->super;
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
if (mid != missing) {
c = mrb_class(mrb, recv);
}
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (argc >= 0) {
if (a+2 >= ci->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid));
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->pc = pc + 1;
ci->argc = argc;
/* prepare stack */
mrb->c->stack += a;
mrb->c->stack[0] = recv;
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v;
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
ci->proc = MRB_METHOD_PROC(m);
}
v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return v;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = v;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* fill callinfo */
ci->acc = a;
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_ARGARY) {
/* A Bx R(A) := argument array (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) {
mrb_value exc;
L_NOSUPER:
exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e) goto L_NOSUPER;
if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1)
goto L_NOSUPER;
stack = e->stack + 1;
}
if (r == 0) {
regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
}
else {
mrb_value *pp = NULL;
struct RArray *rest;
int len = 0;
if (mrb_array_p(stack[m1])) {
struct RArray *ary = mrb_ary_ptr(stack[m1]);
pp = ARY_PTR(ary);
len = (int)ARY_LEN(ary);
}
regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
rest = mrb_ary_ptr(regs[a]);
if (m1 > 0) {
stack_copy(ARY_PTR(rest), stack, m1);
}
if (len > 0) {
stack_copy(ARY_PTR(rest)+m1, pp, len);
}
if (m2 > 0) {
stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
}
ARY_SET_LEN(rest, m1+len+m2);
}
regs[a+1] = stack[m1+r+m2];
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ENTER) {
/* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */
/* number of optional arguments times OP_JMP should follow */
mrb_aspec ax = GETARG_Ax(i);
int m1 = MRB_ASPEC_REQ(ax);
int o = MRB_ASPEC_OPT(ax);
int r = MRB_ASPEC_REST(ax);
int m2 = MRB_ASPEC_POST(ax);
/* unused
int k = MRB_ASPEC_KEY(ax);
int kd = MRB_ASPEC_KDICT(ax);
int b = MRB_ASPEC_BLOCK(ax);
*/
int argc = mrb->c->ci->argc;
mrb_value *argv = regs+1;
mrb_value *argv0 = argv;
int len = m1 + o + r + m2;
mrb_value *blk = &argv[argc < 0 ? 1 : argc];
if (argc < 0) {
struct RArray *ary = mrb_ary_ptr(regs[1]);
argv = ARY_PTR(ary);
argc = (int)ARY_LEN(ary);
mrb_gc_protect(mrb, regs[1]);
}
if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) {
if (argc >= 0) {
if (argc < m1 + m2 || (r == 0 && argc > len)) {
argnum_error(mrb, m1+m2);
goto L_RAISE;
}
}
}
else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
mrb_gc_protect(mrb, argv[0]);
argc = (int)RARRAY_LEN(argv[0]);
argv = RARRAY_PTR(argv[0]);
}
if (argc < len) {
int mlen = m2;
if (argc < m1+m2) {
if (m1 < argc)
mlen = argc - m1;
else
mlen = 0;
}
regs[len+1] = *blk; /* move block */
SET_NIL_VALUE(regs[argc+1]);
if (argv0 != argv) {
value_move(®s[1], argv, argc-mlen); /* m1 + o */
}
if (argc < m1) {
stack_clear(®s[argc+1], m1-argc);
}
if (mlen) {
value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
}
if (mlen < m2) {
stack_clear(®s[len-m2+mlen+1], m2-mlen);
}
if (r) {
regs[m1+o+1] = mrb_ary_new_capa(mrb, 0);
}
if (o == 0 || argc < m1+m2) pc++;
else
pc += argc - m1 - m2 + 1;
}
else {
int rnum = 0;
if (argv0 != argv) {
regs[len+1] = *blk; /* move block */
value_move(®s[1], argv, m1+o);
}
if (r) {
rnum = argc-m1-o-m2;
regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
}
if (m2) {
if (argc-m2 > m1) {
value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
}
}
if (argv0 == argv) {
regs[len+1] = *blk; /* move block */
}
pc += o + 1;
}
mrb->c->ci->argc = len;
/* clear local (but non-argument) variables */
if (irep->nlocals-len-2 > 0) {
stack_clear(®s[len+2], irep->nlocals-len-2);
}
JUMP;
}
CASE(OP_KARG) {
/* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */
/* if C == 2; raise unless kdict.empty? */
/* OP_JMP should follow to skip init code */
NEXT;
}
CASE(OP_KDICT) {
/* A C R(A) := kdict */
NEXT;
}
L_RETURN:
i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL);
/* fall through */
CASE(OP_RETURN) {
/* A B return R(A) (B=normal,in-block return/break) */
mrb_callinfo *ci;
#define ecall_adjust() do {\
ptrdiff_t cioff = ci - mrb->c->cibase;\
ecall(mrb);\
ci = mrb->c->cibase + cioff;\
} while (0)
ci = mrb->c->ci;
if (ci->mid) {
mrb_value blk;
if (ci->argc < 0) {
blk = regs[2];
}
else {
blk = regs[ci->argc+1];
}
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (!MRB_PROC_STRICT_P(p) &&
ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (mrb->exc) {
mrb_callinfo *ci0;
L_RAISE:
ci0 = ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) goto L_FTOP;
goto L_RESCUE;
}
while (ci[0].ridx == ci[-1].ridx) {
cipop(mrb);
mrb->c->stack = ci->stackent;
if (ci->acc == CI_ACC_SKIP && prev_jmp) {
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) {
L_FTOP: /* fiber top */
if (mrb->c == mrb->root_c) {
mrb->c->stack = mrb->c->stbase;
goto L_STOP;
}
else {
struct mrb_context *c = mrb->c;
while (c->eidx > ci->epos) {
ecall_adjust();
}
if (c->fib) {
mrb_write_barrier(mrb, (struct RBasic*)c->fib);
}
mrb->c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
goto L_RAISE;
}
}
break;
}
/* call ensure only when we skip this callinfo */
if (ci[0].ridx == ci[-1].ridx) {
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
}
}
L_RESCUE:
if (ci->ridx == 0) goto L_STOP;
proc = ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci < ci0) {
mrb->c->stack = ci[1].stackent;
}
stack_extend(mrb, irep->nregs);
pc = mrb->c->rescue[--ci->ridx];
}
else {
int acc;
mrb_value v;
struct RProc *dst;
ci = mrb->c->ci;
v = regs[GETARG_A(i)];
mrb_gc_protect(mrb, v);
switch (GETARG_B(i)) {
case OP_R_RETURN:
/* Fall through to OP_R_NORMAL otherwise */
if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
mrb_callinfo *cibase = mrb->c->cibase;
dst = top_proc(mrb, proc);
if (MRB_PROC_ENV_P(dst)) {
struct REnv *e = MRB_PROC_ENV(dst);
if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
}
while (cibase <= ci && ci->proc != dst) {
if (ci->acc < 0) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
ci--;
}
if (ci <= cibase) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
break;
}
case OP_R_NORMAL:
NORMAL_RETURN:
if (ci == mrb->c->cibase) {
struct mrb_context *c;
if (!mrb->c->prev) { /* toplevel return */
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
if (mrb->c->prev->ci == mrb->c->prev->cibase) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, "double resume");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
while (mrb->c->eidx > 0) {
ecall(mrb);
}
/* automatic yield at the end */
c = mrb->c;
c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
mrb->c->status = MRB_FIBER_RUNNING;
ci = mrb->c->ci;
}
break;
case OP_R_BREAK:
if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
if (MRB_PROC_ORPHAN_P(proc)) {
mrb_value exc;
L_BREAK_ERROR:
exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR,
"break from proc-closure");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) {
goto L_BREAK_ERROR;
}
else {
struct REnv *e = MRB_PROC_ENV(proc);
if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) {
goto L_BREAK_ERROR;
}
if (e->cxt != mrb->c) {
goto L_BREAK_ERROR;
}
}
while (mrb->c->eidx > mrb->c->ci->epos) {
ecall_adjust();
}
/* break from fiber block */
if (ci == mrb->c->cibase && ci->pc) {
struct mrb_context *c = mrb->c;
mrb->c = c->prev;
c->prev = NULL;
ci = mrb->c->ci;
}
if (ci->acc < 0) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->exc = (struct RObject*)break_new(mrb, proc, v);
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
if (FALSE) {
L_BREAK:
v = ((struct RBreak*)mrb->exc)->val;
proc = ((struct RBreak*)mrb->exc)->proc;
mrb->exc = NULL;
ci = mrb->c->ci;
}
mrb->c->stack = ci->stackent;
proc = proc->upper;
while (mrb->c->cibase < ci && ci[-1].proc != proc) {
if (ci[-1].acc == CI_ACC_SKIP) {
while (ci < mrb->c->ci) {
cipop(mrb);
}
goto L_BREAK_ERROR;
}
ci--;
}
if (ci == mrb->c->cibase) {
goto L_BREAK_ERROR;
}
break;
default:
/* cannot happen */
break;
}
while (ci < mrb->c->ci) {
cipop(mrb);
}
ci[0].ridx = ci[-1].ridx;
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
if (mrb->c->vmexec && !ci->target_class) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->jmp = prev_jmp;
return v;
}
acc = ci->acc;
mrb->c->stack = ci->stackent;
cipop(mrb);
if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) {
mrb_gc_arena_restore(mrb, ai);
mrb->jmp = prev_jmp;
return v;
}
pc = ci->pc;
ci = mrb->c->ci;
DEBUG(fprintf(stderr, "from :%s\n", mrb_sym2name(mrb, ci->mid)));
proc = mrb->c->ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
regs[acc] = v;
mrb_gc_arena_restore(mrb, ai);
}
JUMP;
}
CASE(OP_TAILCALL) {
/* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int n = GETARG_C(i);
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci;
mrb_value recv;
mrb_sym mid = syms[b];
recv = regs[a];
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value sym = mrb_symbol_value(mid);
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args;
if (n == CALL_MAXARGS) {
args = regs[a+1];
}
else {
args = mrb_ary_new_from_values(mrb, n, regs+a+1);
}
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (n == CALL_MAXARGS) {
mrb_ary_unshift(mrb, regs[a+1], sym);
}
else {
value_move(regs+a+2, regs+a+1, ++n);
regs[a+1] = sym;
}
}
/* replace callinfo */
ci = mrb->c->ci;
ci->mid = mid;
ci->target_class = c;
if (n == CALL_MAXARGS) {
ci->argc = -1;
}
else {
ci->argc = n;
}
/* move stack */
value_move(mrb->c->stack, ®s[a], ci->argc+1);
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb->c->stack[0] = v;
mrb_gc_arena_restore(mrb, ai);
goto L_RETURN;
}
else {
/* setup environment for calling method */
struct RProc *p = MRB_METHOD_PROC(m);
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci->argc < 0) {
stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs);
}
else {
stack_extend(mrb, irep->nregs);
}
pc = irep->iseq;
}
JUMP;
}
CASE(OP_BLKPUSH) {
/* A Bx R(A) := block (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) ||
MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
stack = e->stack + 1;
}
if (mrb_nil_p(stack[m1+r+m2])) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
regs[a] = stack[m1+r+m2];
NEXT;
}
#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH_BODY(op,v1,v2) do {\
v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\
} while(0)
CASE(OP_ADD) {
/* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
mrb_value *regs_a = regs + a;
x = mrb_fixnum(regs_a[0]);
y = mrb_fixnum(regs_a[1]);
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_float);
#endif
break;
#endif
case TYPES2(MRB_TT_STRING,MRB_TT_STRING):
regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);
break;
default:
goto L_SEND;
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SUB) {
/* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_MUL) {
/* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_mul_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_DIV) {
/* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/
int a = GETARG_A(i);
#ifndef MRB_WITHOUT_FLOAT
double x, y, f;
#endif
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
#ifdef MRB_WITHOUT_FLOAT
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_INT_VALUE(regs[a], y ? x / y : 0);
}
break;
#else
x = (mrb_float)mrb_fixnum(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
x = (mrb_float)mrb_fixnum(regs[a]);
y = mrb_float(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
x = mrb_float(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
x = mrb_float(regs[a]);
y = mrb_float(regs[a+1]);
break;
#endif
default:
goto L_SEND;
}
#ifndef MRB_WITHOUT_FLOAT
if (y == 0) {
if (x > 0) f = INFINITY;
else if (x < 0) f = -INFINITY;
else /* if (x == 0) */ f = NAN;
}
else {
f = x / y;
}
SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
NEXT;
}
CASE(OP_ADDI) {
/* A B C R(A) := R(A)+C (Syms[B]=:+)*/
int a = GETARG_A(i);
/* need to check if + is overridden */
switch (mrb_type(regs[a])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i));
}
#else
mrb_float(regs[a]) += GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs[a+1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
CASE(OP_SUBI) {
/* A B C R(A) := R(A)-C (Syms[B]=:-)*/
int a = GETARG_A(i);
mrb_value *regs_a = regs + a;
/* need to check if + is overridden */
switch (mrb_type(regs_a[0])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs_a[0]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs_a[0], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i));
}
#else
mrb_float(regs_a[0]) -= GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs_a[1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))
#ifdef MRB_WITHOUT_FLOAT
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#else
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_float,mrb_float);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#endif
CASE(OP_EQ) {
/* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/
int a = GETARG_A(i);
if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
SET_TRUE_VALUE(regs[a]);
}
else {
OP_CMP(==);
}
NEXT;
}
CASE(OP_LT) {
/* A B C R(A) := R(A)<R(A+1) (Syms[B]=:<,C=1)*/
int a = GETARG_A(i);
OP_CMP(<);
NEXT;
}
CASE(OP_LE) {
/* A B C R(A) := R(A)<=R(A+1) (Syms[B]=:<=,C=1)*/
int a = GETARG_A(i);
OP_CMP(<=);
NEXT;
}
CASE(OP_GT) {
/* A B C R(A) := R(A)>R(A+1) (Syms[B]=:>,C=1)*/
int a = GETARG_A(i);
OP_CMP(>);
NEXT;
}
CASE(OP_GE) {
/* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/
int a = GETARG_A(i);
OP_CMP(>=);
NEXT;
}
CASE(OP_ARRAY) {
/* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]);
regs[a] = v;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYCAT) {
/* A B mrb_ary_concat(R(A),R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_value splat = mrb_ary_splat(mrb, regs[b]);
mrb_ary_concat(mrb, regs[a], splat);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYPUSH) {
/* A B R(A).push(R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_ary_push(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_AREF) {
/* A B C R(A) := R(B)[C] */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = regs[b];
if (!mrb_array_p(v)) {
if (c == 0) {
regs[a] = v;
}
else {
SET_NIL_VALUE(regs[a]);
}
}
else {
v = mrb_ary_ref(mrb, v, c);
regs[a] = v;
}
NEXT;
}
CASE(OP_ASET) {
/* A B C R(B)[C] := R(A) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_ary_set(mrb, regs[b], c, regs[a]);
NEXT;
}
CASE(OP_APOST) {
/* A B C *R(A),R(A+1)..R(A+C) := R(A) */
int a = GETARG_A(i);
mrb_value v = regs[a];
int pre = GETARG_B(i);
int post = GETARG_C(i);
struct RArray *ary;
int len, idx;
if (!mrb_array_p(v)) {
v = mrb_ary_new_from_values(mrb, 1, ®s[a]);
}
ary = mrb_ary_ptr(v);
len = (int)ARY_LEN(ary);
if (len > pre + post) {
v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
regs[a++] = v;
while (post--) {
regs[a++] = ARY_PTR(ary)[len-post-1];
}
}
else {
v = mrb_ary_new_capa(mrb, 0);
regs[a++] = v;
for (idx=0; idx+pre<len; idx++) {
regs[a+idx] = ARY_PTR(ary)[pre+idx];
}
while (idx < post) {
SET_NIL_VALUE(regs[a+idx]);
idx++;
}
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRING) {
/* A Bx R(A) := str_new(Lit(Bx)) */
mrb_int a = GETARG_A(i);
mrb_int bx = GETARG_Bx(i);
mrb_value str = mrb_str_dup(mrb, pool[bx]);
regs[a] = str;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRCAT) {
/* A B R(A).concat(R(B)) */
mrb_int a = GETARG_A(i);
mrb_int b = GETARG_B(i);
mrb_str_concat(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_HASH) {
/* A B C R(A) := hash_new(R(B),R(B+1)..R(B+C)) */
int b = GETARG_B(i);
int c = GETARG_C(i);
int lim = b+c*2;
mrb_value hash = mrb_hash_new_capa(mrb, c);
while (b < lim) {
mrb_hash_set(mrb, hash, regs[b], regs[b+1]);
b+=2;
}
regs[GETARG_A(i)] = hash;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_LAMBDA) {
/* A b c R(A) := lambda(SEQ[b],c) (b:c = 14:2) */
struct RProc *p;
int a = GETARG_A(i);
int b = GETARG_b(i);
int c = GETARG_c(i);
mrb_irep *nirep = irep->reps[b];
if (c & OP_L_CAPTURE) {
p = mrb_closure_new(mrb, nirep);
}
else {
p = mrb_proc_new(mrb, nirep);
p->flags |= MRB_PROC_SCOPE;
}
if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
regs[a] = mrb_obj_value(p);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_OCLASS) {
/* A R(A) := ::Object */
regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class);
NEXT;
}
CASE(OP_CLASS) {
/* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base, super;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
super = regs[a+1];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_class(mrb, base, super, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_MODULE) {
/* A B R(A) := newmodule(R(A),Syms(B)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_module(mrb, base, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EXEC) {
/* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_callinfo *ci;
mrb_value recv = regs[a];
struct RProc *p;
mrb_irep *nirep = irep->reps[bx];
/* prepare closure */
p = mrb_proc_new(mrb, nirep);
p->c = NULL;
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
p->flags |= MRB_PROC_SCOPE;
/* prepare call stack */
ci = cipush(mrb);
ci->pc = pc + 1;
ci->acc = a;
ci->mid = 0;
ci->stackent = mrb->c->stack;
ci->argc = 0;
ci->target_class = mrb_class_ptr(recv);
/* prepare stack */
mrb->c->stack += a;
/* setup block to call */
ci->proc = p;
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
stack_clear(regs+1, ci->nregs-1);
pc = irep->iseq;
JUMP;
}
CASE(OP_METHOD) {
/* A B R(A).newmethod(Syms(B),R(A+1)) */
int a = GETARG_A(i);
struct RClass *c = mrb_class_ptr(regs[a]);
struct RProc *p = mrb_proc_ptr(regs[a+1]);
mrb_method_t m;
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SCLASS) {
/* A B R(A) := R(B).singleton_class */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = mrb_singleton_class(mrb, regs[b]);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_TCLASS) {
/* A R(A) := target_class */
if (!mrb->c->ci->target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, "no target class or module");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class);
NEXT;
}
CASE(OP_RANGE) {
/* A B C R(A) := range_new(R(B),R(B+1),C) */
int b = GETARG_B(i);
mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i));
regs[GETARG_A(i)] = val;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_DEBUG) {
/* A B C debug print R(A),R(B),R(C) */
#ifdef MRB_ENABLE_DEBUG_HOOK
mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_DISABLE_STDIO
printf("OP_DEBUG %d %d %d\n", GETARG_A(i), GETARG_B(i), GETARG_C(i));
#else
abort();
#endif
#endif
NEXT;
}
CASE(OP_STOP) {
/* stop VM */
L_STOP:
while (mrb->c->eidx > 0) {
ecall(mrb);
}
ERR_PC_CLR(mrb);
mrb->jmp = prev_jmp;
if (mrb->exc) {
return mrb_obj_value(mrb->exc);
}
return regs[irep->nlocals];
}
CASE(OP_ERR) {
/* Bx raise RuntimeError with message Lit(Bx) */
mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]);
mrb_value exc;
if (GETARG_A(i) == 0) {
exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg);
}
else {
exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg);
}
ERR_PC_SET(mrb, pc);
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
END_DISPATCH;
#undef regs
}
MRB_CATCH(&c_jmp) {
exc_catched = TRUE;
goto RETRY_TRY_BLOCK;
}
MRB_END_EXC(&c_jmp);
}
|
CWE-190
| 182,428 | 3,723 |
140181947558548585333504127925313669075
| null | null | null |
linux
|
4ea77014af0d6205b05503d1c7aac6eace11d473
| 1 |
static int kill_something_info(int sig, struct siginfo *info, pid_t pid)
{
int ret;
if (pid > 0) {
rcu_read_lock();
ret = kill_pid_info(sig, info, find_vpid(pid));
rcu_read_unlock();
return ret;
}
read_lock(&tasklist_lock);
if (pid != -1) {
ret = __kill_pgrp_info(sig, info,
pid ? find_vpid(-pid) : task_pgrp(current));
} else {
int retval = 0, count = 0;
struct task_struct * p;
for_each_process(p) {
if (task_pid_vnr(p) > 1 &&
!same_thread_group(p, current)) {
int err = group_send_sig_info(sig, info, p);
++count;
if (err != -EPERM)
retval = err;
}
}
ret = count ? retval : -ESRCH;
}
read_unlock(&tasklist_lock);
return ret;
}
|
CWE-119
| 182,429 | 3,724 |
233236629790152586691706983027629350757
| null | null | null |
linux
|
9903e41ae1f5d50c93f268ca3304d4d7c64b9311
| 1 |
static int hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
}
|
CWE-476
| 182,431 | 3,725 |
198852483878198214181690678349829339386
| null | null | null |
mbedtls
|
740b218386083dc708ce98ccc94a63a95cd5629e
| 1 |
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
|
CWE-125
| 182,437 | 3,729 |
249660299586144348379439142914448427964
| null | null | null |
mbedtls
|
a1098f81c252b317ad34ea978aea2bc47760b215
| 1 |
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
|
CWE-119
| 182,438 | 3,730 |
126675777471818343186858047579529685939
| null | null | null |
openvpn
|
1394192b210cb3c6624a7419bcf3ff966742e79b
| 1 |
GetStartupData(HANDLE pipe, STARTUP_DATA *sud)
{
size_t size, len;
BOOL ret = FALSE;
WCHAR *data = NULL;
DWORD bytes, read;
bytes = PeekNamedPipeAsync(pipe, 1, &exit_event);
if (bytes == 0)
{
MsgToEventLog(M_SYSERR, TEXT("PeekNamedPipeAsync failed"));
ReturnLastError(pipe, L"PeekNamedPipeAsync");
goto out;
}
size = bytes / sizeof(*data);
if (size == 0)
{
MsgToEventLog(M_SYSERR, TEXT("malformed startup data: 1 byte received"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
data = malloc(bytes);
if (data == NULL)
{
MsgToEventLog(M_SYSERR, TEXT("malloc failed"));
ReturnLastError(pipe, L"malloc");
goto out;
}
read = ReadPipeAsync(pipe, data, bytes, 1, &exit_event);
if (bytes != read)
{
MsgToEventLog(M_SYSERR, TEXT("ReadPipeAsync failed"));
ReturnLastError(pipe, L"ReadPipeAsync");
goto out;
}
if (data[size - 1] != 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data is not NULL terminated"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->directory = data;
len = wcslen(sud->directory) + 1;
size -= len;
if (size <= 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data ends at working directory"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->options = sud->directory + len;
len = wcslen(sud->options) + 1;
size -= len;
if (size <= 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data ends at command line options"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->std_input = sud->options + len;
data = NULL; /* don't free data */
ret = TRUE;
out:
free(data);
return ret;
}
|
CWE-415
| 182,439 | 3,731 |
292015260812614415088040550513848138714
| null | null | null |
yubico-pam
|
0f6ceabab0a8849b47f67d727aa526c2656089ba
| 1 |
check_user_token (const char *authfile,
const char *username,
const char *otp_id,
int verbose,
FILE *debug_file)
{
char buf[1024];
char *s_user, *s_token;
int retval = AUTH_ERROR;
int fd;
struct stat st;
FILE *opwfile;
fd = open(authfile, O_RDONLY, 0);
if (fd < 0) {
if(verbose)
D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
return retval;
}
if (fstat(fd, &st) < 0) {
if(verbose)
D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
close(fd);
return retval;
}
if (!S_ISREG(st.st_mode)) {
if(verbose)
D (debug_file, "%s is not a regular file", authfile);
close(fd);
return retval;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if(verbose)
D (debug_file, "fdopen: %s", strerror(errno));
close(fd);
return retval;
}
retval = AUTH_NO_TOKENS;
while (fgets (buf, 1024, opwfile))
{
char *saveptr = NULL;
if (buf[strlen (buf) - 1] == '\n')
buf[strlen (buf) - 1] = '\0';
if (buf[0] == '#') {
/* This is a comment and we may skip it. */
if(verbose)
D (debug_file, "Skipping comment line: %s", buf);
continue;
}
if(verbose)
D (debug_file, "Authorization line: %s", buf);
s_user = strtok_r (buf, ":", &saveptr);
if (s_user && strcmp (username, s_user) == 0)
{
if(verbose)
D (debug_file, "Matched user: %s", s_user);
retval = AUTH_NOT_FOUND; /* We found at least one line for the user */
do
{
s_token = strtok_r (NULL, ":", &saveptr);
if(verbose)
D (debug_file, "Authorization token: %s", s_token);
if (s_token && otp_id && strcmp (otp_id, s_token) == 0)
{
if(verbose)
D (debug_file, "Match user/token as %s/%s", username, otp_id);
return AUTH_FOUND;
}
}
while (s_token != NULL);
}
}
fclose (opwfile);
return retval;
}
|
CWE-200
| 182,440 | 3,732 |
73976873416705265710304478501048190668
| null | null | null |
openbsd
|
0654414afcce51a16d35d05060190a3ec4618d42
| 1 |
int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode,
const char *name, size_t namelen)
{
char *copy;
/*
* Refuse names with embedded NUL bytes.
* XXX: Do we need to push an error onto the error stack?
*/
if (name && memchr(name, '\0', namelen))
return 0;
if (mode == SET_HOST && id->hosts) {
string_stack_free(id->hosts);
id->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = strndup(name, namelen);
if (copy == NULL)
return 0;
if (id->hosts == NULL &&
(id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(id->hosts, copy)) {
free(copy);
if (sk_OPENSSL_STRING_num(id->hosts) == 0) {
sk_OPENSSL_STRING_free(id->hosts);
id->hosts = NULL;
}
return 0;
}
return 1;
}
|
CWE-295
| 182,441 | 3,733 |
281204162380877218906425244125088896065
| null | null | null |
linux
|
d8ba61ba58c88d5207c1ba2f7d9a2280e7d03be9
| 1 |
dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)
{
#ifdef CONFIG_DYNAMIC_FTRACE
/*
* ftrace must be first, everything else may cause a recursive crash.
* See note by declaration of modifying_ftrace_code in ftrace.c
*/
if (unlikely(atomic_read(&modifying_ftrace_code)) &&
ftrace_int3_handler(regs))
return;
#endif
if (poke_int3_handler(regs))
return;
ist_enter(regs);
RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
#ifdef CONFIG_KPROBES
if (kprobe_int3_handler(regs))
goto exit;
#endif
if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
/*
* Let others (NMI) know that the debug stack is in use
* as we may switch to the interrupt stack.
*/
debug_stack_usage_inc();
cond_local_irq_enable(regs);
do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, NULL);
cond_local_irq_disable(regs);
debug_stack_usage_dec();
exit:
ist_exit(regs);
}
|
CWE-362
| 182,442 | 3,734 |
106804786307522769337792693309412085782
| null | null | null |
kamailio
|
e1d8008a09d9390ebaf698abe8909e10dfec4097
| 1 |
int tmx_check_pretran(sip_msg_t *msg)
{
unsigned int chid;
unsigned int slotid;
int dsize;
struct via_param *vbr;
str scallid;
str scseqmet;
str scseqnum;
str sftag;
str svbranch = {NULL, 0};
pretran_t *it;
if(_tmx_ptran_table==NULL) {
LM_ERR("pretran hash table not initialized yet\n");
return -1;
}
if(get_route_type()!=REQUEST_ROUTE) {
LM_ERR("invalid usage - not in request route\n");
return -1;
}
if(msg->first_line.type!=SIP_REQUEST) {
LM_ERR("invalid usage - not a sip request\n");
return -1;
}
if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) {
LM_ERR("failed to parse required headers\n");
return -1;
}
if(msg->cseq==NULL || msg->cseq->parsed==NULL) {
LM_ERR("failed to parse cseq headers\n");
return -1;
}
if(get_cseq(msg)->method_id==METHOD_ACK
|| get_cseq(msg)->method_id==METHOD_CANCEL) {
LM_DBG("no pre-transaction management for ACK or CANCEL\n");
return -1;
}
if (msg->via1==0) {
LM_ERR("failed to get Via header\n");
return -1;
}
if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) {
LM_ERR("failed to get From header\n");
return -1;
}
if (msg->callid==NULL || msg->callid->body.s==NULL) {
LM_ERR("failed to parse callid headers\n");
return -1;
}
vbr = msg->via1->branch;
scallid = msg->callid->body;
trim(&scallid);
scseqmet = get_cseq(msg)->method;
trim(&scseqmet);
scseqnum = get_cseq(msg)->number;
trim(&scseqnum);
sftag = get_from(msg)->tag_value;
trim(&sftag);
chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len);
slotid = chid & (_tmx_ptran_size-1);
if(unlikely(_tmx_proc_ptran == NULL)) {
_tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t));
if(_tmx_proc_ptran == NULL) {
LM_ERR("not enough memory for pretran structure\n");
return -1;
}
memset(_tmx_proc_ptran, 0, sizeof(pretran_t));
_tmx_proc_ptran->pid = my_pid();
}
dsize = scallid.len + scseqnum.len + scseqmet.len
+ sftag.len + 4;
if(likely(vbr!=NULL)) {
svbranch = vbr->value;
trim(&svbranch);
dsize += svbranch.len;
}
if(dsize<256) dsize = 256;
tmx_pretran_unlink();
if(dsize > _tmx_proc_ptran->dbuf.len) {
if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s);
_tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize);
if(_tmx_proc_ptran->dbuf.s==NULL) {
LM_ERR("not enough memory for pretran data\n");
return -1;
}
_tmx_proc_ptran->dbuf.len = dsize;
}
_tmx_proc_ptran->hid = chid;
_tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id;
_tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s;
memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len);
_tmx_proc_ptran->callid.len = scallid.len;
_tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0';
_tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s
+ _tmx_proc_ptran->callid.len + 1;
memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len);
_tmx_proc_ptran->ftag.len = sftag.len;
_tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0';
_tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s
+ _tmx_proc_ptran->ftag.len + 1;
memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len);
_tmx_proc_ptran->cseqnum.len = scseqnum.len;
_tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0';
_tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s
+ _tmx_proc_ptran->cseqnum.len + 1;
memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len);
_tmx_proc_ptran->cseqmet.len = scseqmet.len;
_tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0';
if(likely(vbr!=NULL)) {
_tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s
+ _tmx_proc_ptran->cseqmet.len + 1;
memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len);
_tmx_proc_ptran->vbranch.len = svbranch.len;
_tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0';
} else {
_tmx_proc_ptran->vbranch.s = NULL;
_tmx_proc_ptran->vbranch.len = 0;
}
lock_get(&_tmx_ptran_table[slotid].lock);
it = _tmx_ptran_table[slotid].plist;
tmx_pretran_link_safe(slotid);
for(; it!=NULL; it=it->next) {
if(_tmx_proc_ptran->hid != it->hid
|| _tmx_proc_ptran->cseqmetid != it->cseqmetid
|| _tmx_proc_ptran->callid.len != it->callid.len
|| _tmx_proc_ptran->ftag.len != it->ftag.len
|| _tmx_proc_ptran->cseqmet.len != it->cseqmet.len
|| _tmx_proc_ptran->cseqnum.len != it->cseqnum.len)
continue;
if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) {
if(_tmx_proc_ptran->vbranch.len != it->vbranch.len)
continue;
/* shortcut - check last char in Via branch
* - kamailio/ser adds there branch index => in case of paralel
* forking by previous hop, catch it here quickly */
if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1]
!= it->vbranch.s[it->vbranch.len-1])
continue;
if(memcmp(_tmx_proc_ptran->vbranch.s,
it->vbranch.s, it->vbranch.len)!=0)
continue;
/* shall stop by matching magic cookie?
* if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN
* && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) {
* LM_DBG("rfc3261 cookie found in Via branch\n");
* }
*/
}
if(memcmp(_tmx_proc_ptran->callid.s,
it->callid.s, it->callid.len)!=0
|| memcmp(_tmx_proc_ptran->ftag.s,
it->ftag.s, it->ftag.len)!=0
|| memcmp(_tmx_proc_ptran->cseqnum.s,
it->cseqnum.s, it->cseqnum.len)!=0)
continue;
if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF)
&& memcmp(_tmx_proc_ptran->cseqmet.s,
it->cseqmet.s, it->cseqmet.len)!=0)
continue;
LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n",
it->pid, it->callid.len, it->callid.s);
lock_release(&_tmx_ptran_table[slotid].lock);
return 1;
}
lock_release(&_tmx_ptran_table[slotid].lock);
return 0;
}
|
CWE-119
| 182,443 | 3,735 |
133412845150430061179165001055722685868
| null | null | null |
FreeRDP
|
d1112c279bd1a327e8e4d0b5f371458bf2579659
| 1 |
static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 len;
UINT32 left;
BYTE value;
left = originalSize;
while (left > 4)
{
value = *in++;
if (left == 5)
{
*out++ = value;
left--;
}
else if (value == *in)
{
in++;
if (*in < 0xFF)
{
len = (UINT32) * in++;
len += 2;
}
else
{
in++;
len = *((UINT32*) in);
in += 4;
}
FillMemory(out, len, value);
out += len;
left -= len;
}
else
{
*out++ = value;
left--;
}
}
*((UINT32*)out) = *((UINT32*)in);
}
|
CWE-787
| 182,456 | 3,746 |
6048075215570503471072640280256640091
| null | null | null |
FreeRDP
|
09b9d4f1994a674c4ec85b4947aa656eda1aed8a
| 1 |
static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap,
const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight,
UINT32 bpp, UINT32 length, BOOL compressed,
UINT32 codecId)
{
UINT32 SrcSize = length;
rdpGdi* gdi = context->gdi;
bitmap->compressed = FALSE;
bitmap->format = gdi->dstFormat;
bitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format);
bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16);
if (!bitmap->data)
return FALSE;
if (compressed)
{
if (bpp < 32)
{
if (!interleaved_decompress(context->codecs->interleaved,
pSrcData, SrcSize,
DstWidth, DstHeight,
bpp,
bitmap->data, bitmap->format,
0, 0, 0, DstWidth, DstHeight,
&gdi->palette))
return FALSE;
}
else
{
if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize,
DstWidth, DstHeight,
bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, TRUE))
return FALSE;
}
}
else
{
const UINT32 SrcFormat = gdi_get_pixel_format(bpp);
const size_t sbpp = GetBytesPerPixel(SrcFormat);
const size_t dbpp = GetBytesPerPixel(bitmap->format);
if ((sbpp == 0) || (dbpp == 0))
return FALSE;
else
{
const size_t dstSize = SrcSize * dbpp / sbpp;
if (dstSize < bitmap->length)
return FALSE;
}
if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0,
DstWidth, DstHeight, pSrcData, SrcFormat,
0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL))
return FALSE;
}
return TRUE;
}
|
CWE-190
| 182,464 | 3,752 |
8582638630962748390171543430238240024
| null | null | null |
FreeRDP
|
445a5a42c500ceb80f8fa7f2c11f3682538033f3
| 1 |
BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT16 count;
BITMAP_DATA* newdata;
count = bitmapUpdate->number * 2;
newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
|
CWE-119
| 182,465 | 3,753 |
282936062818017583261372385968135342966
| null | null | null |
FreeRDP
|
602f4a2e14b41703b5f431de3154cd46a5750a2d
| 1 |
int zgfx_decompress(ZGFX_CONTEXT* zgfx, const BYTE* pSrcData, UINT32 SrcSize, BYTE** ppDstData,
UINT32* pDstSize, UINT32 flags)
{
int status = -1;
BYTE descriptor;
wStream* stream = Stream_New((BYTE*)pSrcData, SrcSize);
if (!stream)
return -1;
if (Stream_GetRemainingLength(stream) < 1)
goto fail;
Stream_Read_UINT8(stream, descriptor); /* descriptor (1 byte) */
if (descriptor == ZGFX_SEGMENTED_SINGLE)
{
if (!zgfx_decompress_segment(zgfx, stream, Stream_GetRemainingLength(stream)))
goto fail;
*ppDstData = NULL;
if (zgfx->OutputCount > 0)
*ppDstData = (BYTE*) malloc(zgfx->OutputCount);
if (!*ppDstData)
goto fail;
*pDstSize = zgfx->OutputCount;
CopyMemory(*ppDstData, zgfx->OutputBuffer, zgfx->OutputCount);
}
else if (descriptor == ZGFX_SEGMENTED_MULTIPART)
{
UINT32 segmentSize;
UINT16 segmentNumber;
UINT16 segmentCount;
UINT32 uncompressedSize;
BYTE* pConcatenated;
if (Stream_GetRemainingLength(stream) < 6)
goto fail;
Stream_Read_UINT16(stream, segmentCount); /* segmentCount (2 bytes) */
Stream_Read_UINT32(stream, uncompressedSize); /* uncompressedSize (4 bytes) */
if (Stream_GetRemainingLength(stream) < segmentCount * sizeof(UINT32))
goto fail;
pConcatenated = (BYTE*) malloc(uncompressedSize);
if (!pConcatenated)
goto fail;
*ppDstData = pConcatenated;
*pDstSize = uncompressedSize;
for (segmentNumber = 0; segmentNumber < segmentCount; segmentNumber++)
{
if (Stream_GetRemainingLength(stream) < sizeof(UINT32))
goto fail;
Stream_Read_UINT32(stream, segmentSize); /* segmentSize (4 bytes) */
if (!zgfx_decompress_segment(zgfx, stream, segmentSize))
goto fail;
CopyMemory(pConcatenated, zgfx->OutputBuffer, zgfx->OutputCount);
pConcatenated += zgfx->OutputCount;
}
}
else
{
goto fail;
}
status = 1;
fail:
Stream_Free(stream, FALSE);
return status;
}
|
CWE-119
| 182,466 | 3,754 |
318980867436274150711496781444231536419
| null | null | null |
FreeRDP
|
17c363a5162fd4dc77b1df54e48d7bd9bf6b3be7
| 1 |
static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize)
{
BYTE c;
BYTE flags;
UINT32 extra = 0;
int opIndex;
int haveBits;
int inPrefix;
UINT32 count;
UINT32 distance;
BYTE* pbSegment;
size_t cbSegment = segmentSize - 1;
if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1))
return FALSE;
Stream_Read_UINT8(stream, flags); /* header (1 byte) */
zgfx->OutputCount = 0;
pbSegment = Stream_Pointer(stream);
Stream_Seek(stream, cbSegment);
if (!(flags & PACKET_COMPRESSED))
{
zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment);
CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment);
zgfx->OutputCount = cbSegment;
return TRUE;
}
zgfx->pbInputCurrent = pbSegment;
zgfx->pbInputEnd = &pbSegment[cbSegment - 1];
/* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */
zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
while (zgfx->cBitsRemaining)
{
haveBits = 0;
inPrefix = 0;
for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++)
{
while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength)
{
zgfx_GetBits(zgfx, 1);
inPrefix = (inPrefix << 1) + zgfx->bits;
haveBits++;
}
if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode)
{
if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0)
{
/* Literal */
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits);
zgfx->HistoryBuffer[zgfx->HistoryIndex] = c;
if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize)
zgfx->HistoryIndex = 0;
zgfx->OutputBuffer[zgfx->OutputCount++] = c;
}
else
{
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits;
if (distance != 0)
{
/* Match */
zgfx_GetBits(zgfx, 1);
if (zgfx->bits == 0)
{
count = 3;
}
else
{
count = 4;
extra = 2;
zgfx_GetBits(zgfx, 1);
while (zgfx->bits == 1)
{
count *= 2;
extra++;
zgfx_GetBits(zgfx, 1);
}
zgfx_GetBits(zgfx, extra);
count += zgfx->bits;
}
zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx->OutputCount += count;
}
else
{
/* Unencoded */
zgfx_GetBits(zgfx, 15);
count = zgfx->bits;
zgfx->cBitsRemaining -= zgfx->cBitsCurrent;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count);
zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count);
zgfx->pbInputCurrent += count;
zgfx->cBitsRemaining -= (8 * count);
zgfx->OutputCount += count;
}
}
break;
}
}
}
return TRUE;
}
|
CWE-119
| 182,469 | 3,757 |
48551217187937527622734427906652609974
| null | null | null |
libgit2
|
3207ddb0103543da8ad2139ec6539f590f9900c1
| 1 |
static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
|
CWE-190
| 182,473 | 3,759 |
197322156807941714074323411153686600335
| null | null | null |
linux
|
0ddcff49b672239dda94d70d0fcf50317a9f4b51
| 1 |
static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct hwsim_new_radio_params param = { 0 };
const char *hwname = NULL;
int ret;
param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
param.channels = channels;
param.destroy_on_close =
info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
if (info->attrs[HWSIM_ATTR_CHANNELS])
param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
if (info->attrs[HWSIM_ATTR_NO_VIF])
param.no_vif = true;
if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
param.hwname = hwname;
}
if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
param.use_chanctx = true;
else
param.use_chanctx = (param.channels > 1);
if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
param.reg_alpha2 =
nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom))
return -EINVAL;
param.regd = hwsim_world_regdom_custom[idx];
}
ret = mac80211_hwsim_new_radio(info, ¶m);
kfree(hwname);
return ret;
}
|
CWE-772
| 182,474 | 3,760 |
260520256202264536234846464821534110181
| null | null | null |
linux
|
297a6961ffb8ff4dc66c9fbf53b924bd1dda05d5
| 1 |
static int unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
}
|
CWE-476
| 182,475 | 3,761 |
265342746482685363126426227132881302089
| null | null | null |
libvips
|
20d840e6da15c1574b3ed998bc92f91d1e36c2a5
| 1 |
vips_foreign_load_start( VipsImage *out, void *a, void *b )
{
VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );
VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );
if( !load->real ) {
if( !(load->real = vips_foreign_load_temp( load )) )
return( NULL );
#ifdef DEBUG
printf( "vips_foreign_load_start: triggering ->load()\n" );
#endif /*DEBUG*/
/* Read the image in. This may involve a long computation and
* will finish with load->real holding the decompressed image.
*
* We want our caller to be able to see this computation on
* @out, so eval signals on ->real need to appear on ->out.
*/
load->real->progress_signal = load->out;
/* Note the load object on the image. Loaders can use
* this to signal invalidate if they hit a load error. See
* vips_foreign_load_invalidate() below.
*/
g_object_set_qdata( G_OBJECT( load->real ),
vips__foreign_load_operation, load );
if( class->load( load ) ||
vips_image_pio_input( load->real ) )
return( NULL );
/* ->header() read the header into @out, load has read the
* image into @real. They must match exactly in size, bands,
* format and coding for the copy to work.
*
* Some versions of ImageMagick give different results between
* Ping and Load for some formats, for example.
*/
if( !vips_foreign_load_iscompat( load->real, out ) )
return( NULL );
/* We have to tell vips that out depends on real. We've set
* the demand hint below, but not given an input there.
*/
vips_image_pipelinev( load->out, load->out->dhint,
load->real, NULL );
}
return( vips_region_new( load->real ) );
}
|
CWE-362
| 182,476 | 3,762 |
279924439095021864874877805092436569315
| null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.