text
stringlengths 478
483k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0;
int64_t total_samples = 0, infilesize;
RiffChunkHeader riff_chunk_header;
ChunkHeader chunk_header;
WaveHeader WaveHeader;
DS64Chunk ds64_chunk;
uint32_t bcount;
CLEAR (WaveHeader);
CLEAR (ds64_chunk);
infilesize = DoGetFileSize (infile);
if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) {
error_line ("can't handle .WAV files larger than 4 GB (non-standard)!");
return WAVPACK_SOFT_ERROR;
}
memcpy (&riff_chunk_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) ||
bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) ||
bcount != sizeof (ChunkHeader)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat);
if (!strncmp (chunk_header.ckID, "ds64", 4)) {
if (chunk_header.ckSize < sizeof (DS64Chunk) ||
!DoReadFile (infile, &ds64_chunk, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &ds64_chunk, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
got_ds64 = 1;
WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat);
if (debug_logging_mode)
error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d",
(long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64,
(long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength);
if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
while (ds64_chunk.tableLength--) {
CS64Chunk cs64_chunk;
if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) ||
bcount != sizeof (CS64Chunk) ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
}
}
else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and
int supported = TRUE, format; // make sure it's a .wav file we can handle
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .WAV format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this WAV file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else if (config->float_norm_exp)
error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)",
config->float_norm_exp - 126, 150 - config->float_norm_exp);
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop
int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ?
ds64_chunk.dataSize64 : chunk_header.ckSize;
if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required)
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) {
error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (config->qmode & QMODE_IGNORE_LENGTH) {
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
total_samples = data_chunk_size / WaveHeader.BlockAlign;
if (got_ds64 && total_samples != ds64_chunk.sampleCount64) {
error_line ("%s is not a valid .WAV file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (!total_samples) {
error_line ("this .WAV file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L;
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'issue #27, do not overwrite stack on corrupt RF64 file'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: char *uwsgi_expand_path(char *dir, int dir_len, char *ptr) {
char src[PATH_MAX + 1];
memcpy(src, dir, dir_len);
src[dir_len] = 0;
char *dst = ptr;
if (!dst)
dst = uwsgi_malloc(PATH_MAX + 1);
if (!realpath(src, dst)) {
uwsgi_error_realpath(src);
if (!ptr)
free(dst);
return NULL;
}
return dst;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-703', 'CWE-787'], 'message': 'improve uwsgi_expand_path() to sanitize input, avoiding stack corruption and potential security issue'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: __zzip_fetch_disk_trailer(int fd, zzip_off_t filesize,
struct _disk_trailer *_zzip_restrict trailer,
zzip_plugin_io_t io)
{
#ifdef DEBUG
#define return(val) { e=val; HINT2("%s", zzip_strerror(e)); goto cleanup; }
#else
#define return(val) { e=val; goto cleanup; }
#endif
register int e;
#ifndef _LOWSTK
auto char buffer[2 * ZZIP_BUFSIZ];
char *buf = buffer;
#else
char *buf = malloc(2 * ZZIP_BUFSIZ);
#endif
zzip_off_t offset = 0;
zzip_ssize_t maplen = 0; /* mmap(),read(),getpagesize() use size_t !! */
char *fd_map = 0;
if (! trailer)
{ return(EINVAL); }
if (filesize < __sizeof(struct zzip_disk_trailer))
{ return(ZZIP_DIR_TOO_SHORT); }
if (! buf)
{ return(ZZIP_OUTOFMEM); }
offset = filesize; /* a.k.a. old offset */
while (1) /* outer loop */
{
register unsigned char *mapped;
if (offset <= 0)
{ return(ZZIP_DIR_EDH_MISSING); }
/* trailer cannot be farther away than 64K from fileend */
if (filesize - offset > 64 * 1024)
{ return(ZZIP_DIR_EDH_MISSING); }
/* the new offset shall overlap with the area after the old offset! */
if (USE_MMAP && io->fd.sys)
{
zzip_off_t mapoff = offset;
{
zzip_ssize_t pagesize = _zzip_getpagesize(io->fd.sys);
if (pagesize < ZZIP_BUFSIZ)
goto non_mmap; /* an error? */
if (mapoff == filesize && filesize > pagesize)
mapoff -= pagesize;
if (mapoff < pagesize)
{
maplen = (zzip_ssize_t) mapoff + pagesize;
mapoff = 0;
} else
{
mapoff -= pagesize;
maplen = 2 * pagesize;
if ((zzip_ssize_t) mapoff & (pagesize - 1))
{ /*only 1. run */
pagesize -= (zzip_ssize_t) mapoff & (pagesize - 1);
mapoff += pagesize;
maplen -= pagesize;
}
}
if (mapoff + maplen > filesize)
maplen = filesize - mapoff;
}
fd_map = _zzip_mmap(io->fd.sys, fd, mapoff, (zzip_size_t) maplen);
if (fd_map == MAP_FAILED)
goto non_mmap;
mapped = (unsigned char *) fd_map;
offset = mapoff; /* success */
HINT3("mapped *%p len=%li", fd_map, (long) maplen);
} else
{
non_mmap:
fd_map = 0; /* have no mmap */
{
zzip_off_t pagesize = ZZIP_BUFSIZ;
if (offset == filesize && filesize > pagesize)
offset -= pagesize;
if (offset < pagesize)
{
maplen = (zzip_ssize_t) offset + pagesize;
offset = 0;
} else
{
offset -= pagesize;
maplen = 2 * pagesize;
if ((zzip_ssize_t) offset & (pagesize - 1))
{ /*on 1st run */
pagesize -= (zzip_ssize_t) offset & (pagesize - 1);
offset += pagesize;
maplen -= pagesize;
}
}
if (offset + maplen > filesize)
maplen = filesize - offset;
}
if (io->fd.seeks(fd, offset, SEEK_SET) < 0)
{ return(ZZIP_DIR_SEEK); }
if (io->fd.read(fd, buf, (zzip_size_t) maplen) < maplen)
{ return(ZZIP_DIR_READ); }
mapped = (unsigned char *) buf; /* success */
HINT5("offs=$%lx len=%li filesize=%li pagesize=%i",
(long) offset, (long) maplen, (long) filesize, ZZIP_BUFSIZ);
}
{ /* now, check for the trailer-magic, hopefully near the end of file */
register unsigned char *end = mapped + maplen;
register unsigned char *tail;
for (tail = end - 1; (tail >= mapped); tail--)
{
if ((*tail == 'P') && /* quick pre-check for trailer magic */
end - tail >= __sizeof(struct zzip_disk_trailer) - 2 &&
zzip_disk_trailer_check_magic(tail))
{
# ifndef ZZIP_DISK64_TRAILER
/* if the file-comment is not present, it happens
that the z_comment field often isn't either */
if (end - tail >= __sizeof(*trailer))
{
memcpy(trailer, tail, sizeof(*trailer));
} else
{
memcpy(trailer, tail, sizeof(*trailer) - 2);
trailer->z_comment[0] = 0;
trailer->z_comment[1] = 0;
}
# else
struct zzip_disk_trailer *orig =
(struct zzip_disk_trailer *) tail;
trailer->zz_tail = tail;
trailer->zz_entries = zzip_disk_trailer_localentries(orig);
trailer->zz_finalentries =
zzip_disk_trailer_finalentries(orig);
trailer->zz_rootseek = zzip_disk_trailer_rootseek(orig);
trailer->zz_rootsize = zzip_disk_trailer_rootsize(orig);
# endif
__fixup_rootseek(offset + tail - mapped, trailer);
{ return(0); }
} else if ((*tail == 'P') &&
end - tail >=
__sizeof(struct zzip_disk64_trailer) - 2
&& zzip_disk64_trailer_check_magic(tail))
{
# ifndef ZZIP_DISK64_TRAILER
return (ZZIP_DIR_LARGEFILE);
# else
struct zzip_disk64_trailer *orig =
(struct zzip_disk64_trailer *) tail;
trailer->zz_tail = tail;
trailer->zz_entries =
zzip_disk64_trailer_localentries(orig);
trailer->zz_finalentries =
zzip_disk64_trailer_finalentries(orig);
trailer->zz_rootseek = zzip_disk64_trailer_rootseek(orig);
trailer->zz_rootsize = zzip_disk64_trailer_rootsize(orig);
{ return(0); }
# endif
}
}
}
if (USE_MMAP && fd_map)
{
HINT3("unmap *%p len=%li", fd_map, (long) maplen);
_zzip_munmap(io->fd.sys, fd_map, (zzip_size_t) maplen);
fd_map = 0;
}
} /*outer loop */
cleanup:
if (USE_MMAP && fd_map)
{
HINT3("unmap *%p len=%li", fd_map, (long) maplen);
_zzip_munmap(io->fd.sys, fd_map, (zzip_size_t) maplen);
}
# ifdef _LOWSTK
free(buf);
# endif
# undef return
return e;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'Reject the ZIP file and report it as corrupt if the size of the
central directory and/or the offset of start of central directory
point beyond the end of the ZIP file. [CVE-2018-6484]'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int amd_gpio_remove(struct platform_device *pdev)
{
struct amd_gpio *gpio_dev;
gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&gpio_dev->gc);
pinctrl_unregister(gpio_dev->pctrl);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration
Use devm_pinctrl_register() for pin control registration and clean
error path.
Signed-off-by: Laxman Dewangan <[email protected]>
Signed-off-by: Linus Walleij <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
u32 __user *uaddr2, int nr_wake, int nr_requeue,
u32 *cmpval, int requeue_pi)
{
union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
int drop_count = 0, task_count = 0, ret;
struct futex_pi_state *pi_state = NULL;
struct futex_hash_bucket *hb1, *hb2;
struct futex_q *this, *next;
DEFINE_WAKE_Q(wake_q);
/*
* When PI not supported: return -ENOSYS if requeue_pi is true,
* consequently the compiler knows requeue_pi is always false past
* this point which will optimize away all the conditional code
* further down.
*/
if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
return -ENOSYS;
if (requeue_pi) {
/*
* Requeue PI only works on two distinct uaddrs. This
* check is only valid for private futexes. See below.
*/
if (uaddr1 == uaddr2)
return -EINVAL;
/*
* requeue_pi requires a pi_state, try to allocate it now
* without any locks in case it fails.
*/
if (refill_pi_state_cache())
return -ENOMEM;
/*
* requeue_pi must wake as many tasks as it can, up to nr_wake
* + nr_requeue, since it acquires the rt_mutex prior to
* returning to userspace, so as to not leave the rt_mutex with
* waiters and no owner. However, second and third wake-ups
* cannot be predicted as they involve race conditions with the
* first wake and a fault while looking up the pi_state. Both
* pthread_cond_signal() and pthread_cond_broadcast() should
* use nr_wake=1.
*/
if (nr_wake != 1)
return -EINVAL;
}
retry:
ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
if (unlikely(ret != 0))
goto out;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
requeue_pi ? VERIFY_WRITE : VERIFY_READ);
if (unlikely(ret != 0))
goto out_put_key1;
/*
* The check above which compares uaddrs is not sufficient for
* shared futexes. We need to compare the keys:
*/
if (requeue_pi && match_futex(&key1, &key2)) {
ret = -EINVAL;
goto out_put_keys;
}
hb1 = hash_futex(&key1);
hb2 = hash_futex(&key2);
retry_private:
hb_waiters_inc(hb2);
double_lock_hb(hb1, hb2);
if (likely(cmpval != NULL)) {
u32 curval;
ret = get_futex_value_locked(&curval, uaddr1);
if (unlikely(ret)) {
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
ret = get_user(curval, uaddr1);
if (ret)
goto out_put_keys;
if (!(flags & FLAGS_SHARED))
goto retry_private;
put_futex_key(&key2);
put_futex_key(&key1);
goto retry;
}
if (curval != *cmpval) {
ret = -EAGAIN;
goto out_unlock;
}
}
if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
/*
* Attempt to acquire uaddr2 and wake the top waiter. If we
* intend to requeue waiters, force setting the FUTEX_WAITERS
* bit. We force this here where we are able to easily handle
* faults rather in the requeue loop below.
*/
ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
&key2, &pi_state, nr_requeue);
/*
* At this point the top_waiter has either taken uaddr2 or is
* waiting on it. If the former, then the pi_state will not
* exist yet, look it up one more time to ensure we have a
* reference to it. If the lock was taken, ret contains the
* vpid of the top waiter task.
* If the lock was not taken, we have pi_state and an initial
* refcount on it. In case of an error we have nothing.
*/
if (ret > 0) {
WARN_ON(pi_state);
drop_count++;
task_count++;
/*
* If we acquired the lock, then the user space value
* of uaddr2 should be vpid. It cannot be changed by
* the top waiter as it is blocked on hb2 lock if it
* tries to do so. If something fiddled with it behind
* our back the pi state lookup might unearth it. So
* we rather use the known value than rereading and
* handing potential crap to lookup_pi_state.
*
* If that call succeeds then we have pi_state and an
* initial refcount on it.
*/
ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state);
}
switch (ret) {
case 0:
/* We hold a reference on the pi state. */
break;
/* If the above failed, then pi_state is NULL */
case -EFAULT:
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
ret = fault_in_user_writeable(uaddr2);
if (!ret)
goto retry;
goto out;
case -EAGAIN:
/*
* Two reasons for this:
* - Owner is exiting and we just wait for the
* exit to complete.
* - The user space value changed.
*/
double_unlock_hb(hb1, hb2);
hb_waiters_dec(hb2);
put_futex_key(&key2);
put_futex_key(&key1);
cond_resched();
goto retry;
default:
goto out_unlock;
}
}
plist_for_each_entry_safe(this, next, &hb1->chain, list) {
if (task_count - nr_wake >= nr_requeue)
break;
if (!match_futex(&this->key, &key1))
continue;
/*
* FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
* be paired with each other and no other futex ops.
*
* We should never be requeueing a futex_q with a pi_state,
* which is awaiting a futex_unlock_pi().
*/
if ((requeue_pi && !this->rt_waiter) ||
(!requeue_pi && this->rt_waiter) ||
this->pi_state) {
ret = -EINVAL;
break;
}
/*
* Wake nr_wake waiters. For requeue_pi, if we acquired the
* lock, we already woke the top_waiter. If not, it will be
* woken by futex_unlock_pi().
*/
if (++task_count <= nr_wake && !requeue_pi) {
mark_wake_futex(&wake_q, this);
continue;
}
/* Ensure we requeue to the expected futex for requeue_pi. */
if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
ret = -EINVAL;
break;
}
/*
* Requeue nr_requeue waiters and possibly one more in the case
* of requeue_pi if we couldn't acquire the lock atomically.
*/
if (requeue_pi) {
/*
* Prepare the waiter to take the rt_mutex. Take a
* refcount on the pi_state and store the pointer in
* the futex_q object of the waiter.
*/
get_pi_state(pi_state);
this->pi_state = pi_state;
ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
this->rt_waiter,
this->task);
if (ret == 1) {
/*
* We got the lock. We do neither drop the
* refcount on pi_state nor clear
* this->pi_state because the waiter needs the
* pi_state for cleaning up the user space
* value. It will drop the refcount after
* doing so.
*/
requeue_pi_wake_futex(this, &key2, hb2);
drop_count++;
continue;
} else if (ret) {
/*
* rt_mutex_start_proxy_lock() detected a
* potential deadlock when we tried to queue
* that waiter. Drop the pi_state reference
* which we took above and remove the pointer
* to the state from the waiters futex_q
* object.
*/
this->pi_state = NULL;
put_pi_state(pi_state);
/*
* We stop queueing more waiters and let user
* space deal with the mess.
*/
break;
}
}
requeue_futex(this, hb1, hb2, &key2);
drop_count++;
}
/*
* We took an extra initial reference to the pi_state either
* in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
* need to drop it here again.
*/
put_pi_state(pi_state);
out_unlock:
double_unlock_hb(hb1, hb2);
wake_up_q(&wake_q);
hb_waiters_dec(hb2);
/*
* drop_futex_key_refs() must be called outside the spinlocks. During
* the requeue we moved futex_q's from the hash bucket at key1 to the
* one at key2 and updated their key pointer. We no longer need to
* hold the references to key1.
*/
while (--drop_count >= 0)
drop_futex_key_refs(&key1);
out_put_keys:
put_futex_key(&key2);
out_put_key1:
put_futex_key(&key1);
out:
return ret ? ret : task_count;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'futex: Prevent overflow by strengthen input validation
UBSAN reports signed integer overflow in kernel/futex.c:
UBSAN: Undefined behaviour in kernel/futex.c:2041:18
signed integer overflow:
0 - -2147483648 cannot be represented in type 'int'
Add a sanity check to catch negative values of nr_wake and nr_requeue.
Signed-off-by: Li Jinyue <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Link: https://lkml.kernel.org/r/[email protected]'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool blk_kick_flush(struct request_queue *q, struct blk_flush_queue *fq)
{
struct list_head *pending = &fq->flush_queue[fq->flush_pending_idx];
struct request *first_rq =
list_first_entry(pending, struct request, flush.list);
struct request *flush_rq = fq->flush_rq;
/* C1 described at the top of this file */
if (fq->flush_pending_idx != fq->flush_running_idx || list_empty(pending))
return false;
/* C2 and C3 */
if (!list_empty(&fq->flush_data_in_flight) &&
time_before(jiffies,
fq->flush_pending_since + FLUSH_PENDING_TIMEOUT))
return false;
/*
* Issue flush and toggle pending_idx. This makes pending_idx
* different from running_idx, which means flush is in flight.
*/
fq->flush_pending_idx ^= 1;
blk_rq_init(q, flush_rq);
/*
* Borrow tag from the first request since they can't
* be in flight at the same time.
*/
if (q->mq_ops) {
flush_rq->mq_ctx = first_rq->mq_ctx;
flush_rq->tag = first_rq->tag;
}
flush_rq->cmd_type = REQ_TYPE_FS;
flush_rq->cmd_flags = WRITE_FLUSH | REQ_FLUSH_SEQ;
flush_rq->rq_disk = first_rq->rq_disk;
flush_rq->end_io = flush_end_io;
return blk_flush_queue_rq(flush_rq, false);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-264'], 'message': 'blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void flush_end_io(struct request *flush_rq, int error)
{
struct request_queue *q = flush_rq->q;
struct list_head *running;
bool queued = false;
struct request *rq, *n;
unsigned long flags = 0;
struct blk_flush_queue *fq = blk_get_flush_queue(q, flush_rq->mq_ctx);
if (q->mq_ops) {
spin_lock_irqsave(&fq->mq_flush_lock, flags);
flush_rq->tag = -1;
}
running = &fq->flush_queue[fq->flush_running_idx];
BUG_ON(fq->flush_pending_idx == fq->flush_running_idx);
/* account completion of the flush request */
fq->flush_running_idx ^= 1;
if (!q->mq_ops)
elv_completed_request(q, flush_rq);
/* and push the waiting requests to the next stage */
list_for_each_entry_safe(rq, n, running, flush.list) {
unsigned int seq = blk_flush_cur_seq(rq);
BUG_ON(seq != REQ_FSEQ_PREFLUSH && seq != REQ_FSEQ_POSTFLUSH);
queued |= blk_flush_complete_seq(rq, fq, seq, error);
}
/*
* Kick the queue to avoid stall for two cases:
* 1. Moving a request silently to empty queue_head may stall the
* queue.
* 2. When flush request is running in non-queueable queue, the
* queue is hold. Restart the queue after flush request is finished
* to avoid stall.
* This function is called from request completion path and calling
* directly into request_fn may confuse the driver. Always use
* kblockd.
*/
if (queued || fq->flush_queue_delayed) {
WARN_ON(q->mq_ops);
blk_run_queue_async(q);
}
fq->flush_queue_delayed = 0;
if (q->mq_ops)
spin_unlock_irqrestore(&fq->mq_flush_lock, flags);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-264'], 'message': 'blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void bt_for_each(struct blk_mq_hw_ctx *hctx,
struct blk_mq_bitmap_tags *bt, unsigned int off,
busy_iter_fn *fn, void *data, bool reserved)
{
struct request *rq;
int bit, i;
for (i = 0; i < bt->map_nr; i++) {
struct blk_align_bitmap *bm = &bt->map[i];
for (bit = find_first_bit(&bm->word, bm->depth);
bit < bm->depth;
bit = find_next_bit(&bm->word, bm->depth, bit + 1)) {
rq = blk_mq_tag_to_rq(hctx->tags, off + bit);
if (rq->q == hctx->queue)
fn(hctx, rq, data, reserved);
}
off += (1 << bt->bits_per_word);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-264'], 'message': 'blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: Header readHeader(BasicIo& io)
{
byte header[2];
io.read(header, 2);
ByteOrder byteOrder = invalidByteOrder;
if (header[0] == 'I' && header[1] == 'I')
byteOrder = littleEndian;
else if (header[0] == 'M' && header[1] == 'M')
byteOrder = bigEndian;
if (byteOrder == invalidByteOrder)
return Header();
byte version[2];
io.read(version, 2);
const uint16_t magic = getUShort(version, byteOrder);
if (magic != 0x2A && magic != 0x2B)
return Header();
Header result;
if (magic == 0x2A)
{
byte buffer[4];
io.read(buffer, 4);
const uint32_t offset = getULong(buffer, byteOrder);
result = Header(byteOrder, magic, 4, offset);
}
else
{
byte buffer[8];
io.read(buffer, 2);
const int size = getUShort(buffer, byteOrder);
assert(size == 8);
io.read(buffer, 2); // null
io.read(buffer, 8);
const uint64_t offset = getULongLong(buffer, byteOrder);
result = Header(byteOrder, magic, size, offset);
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-617'], 'message': 'fix for crash in bigtiff (issue #208)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: DataBuf FileIo::read(long rcount)
{
assert(p_->fp_ != 0);
DataBuf buf(rcount);
long readCount = read(buf.pData_, buf.size_);
buf.size_ = readCount;
return buf;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fix https://github.com/Exiv2/exiv2/issues/55'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void Image::printIFDStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,uint32_t start,bool bSwap,char c,int depth)
{
depth++;
bool bFirst = true ;
// buffer
const size_t dirSize = 32;
DataBuf dir(dirSize);
bool bPrint = option == kpsBasic || option == kpsRecursive;
do {
// Read top of directory
io.seek(start,BasicIo::beg);
io.read(dir.pData_, 2);
uint16_t dirLength = byteSwap2(dir,0,bSwap);
bool tooBig = dirLength > 500;
if ( tooBig ) throw Error(55);
if ( bFirst && bPrint ) {
out << Internal::indent(depth) << Internal::stringFormat("STRUCTURE OF TIFF FILE (%c%c): ",c,c) << io.path() << std::endl;
if ( tooBig ) out << Internal::indent(depth) << "dirLength = " << dirLength << std::endl;
}
// Read the dictionary
for ( int i = 0 ; i < dirLength ; i ++ ) {
if ( bFirst && bPrint ) {
out << Internal::indent(depth)
<< " address | tag | "
<< " type | count | offset | value\n";
}
bFirst = false;
io.read(dir.pData_, 12);
uint16_t tag = byteSwap2(dir,0,bSwap);
uint16_t type = byteSwap2(dir,2,bSwap);
uint32_t count = byteSwap4(dir,4,bSwap);
uint32_t offset = byteSwap4(dir,8,bSwap);
// Break for unknown tag types else we may segfault.
if ( !typeValid(type) ) {
std::cerr << "invalid type value detected in Image::printIFDStructure: " << type << std::endl;
start = 0; // break from do loop
throw Error(56);
break; // break from for loop
}
std::string sp = "" ; // output spacer
//prepare to print the value
uint32_t kount = isPrintXMP(tag,option) ? count // haul in all the data
: isPrintICC(tag,option) ? count // ditto
: isStringType(type) ? (count > 32 ? 32 : count) // restrict long arrays
: count > 5 ? 5
: count
;
uint32_t pad = isStringType(type) ? 1 : 0;
uint32_t size = isStringType(type) ? 1
: is2ByteType(type) ? 2
: is4ByteType(type) ? 4
: is8ByteType(type) ? 8
: 1
;
// if ( offset > io.size() ) offset = 0; // Denial of service?
// #55 memory allocation crash test/data/POC8
long long allocate = (long long) (size*count + pad+20);
if ( allocate > (long long) io.size() ) {
throw Error(57);
}
DataBuf buf((long)allocate); // allocate a buffer
std::memcpy(buf.pData_,dir.pData_+8,4); // copy dir[8:11] into buffer (short strings)
const bool bOffsetIsPointer = count*size > 4;
if ( bOffsetIsPointer ) { // read into buffer
size_t restore = io.tell(); // save
io.seek(offset,BasicIo::beg); // position
io.read(buf.pData_,count*size);// read
io.seek(restore,BasicIo::beg); // restore
}
if ( bPrint ) {
const uint32_t address = start + 2 + i*12 ;
const std::string offsetString = bOffsetIsPointer?
Internal::stringFormat("%10u", offset):
"";
out << Internal::indent(depth)
<< Internal::stringFormat("%8u | %#06x %-28s |%10s |%9u |%10s | "
,address,tag,tagName(tag).c_str(),typeName(type),count,offsetString.c_str());
if ( isShortType(type) ){
for ( size_t k = 0 ; k < kount ; k++ ) {
out << sp << byteSwap2(buf,k*size,bSwap);
sp = " ";
}
} else if ( isLongType(type) ){
for ( size_t k = 0 ; k < kount ; k++ ) {
out << sp << byteSwap4(buf,k*size,bSwap);
sp = " ";
}
} else if ( isRationalType(type) ){
for ( size_t k = 0 ; k < kount ; k++ ) {
uint32_t a = byteSwap4(buf,k*size+0,bSwap);
uint32_t b = byteSwap4(buf,k*size+4,bSwap);
out << sp << a << "/" << b;
sp = " ";
}
} else if ( isStringType(type) ) {
out << sp << Internal::binaryToString(buf, kount);
}
sp = kount == count ? "" : " ...";
out << sp << std::endl;
if ( option == kpsRecursive && (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd) ) {
for ( size_t k = 0 ; k < count ; k++ ) {
size_t restore = io.tell();
uint32_t offset = byteSwap4(buf,k*size,bSwap);
printIFDStructure(io,out,option,offset,bSwap,c,depth);
io.seek(restore,BasicIo::beg);
}
} else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ ) {
size_t restore = io.tell(); // save
io.seek(offset,BasicIo::beg); // position
byte* bytes=new byte[count] ; // allocate memory
io.read(bytes,count) ; // read
io.seek(restore,BasicIo::beg); // restore
IptcData::printStructure(out,bytes,count,depth);
delete[] bytes; // free
} else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10) {
size_t restore = io.tell(); // save
uint32_t jump= 10 ;
byte bytes[20] ;
const char* chars = (const char*) &bytes[0] ;
io.seek(offset,BasicIo::beg); // position
io.read(bytes,jump ) ; // read
bytes[jump]=0 ;
if ( ::strcmp("Nikon",chars) == 0 ) {
// tag is an embedded tiff
byte* bytes=new byte[count-jump] ; // allocate memory
io.read(bytes,count-jump) ; // read
MemIo memIo(bytes,count-jump) ; // create a file
printTiffStructure(memIo,out,option,depth);
delete[] bytes ; // free
} else {
// tag is an IFD
io.seek(0,BasicIo::beg); // position
printIFDStructure(io,out,option,offset,bSwap,c,depth);
}
io.seek(restore,BasicIo::beg); // restore
}
}
if ( isPrintXMP(tag,option) ) {
buf.pData_[count]=0;
out << (char*) buf.pData_;
}
if ( isPrintICC(tag,option) ) {
out.write((const char*)buf.pData_,count);
}
}
if ( start ) {
io.read(dir.pData_, 4);
start = tooBig ? 0 : byteSwap4(dir,0,bSwap);
}
} while (start) ;
if ( bPrint ) {
out << Internal::indent(depth) << "END " << io.path() << std::endl;
}
out.flush();
depth--;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fixed wrong brackets: size*count + pad can overflow before the cast
=> Should fix #76 (most of the work has been done by Robin Mills in
6e3855aed7ba8bb4731fc4087ca7f9078b2f3d97)
The problem with #76 is the contents of the 26th IFD, with the
following contents:
tag: 0x8649
type: 0x1
count: 0xffff ffff
offset: 0x4974
The issue is the size of count (uint32_t), as adding anything to it
causes an overflow. Especially the expression:
(size*count + pad+20)
results in an overflow and gives 20 as a result instead of
0x100000014, thus the condition in the if in the next line is false
and the program continues to run (until it crashes at io.read).
To properly account for the overflow, the brackets have to be removed,
as then the result is saved in the correctly sized type and not cast
after being calculated in the smaller type.
The brackets have also been removed from bigtiffimage.cpp, where the
same issue is present.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compute_U_value_R2(std::string const& user_password,
QPDF::EncryptionData const& data)
{
// Algorithm 3.4 from the PDF 1.7 Reference Manual
std::string k1 = QPDF::compute_encryption_key(user_password, data);
char udata[key_bytes];
pad_or_truncate_password_V4("", udata);
iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes,
QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(), 1, false);
return std::string(udata, key_bytes);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compute_U_value_R3(std::string const& user_password,
QPDF::EncryptionData const& data)
{
// Algorithm 3.5 from the PDF 1.7 Reference Manual
std::string k1 = QPDF::compute_encryption_key(user_password, data);
MD5 md5;
md5.encodeDataIncrementally(
pad_or_truncate_password_V4("").c_str(), key_bytes);
md5.encodeDataIncrementally(data.getId1().c_str(),
data.getId1().length());
MD5::Digest digest;
md5.digest(digest);
iterate_rc4(digest, sizeof(MD5::Digest),
QUtil::unsigned_char_pointer(k1),
data.getLengthBytes(), 20, false);
char result[key_bytes];
memcpy(result, digest, sizeof(MD5::Digest));
// pad with arbitrary data -- make it consistent for the sake of
// testing
for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i)
{
result[i] = static_cast<char>((i * i) % 0xff);
}
return std::string(result, key_bytes);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: compute_O_value(std::string const& user_password,
std::string const& owner_password,
QPDF::EncryptionData const& data)
{
// Algorithm 3.3 from the PDF 1.7 Reference Manual
unsigned char O_key[OU_key_bytes_V4];
compute_O_rc4_key(user_password, owner_password, data, O_key);
char upass[key_bytes];
pad_or_truncate_password_V4(user_password, upass);
iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes,
O_key, data.getLengthBytes(),
(data.getR() >= 3) ? 20 : 1, false);
return std::string(upass, key_bytes);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Pad keys to avoid memory errors (fixes #147)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void string_conversion_test()
{
std::cout << QUtil::int_to_string(16059) << std::endl
<< QUtil::int_to_string(16059, 7) << std::endl
<< QUtil::int_to_string(16059, -7) << std::endl
<< QUtil::double_to_string(3.14159) << std::endl
<< QUtil::double_to_string(3.14159, 3) << std::endl
<< QUtil::double_to_string(1000.123, -1024) << std::endl
<< QUtil::double_to_string(.1234, 5) << std::endl
<< QUtil::double_to_string(.0001234, 5) << std::endl
<< QUtil::double_to_string(.123456, 5) << std::endl
<< QUtil::double_to_string(.000123456, 5) << std::endl
<< QUtil::int_to_string_base(16059, 10) << std::endl
<< QUtil::int_to_string_base(16059, 8) << std::endl
<< QUtil::int_to_string_base(16059, 16) << std::endl;
std::string embedded_null = "one";
embedded_null += '\0';
embedded_null += "two";
std::cout << embedded_null.c_str() << std::endl;
std::cout << embedded_null.length() << std::endl;
char* tmp = QUtil::copy_string(embedded_null);
if (memcmp(tmp, embedded_null.c_str(), 7) == 0)
{
std::cout << "compare okay" << std::endl;
}
else
{
std::cout << "compare failed" << std::endl;
}
delete [] tmp;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Detect integer overflow/underflow'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void parse_rotation_parameter(Options& o, std::string const& parameter)
{
std::string angle_str;
std::string range;
size_t colon = parameter.find(':');
int relative = 0;
if (colon != std::string::npos)
{
if (colon > 0)
{
angle_str = parameter.substr(0, colon);
if (angle_str.length() > 0)
{
char first = angle_str.at(0);
if ((first == '+') || (first == '-'))
{
relative = ((first == '+') ? 1 : -1);
angle_str = angle_str.substr(1);
}
else if (! QUtil::is_digit(angle_str.at(0)))
{
angle_str = "";
}
}
}
if (colon + 1 < parameter.length())
{
range = parameter.substr(colon + 1);
}
}
bool range_valid = false;
try
{
parse_numrange(range.c_str(), 0, true);
range_valid = true;
}
catch (std::runtime_error)
{
// ignore
}
if (range_valid &&
((angle_str == "90") || (angle_str == "180") || (angle_str == "270")))
{
int angle = atoi(angle_str.c_str());
if (relative == -1)
{
angle = -angle;
}
o.rotations[range] = RotationSpec(angle, (relative != 0));
}
else
{
usage("invalid parameter to rotate: " + parameter);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDF::reconstruct_xref(QPDFExc& e)
{
if (this->m->reconstructed_xref)
{
// Avoid xref reconstruction infinite loops. This is getting
// very hard to reproduce because qpdf is throwing many fewer
// exceptions while parsing. Most situations are warnings now.
throw e;
}
this->m->reconstructed_xref = true;
warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
"file is damaged"));
warn(e);
warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
"Attempting to reconstruct cross-reference table"));
// Delete all references to type 1 (uncompressed) objects
std::set<QPDFObjGen> to_delete;
for (std::map<QPDFObjGen, QPDFXRefEntry>::iterator iter =
this->m->xref_table.begin();
iter != this->m->xref_table.end(); ++iter)
{
if (((*iter).second).getType() == 1)
{
to_delete.insert((*iter).first);
}
}
for (std::set<QPDFObjGen>::iterator iter = to_delete.begin();
iter != to_delete.end(); ++iter)
{
this->m->xref_table.erase(*iter);
}
this->m->file->seek(0, SEEK_END);
qpdf_offset_t eof = this->m->file->tell();
this->m->file->seek(0, SEEK_SET);
bool in_obj = false;
qpdf_offset_t line_start = 0;
// Don't allow very long tokens here during recovery.
static size_t const MAX_LEN = 100;
while (this->m->file->tell() < eof)
{
this->m->file->findAndSkipNextEOL();
qpdf_offset_t next_line_start = this->m->file->tell();
this->m->file->seek(line_start, SEEK_SET);
QPDFTokenizer::Token t1 = readToken(this->m->file, true, MAX_LEN);
qpdf_offset_t token_start =
this->m->file->tell() - t1.getValue().length();
if (token_start >= next_line_start)
{
// don't process yet
}
else if (in_obj)
{
if (t1 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))
{
in_obj = false;
}
}
else
{
if (t1.getType() == QPDFTokenizer::tt_integer)
{
QPDFTokenizer::Token t2 =
readToken(this->m->file, true, MAX_LEN);
QPDFTokenizer::Token t3 =
readToken(this->m->file, true, MAX_LEN);
if ((t2.getType() == QPDFTokenizer::tt_integer) &&
(t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")))
{
in_obj = true;
int obj = atoi(t1.getValue().c_str());
int gen = atoi(t2.getValue().c_str());
insertXrefEntry(obj, 1, token_start, gen, true);
}
}
else if ((! this->m->trailer.isInitialized()) &&
(t1 == QPDFTokenizer::Token(
QPDFTokenizer::tt_word, "trailer")))
{
QPDFObjectHandle t =
readObject(this->m->file, "trailer", 0, 0, false);
if (! t.isDictionary())
{
// Oh well. It was worth a try.
}
else
{
setTrailer(t);
}
}
}
this->m->file->seek(next_line_start, SEEK_SET);
line_start = next_line_start;
}
if (! this->m->trailer.isInitialized())
{
// We could check the last encountered object to see if it was
// an xref stream. If so, we could try to get the trailer
// from there. This may make it possible to recover files
// with bad startxref pointers even when they have object
// streams.
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
"unable to find trailer "
"dictionary while recovering damaged file");
}
// We could iterate through the objects looking for streams and
// try to find objects inside of them, but it's probably not worth
// the trouble. Acrobat can't recover files with any errors in an
// xref stream, and this would be a real long shot anyway. If we
// wanted to do anything that involved looking at stream contents,
// we'd also have to call initializeEncryption() here. It's safe
// to call it more than once.
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDFWriter::parseVersion(std::string const& version,
int& major, int& minor) const
{
major = atoi(version.c_str());
minor = 0;
size_t p = version.find('.');
if ((p != std::string::npos) && (version.length() > p))
{
minor = atoi(version.substr(p + 1).c_str());
}
std::string tmp = QUtil::int_to_string(major) + "." +
QUtil::int_to_string(minor);
if (tmp != version)
{
throw std::logic_error(
"INTERNAL ERROR: QPDFWriter::parseVersion"
" called with invalid version number " + version);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDF::parse_xrefEntry(std::string const& line,
qpdf_offset_t& f1, int& f2, char& type)
{
// is_space and is_digit both return false on '\0', so this will
// not overrun the null-terminated buffer.
char const* p = line.c_str();
// Skip zero or more spaces. There aren't supposed to be any.
bool invalid = false;
while (QUtil::is_space(*p))
{
++p;
QTC::TC("qpdf", "QPDF ignore first space in xref entry");
invalid = true;
}
// Require digit
if (! QUtil::is_digit(*p))
{
return false;
}
// Gather digits
std::string f1_str;
while (QUtil::is_digit(*p))
{
f1_str.append(1, *p++);
}
// Require space
if (! QUtil::is_space(*p))
{
return false;
}
if (QUtil::is_space(*(p+1)))
{
QTC::TC("qpdf", "QPDF ignore first extra space in xref entry");
invalid = true;
}
// Skip spaces
while (QUtil::is_space(*p))
{
++p;
}
// Require digit
if (! QUtil::is_digit(*p))
{
return false;
}
// Gather digits
std::string f2_str;
while (QUtil::is_digit(*p))
{
f2_str.append(1, *p++);
}
// Require space
if (! QUtil::is_space(*p))
{
return false;
}
if (QUtil::is_space(*(p+1)))
{
QTC::TC("qpdf", "QPDF ignore second extra space in xref entry");
invalid = true;
}
// Skip spaces
while (QUtil::is_space(*p))
{
++p;
}
if ((*p == 'f') || (*p == 'n'))
{
type = *p;
}
else
{
return false;
}
if ((f1_str.length() != 10) || (f2_str.length() != 5))
{
QTC::TC("qpdf", "QPDF ignore length error xref entry");
invalid = true;
}
if (invalid)
{
warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"xref table",
this->m->file->getLastOffset(),
"accepting invalid xref table entry"));
}
f1 = QUtil::string_to_ll(f1_str.c_str());
f2 = atoi(f2_str.c_str());
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDF::resolveObjectsInStream(int obj_stream_number)
{
// Force resolution of object stream
QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0);
if (! obj_stream.isStream())
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" is not a stream");
}
// For linearization data in the object, use the data from the
// object stream for the objects in the stream.
QPDFObjGen stream_og(obj_stream_number, 0);
qpdf_offset_t end_before_space =
this->m->obj_cache[stream_og].end_before_space;
qpdf_offset_t end_after_space =
this->m->obj_cache[stream_og].end_after_space;
QPDFObjectHandle dict = obj_stream.getDict();
if (! (dict.getKey("/Type").isName() &&
dict.getKey("/Type").getName() == "/ObjStm"))
{
QTC::TC("qpdf", "QPDF ERR object stream with wrong type");
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"supposed object stream " +
QUtil::int_to_string(obj_stream_number) +
" has wrong type");
}
if (! (dict.getKey("/N").isInteger() &&
dict.getKey("/First").isInteger()))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
this->m->last_object_description,
this->m->file->getLastOffset(),
"object stream " +
QUtil::int_to_string(obj_stream_number) +
" has incorrect keys");
}
int n = dict.getKey("/N").getIntValue();
int first = dict.getKey("/First").getIntValue();
std::map<int, int> offsets;
PointerHolder<Buffer> bp = obj_stream.getStreamData();
PointerHolder<InputSource> input = new BufferInputSource(
"object stream " + QUtil::int_to_string(obj_stream_number),
bp.getPointer());
for (int i = 0; i < n; ++i)
{
QPDFTokenizer::Token tnum = readToken(input);
QPDFTokenizer::Token toffset = readToken(input);
if (! ((tnum.getType() == QPDFTokenizer::tt_integer) &&
(toffset.getType() == QPDFTokenizer::tt_integer)))
{
throw QPDFExc(qpdf_e_damaged_pdf, input->getName(),
this->m->last_object_description,
input->getLastOffset(),
"expected integer in object stream header");
}
int num = atoi(tnum.getValue().c_str());
int offset = QUtil::string_to_ll(toffset.getValue().c_str());
offsets[num] = offset + first;
}
// To avoid having to read the object stream multiple times, store
// all objects that would be found here in the cache. Remember
// that some objects stored here might have been overridden by new
// objects appended to the file, so it is necessary to recheck the
// xref table and only cache what would actually be resolved here.
for (std::map<int, int>::iterator iter = offsets.begin();
iter != offsets.end(); ++iter)
{
int obj = (*iter).first;
QPDFObjGen og(obj, 0);
QPDFXRefEntry const& entry = this->m->xref_table[og];
if ((entry.getType() == 2) &&
(entry.getObjStreamNumber() == obj_stream_number))
{
int offset = (*iter).second;
input->seek(offset, SEEK_SET);
QPDFObjectHandle oh = readObject(input, "", obj, 0, true);
this->m->obj_cache[og] =
ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
end_before_space, end_after_space);
}
else
{
QTC::TC("qpdf", "QPDF not caching overridden objstm object");
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDF::parse_xrefFirst(std::string const& line,
int& obj, int& num, int& bytes)
{
// is_space and is_digit both return false on '\0', so this will
// not overrun the null-terminated buffer.
char const* p = line.c_str();
char const* start = line.c_str();
// Skip zero or more spaces
while (QUtil::is_space(*p))
{
++p;
}
// Require digit
if (! QUtil::is_digit(*p))
{
return false;
}
// Gather digits
std::string obj_str;
while (QUtil::is_digit(*p))
{
obj_str.append(1, *p++);
}
// Require space
if (! QUtil::is_space(*p))
{
return false;
}
// Skip spaces
while (QUtil::is_space(*p))
{
++p;
}
// Require digit
if (! QUtil::is_digit(*p))
{
return false;
}
// Gather digits
std::string num_str;
while (QUtil::is_digit(*p))
{
num_str.append(1, *p++);
}
// Skip any space including line terminators
while (QUtil::is_space(*p))
{
++p;
}
bytes = p - start;
obj = atoi(obj_str.c_str());
num = atoi(num_str.c_str());
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char* argv[])
{
QUtil::setLineBuf(stdout);
if ((whoami = strrchr(argv[0], '/')) == NULL)
{
whoami = argv[0];
}
else
{
++whoami;
}
// For libtool's sake....
if (strncmp(whoami, "lt-", 3) == 0)
{
whoami += 3;
}
if (argc != 2)
{
usage();
}
try
{
int n = atoi(argv[1]);
runtest(n);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
exit(2);
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Replace all atoi calls with QUtil::string_to_int
The latter catches underflow/overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: QPDF::read_xref(qpdf_offset_t xref_offset)
{
std::map<int, int> free_table;
while (xref_offset)
{
char buf[7];
memset(buf, 0, sizeof(buf));
this->m->file->seek(xref_offset, SEEK_SET);
this->m->file->read(buf, sizeof(buf) - 1);
// The PDF spec says xref must be followed by a line
// terminator, but files exist in the wild where it is
// terminated by arbitrary whitespace.
if ((strncmp(buf, "xref", 4) == 0) &&
QUtil::is_space(buf[4]))
{
QTC::TC("qpdf", "QPDF xref space",
((buf[4] == '\n') ? 0 :
(buf[4] == '\r') ? 1 :
(buf[4] == ' ') ? 2 : 9999));
int skip = 4;
// buf is null-terminated, and QUtil::is_space('\0') is
// false, so this won't overrun.
while (QUtil::is_space(buf[skip]))
{
++skip;
}
xref_offset = read_xrefTable(xref_offset + skip);
}
else
{
xref_offset = read_xrefStream(xref_offset);
}
}
if (! this->m->trailer.isInitialized())
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
"unable to find trailer while reading xref");
}
int size = this->m->trailer.getKey("/Size").getIntValue();
int max_obj = 0;
if (! this->m->xref_table.empty())
{
max_obj = (*(this->m->xref_table.rbegin())).first.getObj();
}
if (! this->m->deleted_objects.empty())
{
max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin()));
}
if (size != max_obj + 1)
{
QTC::TC("qpdf", "QPDF xref size mismatch");
warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0,
std::string("reported number of objects (") +
QUtil::int_to_string(size) +
") inconsistent with actual number of objects (" +
QUtil::int_to_string(max_obj + 1) + ")"));
}
// We no longer need the deleted_objects table, so go ahead and
// clear it out to make sure we never depend on its being set.
this->m->deleted_objects.clear();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Detect xref pointer infinite loop (fixes #149)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
const unsigned char *end )
{
int ret = 0;
size_t n;
if( ssl->conf->f_psk == NULL &&
( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Receive client pre-shared key identity name
*/
if( *p + 2 > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
n = ( (*p)[0] << 8 ) | (*p)[1];
*p += 2;
if( n < 1 || n > 65535 || *p + n > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ssl->conf->f_psk != NULL )
{
if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
else
{
/* Identity is not a big secret since clients send it in the clear,
* but treat it carefully anyway, just in case */
if( n != ssl->conf->psk_identity_len ||
mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
{
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
}
if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
{
MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
}
*p += n;
return( 0 );
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'Prevent bounds check bypass through overflow in PSK identity parsing
The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is
unsafe because `*p + n` might overflow, thus bypassing the check. As
`n` is a user-specified value up to 65K, this is relevant if the
library happens to be located in the last 65K of virtual memory.
This commit replaces the check by a safe version.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc,
char **argv)
{
char *filein, *str, *tempfile, *prestring, *outprotos, *protostr;
const char *spacestr = " ";
char buf[L_BUF_SIZE];
l_uint8 *allheaders;
l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret;
size_t nbytes;
L_BYTEA *ba, *ba2;
SARRAY *sa, *safirst;
static char mainName[] = "xtractprotos";
if (argc == 1) {
fprintf(stderr,
"xtractprotos [-prestring=<string>] [-protos=<where>] "
"[list of C files]\n"
"where the prestring is prepended to each prototype, and \n"
"protos can be either 'inline' or the name of an output "
"prototype file\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Parse input flags and find prestring and outprotos, if requested */
/* ---------------------------------------------------------------- */
prestring = outprotos = NULL;
in_line = FALSE;
nflags = 0;
maxindex = L_MIN(3, argc);
for (i = 1; i < maxindex; i++) {
if (argv[i][0] == '-') {
if (!strncmp(argv[i], "-prestring", 10)) {
nflags++;
ret = sscanf(argv[i] + 1, "prestring=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for prestring\n");
return 1;
}
if ((len = strlen(buf)) > L_BUF_SIZE - 3) {
L_WARNING("prestring too large; omitting!\n", mainName);
} else {
buf[len] = ' ';
buf[len + 1] = '\0';
prestring = stringNew(buf);
}
} else if (!strncmp(argv[i], "-protos", 7)) {
nflags++;
ret = sscanf(argv[i] + 1, "protos=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for protos\n");
return 1;
}
outprotos = stringNew(buf);
if (!strncmp(outprotos, "inline", 7))
in_line = TRUE;
}
}
}
if (argc - nflags < 2) {
fprintf(stderr, "no files specified!\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Generate the prototype string */
/* ---------------------------------------------------------------- */
ba = l_byteaCreate(500);
/* First the extern C head */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"/*", L_COPY);
snprintf(buf, L_BUF_SIZE,
" * These prototypes were autogen'd by xtractprotos, v. %s",
version);
sarrayAddString(sa, buf, L_COPY);
sarrayAddString(sa, (char *)" */", L_COPY);
sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
/* Then the prototypes */
firstfile = 1 + nflags;
protos_added = FALSE;
if ((tempfile = l_makeTempFilename()) == NULL) {
fprintf(stderr, "failure to make a writeable temp file\n");
return 1;
}
for (i = firstfile; i < argc; i++) {
filein = argv[i];
len = strlen(filein);
if (filein[len - 1] == 'h') /* skip .h files */
continue;
snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s",
filein, tempfile);
ret = system(buf); /* cpp */
if (ret) {
fprintf(stderr, "cpp failure for %s; continuing\n", filein);
continue;
}
if ((str = parseForProtos(tempfile, prestring)) == NULL) {
fprintf(stderr, "parse failure for %s; continuing\n", filein);
continue;
}
if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */
l_byteaAppendString(ba, str);
protos_added = TRUE;
}
lept_free(str);
}
lept_rmfile(tempfile);
lept_free(tempfile);
/* Lastly the extern C tail */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"}", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
protostr = (char *)l_byteaCopyData(ba, &nbytes);
l_byteaDestroy(&ba);
/* ---------------------------------------------------------------- */
/* Generate the output */
/* ---------------------------------------------------------------- */
if (!outprotos) { /* just write to stdout */
fprintf(stderr, "%s\n", protostr);
lept_free(protostr);
return 0;
}
/* If no protos were found, do nothing further */
if (!protos_added) {
fprintf(stderr, "No protos found\n");
lept_free(protostr);
return 1;
}
/* Make the output files */
ba = l_byteaInitFromFile("allheaders_top.txt");
if (!in_line) {
snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos);
l_byteaAppendString(ba, buf);
l_binaryWrite(outprotos, "w", protostr, nbytes);
} else {
l_byteaAppendString(ba, protostr);
}
ba2 = l_byteaInitFromFile("allheaders_bot.txt");
l_byteaJoin(ba, &ba2);
l_byteaWrite("allheaders.h", ba, 0, 0);
l_byteaDestroy(&ba);
lept_free(protostr);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gplotCreate(const char *rootname,
l_int32 outformat,
const char *title,
const char *xlabel,
const char *ylabel)
{
char *newroot;
char buf[L_BUF_SIZE];
l_int32 badchar;
GPLOT *gplot;
PROCNAME("gplotCreate");
if (!rootname)
return (GPLOT *)ERROR_PTR("rootname not defined", procName, NULL);
if (outformat != GPLOT_PNG && outformat != GPLOT_PS &&
outformat != GPLOT_EPS && outformat != GPLOT_LATEX)
return (GPLOT *)ERROR_PTR("outformat invalid", procName, NULL);
stringCheckForChars(rootname, "`;&|><\"?*", &badchar);
if (badchar) /* danger of command injection */
return (GPLOT *)ERROR_PTR("invalid rootname", procName, NULL);
if ((gplot = (GPLOT *)LEPT_CALLOC(1, sizeof(GPLOT))) == NULL)
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
gplot->cmddata = sarrayCreate(0);
gplot->datanames = sarrayCreate(0);
gplot->plotdata = sarrayCreate(0);
gplot->plottitles = sarrayCreate(0);
gplot->plotstyles = numaCreate(0);
/* Save title, labels, rootname, outformat, cmdname, outname */
newroot = genPathname(rootname, NULL);
gplot->rootname = newroot;
gplot->outformat = outformat;
snprintf(buf, L_BUF_SIZE, "%s.cmd", rootname);
gplot->cmdname = stringNew(buf);
if (outformat == GPLOT_PNG)
snprintf(buf, L_BUF_SIZE, "%s.png", newroot);
else if (outformat == GPLOT_PS)
snprintf(buf, L_BUF_SIZE, "%s.ps", newroot);
else if (outformat == GPLOT_EPS)
snprintf(buf, L_BUF_SIZE, "%s.eps", newroot);
else if (outformat == GPLOT_LATEX)
snprintf(buf, L_BUF_SIZE, "%s.tex", newroot);
gplot->outname = stringNew(buf);
if (title) gplot->title = stringNew(title);
if (xlabel) gplot->xlabel = stringNew(xlabel);
if (ylabel) gplot->ylabel = stringNew(ylabel);
return gplot;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: selReadStream(FILE *fp)
{
char *selname;
char linebuf[L_BUF_SIZE];
l_int32 sy, sx, cy, cx, i, j, version, ignore;
SEL *sel;
PROCNAME("selReadStream");
if (!fp)
return (SEL *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, " Sel Version %d\n", &version) != 1)
return (SEL *)ERROR_PTR("not a sel file", procName, NULL);
if (version != SEL_VERSION_NUMBER)
return (SEL *)ERROR_PTR("invalid sel version", procName, NULL);
if (fgets(linebuf, L_BUF_SIZE, fp) == NULL)
return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL);
selname = stringNew(linebuf);
sscanf(linebuf, " ------ %s ------", selname);
if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n",
&sy, &sx, &cy, &cx) != 4) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("dimensions not read", procName, NULL);
}
if ((sel = selCreate(sy, sx, selname)) == NULL) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
}
selSetOrigin(sel, cy, cx);
for (i = 0; i < sy; i++) {
ignore = fscanf(fp, " ");
for (j = 0; j < sx; j++)
ignore = fscanf(fp, "%1d", &sel->data[i][j]);
ignore = fscanf(fp, "\n");
}
ignore = fscanf(fp, "\n");
LEPT_FREE(selname);
return sel;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gplotMakeOutput(GPLOT *gplot)
{
char buf[L_BUF_SIZE];
char *cmdname;
l_int32 ignore;
PROCNAME("gplotMakeOutput");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
gplotGenCommandFile(gplot);
gplotGenDataFiles(gplot);
cmdname = genPathname(gplot->cmdname, NULL);
#ifndef _WIN32
snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname);
#else
snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname);
#endif /* _WIN32 */
#ifndef OS_IOS /* iOS 11 does not support system() */
ignore = system(buf); /* gnuplot || wgnuplot */
#endif /* !OS_IOS */
LEPT_FREE(cmdname);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: gplotRead(const char *filename)
{
char buf[L_BUF_SIZE];
char *rootname, *title, *xlabel, *ylabel, *ignores;
l_int32 outformat, ret, version, ignore;
FILE *fp;
GPLOT *gplot;
PROCNAME("gplotRead");
if (!filename)
return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL);
ret = fscanf(fp, "Gplot Version %d\n", &version);
if (ret != 1) {
fclose(fp);
return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL);
}
if (version != GPLOT_VERSION_NUMBER) {
fclose(fp);
return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL);
}
ignore = fscanf(fp, "Rootname: %s\n", buf);
rootname = stringNew(buf);
ignore = fscanf(fp, "Output format: %d\n", &outformat);
ignores = fgets(buf, L_BUF_SIZE, fp); /* Title: ... */
title = stringNew(buf + 7);
title[strlen(title) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* X axis label: ... */
xlabel = stringNew(buf + 14);
xlabel[strlen(xlabel) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* Y axis label: ... */
ylabel = stringNew(buf + 14);
ylabel[strlen(ylabel) - 1] = '\0';
gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel);
LEPT_FREE(rootname);
LEPT_FREE(title);
LEPT_FREE(xlabel);
LEPT_FREE(ylabel);
if (!gplot) {
fclose(fp);
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
}
sarrayDestroy(&gplot->cmddata);
sarrayDestroy(&gplot->datanames);
sarrayDestroy(&gplot->plotdata);
sarrayDestroy(&gplot->plottitles);
numaDestroy(&gplot->plotstyles);
ignore = fscanf(fp, "Commandfile name: %s\n", buf);
stringReplace(&gplot->cmdname, buf);
ignore = fscanf(fp, "\nCommandfile data:");
gplot->cmddata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nDatafile names:");
gplot->datanames = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot data:");
gplot->plotdata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot titles:");
gplot->plottitles = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot styles:");
gplot->plotstyles = numaReadStream(fp);
ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots);
ignore = fscanf(fp, "Output file name: %s\n", buf);
stringReplace(&gplot->outname, buf);
ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling);
fclose(fp);
return gplot;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sig_print_starting(TEXT_DEST_REC *dest)
{
NETJOIN_SERVER_REC *rec;
if (printing_joins)
return;
if (!IS_IRC_SERVER(dest->server))
return;
if (!(dest->level & MSGLEVEL_PUBLIC))
return;
if (!server_ischannel(dest->server, dest->target))
return;
rec = netjoin_find_server(IRC_SERVER(dest->server));
if (rec != NULL && rec->netjoins != NULL)
print_netjoins(rec, dest->target);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge pull request #812 from ailin-nemui/tape-netsplit
revert netsplit print optimisation
(cherry picked from commit 7de1378dab8081932d9096e19ae3d0921e560230)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sig_print_starting(TEXT_DEST_REC *dest)
{
NETJOIN_SERVER_REC *rec;
if (printing_joins)
return;
if (!IS_IRC_SERVER(dest->server))
return;
if (!server_ischannel(dest->server, dest->target))
return;
rec = netjoin_find_server(IRC_SERVER(dest->server));
if (rec != NULL && rec->netjoins != NULL)
print_netjoins(rec, NULL);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge pull request #824 from dequis/more-netsplit-revert
Revert more of the netsplit print optimisation to fix crashes
(cherry picked from commit cfcc021c81eea84bd982a64764f62e163128acf3)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void irc_core_deinit(void)
{
signal_emit("chat protocol deinit", 1, chat_protocol_find("IRC"));
cap_deinit();
irc_expandos_deinit();
netsplit_deinit();
lag_deinit();
irc_commands_deinit();
ctcp_deinit();
irc_queries_deinit();
irc_channels_deinit();
irc_irc_deinit();
irc_servers_deinit();
irc_chatnets_deinit();
irc_session_deinit();
chat_protocol_unregister("IRC");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'SASL support
The only supported methods are PLAIN and EXTERNAL, the latter is untested as of
now.
The code gets the values from the keys named sasl_{mechanism,username,password}
specified for each chatnet.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void server_init(IRC_SERVER_REC *server)
{
IRC_SERVER_CONNECT_REC *conn;
char *address, *ptr, *username, *cmd;
GTimeVal now;
g_return_if_fail(server != NULL);
conn = server->connrec;
if (conn->proxy != NULL && conn->proxy_password != NULL &&
*conn->proxy_password != '\0') {
cmd = g_strdup_printf("PASS %s", conn->proxy_password);
irc_send_cmd_now(server, cmd);
g_free(cmd);
}
if (conn->proxy != NULL && conn->proxy_string != NULL) {
cmd = g_strdup_printf(conn->proxy_string, conn->address, conn->port);
irc_send_cmd_now(server, cmd);
g_free(cmd);
}
irc_send_cmd_now(server, "CAP LS");
if (conn->password != NULL && *conn->password != '\0') {
/* send password */
cmd = g_strdup_printf("PASS %s", conn->password);
irc_send_cmd_now(server, cmd);
g_free(cmd);
}
/* send nick */
cmd = g_strdup_printf("NICK %s", conn->nick);
irc_send_cmd_now(server, cmd);
g_free(cmd);
/* send user/realname */
address = server->connrec->address;
ptr = strrchr(address, ':');
if (ptr != NULL) {
/* IPv6 address .. doesn't work here, use the string after
the last : char */
address = ptr+1;
if (*address == '\0')
address = "x";
}
username = g_strdup(conn->username);
ptr = strchr(username, ' ');
if (ptr != NULL) *ptr = '\0';
cmd = g_strdup_printf("USER %s %s %s :%s", username, username, address, conn->realname);
irc_send_cmd_now(server, cmd);
g_free(cmd);
g_free(username);
if (conn->proxy != NULL && conn->proxy_string_after != NULL) {
cmd = g_strdup_printf(conn->proxy_string_after, conn->address, conn->port);
irc_send_cmd_now(server, cmd);
g_free(cmd);
}
server->isupport = g_hash_table_new((GHashFunc) g_istr_hash,
(GCompareFunc) g_istr_equal);
/* set the standards */
g_hash_table_insert(server->isupport, g_strdup("CHANMODES"), g_strdup("beI,k,l,imnpst"));
g_hash_table_insert(server->isupport, g_strdup("PREFIX"), g_strdup("(ohv)@%+"));
server->cmdcount = 0;
/* prevent the queue from sending too early, we have a max cut off of 120 secs */
/* this will reset to 1 sec after we get the 001 event */
g_get_current_time(&now);
memcpy(&((IRC_SERVER_REC *)server)->wait_cmd, &now, sizeof(GTimeVal));
((IRC_SERVER_REC *)server)->wait_cmd.tv_sec += 120;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'SASL support
The only supported methods are PLAIN and EXTERNAL, the latter is untested as of
now.
The code gets the values from the keys named sasl_{mechanism,username,password}
specified for each chatnet.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sig_chatnet_destroyed(IRC_CHATNET_REC *rec)
{
if (IS_IRC_CHATNET(rec))
g_free(rec->usermode);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'SASL support
The only supported methods are PLAIN and EXTERNAL, the latter is untested as of
now.
The code gets the values from the keys named sasl_{mechanism,username,password}
specified for each chatnet.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sasl_disconnected(IRC_SERVER_REC *server)
{
g_return_if_fail(server != NULL);
if (!IS_IRC_SERVER(server)) {
return;
}
if (server->sasl_timeout != 0) {
g_source_remove(server->sasl_timeout);
server->sasl_timeout = 0;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sasl_fail(IRC_SERVER_REC *server, const char *data, const char *from)
{
char *params, *error;
/* Stop any pending timeout, if any */
if (server->sasl_timeout != 0) {
g_source_remove(server->sasl_timeout);
server->sasl_timeout = 0;
}
params = event_get_params(data, 2, NULL, &error);
server->sasl_success = FALSE;
signal_emit("server sasl failure", 2, server, error);
/* Terminate the negotiation */
cap_finish_negotiation(server);
g_free(params);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sig_message_public(SERVER_REC *server, const char *msg,
const char *nick, const char *address,
const char *target)
{
CHANNEL_REC *channel;
int own;
channel = channel_find(server, target);
if (channel != NULL) {
own = nick_match_msg(channel, msg, server->nick);
CHANNEL_LAST_MSG_ADD(channel, nick, own);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sasl_step_fail(IRC_SERVER_REC *server)
{
irc_send_cmd_now(server, "AUTHENTICATE *");
cap_finish_negotiation(server);
server->sasl_timeout = 0;
signal_emit("server sasl failure", 2, server, "The server sent an invalid payload");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void sig_message_join(SERVER_REC *server, const char *channel,
const char *nick, const char *address)
{
CHANNEL_REC *chanrec;
chanrec = channel_find(server, channel);
if (chanrec != NULL)
CHANNEL_LAST_MSG_ADD(chanrec, nick, FALSE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void cmd_oper_got_pass(const char *password, OPER_PASS_REC *rec)
{
if (*password != '\0')
irc_send_cmdv(rec->server, "OPER %s %s", rec->nick, password);
g_free(rec->nick);
g_free(rec);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master'
Security
See merge request irssi/irssi!34
(cherry picked from commit b0d9cb33cd9ef9da7c331409e8b7c57a6f3aef3f)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static char *theme_format_expand_abstract(THEME_REC *theme,
const char **formatp,
char default_fg, char default_bg,
int flags)
{
const char *p, *format;
char *abstract, *data, *ret;
int len;
format = *formatp;
/* get abstract name first */
p = format;
while (*p != '\0' && *p != ' ' &&
*p != '{' && *p != '}') p++;
if (*p == '\0' || p == format)
return NULL; /* error */
len = (int) (p-format);
abstract = g_strndup(format, len);
/* skip the following space, if there's any more spaces they're
treated as arguments */
if (*p == ' ') {
len++;
if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {
*formatp = p;
g_free(abstract);
return NULL;
}
}
*formatp = format+len;
/* get the abstract data */
data = g_hash_table_lookup(theme->abstracts, abstract);
g_free(abstract);
if (data == NULL) {
/* unknown abstract, just display the data */
data = "$0-";
}
abstract = g_strdup(data);
/* we'll need to get the data part. it may contain
more abstracts, they are _NOT_ expanded. */
data = theme_format_expand_get(theme, formatp);
len = strlen(data);
if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {
/* ends with $<digit> .. this breaks things if next
character is digit or '-' */
char digit, *tmp;
tmp = data;
digit = tmp[len-1];
tmp[len-1] = '\0';
data = g_strdup_printf("%s{%c}", tmp, digit);
g_free(tmp);
}
ret = parse_special_string(abstract, NULL, NULL, data, NULL,
PARSE_FLAG_ONLY_ARGS);
g_free(abstract);
g_free(data);
abstract = ret;
/* abstract may itself contain abstracts or replaces */
p = abstract;
ret = theme_format_expand_data(theme, &p, default_fg, default_bg,
&default_fg, &default_bg,
flags | EXPAND_FLAG_LASTCOLOR_ARG);
g_free(abstract);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Previous theme patch fixes by c0ffee
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@3058 dbcabf3a-b0e7-0310-adc4-f8d773084564'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static char *theme_format_expand_abstract(THEME_REC *theme, const char **formatp,
theme_rm_col *last_fg, theme_rm_col *last_bg, int flags,
GTree *block_list)
{
GString *str;
const char *p, *format;
char *abstract, *data, *ret;
theme_rm_col default_fg, default_bg;
int len;
format = *formatp;
default_fg = *last_fg;
default_bg = *last_bg;
/* get abstract name first */
p = format;
while (*p != '\0' && *p != ' ' &&
*p != '{' && *p != '}') p++;
if (*p == '\0' || p == format)
return NULL; /* error */
len = (int) (p-format);
abstract = g_strndup(format, len);
/* skip the following space, if there's any more spaces they're
treated as arguments */
if (*p == ' ') {
len++;
if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {
*formatp = p;
g_free(abstract);
return NULL;
}
}
*formatp = format+len;
if (block_list == NULL) {
block_list = g_tree_new_full((GCompareDataFunc) g_strcmp0, NULL, g_free, NULL);
} else {
g_tree_ref(block_list);
}
/* get the abstract data */
data = g_hash_table_lookup(theme->abstracts, abstract);
if (data == NULL || g_tree_lookup(block_list, abstract) != NULL) {
/* unknown abstract, just display the data */
data = "$0-";
g_free(abstract);
} else {
g_tree_insert(block_list, abstract, abstract);
}
abstract = g_strdup(data);
/* we'll need to get the data part. it may contain
more abstracts, they are _NOT_ expanded. */
data = theme_format_expand_get(theme, formatp);
len = strlen(data);
if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {
/* ends with $<digit> .. this breaks things if next
character is digit or '-' */
char digit, *tmp;
tmp = data;
digit = tmp[len-1];
tmp[len-1] = '\0';
data = g_strdup_printf("%s{%c}", tmp, digit);
g_free(tmp);
}
ret = parse_special_string(abstract, NULL, NULL, data, NULL,
PARSE_FLAG_ONLY_ARGS);
g_free(abstract);
g_free(data);
str = g_string_new(NULL);
p = ret;
while (*p != '\0') {
if (*p == '\\') {
int chr;
p++;
chr = expand_escape(&p);
g_string_append_c(str, chr != -1 ? chr : *p);
} else
g_string_append_c(str, *p);
p++;
}
g_free(ret);
abstract = str->str;
g_string_free(str, FALSE);
/* abstract may itself contain abstracts or replaces */
p = abstract;
ret = theme_format_expand_data_rec(theme, &p, default_fg, default_bg, last_fg, last_bg,
flags | EXPAND_FLAG_LASTCOLOR_ARG, block_list);
g_free(abstract);
g_tree_unref(block_list);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Do not read beyond end of escaped string
Credit to OSS-Fuzz'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pixHtmlViewer(const char *dirin,
const char *dirout,
const char *rootname,
l_int32 thumbwidth,
l_int32 viewwidth)
{
char *fname, *fullname, *outname;
char *mainname, *linkname, *linknameshort;
char *viewfile, *thumbfile;
char *shtml, *slink;
char charbuf[512];
char htmlstring[] = "<html>";
char framestring[] = "</frameset></html>";
l_int32 i, nfiles, index, w, d, nimages, ret;
l_float32 factor;
PIX *pix, *pixthumb, *pixview;
SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink;
PROCNAME("pixHtmlViewer");
if (!dirin)
return ERROR_INT("dirin not defined", procName, 1);
if (!dirout)
return ERROR_INT("dirout not defined", procName, 1);
if (!rootname)
return ERROR_INT("rootname not defined", procName, 1);
if (thumbwidth == 0)
thumbwidth = DEFAULT_THUMB_WIDTH;
if (thumbwidth < MIN_THUMB_WIDTH) {
L_WARNING("thumbwidth too small; using min value\n", procName);
thumbwidth = MIN_THUMB_WIDTH;
}
if (viewwidth == 0)
viewwidth = DEFAULT_VIEW_WIDTH;
if (viewwidth < MIN_VIEW_WIDTH) {
L_WARNING("viewwidth too small; using min value\n", procName);
viewwidth = MIN_VIEW_WIDTH;
}
/* Make the output directory if it doesn't already exist */
#ifndef _WIN32
snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout);
ret = system(charbuf);
#else
ret = CreateDirectory(dirout, NULL) ? 0 : 1;
#endif /* !_WIN32 */
if (ret) {
L_ERROR("output directory %s not made\n", procName, dirout);
return 1;
}
/* Capture the filenames in the input directory */
if ((safiles = getFilenamesInDirectory(dirin)) == NULL)
return ERROR_INT("safiles not made", procName, 1);
/* Generate output text file names */
sprintf(charbuf, "%s/%s.html", dirout, rootname);
mainname = stringNew(charbuf);
sprintf(charbuf, "%s/%s-links.html", dirout, rootname);
linkname = stringNew(charbuf);
linknameshort = stringJoin(rootname, "-links.html");
/* Generate the thumbs and views */
sathumbs = sarrayCreate(0);
saviews = sarrayCreate(0);
nfiles = sarrayGetCount(safiles);
index = 0;
for (i = 0; i < nfiles; i++) {
fname = sarrayGetString(safiles, i, L_NOCOPY);
fullname = genPathname(dirin, fname);
fprintf(stderr, "name: %s\n", fullname);
if ((pix = pixRead(fullname)) == NULL) {
fprintf(stderr, "file %s not a readable image\n", fullname);
lept_free(fullname);
continue;
}
lept_free(fullname);
/* Make and store the thumbnail images */
pixGetDimensions(pix, &w, NULL, &d);
factor = (l_float32)thumbwidth / (l_float32)w;
pixthumb = pixScale(pix, factor, factor);
sprintf(charbuf, "%s_thumb_%03d", rootname, index);
sarrayAddString(sathumbs, charbuf, L_COPY);
outname = genPathname(dirout, charbuf);
WriteFormattedPix(outname, pixthumb);
lept_free(outname);
pixDestroy(&pixthumb);
/* Make and store the view images */
factor = (l_float32)viewwidth / (l_float32)w;
if (factor >= 1.0)
pixview = pixClone(pix); /* no upscaling */
else
pixview = pixScale(pix, factor, factor);
snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index);
sarrayAddString(saviews, charbuf, L_COPY);
outname = genPathname(dirout, charbuf);
WriteFormattedPix(outname, pixview);
lept_free(outname);
pixDestroy(&pixview);
pixDestroy(&pix);
index++;
}
/* Generate the main html file */
sahtml = sarrayCreate(0);
sarrayAddString(sahtml, htmlstring, L_COPY);
sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30);
sarrayAddString(sahtml, charbuf, L_COPY);
sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort);
sarrayAddString(sahtml, charbuf, L_COPY);
sprintf(charbuf, "<frame name=\"views\" src=\"%s\">",
sarrayGetString(saviews, 0, L_NOCOPY));
sarrayAddString(sahtml, charbuf, L_COPY);
sarrayAddString(sahtml, framestring, L_COPY);
shtml = sarrayToString(sahtml, 1);
l_binaryWrite(mainname, "w", shtml, strlen(shtml));
fprintf(stderr, "******************************************\n"
"Writing html file: %s\n"
"******************************************\n", mainname);
lept_free(shtml);
lept_free(mainname);
/* Generate the link html file */
nimages = sarrayGetCount(saviews);
fprintf(stderr, "num. images = %d\n", nimages);
salink = sarrayCreate(0);
for (i = 0; i < nimages; i++) {
viewfile = sarrayGetString(saviews, i, L_NOCOPY);
thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY);
sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>",
viewfile, thumbfile);
sarrayAddString(salink, charbuf, L_COPY);
}
slink = sarrayToString(salink, 1);
l_binaryWrite(linkname, "w", slink, strlen(slink));
lept_free(slink);
lept_free(linkname);
lept_free(linknameshort);
sarrayDestroy(&safiles);
sarrayDestroy(&sathumbs);
sarrayDestroy(&saviews);
sarrayDestroy(&sahtml);
sarrayDestroy(&salink);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'prog/htmlviewer: Catch unbound memory access (CID 1386222)
rootname can have any size, so limit the amount of copied bytes.
Signed-off-by: Stefan Weil <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool Webm2Pes::WritePesPacket(const VideoFrame& frame,
PacketDataBuffer* packet_data) {
if (frame.buffer().data.get() == nullptr || frame.buffer().length < 1)
return false;
Ranges frame_ranges;
if (frame.codec() == VideoFrame::kVP9) {
const bool has_superframe_index = ParseVP9SuperFrameIndex(
frame.buffer().data.get(), frame.buffer().length, &frame_ranges);
if (has_superframe_index == false) {
frame_ranges.push_back(Range(0, frame.buffer().length));
}
} else {
frame_ranges.push_back(Range(0, frame.buffer().length));
}
const std::int64_t khz90_pts =
NanosecondsTo90KhzTicks(frame.nanosecond_pts());
PesHeader header;
header.optional_header.SetPtsBits(khz90_pts);
packet_data->clear();
for (const Range& packet_payload_range : frame_ranges) {
std::size_t extra_bytes = 0;
if (packet_payload_range.length > kMaxPayloadSize) {
extra_bytes = packet_payload_range.length - kMaxPayloadSize;
}
// First packet of new frame. Always include PTS and BCMV header.
header.packet_length =
packet_payload_range.length - extra_bytes + BCMVHeader::size();
if (header.Write(true, packet_data) != true) {
std::fprintf(stderr, "Webm2Pes: packet header write failed.\n");
return false;
}
BCMVHeader bcmv_header(static_cast<uint32_t>(packet_payload_range.length));
if (bcmv_header.Write(packet_data) != true) {
std::fprintf(stderr, "Webm2Pes: BCMV write failed.\n");
return false;
}
// Insert the payload at the end of |packet_data|.
const std::uint8_t* const payload_start =
frame.buffer().data.get() + packet_payload_range.offset;
const std::size_t bytes_to_copy = packet_payload_range.length - extra_bytes;
if (CopyAndEscapeStartCodes(payload_start, bytes_to_copy, packet_data) ==
false) {
fprintf(stderr, "Webm2Pes: Payload write failed.\n");
return false;
}
std::size_t bytes_copied = bytes_to_copy;
while (extra_bytes) {
// Write PES packets for the remaining data, but omit the PTS and BCMV
// header.
const std::size_t extra_bytes_to_copy =
std::min(kMaxPayloadSize, extra_bytes);
extra_bytes -= extra_bytes_to_copy;
header.packet_length = extra_bytes_to_copy;
if (header.Write(false, packet_data) != true) {
fprintf(stderr, "Webm2pes: fragment write failed.\n");
return false;
}
const std::uint8_t* fragment_start = payload_start + bytes_copied;
if (CopyAndEscapeStartCodes(fragment_start, extra_bytes_to_copy,
packet_data) == false) {
fprintf(stderr, "Webm2Pes: Payload write failed.\n");
return false;
}
bytes_copied += extra_bytes_to_copy;
}
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'webm2pes: Avoid OOB reads caused by invalid superframe index.
BUG=webm:1492
Change-Id: Ibd5781731fe8f6fcdf5f1cc6e5807d17b3b92d4d'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
uint32_t chan_chunk = 0, channel_layout = 0, bcount;
unsigned char *channel_identities = NULL;
unsigned char *channel_reorder = NULL;
int64_t total_samples = 0, infilesize;
CAFFileHeader caf_file_header;
CAFChunkHeader caf_chunk_header;
CAFAudioFormat caf_audio_format;
int i;
infilesize = DoGetFileSize (infile);
memcpy (&caf_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) ||
bcount != sizeof (CAFFileHeader) - 4)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat);
if (caf_file_header.mFileVersion != 1) {
error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion);
return WAVPACK_SOFT_ERROR;
}
// loop through all elements of the RIFF wav header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) ||
bcount != sizeof (CAFChunkHeader)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat);
// if it's the format chunk, we want to get some info out of there and
// make sure it's a .caf file we can handle
if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) {
int supported = TRUE;
if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) ||
!DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat);
if (debug_logging_mode) {
char formatstr [5];
memcpy (formatstr, caf_audio_format.mFormatID, 4);
formatstr [4] = 0;
error_line ("format = %s, flags = %x, sampling rate = %g",
formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate);
error_line ("packet = %d bytes and %d frames",
caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket);
error_line ("channels per frame = %d, bits per channel = %d",
caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel);
}
if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3))
supported = FALSE;
else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 ||
caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate))
supported = FALSE;
else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256)
supported = FALSE;
else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 ||
((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32))
supported = FALSE;
else if (caf_audio_format.mFramesPerPacket != 1 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 ||
caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 ||
caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .CAF format!", infilename);
return WAVPACK_SOFT_ERROR;
}
config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame;
config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0;
config->bits_per_sample = caf_audio_format.mBitsPerChannel;
config->num_channels = caf_audio_format.mChannelsPerFrame;
config->sample_rate = (int) caf_audio_format.mSampleRate;
if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1)
config->qmode |= QMODE_BIG_ENDIAN;
if (config->bytes_per_sample == 1)
config->qmode |= QMODE_SIGNED_BYTES;
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little");
else
error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)",
config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample);
}
}
else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) {
CAFChannelLayout *caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize);
if (caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout) ||
!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) ||
bcount != caf_chunk_header.mChunkSize) {
error_line ("%s is not a valid .CAF file!", infilename);
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat);
chan_chunk = 1;
if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) {
error_line ("this CAF file already has channel order information!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
switch (caf_channel_layout->mChannelLayoutTag) {
case kCAFChannelLayoutTag_UseChannelDescriptions:
{
CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1);
int num_descriptions = caf_channel_layout->mNumberChannelDescriptions;
int label, cindex = 0, idents = 0;
if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions ||
num_descriptions != config->num_channels) {
error_line ("channel descriptions in 'chan' chunk are the wrong size!");
free (caf_channel_layout);
return WAVPACK_SOFT_ERROR;
}
if (num_descriptions >= 256) {
error_line ("%d channel descriptions is more than we can handle...ignoring!");
break;
}
// we allocate (and initialize to invalid values) a channel reorder array
// (even though we might not end up doing any reordering) and a string for
// any non-Microsoft channels we encounter
channel_reorder = malloc (num_descriptions);
memset (channel_reorder, -1, num_descriptions);
channel_identities = malloc (num_descriptions+1);
// convert the descriptions array to our native endian so it's easy to access
for (i = 0; i < num_descriptions; ++i) {
WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat);
if (debug_logging_mode)
error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel);
}
// first, we go though and find any MS channels present, and move those to the beginning
for (label = 1; label <= 18; ++label)
for (i = 0; i < num_descriptions; ++i)
if (descriptions [i].mChannelLabel == label) {
config->channel_mask |= 1 << (label - 1);
channel_reorder [i] = cindex++;
break;
}
// next, we go though the channels again assigning any we haven't done
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] == (unsigned char) -1) {
uint32_t clabel = descriptions [i].mChannelLabel;
if (clabel == 0 || clabel == 0xffffffff || clabel == 100)
channel_identities [idents++] = 0xff;
else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305))
channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel;
else {
error_line ("warning: unknown channel descriptions label: %d", clabel);
channel_identities [idents++] = 0xff;
}
channel_reorder [i] = cindex++;
}
// then, go through the reordering array and see if we really have to reorder
for (i = 0; i < num_descriptions; ++i)
if (channel_reorder [i] != i)
break;
if (i == num_descriptions) {
free (channel_reorder); // no reordering required, so don't
channel_reorder = NULL;
}
else {
config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout
channel_layout = num_descriptions;
}
if (!idents) { // if no non-MS channels, free the identities string
free (channel_identities);
channel_identities = NULL;
}
else
channel_identities [idents] = 0; // otherwise NULL terminate it
if (debug_logging_mode) {
error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS",
caf_channel_layout->mChannelLayoutTag, config->channel_mask,
caf_channel_layout->mNumberChannelDescriptions, idents);
// if debugging, display the reordering as a string (but only little ones)
if (channel_reorder && num_descriptions <= 8) {
char reorder_string [] = "12345678";
for (i = 0; i < num_descriptions; ++i)
reorder_string [i] = channel_reorder [i] + '1';
reorder_string [i] = 0;
error_line ("reordering string = \"%s\"\n", reorder_string);
}
}
}
break;
case kCAFChannelLayoutTag_UseChannelBitmap:
config->channel_mask = caf_channel_layout->mChannelBitmap;
if (debug_logging_mode)
error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x",
caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap);
break;
default:
for (i = 0; i < NUM_LAYOUTS; ++i)
if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) {
config->channel_mask = layouts [i].mChannelBitmap;
channel_layout = layouts [i].mChannelLayoutTag;
if (layouts [i].mChannelReorder) {
channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder);
config->qmode |= QMODE_REORDERED_CHANS;
}
if (layouts [i].mChannelIdentities)
channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities);
if (debug_logging_mode)
error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s",
channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no");
break;
}
if (i == NUM_LAYOUTS && debug_logging_mode)
error_line ("layout_tag 0x%08x not found in table...all channels unassigned",
caf_channel_layout->mChannelLayoutTag);
break;
}
free (caf_channel_layout);
}
else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop
uint32_t mEditCount;
if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) ||
bcount != sizeof (mEditCount)) {
error_line ("%s is not a valid .CAF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) {
error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) {
error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename);
return WAVPACK_SOFT_ERROR;
}
total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket;
if (!total_samples) {
error_line ("this .CAF file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize;
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2],
caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED))
config->channel_mask = 0x5 - config->num_channels;
if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
if (channel_identities)
free (channel_identities);
if (channel_layout || channel_reorder) {
if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) {
error_line ("problem with setting channel layout (should not happen)");
return WAVPACK_SOFT_ERROR;
}
if (channel_reorder)
free (channel_reorder);
}
return WAVPACK_NO_ERROR;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'issue #28, fix buffer overflows and bad allocs on corrupt CAF files'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ip6t_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ip6t_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.hotdrop = false;
acpar.state = state;
WARN_ON(!(table->valid_hooks & (1 << hook)));
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ip6t_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
WARN_ON(!e);
acpar.thoff = 0;
if (!ip6_packet_match(skb, indev, outdev, &e->ipv6,
&acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) {
no_match:
e = ip6t_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ip6t_get_target_c(e);
WARN_ON(!t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0)
e = get_entry(table_base,
private->underflow[hook]);
else
e = ip6t_next_entry(jumpstack[--stackidx]);
continue;
}
if (table_base + v != ip6t_next_entry(e) &&
!(e->ipv6.flags & IP6T_F_GOTO)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE)
e = ip6t_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'netfilter: add back stackpointer size checks
The rationale for removing the check is only correct for rulesets
generated by ip(6)tables.
In iptables, a jump can only occur to a user-defined chain, i.e.
because we size the stack based on number of user-defined chains we
cannot exceed stack size.
However, the underlying binary format has no such restriction,
and the validation step only ensures that the jump target is a
valid rule start point.
IOW, its possible to build a rule blob that has no user-defined
chains but does contain a jump.
If this happens, no jump stack gets allocated and crash occurs
because no jumpstack was allocated.
Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset")
Reported-by: [email protected]
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_v4l2_framebuffer32(struct v4l2_framebuffer *kp, struct v4l2_framebuffer32 __user *up)
{
u32 tmp;
if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
get_user(tmp, &up->base) ||
get_user(kp->capability, &up->capability) ||
get_user(kp->flags, &up->flags) ||
copy_from_user(&kp->fmt, &up->fmt, sizeof(up->fmt)))
return -EFAULT;
kp->base = (__force void *)compat_ptr(tmp);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_v4l2_window32(struct v4l2_window *kp, struct v4l2_window32 __user *up)
{
struct v4l2_clip32 __user *uclips;
struct v4l2_clip __user *kclips;
compat_caddr_t p;
u32 n;
if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
copy_from_user(&kp->w, &up->w, sizeof(up->w)) ||
get_user(kp->field, &up->field) ||
get_user(kp->chromakey, &up->chromakey) ||
get_user(kp->clipcount, &up->clipcount) ||
get_user(kp->global_alpha, &up->global_alpha))
return -EFAULT;
if (kp->clipcount > 2048)
return -EINVAL;
if (!kp->clipcount) {
kp->clips = NULL;
return 0;
}
n = kp->clipcount;
if (get_user(p, &up->clips))
return -EFAULT;
uclips = compat_ptr(p);
kclips = compat_alloc_user_space(n * sizeof(*kclips));
kp->clips = kclips;
while (n--) {
if (copy_in_user(&kclips->c, &uclips->c, sizeof(uclips->c)))
return -EFAULT;
if (put_user(n ? kclips + 1 : NULL, &kclips->next))
return -EFAULT;
uclips++;
kclips++;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static long do_video_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
union {
struct v4l2_format v2f;
struct v4l2_buffer v2b;
struct v4l2_framebuffer v2fb;
struct v4l2_input v2i;
struct v4l2_standard v2s;
struct v4l2_ext_controls v2ecs;
struct v4l2_event v2ev;
struct v4l2_create_buffers v2crt;
struct v4l2_edid v2edid;
unsigned long vx;
int vi;
} karg;
void __user *up = compat_ptr(arg);
int compatible_arg = 1;
long err = 0;
/* First, convert the command. */
switch (cmd) {
case VIDIOC_G_FMT32: cmd = VIDIOC_G_FMT; break;
case VIDIOC_S_FMT32: cmd = VIDIOC_S_FMT; break;
case VIDIOC_QUERYBUF32: cmd = VIDIOC_QUERYBUF; break;
case VIDIOC_G_FBUF32: cmd = VIDIOC_G_FBUF; break;
case VIDIOC_S_FBUF32: cmd = VIDIOC_S_FBUF; break;
case VIDIOC_QBUF32: cmd = VIDIOC_QBUF; break;
case VIDIOC_DQBUF32: cmd = VIDIOC_DQBUF; break;
case VIDIOC_ENUMSTD32: cmd = VIDIOC_ENUMSTD; break;
case VIDIOC_ENUMINPUT32: cmd = VIDIOC_ENUMINPUT; break;
case VIDIOC_TRY_FMT32: cmd = VIDIOC_TRY_FMT; break;
case VIDIOC_G_EXT_CTRLS32: cmd = VIDIOC_G_EXT_CTRLS; break;
case VIDIOC_S_EXT_CTRLS32: cmd = VIDIOC_S_EXT_CTRLS; break;
case VIDIOC_TRY_EXT_CTRLS32: cmd = VIDIOC_TRY_EXT_CTRLS; break;
case VIDIOC_DQEVENT32: cmd = VIDIOC_DQEVENT; break;
case VIDIOC_OVERLAY32: cmd = VIDIOC_OVERLAY; break;
case VIDIOC_STREAMON32: cmd = VIDIOC_STREAMON; break;
case VIDIOC_STREAMOFF32: cmd = VIDIOC_STREAMOFF; break;
case VIDIOC_G_INPUT32: cmd = VIDIOC_G_INPUT; break;
case VIDIOC_S_INPUT32: cmd = VIDIOC_S_INPUT; break;
case VIDIOC_G_OUTPUT32: cmd = VIDIOC_G_OUTPUT; break;
case VIDIOC_S_OUTPUT32: cmd = VIDIOC_S_OUTPUT; break;
case VIDIOC_CREATE_BUFS32: cmd = VIDIOC_CREATE_BUFS; break;
case VIDIOC_PREPARE_BUF32: cmd = VIDIOC_PREPARE_BUF; break;
case VIDIOC_G_EDID32: cmd = VIDIOC_G_EDID; break;
case VIDIOC_S_EDID32: cmd = VIDIOC_S_EDID; break;
}
switch (cmd) {
case VIDIOC_OVERLAY:
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF:
case VIDIOC_S_INPUT:
case VIDIOC_S_OUTPUT:
err = get_user(karg.vi, (s32 __user *)up);
compatible_arg = 0;
break;
case VIDIOC_G_INPUT:
case VIDIOC_G_OUTPUT:
compatible_arg = 0;
break;
case VIDIOC_G_EDID:
case VIDIOC_S_EDID:
err = get_v4l2_edid32(&karg.v2edid, up);
compatible_arg = 0;
break;
case VIDIOC_G_FMT:
case VIDIOC_S_FMT:
case VIDIOC_TRY_FMT:
err = get_v4l2_format32(&karg.v2f, up);
compatible_arg = 0;
break;
case VIDIOC_CREATE_BUFS:
err = get_v4l2_create32(&karg.v2crt, up);
compatible_arg = 0;
break;
case VIDIOC_PREPARE_BUF:
case VIDIOC_QUERYBUF:
case VIDIOC_QBUF:
case VIDIOC_DQBUF:
err = get_v4l2_buffer32(&karg.v2b, up);
compatible_arg = 0;
break;
case VIDIOC_S_FBUF:
err = get_v4l2_framebuffer32(&karg.v2fb, up);
compatible_arg = 0;
break;
case VIDIOC_G_FBUF:
compatible_arg = 0;
break;
case VIDIOC_ENUMSTD:
err = get_v4l2_standard32(&karg.v2s, up);
compatible_arg = 0;
break;
case VIDIOC_ENUMINPUT:
err = get_v4l2_input32(&karg.v2i, up);
compatible_arg = 0;
break;
case VIDIOC_G_EXT_CTRLS:
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
err = get_v4l2_ext_controls32(file, &karg.v2ecs, up);
compatible_arg = 0;
break;
case VIDIOC_DQEVENT:
compatible_arg = 0;
break;
}
if (err)
return err;
if (compatible_arg)
err = native_ioctl(file, cmd, (unsigned long)up);
else {
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
err = native_ioctl(file, cmd, (unsigned long)&karg);
set_fs(old_fs);
}
if (err == -ENOTTY)
return err;
/* Special case: even after an error we need to put the
results back for these ioctls since the error_idx will
contain information on which control failed. */
switch (cmd) {
case VIDIOC_G_EXT_CTRLS:
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
if (put_v4l2_ext_controls32(file, &karg.v2ecs, up))
err = -EFAULT;
break;
case VIDIOC_S_EDID:
if (put_v4l2_edid32(&karg.v2edid, up))
err = -EFAULT;
break;
}
if (err)
return err;
switch (cmd) {
case VIDIOC_S_INPUT:
case VIDIOC_S_OUTPUT:
case VIDIOC_G_INPUT:
case VIDIOC_G_OUTPUT:
err = put_user(((s32)karg.vi), (s32 __user *)up);
break;
case VIDIOC_G_FBUF:
err = put_v4l2_framebuffer32(&karg.v2fb, up);
break;
case VIDIOC_DQEVENT:
err = put_v4l2_event32(&karg.v2ev, up);
break;
case VIDIOC_G_EDID:
err = put_v4l2_edid32(&karg.v2edid, up);
break;
case VIDIOC_G_FMT:
case VIDIOC_S_FMT:
case VIDIOC_TRY_FMT:
err = put_v4l2_format32(&karg.v2f, up);
break;
case VIDIOC_CREATE_BUFS:
err = put_v4l2_create32(&karg.v2crt, up);
break;
case VIDIOC_PREPARE_BUF:
case VIDIOC_QUERYBUF:
case VIDIOC_QBUF:
case VIDIOC_DQBUF:
err = put_v4l2_buffer32(&karg.v2b, up);
break;
case VIDIOC_ENUMSTD:
err = put_v4l2_standard32(&karg.v2s, up);
break;
case VIDIOC_ENUMINPUT:
err = put_v4l2_input32(&karg.v2i, up);
break;
}
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline int get_v4l2_input32(struct v4l2_input *kp, struct v4l2_input32 __user *up)
{
if (copy_from_user(kp, up, sizeof(*up)))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int put_v4l2_plane32(struct v4l2_plane __user *up, struct v4l2_plane32 __user *up32,
enum v4l2_memory memory)
{
unsigned long p;
if (copy_in_user(up32, up, 2 * sizeof(__u32)) ||
copy_in_user(&up32->data_offset, &up->data_offset,
sizeof(up->data_offset)))
return -EFAULT;
switch (memory) {
case V4L2_MEMORY_MMAP:
case V4L2_MEMORY_OVERLAY:
if (copy_in_user(&up32->m.mem_offset, &up->m.mem_offset,
sizeof(up->m.mem_offset)))
return -EFAULT;
break;
case V4L2_MEMORY_USERPTR:
if (get_user(p, &up->m.userptr) ||
put_user((compat_ulong_t)ptr_to_compat((__force void *)p),
&up32->m.userptr))
return -EFAULT;
break;
case V4L2_MEMORY_DMABUF:
if (copy_in_user(&up32->m.fd, &up->m.fd,
sizeof(up->m.fd)))
return -EFAULT;
break;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_v4l2_edid32(struct v4l2_edid *kp, struct v4l2_edid32 __user *up)
{
u32 tmp;
if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
get_user(kp->pad, &up->pad) ||
get_user(kp->start_block, &up->start_block) ||
get_user(kp->blocks, &up->blocks) ||
get_user(tmp, &up->edid) ||
copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved)))
return -EFAULT;
kp->edid = (__force u8 *)compat_ptr(tmp);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int put_v4l2_ext_controls32(struct file *file,
struct v4l2_ext_controls *kp,
struct v4l2_ext_controls32 __user *up)
{
struct v4l2_ext_control32 __user *ucontrols;
struct v4l2_ext_control __user *kcontrols =
(__force struct v4l2_ext_control __user *)kp->controls;
int n = kp->count;
compat_caddr_t p;
if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
put_user(kp->which, &up->which) ||
put_user(kp->count, &up->count) ||
put_user(kp->error_idx, &up->error_idx) ||
copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved)))
return -EFAULT;
if (!kp->count)
return 0;
if (get_user(p, &up->controls))
return -EFAULT;
ucontrols = compat_ptr(p);
if (!access_ok(VERIFY_WRITE, ucontrols, n * sizeof(*ucontrols)))
return -EFAULT;
while (--n >= 0) {
unsigned size = sizeof(*ucontrols);
u32 id;
if (get_user(id, &kcontrols->id))
return -EFAULT;
/* Do not modify the pointer when copying a pointer control.
The contents of the pointer was changed, not the pointer
itself. */
if (ctrl_is_pointer(file, id))
size -= sizeof(ucontrols->value64);
if (copy_in_user(ucontrols, kcontrols, size))
return -EFAULT;
ucontrols++;
kcontrols++;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (!access_ok(VERIFY_READ, up, sizeof(*up)))
return -EFAULT;
return __get_v4l2_format32(kp, up);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int put_v4l2_edid32(struct v4l2_edid *kp, struct v4l2_edid32 __user *up)
{
u32 tmp = (u32)((unsigned long)kp->edid);
if (!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
put_user(kp->pad, &up->pad) ||
put_user(kp->start_block, &up->start_block) ||
put_user(kp->blocks, &up->blocks) ||
put_user(tmp, &up->edid) ||
copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved)))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (!access_ok(VERIFY_WRITE, up, sizeof(*up)))
return -EFAULT;
return __put_v4l2_format32(kp, up);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int __put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (put_user(kp->type, &up->type))
return -EFAULT;
switch (kp->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
return copy_to_user(&up->fmt.pix, &kp->fmt.pix,
sizeof(kp->fmt.pix)) ? -EFAULT : 0;
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
return copy_to_user(&up->fmt.pix_mp, &kp->fmt.pix_mp,
sizeof(kp->fmt.pix_mp)) ? -EFAULT : 0;
case V4L2_BUF_TYPE_VIDEO_OVERLAY:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY:
return put_v4l2_window32(&kp->fmt.win, &up->fmt.win);
case V4L2_BUF_TYPE_VBI_CAPTURE:
case V4L2_BUF_TYPE_VBI_OUTPUT:
return copy_to_user(&up->fmt.vbi, &kp->fmt.vbi,
sizeof(kp->fmt.vbi)) ? -EFAULT : 0;
case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
return copy_to_user(&up->fmt.sliced, &kp->fmt.sliced,
sizeof(kp->fmt.sliced)) ? -EFAULT : 0;
case V4L2_BUF_TYPE_SDR_CAPTURE:
case V4L2_BUF_TYPE_SDR_OUTPUT:
return copy_to_user(&up->fmt.sdr, &kp->fmt.sdr,
sizeof(kp->fmt.sdr)) ? -EFAULT : 0;
case V4L2_BUF_TYPE_META_CAPTURE:
return copy_to_user(&up->fmt.meta, &kp->fmt.meta,
sizeof(kp->fmt.meta)) ? -EFAULT : 0;
default:
return -EINVAL;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int get_v4l2_plane32(struct v4l2_plane __user *up, struct v4l2_plane32 __user *up32,
enum v4l2_memory memory)
{
void __user *up_pln;
compat_long_t p;
if (copy_in_user(up, up32, 2 * sizeof(__u32)) ||
copy_in_user(&up->data_offset, &up32->data_offset,
sizeof(up->data_offset)))
return -EFAULT;
switch (memory) {
case V4L2_MEMORY_MMAP:
case V4L2_MEMORY_OVERLAY:
if (copy_in_user(&up->m.mem_offset, &up32->m.mem_offset,
sizeof(up32->m.mem_offset)))
return -EFAULT;
break;
case V4L2_MEMORY_USERPTR:
if (get_user(p, &up32->m.userptr))
return -EFAULT;
up_pln = compat_ptr(p);
if (put_user((unsigned long)up_pln, &up->m.userptr))
return -EFAULT;
break;
case V4L2_MEMORY_DMABUF:
if (copy_in_user(&up->m.fd, &up32->m.fd, sizeof(up32->m.fd)))
return -EFAULT;
break;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'media: v4l2-compat-ioctl32.c: refactor compat ioctl32 logic
The 32-bit compat v4l2 ioctl handling is implemented based on its 64-bit
equivalent. It converts 32-bit data structures into its 64-bit
equivalents and needs to provide the data to the 64-bit ioctl in user
space memory which is commonly allocated using
compat_alloc_user_space().
However, due to how that function is implemented, it can only be called
a single time for every syscall invocation.
Supposedly to avoid this limitation, the existing code uses a mix of
memory from the kernel stack and memory allocated through
compat_alloc_user_space().
Under normal circumstances, this would not work, because the 64-bit
ioctl expects all pointers to point to user space memory. As a
workaround, set_fs(KERNEL_DS) is called to temporarily disable this
extra safety check and allow kernel pointers. However, this might
introduce a security vulnerability: The result of the 32-bit to 64-bit
conversion is writeable by user space because the output buffer has been
allocated via compat_alloc_user_space(). A malicious user space process
could then manipulate pointers inside this output buffer, and due to the
previous set_fs(KERNEL_DS) call, functions like get_user() or put_user()
no longer prevent kernel memory access.
The new approach is to pre-calculate the total amount of user space
memory that is needed, allocate it using compat_alloc_user_space() and
then divide up the allocated memory to accommodate all data structures
that need to be converted.
An alternative approach would have been to retain the union type karg
that they allocated on the kernel stack in do_video_ioctl(), copy all
data from user space into karg and then back to user space. However, we
decided against this approach because it does not align with other
compat syscall implementations. Instead, we tried to replicate the
get_user/put_user pairs as found in other places in the kernel:
if (get_user(clipcount, &up->clipcount) ||
put_user(clipcount, &kp->clipcount)) return -EFAULT;
Notes from [email protected]:
This patch was taken from:
https://github.com/LineageOS/android_kernel_samsung_apq8084/commit/97b733953c06e4f0398ade18850f0817778255f7
Clearly nobody could be bothered to upstream this patch or at minimum
tell us :-( We only heard about this a week ago.
This patch was rebased and cleaned up. Compared to the original I
also swapped the order of the convert_in_user arguments so that they
matched copy_in_user. It was hard to review otherwise. I also replaced
the ALLOC_USER_SPACE/ALLOC_AND_GET by a normal function.
Fixes: 6b5a9492ca ("v4l: introduce string control support.")
Signed-off-by: Daniel Mentz <[email protected]>
Co-developed-by: Hans Verkuil <[email protected]>
Acked-by: Sakari Ailus <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Cc: <[email protected]> # for v4.15 and up
Signed-off-by: Mauro Carvalho Chehab <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int xar_get_numeric_from_xml_element(xmlTextReaderPtr reader, long * value)
{
const xmlChar * numstr;
if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {
numstr = xmlTextReaderConstValue(reader);
if (numstr) {
*value = atol((const char *)numstr);
if (*value < 0) {
cli_dbgmsg("cli_scanxar: XML element value %li\n", *value);
return CL_EFORMAT;
}
return CL_SUCCESS;
}
}
cli_dbgmsg("cli_scanxar: No text for XML element\n");
return CL_EFORMAT;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'bb11588 - fix out of bounds read.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int xar_hash_check(int hash, const void * result, const void * expected)
{
int len;
if (!result || !expected)
return 1;
switch (hash) {
case XAR_CKSUM_SHA1:
len = SHA1_HASH_SIZE;
break;
case XAR_CKSUM_MD5:
len = CLI_HASH_MD5;
break;
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
default:
return 1;
}
return memcmp(result, expected, len);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'bb11588 - fix out of bounds read.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int xar_get_toc_data_values(xmlTextReaderPtr reader, long *length, long *offset, long *size, int *encoding,
unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)
{
const xmlChar *name;
int indata = 0, inea = 0;
int rc, gotoffset=0, gotlength=0, gotsize=0;
*a_cksum = NULL;
*a_hash = XAR_CKSUM_NONE;
*e_cksum = NULL;
*e_hash = XAR_CKSUM_NONE;
*encoding = CL_TYPE_ANY;
rc = xmlTextReaderRead(reader);
while (rc == 1) {
name = xmlTextReaderConstLocalName(reader);
if (indata || inea) {
/* cli_dbgmsg("cli_scanxar: xmlTextReaderRead read %s\n", name); */
if (xmlStrEqual(name, (const xmlChar *)"offset") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))
gotoffset=1;
} else if (xmlStrEqual(name, (const xmlChar *)"length") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))
gotlength=1;
} else if (xmlStrEqual(name, (const xmlChar *)"size") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))
gotsize=1;
} else if (xmlStrEqual(name, (const xmlChar *)"archived-checksum") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <archived-checksum>:\n");
xar_get_checksum_values(reader, a_cksum, a_hash);
} else if ((xmlStrEqual(name, (const xmlChar *)"extracted-checksum") ||
xmlStrEqual(name, (const xmlChar *)"unarchived-checksum")) &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <extracted-checksum>:\n");
xar_get_checksum_values(reader, e_cksum, e_hash);
} else if (xmlStrEqual(name, (const xmlChar *)"encoding") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)"style");
if (style == NULL) {
cli_dbgmsg("cli_scaxar: xmlTextReaderGetAttribute no style attribute "
"for encoding element\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-gzip")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-gzip.\n");
*encoding = CL_TYPE_GZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/octet-stream")) {
cli_dbgmsg("cli_scanxar: encoding = application/octet-stream.\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-bzip2")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-bzip2.\n");
*encoding = CL_TYPE_BZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-lzma")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-lzma.\n");
*encoding = CL_TYPE_7Z;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-xz")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-xz.\n");
*encoding = CL_TYPE_XZ;
} else {
cli_dbgmsg("cli_scaxar: unknown style value=%s for encoding element\n", style);
*encoding = CL_TYPE_ANY;
}
if (style != NULL)
xmlFree(style);
} else if (indata && xmlStrEqual(name, (const xmlChar *)"data") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
} else if (inea && xmlStrEqual(name, (const xmlChar *)"ea") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
}
} else {
if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (xmlStrEqual(name, (const xmlChar *)"data")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <data>\n");
indata = 1;
} else if (xmlStrEqual(name, (const xmlChar *)"ea")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <ea>\n");
inea = 1;
}
} else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&
xmlStrEqual(name, (const xmlChar *)"xar")) {
cli_dbgmsg("cli_scanxar: finished parsing xar TOC.\n");
break;
}
}
rc = xmlTextReaderRead(reader);
}
if (gotoffset && gotlength && gotsize) {
rc = CL_SUCCESS;
}
else if (0 == gotoffset + gotlength + gotsize)
rc = CL_BREAK;
else
rc = CL_EFORMAT;
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'bb11588 - fix out of bounds read.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
struct extent_node *en;
struct extent_info ei;
if (!f2fs_may_extent_tree(inode)) {
/* drop largest extent */
if (i_ext && i_ext->len) {
i_ext->len = 0;
return true;
}
return false;
}
et = __grab_extent_tree(inode);
if (!i_ext || !i_ext->len)
return false;
get_extent_info(&ei, i_ext);
write_lock(&et->lock);
if (atomic_read(&et->node_cnt))
goto out;
en = __init_extent_tree(sbi, et, &ei);
if (en) {
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
spin_unlock(&sbi->extent_lock);
}
out:
write_unlock(&et->lock);
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'f2fs: fix a bug caused by NULL extent tree
Thread A: Thread B:
-f2fs_remount
-sbi->mount_opt.opt = 0;
<--- -f2fs_iget
-do_read_inode
-f2fs_init_extent_tree
-F2FS_I(inode)->extent_tree is NULL
-default_options && parse_options
-remount return
<--- -f2fs_map_blocks
-f2fs_lookup_extent_tree
-f2fs_bug_on(sbi, !et);
The same problem with f2fs_new_inode.
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
{
__u64 start = F2FS_BYTES_TO_BLK(range->start);
__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
unsigned int start_segno, end_segno;
struct cp_control cpc;
int err = 0;
if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
return -EINVAL;
cpc.trimmed = 0;
if (end <= MAIN_BLKADDR(sbi))
goto out;
if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
f2fs_msg(sbi->sb, KERN_WARNING,
"Found FS corruption, run fsck to fix.");
goto out;
}
/* start/end segment number in main_area */
start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
GET_SEGNO(sbi, end);
cpc.reason = CP_DISCARD;
cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
/* do checkpoint to issue discard commands safely */
for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
cpc.trim_start = start_segno;
if (sbi->discard_blks == 0)
break;
else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
cpc.trim_end = end_segno;
else
cpc.trim_end = min_t(unsigned int,
rounddown(start_segno +
BATCHED_TRIM_SEGMENTS(sbi),
sbi->segs_per_sec) - 1, end_segno);
mutex_lock(&sbi->gc_mutex);
err = write_checkpoint(sbi, &cpc);
mutex_unlock(&sbi->gc_mutex);
if (err)
break;
schedule();
}
/* It's time to issue all the filed discards */
mark_discard_range_all(sbi);
f2fs_wait_discard_bios(sbi);
out:
range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'f2fs: fix potential panic during fstrim
As Ju Hyung Park reported:
"When 'fstrim' is called for manual trim, a BUG() can be triggered
randomly with this patch.
I'm seeing this issue on both x86 Desktop and arm64 Android phone.
On x86 Desktop, this was caused during Ubuntu boot-up. I have a
cronjob installed which calls 'fstrim -v /' during boot. On arm64
Android, this was caused during GC looping with 1ms gc_min_sleep_time
& gc_max_sleep_time."
Root cause of this issue is that f2fs_wait_discard_bios can only be
used by f2fs_put_super, because during put_super there must be no
other referrers, so it can ignore discard entry's reference count
when removing the entry, otherwise in other caller we will hit bug_on
in __remove_discard_cmd as there may be other issuer added reference
count in discard entry.
Thread A Thread B
- issue_discard_thread
- f2fs_ioc_fitrim
- f2fs_trim_fs
- f2fs_wait_discard_bios
- __issue_discard_cmd
- __submit_discard_cmd
- __wait_discard_cmd
- dc->ref++
- __wait_one_discard_bio
- __wait_discard_cmd
- __remove_discard_cmd
- f2fs_bug_on(sbi, dc->ref)
Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de
Reported-by: Ju Hyung Park <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void f2fs_put_super(struct super_block *sb)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int i;
f2fs_quota_off_umount(sb);
/* prevent remaining shrinker jobs */
mutex_lock(&sbi->umount_mutex);
/*
* We don't need to do checkpoint when superblock is clean.
* But, the previous checkpoint was not done by umount, it needs to do
* clean checkpoint again.
*/
if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
struct cp_control cpc = {
.reason = CP_UMOUNT,
};
write_checkpoint(sbi, &cpc);
}
/* be sure to wait for any on-going discard commands */
f2fs_wait_discard_bios(sbi);
if (f2fs_discard_en(sbi) && !sbi->discard_blks) {
struct cp_control cpc = {
.reason = CP_UMOUNT | CP_TRIMMED,
};
write_checkpoint(sbi, &cpc);
}
/* write_checkpoint can update stat informaion */
f2fs_destroy_stats(sbi);
/*
* normally superblock is clean, so we need to release this.
* In addition, EIO will skip do checkpoint, we need this as well.
*/
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
mutex_unlock(&sbi->umount_mutex);
/* our cp_error case, we can wait for any writeback page */
f2fs_flush_merged_writes(sbi);
iput(sbi->node_inode);
iput(sbi->meta_inode);
/* destroy f2fs internal modules */
destroy_node_manager(sbi);
destroy_segment_manager(sbi);
kfree(sbi->ckpt);
f2fs_unregister_sysfs(sbi);
sb->s_fs_info = NULL;
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->raw_super);
destroy_device_list(sbi);
mempool_destroy(sbi->write_io_dummy);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
destroy_percpu_info(sbi);
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
kfree(sbi);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'f2fs: fix potential panic during fstrim
As Ju Hyung Park reported:
"When 'fstrim' is called for manual trim, a BUG() can be triggered
randomly with this patch.
I'm seeing this issue on both x86 Desktop and arm64 Android phone.
On x86 Desktop, this was caused during Ubuntu boot-up. I have a
cronjob installed which calls 'fstrim -v /' during boot. On arm64
Android, this was caused during GC looping with 1ms gc_min_sleep_time
& gc_max_sleep_time."
Root cause of this issue is that f2fs_wait_discard_bios can only be
used by f2fs_put_super, because during put_super there must be no
other referrers, so it can ignore discard entry's reference count
when removing the entry, otherwise in other caller we will hit bug_on
in __remove_discard_cmd as there may be other issuer added reference
count in discard entry.
Thread A Thread B
- issue_discard_thread
- f2fs_ioc_fitrim
- f2fs_trim_fs
- f2fs_wait_discard_bios
- __issue_discard_cmd
- __submit_discard_cmd
- __wait_discard_cmd
- dc->ref++
- __wait_one_discard_bio
- __wait_discard_cmd
- __remove_discard_cmd
- f2fs_bug_on(sbi, dc->ref)
Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de
Reported-by: Ju Hyung Park <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowTIFFException(severity,message) \
{ \
if (tiff_pixels != (unsigned char *) NULL) \
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \
if (quantum_info != (QuantumInfo *) NULL) \
quantum_info=DestroyQuantumInfo(quantum_info); \
TIFFClose(tiff); \
ThrowReaderException(severity,message); \
}
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
status;
MagickSizeType
number_pixels;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*tiff_pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point",
exception);
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black",
exception);
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white",
exception);
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette",exception);
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB",exception);
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)",
exception);
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception);
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK",exception);
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated",exception);
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown",exception);
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric",
exception));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb",exception);
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb",exception);
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace,exception);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace,exception);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace,exception);
TIFFGetProfiles(tiff,image,exception);
TIFFGetProperties(tiff,image,exception);
option=GetImageOption(image_info,"tiff:exif-properties");
if (IsStringFalse(option) == MagickFalse) /* enabled by default */
TIFFGetEXIFProperties(tiff,image,exception);
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->resolution.x=x_resolution;
image->resolution.y=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);
image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MagickPathExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d",horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor,exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
default: image->compression=RLECompression; break;
}
quantum_info=(QuantumInfo *) NULL;
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
value=(unsigned short) image->scene;
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
goto next_tiff_frame;
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
TIFFClose(tiff);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
tiff_pixels=(unsigned char *) NULL;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified",exception);
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->alpha_trait=BlendPixelTrait;
}
else
for (i=0; i < extra_samples; i++)
{
image->alpha_trait=BlendPixelTrait;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated",
exception);
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
(void) SetImageProperty(image,"tiff:alpha","unassociated",
exception);
}
}
method=ReadGenericMethod;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MagickPathExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MagickPathExtent,"%u",
(unsigned int) rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
}
if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
if ((image->alpha_trait == UndefinedPixelTrait) ||
(samples_per_pixel >= 4))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
if ((image->alpha_trait == UndefinedPixelTrait) ||
(samples_per_pixel >= 5))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
tiff_pixels=(unsigned char *) AcquireMagickMemory(MagickMax(
TIFFScanlineSize(tiff),(ssize_t) (image->columns*samples_per_pixel*
pow(2.0,ceil(log(bits_per_sample)/log(2.0)))*sizeof(uint32))));
if (tiff_pixels == (unsigned char *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
if (image->alpha_trait != UndefinedPixelTrait)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
bits_per_sample)/log(2))));
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
tiff_pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register Quantum
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=tiff_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)),q);
SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)),q);
SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)),q);
SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);
q+=GetPixelChannels(image);
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) tiff_pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
ThrowTIFFException(CoderError,"ImageIsNotTiled");
if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,rows) == MagickFalse))
ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit");
(void) SetImageStorageClass(image,DirectClass,exception);
number_pixels=(MagickSizeType) columns*rows;
if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
register ssize_t
x;
register Quantum
*magick_restrict q,
*magick_restrict tile;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
x);
for (row=rows_remaining; row > 0; row--)
{
if (image->alpha_trait != UndefinedPixelTrait)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p++;
q+=GetPixelChannels(image);
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
p++;
q+=GetPixelChannels(image);
}
p+=columns-columns_remaining;
q-=GetPixelChannels(image)*(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(uint32));
if (pixel_info == (MemoryInfo *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
q+=GetPixelChannels(image)*(image->columns-1);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)),q);
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)),q);
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)),q);
p--;
q-=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels);
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image,image_info,exception);
if (image_info->number_scenes != 0)
{
if (image_info->scene >= GetImageListLength(image))
{
/* Subimage was not found in the Photoshop layer */
image=DestroyImageList(image);
return((Image *)NULL);
}
}
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/999'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t snd_seq_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct snd_seq_client *client = file->private_data;
int written = 0, len;
int err = -EINVAL;
struct snd_seq_event event;
if (!(snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_OUTPUT))
return -ENXIO;
/* check client structures are in place */
if (snd_BUG_ON(!client))
return -ENXIO;
if (!client->accept_output || client->pool == NULL)
return -ENXIO;
/* allocate the pool now if the pool is not allocated yet */
if (client->pool->size > 0 && !snd_seq_write_pool_allocated(client)) {
if (snd_seq_pool_init(client->pool) < 0)
return -ENOMEM;
}
/* only process whole events */
while (count >= sizeof(struct snd_seq_event)) {
/* Read in the event header from the user */
len = sizeof(event);
if (copy_from_user(&event, buf, len)) {
err = -EFAULT;
break;
}
event.source.client = client->number; /* fill in client number */
/* Check for extension data length */
if (check_event_type_and_length(&event)) {
err = -EINVAL;
break;
}
/* check for special events */
if (event.type == SNDRV_SEQ_EVENT_NONE)
goto __skip_event;
else if (snd_seq_ev_is_reserved(&event)) {
err = -EINVAL;
break;
}
if (snd_seq_ev_is_variable(&event)) {
int extlen = event.data.ext.len & ~SNDRV_SEQ_EXT_MASK;
if ((size_t)(extlen + len) > count) {
/* back out, will get an error this time or next */
err = -EINVAL;
break;
}
/* set user space pointer */
event.data.ext.len = extlen | SNDRV_SEQ_EXT_USRPTR;
event.data.ext.ptr = (char __force *)buf
+ sizeof(struct snd_seq_event);
len += extlen; /* increment data length */
} else {
#ifdef CONFIG_COMPAT
if (client->convert32 && snd_seq_ev_is_varusr(&event)) {
void *ptr = (void __force *)compat_ptr(event.data.raw32.d[1]);
event.data.ext.ptr = ptr;
}
#endif
}
/* ok, enqueue it */
err = snd_seq_client_enqueue_event(client, &event, file,
!(file->f_flags & O_NONBLOCK),
0, 0);
if (err < 0)
break;
__skip_event:
/* Update pointers and counts */
count -= len;
buf += len;
written += len;
}
return written ? written : err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'ALSA: seq: Fix racy pool initializations
ALSA sequencer core initializes the event pool on demand by invoking
snd_seq_pool_init() when the first write happens and the pool is
empty. Meanwhile user can reset the pool size manually via ioctl
concurrently, and this may lead to UAF or out-of-bound accesses since
the function tries to vmalloc / vfree the buffer.
A simple fix is to just wrap the snd_seq_pool_init() call with the
recently introduced client->ioctl_mutex; as the calls for
snd_seq_pool_init() from other side are always protected with this
mutex, we can avoid the race.
Reported-by: 范龙飞 <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)
{
int status = 0, size_change;
int inode_locked = 0;
struct inode *inode = d_inode(dentry);
struct super_block *sb = inode->i_sb;
struct ocfs2_super *osb = OCFS2_SB(sb);
struct buffer_head *bh = NULL;
handle_t *handle = NULL;
struct dquot *transfer_to[MAXQUOTAS] = { };
int qtype;
int had_lock;
struct ocfs2_lock_holder oh;
trace_ocfs2_setattr(inode, dentry,
(unsigned long long)OCFS2_I(inode)->ip_blkno,
dentry->d_name.len, dentry->d_name.name,
attr->ia_valid, attr->ia_mode,
from_kuid(&init_user_ns, attr->ia_uid),
from_kgid(&init_user_ns, attr->ia_gid));
/* ensuring we don't even attempt to truncate a symlink */
if (S_ISLNK(inode->i_mode))
attr->ia_valid &= ~ATTR_SIZE;
#define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \
| ATTR_GID | ATTR_UID | ATTR_MODE)
if (!(attr->ia_valid & OCFS2_VALID_ATTRS))
return 0;
status = setattr_prepare(dentry, attr);
if (status)
return status;
if (is_quota_modification(inode, attr)) {
status = dquot_initialize(inode);
if (status)
return status;
}
size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
if (size_change) {
status = ocfs2_rw_lock(inode, 1);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
had_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh);
if (had_lock < 0) {
status = had_lock;
goto bail_unlock_rw;
} else if (had_lock) {
/*
* As far as we know, ocfs2_setattr() could only be the first
* VFS entry point in the call chain of recursive cluster
* locking issue.
*
* For instance:
* chmod_common()
* notify_change()
* ocfs2_setattr()
* posix_acl_chmod()
* ocfs2_iop_get_acl()
*
* But, we're not 100% sure if it's always true, because the
* ordering of the VFS entry points in the call chain is out
* of our control. So, we'd better dump the stack here to
* catch the other cases of recursive locking.
*/
mlog(ML_ERROR, "Another case of recursive locking:\n");
dump_stack();
}
inode_locked = 1;
if (size_change) {
status = inode_newsize_ok(inode, attr->ia_size);
if (status)
goto bail_unlock;
inode_dio_wait(inode);
if (i_size_read(inode) >= attr->ia_size) {
if (ocfs2_should_order_data(inode)) {
status = ocfs2_begin_ordered_truncate(inode,
attr->ia_size);
if (status)
goto bail_unlock;
}
status = ocfs2_truncate_file(inode, bh, attr->ia_size);
} else
status = ocfs2_extend_file(inode, bh, attr->ia_size);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
status = -ENOSPC;
goto bail_unlock;
}
}
if ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
(attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
/*
* Gather pointers to quota structures so that allocation /
* freeing of quota structures happens here and not inside
* dquot_transfer() where we have problems with lock ordering
*/
if (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
transfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid));
if (IS_ERR(transfer_to[USRQUOTA])) {
status = PTR_ERR(transfer_to[USRQUOTA]);
goto bail_unlock;
}
}
if (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
transfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid));
if (IS_ERR(transfer_to[GRPQUOTA])) {
status = PTR_ERR(transfer_to[GRPQUOTA]);
goto bail_unlock;
}
}
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +
2 * ocfs2_quota_trans_credits(sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
status = __dquot_transfer(inode, transfer_to);
if (status < 0)
goto bail_commit;
} else {
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
status = ocfs2_mark_inode_dirty(handle, inode, bh);
if (status < 0)
mlog_errno(status);
bail_commit:
ocfs2_commit_trans(osb, handle);
bail_unlock:
if (status && inode_locked) {
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
inode_locked = 0;
}
bail_unlock_rw:
if (size_change)
ocfs2_rw_unlock(inode, 1);
bail:
/* Release quota pointers in case we acquired them */
for (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++)
dqput(transfer_to[qtype]);
if (!status && attr->ia_valid & ATTR_MODE) {
status = ocfs2_acl_chmod(inode, bh);
if (status < 0)
mlog_errno(status);
}
if (inode_locked)
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
brelse(bh);
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401'], 'message': 'ocfs2: should wait dio before inode lock in ocfs2_setattr()
we should wait dio requests to finish before inode lock in
ocfs2_setattr(), otherwise the following deadlock will happen:
process 1 process 2 process 3
truncate file 'A' end_io of writing file 'A' receiving the bast messages
ocfs2_setattr
ocfs2_inode_lock_tracker
ocfs2_inode_lock_full
inode_dio_wait
__inode_dio_wait
-->waiting for all dio
requests finish
dlm_proxy_ast_handler
dlm_do_local_bast
ocfs2_blocking_ast
ocfs2_generic_handle_bast
set OCFS2_LOCK_BLOCKED flag
dio_end_io
dio_bio_end_aio
dio_complete
ocfs2_dio_end_io
ocfs2_dio_end_io_write
ocfs2_inode_lock
__ocfs2_cluster_lock
ocfs2_wait_for_mask
-->waiting for OCFS2_LOCK_BLOCKED
flag to be cleared, that is waiting
for 'process 1' unlocking the inode lock
inode_dio_end
-->here dec the i_dio_count, but will never
be called, so a deadlock happened.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Acked-by: Changwei Ge <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,
__u8 type, __u8 flags, int paylen,
gfp_t gfp)
{
struct sctp_chunkhdr *chunk_hdr;
struct sctp_chunk *retval;
struct sk_buff *skb;
struct sock *sk;
/* No need to allocate LL here, as this is only a chunk. */
skb = alloc_skb(SCTP_PAD4(sizeof(*chunk_hdr) + paylen), gfp);
if (!skb)
goto nodata;
/* Make room for the chunk header. */
chunk_hdr = (struct sctp_chunkhdr *)skb_put(skb, sizeof(*chunk_hdr));
chunk_hdr->type = type;
chunk_hdr->flags = flags;
chunk_hdr->length = htons(sizeof(*chunk_hdr));
sk = asoc ? asoc->base.sk : NULL;
retval = sctp_chunkify(skb, asoc, sk, gfp);
if (!retval) {
kfree_skb(skb);
goto nodata;
}
retval->chunk_hdr = chunk_hdr;
retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(*chunk_hdr);
/* Determine if the chunk needs to be authenticated */
if (sctp_auth_send_cid(type, asoc))
retval->auth = 1;
return retval;
nodata:
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'sctp: verify size of a new chunk in _sctp_make_chunk()
When SCTP makes INIT or INIT_ACK packet the total chunk length
can exceed SCTP_MAX_CHUNK_LEN which leads to kernel panic when
transmitting these packets, e.g. the crash on sending INIT_ACK:
[ 597.804948] skbuff: skb_over_panic: text:00000000ffae06e4 len:120168
put:120156 head:000000007aa47635 data:00000000d991c2de
tail:0x1d640 end:0xfec0 dev:<NULL>
...
[ 597.976970] ------------[ cut here ]------------
[ 598.033408] kernel BUG at net/core/skbuff.c:104!
[ 600.314841] Call Trace:
[ 600.345829] <IRQ>
[ 600.371639] ? sctp_packet_transmit+0x2095/0x26d0 [sctp]
[ 600.436934] skb_put+0x16c/0x200
[ 600.477295] sctp_packet_transmit+0x2095/0x26d0 [sctp]
[ 600.540630] ? sctp_packet_config+0x890/0x890 [sctp]
[ 600.601781] ? __sctp_packet_append_chunk+0x3b4/0xd00 [sctp]
[ 600.671356] ? sctp_cmp_addr_exact+0x3f/0x90 [sctp]
[ 600.731482] sctp_outq_flush+0x663/0x30d0 [sctp]
[ 600.788565] ? sctp_make_init+0xbf0/0xbf0 [sctp]
[ 600.845555] ? sctp_check_transmitted+0x18f0/0x18f0 [sctp]
[ 600.912945] ? sctp_outq_tail+0x631/0x9d0 [sctp]
[ 600.969936] sctp_cmd_interpreter.isra.22+0x3be1/0x5cb0 [sctp]
[ 601.041593] ? sctp_sf_do_5_1B_init+0x85f/0xc30 [sctp]
[ 601.104837] ? sctp_generate_t1_cookie_event+0x20/0x20 [sctp]
[ 601.175436] ? sctp_eat_data+0x1710/0x1710 [sctp]
[ 601.233575] sctp_do_sm+0x182/0x560 [sctp]
[ 601.284328] ? sctp_has_association+0x70/0x70 [sctp]
[ 601.345586] ? sctp_rcv+0xef4/0x32f0 [sctp]
[ 601.397478] ? sctp6_rcv+0xa/0x20 [sctp]
...
Here the chunk size for INIT_ACK packet becomes too big, mostly
because of the state cookie (INIT packet has large size with
many address parameters), plus additional server parameters.
Later this chunk causes the panic in skb_put_data():
skb_packet_transmit()
sctp_packet_pack()
skb_put_data(nskb, chunk->skb->data, chunk->skb->len);
'nskb' (head skb) was previously allocated with packet->size
from u16 'chunk->chunk_hdr->length'.
As suggested by Marcelo we should check the chunk's length in
_sctp_make_chunk() before trying to allocate skb for it and
discard a chunk if its size bigger than SCTP_MAX_CHUNK_LEN.
Signed-off-by: Alexey Kodanev <[email protected]>
Acked-by: Marcelo Ricardo Leitner <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: krb5_ldap_put_principal(krb5_context context, krb5_db_entry *entry,
char **db_args)
{
int l=0, kerberos_principal_object_type=0;
unsigned int ntrees=0, tre=0;
krb5_error_code st=0, tempst=0;
LDAP *ld=NULL;
LDAPMessage *result=NULL, *ent=NULL;
char **subtreelist = NULL;
char *user=NULL, *subtree=NULL, *principal_dn=NULL;
char **values=NULL, *strval[10]={NULL}, errbuf[1024];
char *filtuser=NULL;
struct berval **bersecretkey=NULL;
LDAPMod **mods=NULL;
krb5_boolean create_standalone=FALSE;
krb5_boolean krb_identity_exists=FALSE, establish_links=FALSE;
char *standalone_principal_dn=NULL;
krb5_tl_data *tl_data=NULL;
krb5_key_data **keys=NULL;
kdb5_dal_handle *dal_handle=NULL;
krb5_ldap_context *ldap_context=NULL;
krb5_ldap_server_handle *ldap_server_handle=NULL;
osa_princ_ent_rec princ_ent = {0};
xargs_t xargs = {0};
char *polname = NULL;
OPERATION optype;
krb5_boolean found_entry = FALSE;
/* Clear the global error string */
krb5_clear_error_message(context);
SETUP_CONTEXT();
if (ldap_context->lrparams == NULL || ldap_context->container_dn == NULL)
return EINVAL;
/* get ldap handle */
GET_HANDLE();
if (!is_principal_in_realm(ldap_context, entry->princ)) {
st = EINVAL;
k5_setmsg(context, st,
_("Principal does not belong to the default realm"));
goto cleanup;
}
/* get the principal information to act on */
if (((st=krb5_unparse_name(context, entry->princ, &user)) != 0) ||
((st=krb5_ldap_unparse_principal_name(user)) != 0))
goto cleanup;
filtuser = ldap_filter_correct(user);
if (filtuser == NULL) {
st = ENOMEM;
goto cleanup;
}
/* Identity the type of operation, it can be
* add principal or modify principal.
* hack if the entry->mask has KRB_PRINCIPAL flag set
* then it is a add operation
*/
if (entry->mask & KADM5_PRINCIPAL)
optype = ADD_PRINCIPAL;
else
optype = MODIFY_PRINCIPAL;
if (((st=krb5_get_princ_type(context, entry, &kerberos_principal_object_type)) != 0) ||
((st=krb5_get_userdn(context, entry, &principal_dn)) != 0))
goto cleanup;
if ((st=process_db_args(context, db_args, &xargs, optype)) != 0)
goto cleanup;
if (entry->mask & KADM5_LOAD) {
unsigned int tree = 0;
int numlentries = 0;
char *filter = NULL;
/* A load operation is special, will do a mix-in (add krbprinc
* attrs to a non-krb object entry) if an object exists with a
* matching krbprincipalname attribute so try to find existing
* object and set principal_dn. This assumes that the
* krbprincipalname attribute is unique (only one object entry has
* a particular krbprincipalname attribute).
*/
if (asprintf(&filter, FILTER"%s))", filtuser) < 0) {
filter = NULL;
st = ENOMEM;
goto cleanup;
}
/* get the current subtree list */
if ((st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees)) != 0)
goto cleanup;
found_entry = FALSE;
/* search for entry with matching krbprincipalname attribute */
for (tree = 0; found_entry == FALSE && tree < ntrees; ++tree) {
if (principal_dn == NULL) {
LDAP_SEARCH_1(subtreelist[tree], ldap_context->lrparams->search_scope, filter, principal_attributes, IGNORE_STATUS);
} else {
/* just look for entry with principal_dn */
LDAP_SEARCH_1(principal_dn, LDAP_SCOPE_BASE, filter, principal_attributes, IGNORE_STATUS);
}
if (st == LDAP_SUCCESS) {
numlentries = ldap_count_entries(ld, result);
if (numlentries > 1) {
free(filter);
st = EINVAL;
k5_setmsg(context, st,
_("operation can not continue, more than one "
"entry with principal name \"%s\" found"),
user);
goto cleanup;
} else if (numlentries == 1) {
found_entry = TRUE;
if (principal_dn == NULL) {
ent = ldap_first_entry(ld, result);
if (ent != NULL) {
/* setting principal_dn will cause that entry to be modified further down */
if ((principal_dn = ldap_get_dn(ld, ent)) == NULL) {
ldap_get_option (ld, LDAP_OPT_RESULT_CODE, &st);
st = set_ldap_error (context, st, 0);
free(filter);
goto cleanup;
}
}
}
}
} else if (st != LDAP_NO_SUCH_OBJECT) {
/* could not perform search, return with failure */
st = set_ldap_error (context, st, 0);
free(filter);
goto cleanup;
}
ldap_msgfree(result);
result = NULL;
/*
* If it isn't found then assume a standalone princ entry is to
* be created.
*/
} /* end for (tree = 0; principal_dn == ... */
free(filter);
if (found_entry == FALSE && principal_dn != NULL) {
/*
* if principal_dn is null then there is code further down to
* deal with setting standalone_principal_dn. Also note that
* this will set create_standalone true for
* non-mix-in entries which is okay if loading from a dump.
*/
create_standalone = TRUE;
standalone_principal_dn = strdup(principal_dn);
CHECK_NULL(standalone_principal_dn);
}
} /* end if (entry->mask & KADM5_LOAD */
/* time to generate the DN information with the help of
* containerdn, principalcontainerreference or
* realmcontainerdn information
*/
if (principal_dn == NULL && xargs.dn == NULL) { /* creation of standalone principal */
/* get the subtree information */
if (entry->princ->length == 2 && entry->princ->data[0].length == strlen("krbtgt") &&
strncmp(entry->princ->data[0].data, "krbtgt", entry->princ->data[0].length) == 0) {
/* if the principal is a inter-realm principal, always created in the realm container */
subtree = strdup(ldap_context->lrparams->realmdn);
} else if (xargs.containerdn) {
if ((st=checkattributevalue(ld, xargs.containerdn, NULL, NULL, NULL)) != 0) {
if (st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION) {
int ost = st;
st = EINVAL;
k5_wrapmsg(context, ost, st, _("'%s' not found"),
xargs.containerdn);
}
goto cleanup;
}
subtree = strdup(xargs.containerdn);
} else if (ldap_context->lrparams->containerref && strlen(ldap_context->lrparams->containerref) != 0) {
/*
* Here the subtree should be changed with
* principalcontainerreference attribute value
*/
subtree = strdup(ldap_context->lrparams->containerref);
} else {
subtree = strdup(ldap_context->lrparams->realmdn);
}
CHECK_NULL(subtree);
if (asprintf(&standalone_principal_dn, "krbprincipalname=%s,%s",
filtuser, subtree) < 0)
standalone_principal_dn = NULL;
CHECK_NULL(standalone_principal_dn);
/*
* free subtree when you are done using the subtree
* set the boolean create_standalone to TRUE
*/
create_standalone = TRUE;
free(subtree);
subtree = NULL;
}
/*
* If the DN information is presented by the user, time to
* validate the input to ensure that the DN falls under
* any of the subtrees
*/
if (xargs.dn_from_kbd == TRUE) {
/* make sure the DN falls in the subtree */
int dnlen=0, subtreelen=0;
char *dn=NULL;
krb5_boolean outofsubtree=TRUE;
if (xargs.dn != NULL) {
dn = xargs.dn;
} else if (xargs.linkdn != NULL) {
dn = xargs.linkdn;
} else if (standalone_principal_dn != NULL) {
/*
* Even though the standalone_principal_dn is constructed
* within this function, there is the containerdn input
* from the user that can become part of the it.
*/
dn = standalone_principal_dn;
}
/* Get the current subtree list if we haven't already done so. */
if (subtreelist == NULL) {
st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees);
if (st)
goto cleanup;
}
for (tre=0; tre<ntrees; ++tre) {
if (subtreelist[tre] == NULL || strlen(subtreelist[tre]) == 0) {
outofsubtree = FALSE;
break;
} else {
dnlen = strlen (dn);
subtreelen = strlen(subtreelist[tre]);
if ((dnlen >= subtreelen) && (strcasecmp((dn + dnlen - subtreelen), subtreelist[tre]) == 0)) {
outofsubtree = FALSE;
break;
}
}
}
if (outofsubtree == TRUE) {
st = EINVAL;
k5_setmsg(context, st, _("DN is out of the realm subtree"));
goto cleanup;
}
/*
* dn value will be set either by dn, linkdn or the standalone_principal_dn
* In the first 2 cases, the dn should be existing and in the last case we
* are supposed to create the ldap object. so the below should not be
* executed for the last case.
*/
if (standalone_principal_dn == NULL) {
/*
* If the ldap object is missing, this results in an error.
*/
/*
* Search for krbprincipalname attribute here.
* This is to find if a kerberos identity is already present
* on the ldap object, in which case adding a kerberos identity
* on the ldap object should result in an error.
*/
char *attributes[]={"krbticketpolicyreference", "krbprincipalname", NULL};
ldap_msgfree(result);
result = NULL;
LDAP_SEARCH_1(dn, LDAP_SCOPE_BASE, 0, attributes, IGNORE_STATUS);
if (st == LDAP_SUCCESS) {
ent = ldap_first_entry(ld, result);
if (ent != NULL) {
if ((values=ldap_get_values(ld, ent, "krbticketpolicyreference")) != NULL) {
ldap_value_free(values);
}
if ((values=ldap_get_values(ld, ent, "krbprincipalname")) != NULL) {
krb_identity_exists = TRUE;
ldap_value_free(values);
}
}
} else {
st = set_ldap_error(context, st, OP_SEARCH);
goto cleanup;
}
}
}
/*
* If xargs.dn is set then the request is to add a
* kerberos principal on a ldap object, but if
* there is one already on the ldap object this
* should result in an error.
*/
if (xargs.dn != NULL && krb_identity_exists == TRUE) {
st = EINVAL;
snprintf(errbuf, sizeof(errbuf),
_("ldap object is already kerberized"));
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
}
if (xargs.linkdn != NULL) {
/*
* link information can be changed using modprinc.
* However, link information can be changed only on the
* standalone kerberos principal objects. A standalone
* kerberos principal object is of type krbprincipal
* structural objectclass.
*
* NOTE: kerberos principals on an ldap object can't be
* linked to other ldap objects.
*/
if (optype == MODIFY_PRINCIPAL &&
kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT) {
st = EINVAL;
snprintf(errbuf, sizeof(errbuf),
_("link information can not be set/updated as the "
"kerberos principal belongs to an ldap object"));
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
}
/*
* Check the link information. If there is already a link
* existing then this operation is not allowed.
*/
{
char **linkdns=NULL;
int j=0;
if ((st=krb5_get_linkdn(context, entry, &linkdns)) != 0) {
snprintf(errbuf, sizeof(errbuf),
_("Failed getting object references"));
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
}
if (linkdns != NULL) {
st = EINVAL;
snprintf(errbuf, sizeof(errbuf),
_("kerberos principal is already linked to a ldap "
"object"));
k5_setmsg(context, st, "%s", errbuf);
for (j=0; linkdns[j] != NULL; ++j)
free (linkdns[j]);
free (linkdns);
goto cleanup;
}
}
establish_links = TRUE;
}
if (entry->mask & KADM5_LAST_SUCCESS) {
memset(strval, 0, sizeof(strval));
if ((strval[0]=getstringtime(entry->last_success)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastSuccessfulAuth", LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
if (entry->mask & KADM5_LAST_FAILED) {
memset(strval, 0, sizeof(strval));
if ((strval[0]=getstringtime(entry->last_failed)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastFailedAuth", LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free(strval[0]);
}
if (entry->mask & KADM5_FAIL_AUTH_COUNT) {
krb5_kvno fail_auth_count;
fail_auth_count = entry->fail_auth_count;
if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT)
fail_auth_count++;
st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
LDAP_MOD_REPLACE,
fail_auth_count);
if (st != 0)
goto cleanup;
} else if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) {
int attr_mask = 0;
krb5_boolean has_fail_count;
/* Check if the krbLoginFailedCount attribute exists. (Through
* krb5 1.8.1, it wasn't set in new entries.) */
st = krb5_get_attributes_mask(context, entry, &attr_mask);
if (st != 0)
goto cleanup;
has_fail_count = ((attr_mask & KDB_FAIL_AUTH_COUNT_ATTR) != 0);
/*
* If the client library and server supports RFC 4525,
* then use it to increment by one the value of the
* krbLoginFailedCount attribute. Otherwise, assert the
* (provided) old value by deleting it before adding.
*/
#ifdef LDAP_MOD_INCREMENT
if (ldap_server_handle->server_info->modify_increment &&
has_fail_count) {
st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
LDAP_MOD_INCREMENT, 1);
if (st != 0)
goto cleanup;
} else {
#endif /* LDAP_MOD_INCREMENT */
if (has_fail_count) {
st = krb5_add_int_mem_ldap_mod(&mods,
"krbLoginFailedCount",
LDAP_MOD_DELETE,
entry->fail_auth_count);
if (st != 0)
goto cleanup;
}
st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
LDAP_MOD_ADD,
entry->fail_auth_count + 1);
if (st != 0)
goto cleanup;
#ifdef LDAP_MOD_INCREMENT
}
#endif
} else if (optype == ADD_PRINCIPAL) {
/* Initialize krbLoginFailedCount in new entries to help avoid a
* race during the first failed login. */
st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
LDAP_MOD_ADD, 0);
}
if (entry->mask & KADM5_MAX_LIFE) {
if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxticketlife", LDAP_MOD_REPLACE, entry->max_life)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_MAX_RLIFE) {
if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxrenewableage", LDAP_MOD_REPLACE,
entry->max_renewable_life)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_ATTRIBUTES) {
if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbticketflags", LDAP_MOD_REPLACE,
entry->attributes)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_PRINCIPAL) {
memset(strval, 0, sizeof(strval));
strval[0] = user;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalname", LDAP_MOD_REPLACE, strval)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_PRINC_EXPIRE_TIME) {
memset(strval, 0, sizeof(strval));
if ((strval[0]=getstringtime(entry->expiration)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalexpiration", LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
if (entry->mask & KADM5_PW_EXPIRATION) {
memset(strval, 0, sizeof(strval));
if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration",
LDAP_MOD_REPLACE,
strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
if (entry->mask & KADM5_POLICY || entry->mask & KADM5_KEY_HIST) {
memset(&princ_ent, 0, sizeof(princ_ent));
for (tl_data=entry->tl_data; tl_data; tl_data=tl_data->tl_data_next) {
if (tl_data->tl_data_type == KRB5_TL_KADM_DATA) {
if ((st = krb5_lookup_tl_kadm_data(tl_data, &princ_ent)) != 0) {
goto cleanup;
}
break;
}
}
}
if (entry->mask & KADM5_POLICY) {
if (princ_ent.aux_attributes & KADM5_POLICY) {
memset(strval, 0, sizeof(strval));
if ((st = krb5_ldap_name_to_policydn (context, princ_ent.policy, &polname)) != 0)
goto cleanup;
strval[0] = polname;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, strval)) != 0)
goto cleanup;
} else {
st = EINVAL;
k5_setmsg(context, st, "Password policy value null");
goto cleanup;
}
} else if (entry->mask & KADM5_LOAD && found_entry == TRUE) {
/*
* a load is special in that existing entries must have attrs that
* removed.
*/
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, NULL)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_POLICY_CLR) {
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_DELETE, NULL)) != 0)
goto cleanup;
}
if (entry->mask & KADM5_KEY_HIST) {
bersecretkey = krb5_encode_histkey(&princ_ent);
if (bersecretkey == NULL) {
st = ENOMEM;
goto cleanup;
}
st = krb5_add_ber_mem_ldap_mod(&mods, "krbpwdhistory",
LDAP_MOD_REPLACE | LDAP_MOD_BVALUES,
bersecretkey);
if (st != 0)
goto cleanup;
free_berdata(bersecretkey);
bersecretkey = NULL;
}
if (entry->mask & KADM5_KEY_DATA || entry->mask & KADM5_KVNO) {
krb5_kvno mkvno;
if ((st=krb5_dbe_lookup_mkvno(context, entry, &mkvno)) != 0)
goto cleanup;
bersecretkey = krb5_encode_krbsecretkey (entry->key_data,
entry->n_key_data, mkvno);
if (bersecretkey == NULL) {
st = ENOMEM;
goto cleanup;
}
/* An empty list of bervals is only accepted for modify operations,
* not add operations. */
if (bersecretkey[0] != NULL || !create_standalone) {
st = krb5_add_ber_mem_ldap_mod(&mods, "krbprincipalkey",
LDAP_MOD_REPLACE | LDAP_MOD_BVALUES,
bersecretkey);
if (st != 0)
goto cleanup;
}
if (!(entry->mask & KADM5_PRINCIPAL)) {
memset(strval, 0, sizeof(strval));
if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods,
"krbpasswordexpiration",
LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
/* Update last password change whenever a new key is set */
{
krb5_timestamp last_pw_changed;
if ((st=krb5_dbe_lookup_last_pwd_change(context, entry,
&last_pw_changed)) != 0)
goto cleanup;
memset(strval, 0, sizeof(strval));
if ((strval[0] = getstringtime(last_pw_changed)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastPwdChange",
LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
} /* Modify Key data ends here */
/* Auth indicators will also be stored in krbExtraData when processing
* tl_data. */
st = update_ldap_mod_auth_ind(context, entry, &mods);
if (st != 0)
goto cleanup;
/* Set tl_data */
if (entry->tl_data != NULL) {
int count = 0;
struct berval **ber_tl_data = NULL;
krb5_tl_data *ptr;
krb5_timestamp unlock_time;
for (ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) {
if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE
#ifdef SECURID
|| ptr->tl_data_type == KRB5_TL_DB_ARGS
#endif
|| ptr->tl_data_type == KRB5_TL_KADM_DATA
|| ptr->tl_data_type == KDB_TL_USER_INFO
|| ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL
|| ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK)
continue;
count++;
}
if (count != 0) {
int j;
ber_tl_data = (struct berval **) calloc (count + 1,
sizeof (struct berval*));
if (ber_tl_data == NULL) {
st = ENOMEM;
goto cleanup;
}
for (j = 0, ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) {
/* Ignore tl_data that are stored in separate directory
* attributes */
if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE
#ifdef SECURID
|| ptr->tl_data_type == KRB5_TL_DB_ARGS
#endif
|| ptr->tl_data_type == KRB5_TL_KADM_DATA
|| ptr->tl_data_type == KDB_TL_USER_INFO
|| ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL
|| ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK)
continue;
if ((st = tl_data2berval (ptr, &ber_tl_data[j])) != 0)
break;
j++;
}
if (st == 0) {
ber_tl_data[count] = NULL;
st=krb5_add_ber_mem_ldap_mod(&mods, "krbExtraData",
LDAP_MOD_REPLACE |
LDAP_MOD_BVALUES, ber_tl_data);
}
free_berdata(ber_tl_data);
if (st != 0)
goto cleanup;
}
if ((st=krb5_dbe_lookup_last_admin_unlock(context, entry,
&unlock_time)) != 0)
goto cleanup;
if (unlock_time != 0) {
/* Update last admin unlock */
memset(strval, 0, sizeof(strval));
if ((strval[0] = getstringtime(unlock_time)) == NULL)
goto cleanup;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastAdminUnlock",
LDAP_MOD_REPLACE, strval)) != 0) {
free (strval[0]);
goto cleanup;
}
free (strval[0]);
}
}
/* Directory specific attribute */
if (xargs.tktpolicydn != NULL) {
int tmask=0;
if (strlen(xargs.tktpolicydn) != 0) {
st = checkattributevalue(ld, xargs.tktpolicydn, "objectclass", policyclass, &tmask);
CHECK_CLASS_VALIDITY(st, tmask, _("ticket policy object value: "));
strval[0] = xargs.tktpolicydn;
strval[1] = NULL;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_REPLACE, strval)) != 0)
goto cleanup;
} else {
/* if xargs.tktpolicydn is a empty string, then delete
* already existing krbticketpolicyreference attr */
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_DELETE, NULL)) != 0)
goto cleanup;
}
}
if (establish_links == TRUE) {
memset(strval, 0, sizeof(strval));
strval[0] = xargs.linkdn;
if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbObjectReferences", LDAP_MOD_REPLACE, strval)) != 0)
goto cleanup;
}
/*
* in case mods is NULL then return
* not sure but can happen in a modprinc
* so no need to return an error
* addprinc will at least have the principal name
* and the keys passed in
*/
if (mods == NULL)
goto cleanup;
if (create_standalone == TRUE) {
memset(strval, 0, sizeof(strval));
strval[0] = "krbprincipal";
strval[1] = "krbprincipalaux";
strval[2] = "krbTicketPolicyAux";
if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
goto cleanup;
st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL);
if (st == LDAP_ALREADY_EXISTS && entry->mask & KADM5_LOAD) {
/* a load operation must replace an existing entry */
st = ldap_delete_ext_s(ld, standalone_principal_dn, NULL, NULL);
if (st != LDAP_SUCCESS) {
snprintf(errbuf, sizeof(errbuf),
_("Principal delete failed (trying to replace "
"entry): %s"), ldap_err2string(st));
st = translate_ldap_error (st, OP_ADD);
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
} else {
st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL);
}
}
if (st != LDAP_SUCCESS) {
snprintf(errbuf, sizeof(errbuf), _("Principal add failed: %s"),
ldap_err2string(st));
st = translate_ldap_error (st, OP_ADD);
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
}
} else {
/*
* Here existing ldap object is modified and can be related
* to any attribute, so always ensure that the ldap
* object is extended with all the kerberos related
* objectclasses so that there are no constraint
* violations.
*/
{
char *attrvalues[] = {"krbprincipalaux", "krbTicketPolicyAux", NULL};
int p, q, r=0, amask=0;
if ((st=checkattributevalue(ld, (xargs.dn) ? xargs.dn : principal_dn,
"objectclass", attrvalues, &amask)) != 0)
goto cleanup;
memset(strval, 0, sizeof(strval));
for (p=1, q=0; p<=2; p<<=1, ++q) {
if ((p & amask) == 0)
strval[r++] = attrvalues[q];
}
if (r != 0) {
if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
goto cleanup;
}
}
if (xargs.dn != NULL)
st=ldap_modify_ext_s(ld, xargs.dn, mods, NULL, NULL);
else
st = ldap_modify_ext_s(ld, principal_dn, mods, NULL, NULL);
if (st != LDAP_SUCCESS) {
snprintf(errbuf, sizeof(errbuf), _("User modification failed: %s"),
ldap_err2string(st));
st = translate_ldap_error (st, OP_MOD);
k5_setmsg(context, st, "%s", errbuf);
goto cleanup;
}
if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT)
entry->fail_auth_count++;
}
cleanup:
if (user)
free(user);
if (filtuser)
free(filtuser);
free_xargs(xargs);
if (standalone_principal_dn)
free(standalone_principal_dn);
if (principal_dn)
free (principal_dn);
if (polname != NULL)
free(polname);
for (tre = 0; tre < ntrees; tre++)
free(subtreelist[tre]);
free(subtreelist);
if (subtree)
free (subtree);
if (bersecretkey) {
for (l=0; bersecretkey[l]; ++l) {
if (bersecretkey[l]->bv_val)
free (bersecretkey[l]->bv_val);
free (bersecretkey[l]);
}
free (bersecretkey);
}
if (keys)
free (keys);
ldap_mods_free(mods, 1);
ldap_osa_free_princ_ent(&princ_ent);
ldap_msgfree(result);
krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
return(st);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-90'], 'message': 'Fix flaws in LDAP DN checking
KDB_TL_USER_INFO tl-data is intended to be internal to the LDAP KDB
module, and not used in disk or wire principal entries. Prevent
kadmin clients from sending KDB_TL_USER_INFO tl-data by giving it a
type number less than 256 and filtering out type numbers less than 256
in kadm5_create_principal_3(). (We already filter out low type
numbers in kadm5_modify_principal()).
In the LDAP KDB module, if containerdn and linkdn are both specified
in a put_principal operation, check both linkdn and the computed
standalone_principal_dn for container membership. To that end, factor
out the checks into helper functions and call them on all applicable
client-influenced DNs.
CVE-2018-5729:
In MIT krb5 1.6 or later, an authenticated kadmin user with permission
to add principals to an LDAP Kerberos database can cause a null
dereference in kadmind, or circumvent a DN container check, by
supplying tagged data intended to be internal to the database module.
Thanks to Sharwan Ram and Pooja Anil for discovering the potential
null dereference.
CVE-2018-5730:
In MIT krb5 1.6 or later, an authenticated kadmin user with permission
to add principals to an LDAP Kerberos database can circumvent a DN
containership check by supplying both a "linkdn" and "containerdn"
database argument, or by supplying a DN string which is a left
extension of a container DN string but is not hierarchically within
the container DN.
ticket: 8643 (new)
tags: pullup
target_version: 1.16-next
target_version: 1.15-next'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static long madvise_willneed(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
struct file *file = vma->vm_file;
#ifdef CONFIG_SWAP
if (!file) {
*prev = vma;
force_swapin_readahead(vma, start, end);
return 0;
}
if (shmem_mapping(file->f_mapping)) {
*prev = vma;
force_shm_swapin_readahead(vma, start, end,
file->f_mapping);
return 0;
}
#else
if (!file)
return -EBADF;
#endif
if (IS_DAX(file_inode(file))) {
/* no bad return value, but ignore advice */
return 0;
}
*prev = vma;
start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
if (end > vma->vm_end)
end = vma->vm_end;
end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
force_page_cache_readahead(file->f_mapping, file, start, end - start);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'mm/madvise.c: fix madvise() infinite loop under special circumstances
MADVISE_WILLNEED has always been a noop for DAX (formerly XIP) mappings.
Unfortunately madvise_willneed() doesn't communicate this information
properly to the generic madvise syscall implementation. The calling
convention is quite subtle there. madvise_vma() is supposed to either
return an error or update &prev otherwise the main loop will never
advance to the next vma and it will keep looping for ever without a way
to get out of the kernel.
It seems this has been broken since introduction. Nobody has noticed
because nobody seems to be using MADVISE_WILLNEED on these DAX mappings.
[[email protected]: rewrite changelog]
Link: http://lkml.kernel.org/r/[email protected]
Fixes: fe77ba6f4f97 ("[PATCH] xip: madvice/fadvice: execute in place")
Signed-off-by: chenjie <[email protected]>
Signed-off-by: guoxuenan <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: zhangyi (F) <[email protected]>
Cc: Miao Xie <[email protected]>
Cc: Mike Rapoport <[email protected]>
Cc: Shaohua Li <[email protected]>
Cc: Andrea Arcangeli <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Anshuman Khandual <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Carsten Otte <[email protected]>
Cc: Dan Williams <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int hns_nic_net_xmit_hw(struct net_device *ndev,
struct sk_buff *skb,
struct hns_nic_ring_data *ring_data)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
struct hnae_ring *ring = ring_data->ring;
struct device *dev = ring_to_dev(ring);
struct netdev_queue *dev_queue;
struct skb_frag_struct *frag;
int buf_num;
int seg_num;
dma_addr_t dma;
int size, next_to_use;
int i;
switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) {
case -EBUSY:
ring->stats.tx_busy++;
goto out_net_tx_busy;
case -ENOMEM:
ring->stats.sw_err_cnt++;
netdev_err(ndev, "no memory to xmit!\n");
goto out_err_tx_ok;
default:
break;
}
/* no. of segments (plus a header) */
seg_num = skb_shinfo(skb)->nr_frags + 1;
next_to_use = ring->next_to_use;
/* fill the first part */
size = skb_headlen(skb);
dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX head DMA map failed\n");
ring->stats.sw_err_cnt++;
goto out_err_tx_ok;
}
priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0,
buf_num, DESC_TYPE_SKB, ndev->mtu);
/* fill the fragments */
for (i = 1; i < seg_num; i++) {
frag = &skb_shinfo(skb)->frags[i - 1];
size = skb_frag_size(frag);
dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX frag(%d) DMA map failed\n", i);
ring->stats.sw_err_cnt++;
goto out_map_frag_fail;
}
priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma,
seg_num - 1 == i ? 1 : 0, buf_num,
DESC_TYPE_PAGE, ndev->mtu);
}
/*complete translate all packets*/
dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping);
netdev_tx_sent_queue(dev_queue, skb->len);
wmb(); /* commit all data before submit */
assert(skb->queue_mapping < priv->ae_handle->q_num);
hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num);
ring->stats.tx_pkts++;
ring->stats.tx_bytes += skb->len;
return NETDEV_TX_OK;
out_map_frag_fail:
while (ring->next_to_use != next_to_use) {
unfill_desc(ring);
if (ring->next_to_use != next_to_use)
dma_unmap_page(dev,
ring->desc_cb[ring->next_to_use].dma,
ring->desc_cb[ring->next_to_use].length,
DMA_TO_DEVICE);
else
dma_unmap_single(dev,
ring->desc_cb[next_to_use].dma,
ring->desc_cb[next_to_use].length,
DMA_TO_DEVICE);
}
out_err_tx_ok:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
out_net_tx_busy:
netif_stop_subqueue(ndev, skb->queue_mapping);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
return NETDEV_TX_BUSY;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node)
{
/* through the first node_set .parent
* mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */
return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[[email protected]: v2]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t o2nm_node_local_store(struct config_item *item, const char *page,
size_t count)
{
struct o2nm_node *node = to_o2nm_node(item);
struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node);
unsigned long tmp;
char *p = (char *)page;
ssize_t ret;
tmp = simple_strtoul(p, &p, 0);
if (!p || (*p && (*p != '\n')))
return -EINVAL;
tmp = !!tmp; /* boolean of whether this node wants to be local */
/* setting local turns on networking rx for now so we require having
* set everything else first */
if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) ||
!test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes))
return -EINVAL; /* XXX */
/* the only failure case is trying to set a new local node
* when a different one is already set */
if (tmp && tmp == cluster->cl_has_local &&
cluster->cl_local_node != node->nd_num)
return -EBUSY;
/* bring up the rx thread if we're setting the new local node. */
if (tmp && !cluster->cl_has_local) {
ret = o2net_start_listening(node);
if (ret)
return ret;
}
if (!tmp && cluster->cl_has_local &&
cluster->cl_local_node == node->nd_num) {
o2net_stop_listening(node);
cluster->cl_local_node = O2NM_INVALID_NODE_NUM;
}
node->nd_local = tmp;
if (node->nd_local) {
cluster->cl_has_local = tmp;
cluster->cl_local_node = node->nd_num;
}
return count;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent
The subsystem.su_mutex is required while accessing the item->ci_parent,
otherwise, NULL pointer dereference to the item->ci_parent will be
triggered in the following situation:
add node delete node
sys_write
vfs_write
configfs_write_file
o2nm_node_store
o2nm_node_local_write
do_rmdir
vfs_rmdir
configfs_rmdir
mutex_lock(&subsys->su_mutex);
unlink_obj
item->ci_group = NULL;
item->ci_parent = NULL;
to_o2nm_cluster_from_node
node->nd_item.ci_parent->ci_parent
BUG since of NULL pointer dereference to nd_item.ci_parent
Moreover, the o2nm_cluster also should be protected by the
subsystem.su_mutex.
[[email protected]: v2]
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport MagickBooleanType SetImageRegistry(const RegistryType type,
const char *key,const void *value,ExceptionInfo *exception)
{
MagickBooleanType
status;
RegistryInfo
*registry_info;
void
*clone_value;
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",key);
if (value == (const void *) NULL)
return(MagickFalse);
clone_value=(void *) NULL;
switch (type)
{
case StringRegistryType:
default:
{
const char
*string;
string=(const char *) value;
clone_value=(void *) ConstantString(string);
break;
}
case ImageRegistryType:
{
const Image
*image;
image=(const Image *) value;
if (image->signature != MagickCoreSignature)
{
(void) ThrowMagickException(exception,GetMagickModule(),RegistryError,
"UnableToSetRegistry","%s",key);
return(MagickFalse);
}
clone_value=(void *) CloneImageList(image,exception);
break;
}
case ImageInfoRegistryType:
{
const ImageInfo
*image_info;
image_info=(const ImageInfo *) value;
if (image_info->signature != MagickCoreSignature)
{
(void) ThrowMagickException(exception,GetMagickModule(),RegistryError,
"UnableToSetRegistry","%s",key);
return(MagickFalse);
}
clone_value=(void *) CloneImageInfo(image_info);
break;
}
}
if (clone_value == (void *) NULL)
return(MagickFalse);
registry_info=(RegistryInfo *) AcquireMagickMemory(sizeof(*registry_info));
if (registry_info == (RegistryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(registry_info,0,sizeof(*registry_info));
registry_info->type=type;
registry_info->value=clone_value;
registry_info->signature=MagickCoreSignature;
if (registry == (SplayTreeInfo *) NULL)
{
if (registry_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(®istry_semaphore);
LockSemaphoreInfo(registry_semaphore);
if (registry == (SplayTreeInfo *) NULL)
registry=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyRegistryNode);
UnlockSemaphoreInfo(registry_semaphore);
}
status=AddValueToSplayTree(registry,ConstantString(key),registry_info);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/790'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int crypto_authenticate_and_decrypt (struct crypto_instance *instance,
unsigned char *buf,
int *buf_len)
{
struct crypto_config_header *cch = (struct crypto_config_header *)buf;
const char *guessed_str;
if (cch->crypto_cipher_type != CRYPTO_CIPHER_TYPE_2_3) {
guessed_str = NULL;
if ((cch->crypto_cipher_type == 0xC0 && cch->crypto_hash_type == 0x70) ||
(cch->crypto_cipher_type == 0x70 && cch->crypto_hash_type == 0xC0)) {
guessed_str = "Corosync 3.x";
} else if (cch->crypto_cipher_type == CRYPTO_CIPHER_TYPE_2_2) {
guessed_str = "Corosync 2.2";
} else if (cch->crypto_cipher_type == 0x01) {
guessed_str = "unencrypted Kronosnet";
} else if (cch->crypto_cipher_type >= 0 && cch->crypto_cipher_type <= 5) {
guessed_str = "unencrypted Corosync 2.0/2.1/1.x/OpenAIS";
} else {
guessed_str = "encrypted Kronosnet/Corosync 2.0/2.1/1.x/OpenAIS or unknown";
}
log_printf(instance->log_level_security,
"Unsupported incoming packet (probably sent by %s). Rejecting",
guessed_str);
return -1;
}
if (cch->crypto_hash_type != CRYPTO_HASH_TYPE_2_3) {
log_printf(instance->log_level_security,
"Incoming packet has different hash type. Rejecting");
return -1;
}
/*
* authenticate packet first
*/
if (authenticate_nss_2_3(instance, buf, buf_len) != 0) {
return -1;
}
/*
* now we can "trust" the padding bytes/future features
*/
if ((cch->__pad0 != 0) || (cch->__pad1 != 0)) {
log_printf(instance->log_level_security,
"Incoming packet appears to have features not supported by this version of corosync. Rejecting");
return -1;
}
/*
* decrypt
*/
if (decrypt_nss_2_3(instance, buf, buf_len) != 0) {
return -1;
}
/*
* invalidate config header and kill it
*/
cch = NULL;
memmove(buf, buf + sizeof(struct crypto_config_header), *buf_len);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'totemcrypto: Check length of the packet
Packet has to be longer than crypto_config_header and hash_len,
otherwise unallocated memory is passed into calculate_nss_hash function,
what may result in crash.
Signed-off-by: Jan Friesse <[email protected]>
Reviewed-by: Raphael Sanchez Prudencio <[email protected]>
Reviewed-by: Christine Caulfield <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)
{
int i;
int nr = pagevec_count(pvec);
int delta_munlocked;
struct pagevec pvec_putback;
int pgrescued = 0;
pagevec_init(&pvec_putback, 0);
/* Phase 1: page isolation */
spin_lock_irq(zone_lru_lock(zone));
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (TestClearPageMlocked(page)) {
/*
* We already have pin from follow_page_mask()
* so we can spare the get_page() here.
*/
if (__munlock_isolate_lru_page(page, false))
continue;
else
__munlock_isolation_failed(page);
}
/*
* We won't be munlocking this page in the next phase
* but we still need to release the follow_page_mask()
* pin. We cannot do it under lru_lock however. If it's
* the last pin, __page_cache_release() would deadlock.
*/
pagevec_add(&pvec_putback, pvec->pages[i]);
pvec->pages[i] = NULL;
}
delta_munlocked = -nr + pagevec_count(&pvec_putback);
__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);
spin_unlock_irq(zone_lru_lock(zone));
/* Now we can release pins of pages that we are not munlocking */
pagevec_release(&pvec_putback);
/* Phase 2: page munlock */
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (page) {
lock_page(page);
if (!__putback_lru_fast_prepare(page, &pvec_putback,
&pgrescued)) {
/*
* Slow path. We don't want to lose the last
* pin before unlock_page()
*/
get_page(page); /* for putback_lru_page() */
__munlock_isolated_page(page);
unlock_page(page);
put_page(page); /* from follow_page_mask() */
}
}
}
/*
* Phase 3: page putback for pages that qualified for the fast path
* This will also call put_page() to return pin from follow_page_mask()
*/
if (pagevec_count(&pvec_putback))
__putback_lru_fast(&pvec_putback, pgrescued);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'mlock: fix mlock count can not decrease in race condition
Kefeng reported that when running the follow test, the mlock count in
meminfo will increase permanently:
[1] testcase
linux:~ # cat test_mlockal
grep Mlocked /proc/meminfo
for j in `seq 0 10`
do
for i in `seq 4 15`
do
./p_mlockall >> log &
done
sleep 0.2
done
# wait some time to let mlock counter decrease and 5s may not enough
sleep 5
grep Mlocked /proc/meminfo
linux:~ # cat p_mlockall.c
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#define SPACE_LEN 4096
int main(int argc, char ** argv)
{
int ret;
void *adr = malloc(SPACE_LEN);
if (!adr)
return -1;
ret = mlockall(MCL_CURRENT | MCL_FUTURE);
printf("mlcokall ret = %d\n", ret);
ret = munlockall();
printf("munlcokall ret = %d\n", ret);
free(adr);
return 0;
}
In __munlock_pagevec() we should decrement NR_MLOCK for each page where
we clear the PageMlocked flag. Commit 1ebb7cc6a583 ("mm: munlock: batch
NR_MLOCK zone state updates") has introduced a bug where we don't
decrement NR_MLOCK for pages where we clear the flag, but fail to
isolate them from the lru list (e.g. when the pages are on some other
cpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK
accounting gets permanently disrupted by this.
Fix it by counting the number of page whose PageMlock flag is cleared.
Fixes: 1ebb7cc6a583 (" mm: munlock: batch NR_MLOCK zone state updates")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Yisheng Xie <[email protected]>
Reported-by: Kefeng Wang <[email protected]>
Tested-by: Kefeng Wang <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Joern Engel <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Michel Lespinasse <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Michal Hocko <[email protected]>
Cc: Xishi Qiu <[email protected]>
Cc: zhongjiang <[email protected]>
Cc: Hanjun Guo <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int sas_smp_get_phy_events(struct sas_phy *phy)
{
int res;
u8 *req;
u8 *resp;
struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent);
struct domain_device *dev = sas_find_dev_by_rphy(rphy);
req = alloc_smp_req(RPEL_REQ_SIZE);
if (!req)
return -ENOMEM;
resp = alloc_smp_resp(RPEL_RESP_SIZE);
if (!resp) {
kfree(req);
return -ENOMEM;
}
req[1] = SMP_REPORT_PHY_ERR_LOG;
req[9] = phy->number;
res = smp_execute_task(dev, req, RPEL_REQ_SIZE,
resp, RPEL_RESP_SIZE);
if (!res)
goto out;
phy->invalid_dword_count = scsi_to_u32(&resp[12]);
phy->running_disparity_error_count = scsi_to_u32(&resp[16]);
phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]);
phy->phy_reset_problem_count = scsi_to_u32(&resp[24]);
out:
kfree(resp);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'scsi: libsas: fix memory leak in sas_smp_get_phy_events()
We've got a memory leak with the following producer:
while true;
do cat /sys/class/sas_phy/phy-1:0:12/invalid_dword_count >/dev/null;
done
The buffer req is allocated and not freed after we return. Fix it.
Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver")
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: chenqilin <[email protected]>
CC: chenxiang <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int hns_xgmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_xgmac_stats_string);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int hns_gmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_gmac_stats_string);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ssize_t store_int_with_restart(struct device *s,
struct device_attribute *attr,
const char *buf, size_t size)
{
ssize_t ret = device_store_int(s, attr, buf, size);
mce_restart();
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'x86/MCE: Serialize sysfs changes
The check_interval file in
/sys/devices/system/machinecheck/machinecheck<cpu number>
directory is a global timer value for MCE polling. If it is changed by one
CPU, mce_restart() broadcasts the event to other CPUs to delete and restart
the MCE polling timer and __mcheck_cpu_init_timer() reinitializes the
mce_timer variable.
If more than one CPU writes a specific value to the check_interval file
concurrently, mce_timer is not protected from such concurrent accesses and
all kinds of explosions happen. Since only root can write to those sysfs
variables, the issue is not a big deal security-wise.
However, concurrent writes to these configuration variables is void of
reason so the proper thing to do is to serialize the access with a mutex.
Boris:
- Make store_int_with_restart() use device_store_ulong() to filter out
negative intervals
- Limit min interval to 1 second
- Correct locking
- Massage commit message
Signed-off-by: Seunghun Han <[email protected]>
Signed-off-by: Borislav Petkov <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: Greg Kroah-Hartman <[email protected]>
Cc: Tony Luck <[email protected]>
Cc: linux-edac <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/[email protected]'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: 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;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'net: phy: mdio-bcm-unimac: fix potential NULL dereference in unimac_mdio_probe()
platform_get_resource() may fail and return NULL, so we should
better check it's return value to avoid a NULL pointer dereference
a bit later in the code.
This is detected by Coccinelle semantic patch.
@@
expression pdev, res, n, t, e, e1, e2;
@@
res = platform_get_resource(pdev, t, n);
+ if (!res)
+ return -EINVAL;
... when != res == NULL
e = devm_ioremap(e1, res->start, e2);
Signed-off-by: Wei Yongjun <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: 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;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415', 'CWE-190'], 'message': 'index: fix out-of-bounds read with invalid index entry prefix length
The index format in version 4 has prefix-compressed entries, where every
index entry can compress its path by using a path prefix of the previous
entry. Since implmenting support for this index format version in commit
5625d86b9 (index: support index v4, 2016-05-17), though, we do not
correctly verify that the prefix length that we want to reuse is
actually smaller or equal to the amount of characters than the length of
the previous index entry's path. This can lead to a an integer underflow
and subsequently to an out-of-bounds read.
Fix this by verifying that the prefix is actually smaller than the
previous entry's path length.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static size_t read_entry(
git_index_entry **out,
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 0;
/* 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 0;
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 (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return 0;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return 0;
}
git__free(tmp_path);
return entry_size;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: template <class T> void testFeatTable(const T & table, const char * testName)
{
FeatureMap testFeatureMap;
dummyFace.replace_table(TtfUtil::Tag::Feat, &table, sizeof(T));
gr_face * face = gr_make_face_with_ops(&dummyFace, &face_handle::ops, gr_face_dumbRendering);
if (!face) throw std::runtime_error("failed to load font");
bool readStatus = testFeatureMap.readFeats(*face);
testAssert("readFeats", readStatus);
fprintf(stderr, testName, NULL);
testAssertEqual("test num features %hu,%hu\n", testFeatureMap.numFeats(), table.m_header.m_numFeat);
for (size_t i = 0; i < sizeof(table.m_defs) / sizeof(FeatDefn); i++)
{
const FeatureRef * ref = testFeatureMap.findFeatureRef(table.m_defs[i].m_featId);
testAssert("test feat\n", ref);
testAssertEqual("test feat settings %hu %hu\n", ref->getNumSettings(), table.m_defs[i].m_numFeatSettings);
testAssertEqual("test feat label %hu %hu\n", ref->getNameId(), table.m_defs[i].m_label);
size_t settingsIndex = (table.m_defs[i].m_settingsOffset - sizeof(FeatHeader)
- (sizeof(FeatDefn) * table.m_header.m_numFeat)) / sizeof(FeatSetting);
for (size_t j = 0; j < table.m_defs[i].m_numFeatSettings; j++)
{
testAssertEqual("setting label %hu %hu\n", ref->getSettingName(j),
table.m_settings[settingsIndex+j].m_label);
}
}
gr_face_destroy(face);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Deprecate and make ineffective gr_face_dumbRendering'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: GlyphCache::GlyphCache(const Face & face, const uint32 face_options)
: _glyph_loader(new Loader(face, bool(face_options & gr_face_dumbRendering))),
_glyphs(_glyph_loader && *_glyph_loader && _glyph_loader->num_glyphs()
? grzeroalloc<const GlyphFace *>(_glyph_loader->num_glyphs()) : 0),
_boxes(_glyph_loader && _glyph_loader->has_boxes() && _glyph_loader->num_glyphs()
? grzeroalloc<GlyphBox *>(_glyph_loader->num_glyphs()) : 0),
_num_glyphs(_glyphs ? _glyph_loader->num_glyphs() : 0),
_num_attrs(_glyphs ? _glyph_loader->num_attrs() : 0),
_upem(_glyphs ? _glyph_loader->units_per_em() : 0)
{
if ((face_options & gr_face_preloadGlyphs) && _glyph_loader && _glyphs)
{
int numsubs = 0;
GlyphFace * const glyphs = new GlyphFace [_num_glyphs];
if (!glyphs)
return;
// The 0 glyph is definately required.
_glyphs[0] = _glyph_loader->read_glyph(0, glyphs[0], &numsubs);
// glyphs[0] has the same address as the glyphs array just allocated,
// thus assigning the &glyphs[0] to _glyphs[0] means _glyphs[0] points
// to the entire array.
const GlyphFace * loaded = _glyphs[0];
for (uint16 gid = 1; loaded && gid != _num_glyphs; ++gid)
_glyphs[gid] = loaded = _glyph_loader->read_glyph(gid, glyphs[gid], &numsubs);
if (!loaded)
{
_glyphs[0] = 0;
delete [] glyphs;
}
else if (numsubs > 0 && _boxes)
{
GlyphBox * boxes = (GlyphBox *)gralloc<char>(_num_glyphs * sizeof(GlyphBox) + numsubs * 8 * sizeof(float));
GlyphBox * currbox = boxes;
for (uint16 gid = 0; currbox && gid != _num_glyphs; ++gid)
{
_boxes[gid] = currbox;
currbox = _glyph_loader->read_box(gid, currbox, *_glyphs[gid]);
}
if (!currbox)
{
free(boxes);
_boxes[0] = 0;
}
}
delete _glyph_loader;
_glyph_loader = 0;
}
if (_glyphs && glyph(0) == 0)
{
free(_glyphs);
_glyphs = 0;
if (_boxes)
{
free(_boxes);
_boxes = 0;
}
_num_glyphs = _num_attrs = _upem = 0;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Deprecate and make ineffective gr_face_dumbRendering'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int af_get_page(AFFILE *af,int64_t pagenum,unsigned char *data,size_t *bytes)
{
uint32_t arg=0;
size_t page_len=0;
if (af_trace){
fprintf(af_trace,"af_get_page(%p,pagenum=%" I64d ",buf=%p,bytes=%u)\n",af,pagenum,data,(int)*bytes);
}
/* Find out the size of the segment and if it is compressed or not.
* If we can't find it with new nomenclature, try the old one...
*/
int r = af_get_page_raw(af,pagenum,&arg,0,&page_len);
if(r){
/* Segment doesn't exist.
* If we have been provided with a buffer,
* fill buffer with the 'bad segment' flag and return.
*/
if(data && (af->openmode & AF_BADBLOCK_FILL) && errno == ENOENT)
{
for(size_t i = 0;i <= af->image_pagesize - af->image_sectorsize;
i+= af->image_sectorsize){
memcpy(data+i,af->badflag,af->image_sectorsize);
af->bytes_memcpy += af->image_sectorsize;
}
r = 0;
}
return r; // segment doesn't exist
}
/* If the segment isn't compressed, just get it*/
uint32_t pageflag = 0;
if((arg & AF_PAGE_COMPRESSED)==0){
if(data==0){ // if no data provided, just return size of the segment if requested
if(bytes) *bytes = page_len; // set the number of bytes in the page if requested
return 0;
}
int ret = af_get_page_raw(af,pagenum,&pageflag,data,bytes);
if(*bytes > page_len) *bytes = page_len; // we only read this much
if(ret!=0) return ret; // some error happened?
}
else {
/* Allocate memory to hold the compressed segment */
unsigned char *compressed_data = (unsigned char *)malloc(page_len);
size_t compressed_data_len = page_len;
if(compressed_data==0){
return -2; // memory error
}
/* Get the data */
if(af_get_page_raw(af,pagenum,&pageflag,compressed_data,&compressed_data_len)){
free(compressed_data);
return -3; // read error
}
/* Now uncompress directly into the buffer provided by the caller, unless the caller didn't
* provide a buffer. If that happens, allocate our own...
*/
int res = -1; // 0 is success
bool free_data = false;
if(data==0){
data = (unsigned char *)malloc(af->image_pagesize);
free_data = true;
*bytes = af->image_pagesize; // I can hold this much
}
switch((pageflag & AF_PAGE_COMP_ALG_MASK)){
case AF_PAGE_COMP_ALG_ZERO:
if(compressed_data_len != 4){
(*af->error_reporter)("ALG_ZERO compressed data is %d bytes, expected 4.",compressed_data_len);
break;
}
memset(data,0,af->image_pagesize);
*bytes = ntohl(*(long *)compressed_data);
res = 0; // not very hard to decompress with the ZERO compressor.
break;
case AF_PAGE_COMP_ALG_ZLIB:
res = uncompress(data,(uLongf *)bytes,compressed_data,compressed_data_len);
switch(res){
case Z_OK:
break;
case Z_ERRNO:
(*af->error_reporter)("Z_ERRNOR decompressing segment %" I64d,pagenum);
case Z_STREAM_ERROR:
(*af->error_reporter)("Z_STREAM_ERROR decompressing segment %" I64d,pagenum);
case Z_DATA_ERROR:
(*af->error_reporter)("Z_DATA_ERROR decompressing segment %" I64d,pagenum);
case Z_MEM_ERROR:
(*af->error_reporter)("Z_MEM_ERROR decompressing segment %" I64d,pagenum);
case Z_BUF_ERROR:
(*af->error_reporter)("Z_BUF_ERROR decompressing segment %" I64d,pagenum);
case Z_VERSION_ERROR:
(*af->error_reporter)("Z_VERSION_ERROR decompressing segment %" I64d,pagenum);
default:
(*af->error_reporter)("uncompress returned an invalid value in get_segment");
}
break;
#ifdef USE_LZMA
case AF_PAGE_COMP_ALG_LZMA:
res = lzma_uncompress(data,bytes,compressed_data,compressed_data_len);
if (af_trace) fprintf(af_trace," LZMA decompressed page %" I64d ". %d bytes => %u bytes\n",
pagenum,(int)compressed_data_len,(int)*bytes);
switch(res){
case 0:break; // OK
case 1:(*af->error_reporter)("LZMA header error decompressing segment %" I64d "\n",pagenum);
break;
case 2:(*af->error_reporter)("LZMA memory error decompressing segment %" I64d "\n",pagenum);
break;
}
break;
#endif
default:
(*af->error_reporter)("Unknown compression algorithm 0x%d",
pageflag & AF_PAGE_COMP_ALG_MASK);
break;
}
if(free_data){
free(data);
data = 0; // restore the way it was
}
free(compressed_data); // don't need this one anymore
af->pages_decompressed++;
if(res!=Z_OK) return -1;
}
/* If the page size is larger than the sector_size,
* make sure that the rest of the sector is zeroed, and that the
* rest after that has the 'bad block' notation.
*/
if(data && (af->image_pagesize > af->image_sectorsize)){
const int SECTOR_SIZE = af->image_sectorsize; // for ease of typing
size_t bytes_left_in_sector = (SECTOR_SIZE - (*bytes % SECTOR_SIZE)) % SECTOR_SIZE;
for(size_t i=0;i<bytes_left_in_sector;i++){
data[*bytes + i] = 0;
}
size_t end_of_data = *bytes + bytes_left_in_sector;
/* Now fill to the end of the page... */
for(size_t i = end_of_data; i <= af->image_pagesize-SECTOR_SIZE; i+=SECTOR_SIZE){
memcpy(data+i,af->badflag,SECTOR_SIZE);
af->bytes_memcpy += SECTOR_SIZE;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-295'], 'message': 'Sanity check size passed to malloc...
Add sanity check before calling malloc in af_get_page() function to
avoid undefined behavior (e.g., seg fault) when dealing with a corrupt
AFF image with an invalid pagesize.
Issue found by Luis Rocha ([email protected]).'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_entry_fopen(ZZIP_MEM_DISK * dir, ZZIP_MEM_ENTRY * entry)
{
/* keep this in sync with zzip_disk_entry_fopen */
ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_MEM_DISK_FILE));
if (! file)
return file;
file->buffer = dir->disk->buffer;
file->endbuf = dir->disk->endbuf;
file->avail = zzip_mem_entry_usize(entry);
if (! file->avail || zzip_mem_entry_data_stored(entry))
{ file->stored = zzip_mem_entry_to_data (entry); return file; }
file->stored = 0;
file->zlib.opaque = 0;
file->zlib.zalloc = Z_NULL;
file->zlib.zfree = Z_NULL;
file->zlib.avail_in = zzip_mem_entry_csize(entry);
file->zlib.next_in = zzip_mem_entry_to_data(entry);
if (! zzip_mem_entry_data_deflated(entry) ||
inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK)
{ free (file); return 0; }
return file;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'check zlib space to be within buffer #39'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_fdopen(int fd)
{
ZZIP_DISK* disk = zzip_disk_mmap(fd);
if (! disk) { perror(error[_zzip_mem_disk_fdopen_fail]); return 0; }
___ ZZIP_MEM_DISK* dir = calloc(1, sizeof(*dir));
zzip_mem_disk_load(dir, disk);
return dir; ____;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_disk_entry_fopen (ZZIP_DISK* disk, ZZIP_DISK_ENTRY* entry)
{
ZZIP_DISK_FILE* file = malloc(sizeof(ZZIP_DISK_FILE));
if (! file) return file;
file->buffer = disk->buffer;
file->endbuf = disk->endbuf;
file->header = zzip_disk_entry_to_file_header (disk, entry);
if (! file->header) { free (file); return 0; }
file->avail = zzip_file_header_usize (file->header);
if (! file->avail || zzip_file_header_data_stored (file->header))
{ file->stored = zzip_file_header_to_data (file->header); return file; }
file->stored = 0;
file->zlib.opaque = 0;
file->zlib.zalloc = Z_NULL;
file->zlib.zfree = Z_NULL;
file->zlib.avail_in = zzip_file_header_csize (file->header);
file->zlib.next_in = zzip_file_header_to_data (file->header);
if (! zzip_file_header_data_deflated (file->header) ||
inflateInit2 (& file->zlib, -MAX_WBITS) != Z_OK)
{ free (file); return 0; }
return file;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_entry_new(ZZIP_DISK* disk, ZZIP_DISK_ENTRY* entry)
{
ZZIP_MEM_DISK_ENTRY* item = calloc(1, sizeof(*item));
struct zzip_file_header* header =
zzip_disk_entry_to_file_header(disk, entry);
/* there is a number of duplicated information in the file header
* or the disk entry block. Theoretically some part may be missing
* that exists in the other, so each and every item would need to
* be checked. However, we assume that the "always-exists" fields
* do either (a) exist both and have the same value or (b) the bits
* in the disk entry are correct. Only the variable fields are
* checked in both places: file name, file comment, extra blocks.
* From mmapped.c we do already have two helper functions for that:
*/
item->zz_comment = zzip_disk_entry_strdup_comment(disk, entry);
item->zz_name = zzip_disk_entry_strdup_name(disk, entry);
item->zz_data = zzip_file_header_to_data(header);
item->zz_flags = zzip_disk_entry_get_flags(entry);
item->zz_compr = zzip_disk_entry_get_compr(entry);
item->zz_crc32 = zzip_disk_entry_get_crc32(entry);
item->zz_csize = zzip_disk_entry_get_csize(entry);
item->zz_usize = zzip_disk_entry_get_usize(entry);
item->zz_diskstart = zzip_disk_entry_get_diskstart(entry);
item->zz_filetype = zzip_disk_entry_get_filetype(entry);
{ /* 1. scanning the extra blocks and building a fast-access table. */
size_t extcount = 0;
int extlen = zzip_file_header_get_extras(header);
char* extras = zzip_file_header_to_extras(header);
while (extlen > 0) {
struct zzip_extra_block* ext = (struct zzip_extra_block*) extras;
int size = zzip_extra_block_sizeto_end(ext);
extlen -= size; extras += size; extcount ++;
}
extlen = zzip_disk_entry_get_extras(entry);
extras = zzip_disk_entry_to_extras(entry);
while (extlen > 0) {
struct zzip_extra_block* ext = (struct zzip_extra_block*) extras;
int size = zzip_extra_block_sizeto_end(ext);
extlen -= size; extras += size; extcount ++;
}
if (item->zz_extras) free(item->zz_extras);
item->zz_extras = calloc(extcount,sizeof(struct _zzip_mem_disk_extra));
item->zz_extcount = extcount;
}
{ /* 2. reading the extra blocks and building a fast-access table. */
size_t ext = 0;
int extlen = zzip_file_header_get_extras(header);
char* extras = zzip_file_header_to_extras(header);
struct _zzip_mem_disk_extra* mem = item->zz_extras;
while (extlen > 0) {
struct zzip_extra_block* ext = (struct zzip_extra_block*) extras;
mem[ext].zz_data = extras;
mem[ext].zz_datatype = zzip_extra_block_get_datatype(ext);
mem[ext].zz_datasize = zzip_extra_block_get_datasize(ext);
___ register int size = zzip_extra_block_sizeto_end(ext);
extlen -= size; extras += size; ext ++; ____;
}
extlen = zzip_disk_entry_get_extras(entry);
extras = zzip_disk_entry_to_extras(entry);
while (extlen > 0) {
struct zzip_extra_block* ext = (struct zzip_extra_block*) extras;
mem[ext].zz_data = extras;
mem[ext].zz_datatype = zzip_extra_block_get_datatype(ext);
mem[ext].zz_datasize = zzip_extra_block_get_datasize(ext);
___ register int size = zzip_extra_block_sizeto_end(ext);
extlen -= size; extras += size; ext ++; ____;
}
}
{ /* 3. scanning the extra blocks for platform specific extensions. */
register size_t ext;
for (ext = 0; ext < item->zz_extcount; ext++) {
/* "http://www.pkware.com/company/standards/appnote/" */
switch (item->zz_extras[ext].zz_datatype) {
case 0x0001: { /* ZIP64 extended information extra field */
struct {
char z_datatype[2]; /* Tag for this "extra" block type */
char z_datasize[2]; /* Size of this "extra" block */
char z_usize[8]; /* Original uncompressed file size */
char z_csize[8]; /* Size of compressed data */
char z_offset[8]; /* Offset of local header record */
char z_diskstart[4]; /* Number of the disk for file start*/
} *block = (void*) item->zz_extras[ext].zz_data;
item->zz_usize = __zzip_get64(block->z_usize);
item->zz_csize = __zzip_get64(block->z_csize);
item->zz_offset = __zzip_get64(block->z_offset);
item->zz_diskstart = __zzip_get32(block->z_diskstart);
} break;
case 0x0007: /* AV Info */
case 0x0008: /* Reserved for future Unicode file name data (PFS) */
case 0x0009: /* OS/2 */
case 0x000a: /* NTFS */
case 0x000c: /* OpenVMS */
case 0x000d: /* Unix */
case 0x000e: /* Reserved for file stream and fork descriptors */
case 0x000f: /* Patch Descriptor */
case 0x0014: /* PKCS#7 Store for X.509 Certificates */
case 0x0015: /* X.509 Certificate ID and Signature for file */
case 0x0016: /* X.509 Certificate ID for Central Directory */
case 0x0017: /* Strong Encryption Header */
case 0x0018: /* Record Management Controls */
case 0x0019: /* PKCS#7 Encryption Recipient Certificate List */
case 0x0065: /* IBM S/390, AS/400 attributes - uncompressed */
case 0x0066: /* Reserved for IBM S/390, AS/400 attr - compressed */
case 0x07c8: /* Macintosh */
case 0x2605: /* ZipIt Macintosh */
case 0x2705: /* ZipIt Macintosh 1.3.5+ */
case 0x2805: /* ZipIt Macintosh 1.3.5+ */
case 0x334d: /* Info-ZIP Macintosh */
case 0x4341: /* Acorn/SparkFS */
case 0x4453: /* Windows NT security descriptor (binary ACL) */
case 0x4704: /* VM/CMS */
case 0x470f: /* MVS */
case 0x4b46: /* FWKCS MD5 (see below) */
case 0x4c41: /* OS/2 access control list (text ACL) */
case 0x4d49: /* Info-ZIP OpenVMS */
case 0x4f4c: /* Xceed original location extra field */
case 0x5356: /* AOS/VS (ACL) */
case 0x5455: /* extended timestamp */
case 0x554e: /* Xceed unicode extra field */
case 0x5855: /* Info-ZIP Unix (original, also OS/2, NT, etc) */
case 0x6542: /* BeOS/BeBox */
case 0x756e: /* ASi Unix */
case 0x7855: /* Info-ZIP Unix (new) */
case 0xfd4a: /* SMS/QDOS */
break;
}
}
}
return item;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_findfirst(ZZIP_MEM_DISK* dir) {
return zzip_disk_findfirst(dir->disk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_findfile(ZZIP_MEM_DISK* dir,
char* filename, ZZIP_DISK_ENTRY* after,
zzip_strcmp_fn_t compare) {
return zzip_disk_findfile(dir->disk, filename, after, compare); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_load(ZZIP_MEM_DISK* dir, ZZIP_DISK* disk)
{
if (dir->list) zzip_mem_disk_unload(dir);
___ struct zzip_disk_entry* entry = zzip_disk_findfirst(disk);
for (; entry ; entry = zzip_disk_findnext(disk, entry)) {
ZZIP_MEM_DISK_ENTRY* item = zzip_mem_disk_entry_new(disk, entry);
if (dir->last) { dir->last->zz_next = item; }
else { dir->list = item; }; dir->last = item;
} ____;
dir->disk = disk;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_entry_free(ZZIP_MEM_DISK_ENTRY* _zzip_restrict item)
{
if (item) {
if (item->zz_extras) free(item->zz_extras);
free (item);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_entry_strdup_name(ZZIP_MEM_DISK* dir,
ZZIP_DISK_ENTRY* entry) {
return zzip_disk_entry_strdup_name(dir->disk, entry); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: zzip_mem_disk_findmatch(ZZIP_MEM_DISK* dir,
char* filespec, ZZIP_DISK_ENTRY* after,
zzip_fnmatch_fn_t compare, int flags) {
return zzip_disk_findmatch(dir->disk, filespec, after, compare, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'memdisk
(.)'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: __zzip_parse_root_directory(int fd,
struct _disk_trailer *trailer,
struct zzip_dir_hdr **hdr_return,
zzip_plugin_io_t io)
{
auto struct zzip_disk_entry dirent;
struct zzip_dir_hdr *hdr;
struct zzip_dir_hdr *hdr0;
uint16_t *p_reclen = 0;
zzip_off64_t entries;
zzip_off64_t zz_offset; /* offset from start of root directory */
char *fd_map = 0;
zzip_off64_t zz_fd_gap = 0;
zzip_off64_t zz_entries = _disk_trailer_localentries(trailer);
zzip_off64_t zz_rootsize = _disk_trailer_rootsize(trailer);
zzip_off64_t zz_rootseek = _disk_trailer_rootseek(trailer);
__correct_rootseek(zz_rootseek, zz_rootsize, trailer);
hdr0 = (struct zzip_dir_hdr *) malloc(zz_rootsize);
if (! hdr0)
return ZZIP_DIRSIZE;
hdr = hdr0;
__debug_dir_hdr(hdr);
if (USE_MMAP && io->fd.sys)
{
zz_fd_gap = zz_rootseek & (_zzip_getpagesize(io->fd.sys) - 1);
HINT4(" fd_gap=%ld, mapseek=0x%lx, maplen=%ld", (long) (zz_fd_gap),
(long) (zz_rootseek - zz_fd_gap),
(long) (zz_rootsize + zz_fd_gap));
fd_map =
_zzip_mmap(io->fd.sys, fd, zz_rootseek - zz_fd_gap,
zz_rootsize + zz_fd_gap);
/* if mmap failed we will fallback to seek/read mode */
if (fd_map == MAP_FAILED)
{
NOTE2("map failed: %s", strerror(errno));
fd_map = 0;
} else
{
HINT3("mapped *%p len=%li", fd_map,
(long) (zz_rootsize + zz_fd_gap));
}
}
for (entries=0, zz_offset=0; ; entries++)
{
register struct zzip_disk_entry *d;
uint16_t u_extras, u_comment, u_namlen;
# ifndef ZZIP_ALLOW_MODULO_ENTRIES
if (entries >= zz_entries) {
if (zz_offset + 256 < zz_rootsize) {
FAIL4("%li's entry is long before the end of directory - enable modulo_entries? (O:%li R:%li)",
(long) entries, (long) (zz_offset), (long) zz_rootsize);
}
break;
}
# endif
if (fd_map)
{ d = (void*)(fd_map+zz_fd_gap+zz_offset); } /* fd_map+fd_gap==u_rootseek */
else
{
if (io->fd.seeks(fd, zz_rootseek + zz_offset, SEEK_SET) < 0)
return ZZIP_DIR_SEEK;
if (io->fd.read(fd, &dirent, sizeof(dirent)) < __sizeof(dirent))
return ZZIP_DIR_READ;
d = &dirent;
}
if ((zzip_off64_t) (zz_offset + sizeof(*d)) > zz_rootsize ||
(zzip_off64_t) (zz_offset + sizeof(*d)) < 0)
{
FAIL4("%li's entry stretches beyond root directory (O:%li R:%li)",
(long) entries, (long) (zz_offset), (long) zz_rootsize);
break;
}
if (! zzip_disk_entry_check_magic(d)) {
# ifndef ZZIP_ALLOW_MODULO_ENTRIES
FAIL4("%li's entry has no disk_entry magic indicator (O:%li R:%li)",
(long) entries, (long) (zz_offset), (long) zz_rootsize);
# endif
break;
}
# if 0 && defined DEBUG
zzip_debug_xbuf((unsigned char *) d, sizeof(*d) + 8);
# endif
u_extras = zzip_disk_entry_get_extras(d);
u_comment = zzip_disk_entry_get_comment(d);
u_namlen = zzip_disk_entry_get_namlen(d);
HINT5("offset=0x%lx, size %ld, dirent *%p, hdr %p\n",
(long) (zz_offset + zz_rootseek), (long) zz_rootsize, d, hdr);
/* writes over the read buffer, Since the structure where data is
copied is smaller than the data in buffer this can be done.
It is important that the order of setting the fields is considered
when filling the structure, so that some data is not trashed in
first structure read.
at the end the whole copied list of structures is copied into
newly allocated buffer */
hdr->d_crc32 = zzip_disk_entry_get_crc32(d);
hdr->d_csize = zzip_disk_entry_get_csize(d);
hdr->d_usize = zzip_disk_entry_get_usize(d);
hdr->d_off = zzip_disk_entry_get_offset(d);
hdr->d_compr = zzip_disk_entry_get_compr(d);
if (hdr->d_compr > _255)
hdr->d_compr = 255;
if ((zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) > zz_rootsize ||
(zzip_off64_t) (zz_offset + sizeof(*d) + u_namlen) < 0)
{
FAIL4("%li's name stretches beyond root directory (O:%li N:%li)",
(long) entries, (long) (zz_offset), (long) (u_namlen));
break;
}
if (fd_map)
{ memcpy(hdr->d_name, fd_map+zz_fd_gap + zz_offset+sizeof(*d), u_namlen); }
else
{ io->fd.read(fd, hdr->d_name, u_namlen); }
hdr->d_name[u_namlen] = '\0';
hdr->d_namlen = u_namlen;
/* update offset by the total length of this entry -> next entry */
zz_offset += sizeof(*d) + u_namlen + u_extras + u_comment;
if (zz_offset > zz_rootsize)
{
FAIL3("%li's entry stretches beyond root directory (O:%li)",
(long) entries, (long) (zz_offset));
entries ++;
break;
}
HINT5("file %ld { compr=%d crc32=$%x offset=%d",
(long) entries, hdr->d_compr, hdr->d_crc32, hdr->d_off);
HINT5("csize=%d usize=%d namlen=%d extras=%d",
hdr->d_csize, hdr->d_usize, u_namlen, u_extras);
HINT5("comment=%d name='%s' %s <sizeof %d> } ",
u_comment, hdr->d_name, "", (int) sizeof(*d));
p_reclen = &hdr->d_reclen;
{
register char *p = (char *) hdr;
register char *q = aligned4(p + sizeof(*hdr) + u_namlen + 1);
*p_reclen = (uint16_t) (q - p);
hdr = (struct zzip_dir_hdr *) q;
}
} /*for */
if (USE_MMAP && fd_map)
{
HINT3("unmap *%p len=%li", fd_map, (long) (zz_rootsize + zz_fd_gap));
_zzip_munmap(io->fd.sys, fd_map, zz_rootsize + zz_fd_gap);
}
if (p_reclen)
{
*p_reclen = 0; /* mark end of list */
if (hdr_return)
*hdr_return = hdr0;
} /* else zero (sane) entries */
# ifndef ZZIP_ALLOW_MODULO_ENTRIES
return (entries != zz_entries ? ZZIP_CORRUPTED : 0);
# else
return ((entries & (unsigned)0xFFFF) != zz_entries ? ZZIP_CORRUPTED : 0);
# endif
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'check rootseek after correction #41'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: unzzip_list (int argc, char ** argv, int verbose)
{
int argn;
ZZIP_MEM_DISK* disk;
if (argc == 1)
{
printf (__FILE__" version "ZZIP_PACKAGE" "ZZIP_VERSION"\n");
return EXIT_OK; /* better provide an archive argument */
}
disk = zzip_mem_disk_open (argv[1]);
if (! disk) {
DBG3("disk_open failed [%i] %s", errno, strerror(errno));
perror(argv[1]);
return exitcode(errno);
}
if (argc == 2)
{ /* list all */
ZZIP_MEM_ENTRY* entry = zzip_mem_disk_findfirst(disk);
DBG2("findfirst %p", entry);
for (; entry ; entry = zzip_mem_disk_findnext(disk, entry))
{
char* name = zzip_mem_entry_to_name (entry);
long long usize = entry->zz_usize;
if (!verbose)
{
printf ("%22lli %s\n", usize, name);
} else
{
long long csize = entry->zz_csize;
unsigned compr = entry->zz_compr;
const char* defl = (compr < sizeof(comprlevel)) ? comprlevel[compr] : "(redu)";
printf ("%lli/%lli %s %s\n", csize, usize, defl, name);
}
}
return 0;
}
if (argc == 3)
{ /* list from one spec */
ZZIP_MEM_ENTRY* entry = 0;
while ((entry = zzip_mem_disk_findmatch(disk, argv[2], entry, 0, 0)))
{
char* name = zzip_mem_entry_to_name (entry);
long long usize = entry->zz_usize;
if (!verbose)
{
printf ("%22lli %s\n", usize, name);
} else
{
long long csize = entry->zz_csize;
unsigned compr = entry->zz_compr;
const char* defl = (compr < sizeof(comprlevel)) ? comprlevel[compr] : "(redu)";
printf ("%lli/%lli %s %s\n", csize, usize, defl, name);
}
}
return 0;
}
{ /* list only the matching entries - in order of zip directory */
ZZIP_MEM_ENTRY* entry = zzip_mem_disk_findfirst(disk);
for (; entry ; entry = zzip_mem_disk_findnext(disk, entry))
{
char* name = zzip_mem_entry_to_name (entry);
for (argn=1; argn < argc; argn++)
{
if (! _zzip_fnmatch (argv[argn], name,
_zzip_FNM_NOESCAPE|_zzip_FNM_PATHNAME|_zzip_FNM_PERIOD))
{
char* name = zzip_mem_entry_to_name (entry);
long long usize = entry->zz_usize;
if (!verbose)
{
printf ("%22lli %s\n", usize, name);
} else
{
long long csize = entry->zz_csize;
unsigned compr = entry->zz_compr;
const char* defl = (compr < sizeof(comprlevel)) ? comprlevel[compr] : "(redu)";
printf ("%lli/%lli %s %s\n", csize, usize, defl, name);
}
break; /* match loop */
}
}
}
return 0;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772'], 'message': 'ensure disk_close to avoid mem-leak #40'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) {
char *key;
size_t nkey;
int i = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
assert(c != NULL);
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
while (i-- > 0) {
item_remove(*(c->ilist + i));
}
return;
}
it = item_get(key, nkey, c, DO_UPDATE);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
item_remove(it);
break;
}
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas || !settings.inline_ascii_response)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
item_remove(it);
break;
}
}
suffix = do_cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
STATS_LOCK();
stats.malloc_fails++;
STATS_UNLOCK();
out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix");
item_remove(it);
while (i-- > 0) {
item_remove(*(c->ilist + i));
}
return;
}
*(c->suffixlist + i) = suffix;
int suffix_len = make_ascii_get_suffix(suffix, it, return_cas);
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
(settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) ||
add_iov(c, suffix, suffix_len) != 0)
{
item_remove(it);
break;
}
if ((it->it_flags & ITEM_CHUNKED) == 0) {
add_iov(c, ITEM_data(it), it->nbytes);
} else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0)
{
item_remove(it);
break;
}
if ((it->it_flags & ITEM_CHUNKED) == 0)
{
if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
} else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 ||
add_chunked_item_iovs(c, it, it->nbytes) != 0) {
item_remove(it);
break;
}
}
if (settings.verbose > 1) {
int ii;
fprintf(stderr, ">%d sending key ", c->sfd);
for (ii = 0; ii < it->nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, "\n");
}
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
*(c->ilist + i) = it;
i++;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_misses++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas || !settings.inline_ascii_response) {
c->suffixcurr = c->suffixlist;
c->suffixleft = i;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_of_memory(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190', 'CWE-667'], 'message': 'Don't overflow item refcount on get
Counts as a miss if the refcount is too high. ASCII multigets are the only
time refcounts can be held for so long.
doing a dirty read of refcount. is aligned.
trying to avoid adding an extra refcount branch for all calls of item_get due
to performance. might be able to move it in there after logging refactoring
simplifies some of the branches.'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.