{"code": "static int ape_decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame_ptr, AVPacket *avpkt)\n{\n AVFrame *frame = data;\n const uint8_t *buf = avpkt->data;\n APEContext *s = avctx->priv_data;\n uint8_t *sample8;\n int16_t *sample16;\n int32_t *sample24;\n int i, ch, ret;\n int blockstodecode;\n\n /* this should never be negative, but bad things will happen if it is, so\n check it just to make sure. */\n av_assert0(s->samples >= 0);\n\n if(!s->samples){\n uint32_t nblocks, offset;\n int buf_size;\n\n if (!avpkt->size) {\n *got_frame_ptr = 0;\n return 0;\n }\n if (avpkt->size < 8) {\n av_log(avctx, AV_LOG_ERROR, \"Packet is too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n buf_size = avpkt->size & ~3;\n if (buf_size != avpkt->size) {\n av_log(avctx, AV_LOG_WARNING, \"packet size is not a multiple of 4. \"\n \"extra bytes at the end will be skipped.\\n\");\n }\n if (s->fileversion < 3950) // previous versions overread two bytes\n buf_size += 2;\n av_fast_padded_malloc(&s->data, &s->data_size, buf_size);\n if (!s->data)\n return AVERROR(ENOMEM);\n s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,\n buf_size >> 2);\n memset(s->data + (buf_size & ~3), 0, buf_size & 3);\n s->ptr = s->data;\n s->data_end = s->data + buf_size;\n\n nblocks = bytestream_get_be32(&s->ptr);\n offset = bytestream_get_be32(&s->ptr);\n if (s->fileversion >= 3900) {\n if (offset > 3) {\n av_log(avctx, AV_LOG_ERROR, \"Incorrect offset passed\\n\");\n s->data = NULL;\n return AVERROR_INVALIDDATA;\n }\n if (s->data_end - s->ptr < offset) {\n av_log(avctx, AV_LOG_ERROR, \"Packet is too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n s->ptr += offset;\n } else {\n if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)\n return ret;\n if (s->fileversion > 3800)\n skip_bits_long(&s->gb, offset * 8);\n else\n skip_bits_long(&s->gb, offset);\n }\n\n if (!nblocks || nblocks > INT_MAX) {\n av_log(avctx, AV_LOG_ERROR, \"Invalid sample count: %\"PRIu32\".\\n\",\n nblocks);\n return AVERROR_INVALIDDATA;\n }\n\n /* Initialize the frame decoder */\n if (init_frame_decoder(s) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"Error reading frame header\\n\");\n return AVERROR_INVALIDDATA;\n }\n s->samples = nblocks;\n }\n\n if (!s->data) {\n *got_frame_ptr = 0;\n return avpkt->size;\n }\n\n blockstodecode = FFMIN(s->blocks_per_loop, s->samples);\n // for old files coefficients were not interleaved,\n // so we need to decode all of them at once\n if (s->fileversion < 3930)\n blockstodecode = s->samples;\n\n /* reallocate decoded sample buffer if needed */\n av_fast_malloc(&s->decoded_buffer, &s->decoded_size,\n 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));\n if (!s->decoded_buffer)\n return AVERROR(ENOMEM);\n memset(s->decoded_buffer, 0, s->decoded_size);\n s->decoded[0] = s->decoded_buffer;\n s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);\n\n /* get output buffer */\n frame->nb_samples = blockstodecode;\n if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)\n return ret;\n\n s->error=0;\n\n if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))\n ape_unpack_mono(s, blockstodecode);\n else\n ape_unpack_stereo(s, blockstodecode);\n emms_c();\n\n if (s->error) {\n s->samples=0;\n av_log(avctx, AV_LOG_ERROR, \"Error decoding frame\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n switch (s->bps) {\n case 8:\n for (ch = 0; ch < s->channels; ch++) {\n sample8 = (uint8_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;\n }\n break;\n case 16:\n for (ch = 0; ch < s->channels; ch++) {\n sample16 = (int16_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample16++ = s->decoded[ch][i];\n }\n break;\n case 24:\n for (ch = 0; ch < s->channels; ch++) {\n sample24 = (int32_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample24++ = s->decoded[ch][i] << 8;\n }\n break;\n }\n\n s->samples -= blockstodecode;\n\n *got_frame_ptr = 1;\n\n return !s->samples ? avpkt->size : 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[3163, 3301]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3163, 3301]]}, "_func_name": "ape_decode_frame", "_file_name": "libavcodec/apedec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def create_basename_core(basename):\n try:\n basename = basename.casefold()\n except Exception:\n basename = basename.lower()\n\n basename = re.sub(r'[ \\./]', r'-', basename)\n basename = re.sub(r'<[^>]*>', r'', basename)\n basename = re.sub(r'[^a-z0-9\\-]', r'', basename)\n basename = re.sub(r'\\-\\-', r'-', basename)\n basename = urllib.parse.quote_plus(basename)\n\n return basename", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_basename_core", "_file_name": "MeTal/core/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " static bool TryParse(const char* inp, int length,\n TypedValue* buf, Variant& out,\n JSONContainerType container_type, bool is_tsimplejson) {\n SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);\n bool ok = parser.parseValue();\n if (!ok ||\n (parser.skipSpace(), parser.p != inp + length)) {\n // Unsupported, malformed, or trailing garbage. Release entire stack.\n tvDecRefRange(buf, parser.top);\n return false;\n }\n out = Variant::attach(*--parser.top);\n return true;\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::SimpleParser::TryParse", "_file_name": "hphp/runtime/ext/json/JSON_parser.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return (*elem_rtrn != NULL && *field_rtrn != NULL);\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n\t\treturn false;\n\tif (*field_rtrn == NULL)\n\t\treturn false;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ExprResolveLhs", "_file_name": "src/xkbcomp/expr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_max_task_id_for_project(project_id: int):\n \"\"\"Gets the nights task id currently in use on a project\"\"\"\n sql = \"\"\"select max(id) from tasks where project_id = {0} GROUP BY project_id\"\"\".format(project_id)\n result = db.engine.execute(sql)\n if result.rowcount == 0:\n raise NotFound()\n for row in result:\n return row[0]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[140, 248]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[140, 248]]}, "_func_name": "get_max_task_id_for_project", "_file_name": "server/models/postgis/task.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_get_least_used_nsp(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n # in use count 11 12\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])\n self.assertEqual(nsp, '0:2:1')\n\n # in use count 11 10\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])\n self.assertEqual(nsp, '1:2:1')\n\n # in use count 0 10\n nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])\n self.assertEqual(nsp, '1:1:1')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_get_least_used_nsp", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def writeToDb(self, url):\n try:\n self.cursor.execute(\"INSERT INTO queue (url, visited) VALUES (?, '0');\", url)\n self.db.commit()\n except Exception as e:\n print(e)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "writeToDb", "_file_name": "beta/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "\tdef getFileCacheID(self, pth):\n\t\t\"\"\"\n\t\tReturns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.\n\t\t:param pth:\n\t\t:return:\n\t\t\"\"\"\n\t\tcommand = \"SELECT file_id FROM {0} WHERE path=?;\".format(TABLE_NAME)\n\t\tparams = (pth,)\n\t\tdata = self._run_command(command, params)\n\n\t\ttry:\n\t\t\tdata = data[0][0]\n\t\texcept IndexError:\n\t\t\tdata = None\n\n\t\treturn data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getFileCacheID", "_file_name": "file_db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool extractFileTo(zip* zip, const std::string &file, std::string& to,\n char* buf, size_t len) {\n\n struct zip_stat zipStat;\n // Verify the file to be extracted is actually in the zip file\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto clean_file = file;\n auto sep = std::string::npos;\n // Normally would just use std::string::rfind here, but if we want to be\n // consistent between Windows and Linux, even if techincally Linux won't use\n // backslash for a separator, we are checking for both types.\n int idx = file.length() - 1;\n while (idx >= 0) {\n if (FileUtil::isDirSeparator(file[idx])) {\n sep = idx;\n break;\n }\n idx--;\n }\n if (sep != std::string::npos) {\n // make_relative_path so we do not try to put files or dirs in bad\n // places. This securely \"cleans\" the file.\n clean_file = make_relative_path(file);\n std::string path = to + clean_file;\n bool is_dir_only = true;\n if (sep < file.length() - 1) { // not just a directory\n auto clean_file_dir = HHVM_FN(dirname)(clean_file);\n path = to + clean_file_dir.toCppString();\n is_dir_only = false;\n }\n\n // Make sure the directory path to extract to exists or can be created\n if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {\n return false;\n }\n\n // If we have a good directory to extract to above, we now check whether\n // the \"file\" parameter passed in is a directory or actually a file.\n if (is_dir_only) { // directory, like /usr/bin/\n return true;\n }\n // otherwise file is actually a file, so we actually extract.\n }\n\n // We have ensured that clean_file will be added to a relative path by the\n // time we get here.\n to.append(clean_file);\n\n auto zipFile = zip_fopen_index(zip, zipStat.index, 0);\n FAIL_IF_INVALID_PTR(zipFile);\n\n auto outFile = fopen(to.c_str(), \"wb\");\n if (outFile == nullptr) {\n zip_fclose(zipFile);\n return false;\n }\n\n for (auto n = zip_fread(zipFile, buf, len); n != 0;\n n = zip_fread(zipFile, buf, len)) {\n if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {\n zip_fclose(zipFile);\n fclose(outFile);\n remove(to.c_str());\n return false;\n }\n }\n\n zip_fclose(zipFile);\n if (fclose(outFile) != 0) {\n return false;\n }\n\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::extractFileTo", "_file_name": "hphp/runtime/ext/zip/ext_zip.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def fetch_data(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT data FROM %s WHERE identifier = $1;\" %\n (self.table)\n )\n res = self._query(query, sid)\n try:\n data = res.dictresult()[0]['data']\n except IndexError:\n raise ObjectDoesNotExistException(id)\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000\\\\001', nonTextToken)\n ndata = ndata.replace('\\\\012', '\\n')\n return ndata", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fetch_data", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n if (name_size == 0) return;\n char* name = new char[name_size+1];\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[509, 598]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[509, 598]]}, "_func_name": "AP4_HdlrAtom::AP4_HdlrAtom", "_file_name": "Source/C++/Core/Ap4HdlrAtom.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " @handler.unsupported_on_local_server\n @handler.get(handler.HTML)\n def get(self):\n \"\"\"Handle a get request.\"\"\"\n self.render(\n 'login.html', {\n 'apiKey': local_config.ProjectConfig().get('firebase.api_key'),\n 'authDomain': auth.auth_domain(),\n 'dest': self.request.get('dest'),\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[280, 326]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[280, 326]]}, "_func_name": "get", "_file_name": "src/appengine/handlers/login.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def delete_data(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, str(id))\n query = \"DELETE FROM %s WHERE identifier = $1;\" % (self.table)\n self._query(query, sid)\n return None", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_data", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "next_line(struct archive_read *a,\n const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)\n{\n\tssize_t len;\n\tint quit;\n\t\n\tquit = 0;\n\tif (*avail == 0) {\n\t\t*nl = 0;\n\t\tlen = 0;\n\t} else\n\t\tlen = get_line_size(*b, *avail, nl);\n\t/*\n\t * Read bytes more while it does not reach the end of line.\n\t */\n\twhile (*nl == 0 && len == *avail && !quit) {\n\t\tssize_t diff = *ravail - *avail;\n\t\tsize_t nbytes_req = (*ravail+1023) & ~1023U;\n\t\tssize_t tested;\n\n\t\t/* Increase reading bytes if it is not enough to at least\n\t\t * new two lines. */\n\t\tif (nbytes_req < (size_t)*ravail + 160)\n\t\t\tnbytes_req <<= 1;\n\n\t\t*b = __archive_read_ahead(a, nbytes_req, avail);\n\t\tif (*b == NULL) {\n\t\t\tif (*ravail >= *avail)\n\t\t\t\treturn (0);\n\t\t\t/* Reading bytes reaches the end of file. */\n\t\t\t*b = __archive_read_ahead(a, *avail, avail);\n\t\t\tquit = 1;\n\t\t}\n\t\t*ravail = *avail;\n\t\t*b += diff;\n\t\t*avail -= diff;\n\t\ttested = len;/* Skip some bytes we already determinated. */\n\t\tlen = get_line_size(*b + len, *avail - len, nl);\n\t\tif (len >= 0)\n\t\t\tlen += tested;\n\t}\n\treturn (len);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "next_line", "_file_name": "libarchive/archive_read_support_format_mtree.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _make_fc_map(self, source, target, full_copy):\n copyflag = '' if full_copy else '-copyrate 0'\n fc_map_cli_cmd = ('svctask mkfcmap -source %(src)s -target %(tgt)s '\n '-autodelete %(copyflag)s' %\n {'src': source,\n 'tgt': target,\n 'copyflag': copyflag})\n out, err = self._run_ssh(fc_map_cli_cmd)\n self._driver_assert(\n len(out.strip()),\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n # Ensure that the output is as expected\n match_obj = re.search('FlashCopy Mapping, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n try:\n fc_map_id = match_obj.group(1)\n self._driver_assert(\n fc_map_id is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n except IndexError:\n self._driver_assert(\n False,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n return fc_map_id", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[55, 375]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[55, 375]]}, "_func_name": "_make_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickExport Image *AdaptiveThresholdImage(const Image *image,\n const size_t width,const size_t height,const double bias,\n ExceptionInfo *exception)\n{\n#define AdaptiveThresholdImageTag \"AdaptiveThreshold/Image\"\n\n CacheView\n *image_view,\n *threshold_view;\n\n Image\n *threshold_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickSizeType\n number_pixels;\n\n ssize_t\n y;\n\n /*\n Initialize threshold image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n status=SetImageStorageClass(threshold_image,DirectClass,exception);\n if (status == MagickFalse)\n {\n threshold_image=DestroyImage(threshold_image);\n return((Image *) NULL);\n }\n /*\n Threshold image.\n */\n status=MagickTrue;\n progress=0;\n number_pixels=(MagickSizeType) width*height;\n image_view=AcquireVirtualCacheView(image,exception);\n threshold_view=AcquireAuthenticCacheView(threshold_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,threshold_image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n channel_bias[MaxPixelChannels],\n channel_sum[MaxPixelChannels];\n\n register const Quantum\n *magick_restrict p,\n *magick_restrict pixels;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n center,\n u,\n v;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)\n (height/2L),image->columns+width,height,exception);\n q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,\n 1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+\n GetPixelChannels(image)*(width/2);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n pixels=p;\n channel_bias[channel]=0.0;\n channel_sum[channel]=0.0;\n for (v=0; v < (ssize_t) height; v++)\n {\n for (u=0; u < (ssize_t) width; u++)\n {\n if (u == (ssize_t) (width-1))\n channel_bias[channel]+=pixels[i];\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image);\n }\n pixels+=GetPixelChannels(image)*image->columns;\n }\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n double\n mean;\n\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n channel_sum[channel]-=channel_bias[channel];\n channel_bias[channel]=0.0;\n pixels=p;\n for (v=0; v < (ssize_t) height; v++)\n {\n channel_bias[channel]+=pixels[i];\n pixels+=(width-1)*GetPixelChannels(image);\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image)*(image->columns+1);\n }\n mean=(double) (channel_sum[channel]/number_pixels+bias);\n SetPixelChannel(threshold_image,channel,(Quantum) ((double)\n p[center+i] <= mean ? 0 : QuantumRange),q);\n }\n p+=GetPixelChannels(image);\n q+=GetPixelChannels(threshold_image);\n }\n if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n threshold_image->type=image->type;\n threshold_view=DestroyCacheView(threshold_view);\n image_view=DestroyCacheView(image_view);\n if (status == MagickFalse)\n threshold_image=DestroyImage(threshold_image);\n return(threshold_image);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[904, 974]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[904, 974]]}, "_func_name": "AdaptiveThresholdImage", "_file_name": "MagickCore/threshold.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "std::string TarFileReader::extract(const string &_path) {\n if (_path.empty()) THROW(\"path cannot be empty\");\n if (!hasMore()) THROW(\"No more tar files\");\n\n string path = _path;\n if (SystemUtilities::isDirectory(path)) {\n path += \"/\" + getFilename();\n\n // Check that path is under the target directory\n string a = SystemUtilities::getCanonicalPath(_path);\n string b = SystemUtilities::getCanonicalPath(path);\n if (!String::startsWith(b, a))\n THROW(\"Tar path points outside of the extraction directory: \" << path);\n }\n\n LOG_DEBUG(5, \"Extracting: \" << path);\n\n switch (getType()) {\n case NORMAL_FILE: case CONTIGUOUS_FILE:\n return extract(*SystemUtilities::oopen(path));\n case DIRECTORY: SystemUtilities::ensureDirectory(path); break;\n default: THROW(\"Unsupported tar file type \" << getType());\n }\n\n return getFilename();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TarFileReader::extract", "_file_name": "src/cbang/tar/TarFileReader.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def delete_data(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, str(id))\n query = \"DELETE FROM %s WHERE identifier = '%s';\" % (self.table, sid)\n self._query(query)\n return None", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[212, 290]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[212, 290]]}, "_func_name": "delete_data", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void hid_input_field(struct hid_device *hid, struct hid_field *field,\n\t\t\t __u8 *data, int interrupt)\n{\n\tunsigned n;\n\tunsigned count = field->report_count;\n\tunsigned offset = field->report_offset;\n\tunsigned size = field->report_size;\n\t__s32 min = field->logical_minimum;\n\t__s32 max = field->logical_maximum;\n\t__s32 *value;\n\n\tvalue = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);\n\tif (!value)\n\t\treturn;\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tvalue[n] = min < 0 ?\n\t\t\tsnto32(hid_field_extract(hid, data, offset + n * size,\n\t\t\t size), size) :\n\t\t\thid_field_extract(hid, data, offset + n * size, size);\n\n\t\t/* Ignore report if ErrorRollOver */\n\t\tif (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&\n\t\t value[n] >= min && value[n] <= max &&\n\t\t value[n] - min < field->maxusage &&\n\t\t field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)\n\t\t\tgoto exit;\n\t}\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tif (HID_MAIN_ITEM_VARIABLE & field->flags) {\n\t\t\thid_process_event(hid, field, &field->usage[n], value[n], interrupt);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field->value[n] >= min && field->value[n] <= max\n\t\t\t&& field->value[n] - min < field->maxusage\n\t\t\t&& field->usage[field->value[n] - min].hid\n\t\t\t&& search(value, field->value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);\n\n\t\tif (value[n] >= min && value[n] <= max\n\t\t\t&& value[n] - min < field->maxusage\n\t\t\t&& field->usage[value[n] - min].hid\n\t\t\t&& search(field->value, value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);\n\t}\n\n\tmemcpy(field->value, value, count * sizeof(__s32));\nexit:\n\tkfree(value);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "hid_input_field", "_file_name": "drivers/hid/hid-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "upnp_redirect(const char * rhost, unsigned short eport,\n const char * iaddr, unsigned short iport,\n const char * protocol, const char * desc,\n unsigned int leaseduration)\n{\n\tint proto, r;\n\tchar iaddr_old[32];\n\tchar rhost_old[32];\n\tunsigned short iport_old;\n\tstruct in_addr address;\n\tunsigned int timestamp;\n\n\tproto = proto_atoi(protocol);\n\tif(inet_aton(iaddr, &address) <= 0) {\n\t\tsyslog(LOG_ERR, \"inet_aton(%s) FAILED\", iaddr);\n\t\treturn -1;\n\t}\n\n\tif(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,\n\t eport, address, iport)) {\n\t\tsyslog(LOG_INFO, \"redirection permission check failed for \"\n\t\t \"%hu->%s:%hu %s\", eport, iaddr, iport, protocol);\n\t\treturn -3;\n\t}\n\t/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)\n\t * - 2.2.20.PortMappingDescription :\n\t * Overwriting Previous / Existing Port Mappings:\n\t * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient\n\t * are exactly the same as an existing mapping, the existing mapping values\n\t * for InternalPort, PortMappingDescription, PortMappingEnabled and\n\t * PortMappingLeaseDuration are overwritten.\n\t * Rejecting a New Port Mapping:\n\t * In cases where the RemoteHost, ExternalPort and PortMappingProtocol\n\t * are the same as an existing mapping, but the InternalClient is\n\t * different, the action is rejected with an appropriate error.\n\t * Add or Reject New Port Mapping behavior based on vendor implementation:\n\t * In cases where the ExternalPort, PortMappingProtocol and InternalClient\n\t * are the same, but RemoteHost is different, the vendor can choose to\n\t * support both mappings simultaneously, or reject the second mapping\n\t * with an appropriate error.\n\t *\n\t * - 2.4.16.AddPortMapping\n\t * This action creates a new port mapping or overwrites an existing\n\t * mapping with the same internal client. If the ExternalPort and\n\t * PortMappingProtocol pair is already mapped to another internal client,\n\t * an error is returned.\n\t *\n\t * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)\n\t * Protocol ExternalPort RemoteHost InternalClient Result\n\t * = = ≠ ≠ Failure\n\t * = = ≠ = Failure or success\n\t * (vendor specific)\n\t * = = = ≠ Failure\n\t * = = = = Success (overwrite)\n\t */\n\trhost_old[0] = '\\0';\n\tr = get_redirect_rule(ext_if_name, eport, proto,\n\t iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,\n\t rhost_old, sizeof(rhost_old),\n\t ×tamp, 0, 0);\n\tif(r == 0) {\n\t\tif(strcmp(iaddr, iaddr_old)==0 &&\n\t\t ((rhost == NULL && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, \"*\") == 0) && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, rhost_old) == 0)))) {\n\t\t\tsyslog(LOG_INFO, \"updating existing port mapping %hu %s (rhost '%s') => %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\t\tif(iport != iport_old) {\n\t\t\t\tr = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);\n\t\t\t} else {\n\t\t\t\tr = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);\n\t\t\t}\n#ifdef ENABLE_LEASEFILE\n\t\t\tif(r == 0) {\n\t\t\t\tlease_file_remove(eport, proto);\n\t\t\t\tlease_file_add(eport, iaddr, iport, proto, desc, timestamp);\n\t\t\t}\n#endif /* ENABLE_LEASEFILE */\n\t\t\treturn r;\n\t\t} else {\n\t\t\tsyslog(LOG_INFO, \"port %hu %s (rhost '%s') already redirected to %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\treturn -2;\n\t\t}\n#ifdef CHECK_PORTINUSE\n\t} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {\n\t\tsyslog(LOG_INFO, \"port %hu protocol %s already in use\",\n\t\t eport, protocol);\n\t\treturn -4;\n#endif /* CHECK_PORTINUSE */\n\t} else {\n\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\tsyslog(LOG_INFO, \"redirecting port %hu to %s:%hu protocol %s for: %s\",\n\t\t\teport, iaddr, iport, protocol, desc);\n\t\treturn upnp_redirect_internal(rhost, eport, iaddr, iport, proto,\n\t\t desc, timestamp);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[767, 842]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[767, 842]]}, "_func_name": "upnp_redirect", "_file_name": "miniupnpd/upnpredirect.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/get_asset_and_volume')\ndef get_asset_and_volume():\n asset_id = request.args.get('asset_id')\n\n if not isObject(asset_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_asset_symbols\",[[\"' + asset_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n asset_id = j_l[\"result\"][0][\"id\"]\n\n #print asset_id\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"get_assets\",[[\"' + asset_id + '\"], 0]]}')\n result = ws.recv()\n j = json.loads(result)\n\n dynamic_asset_data_id = j[\"result\"][0][\"dynamic_asset_data_id\"]\n\n ws.send('{\"id\": 1, \"method\": \"call\", \"params\": [0, \"get_objects\", [[\"'+dynamic_asset_data_id+'\"]]]}')\n result2 = ws.recv()\n j2 = json.loads(result2)\n #print j2[\"result\"][0][\"current_supply\"]\n\n j[\"result\"][0][\"current_supply\"] = j2[\"result\"][0][\"current_supply\"]\n j[\"result\"][0][\"confidential_supply\"] = j2[\"result\"][0][\"confidential_supply\"]\n #print j[\"result\"]\n\n j[\"result\"][0][\"accumulated_fees\"] = j2[\"result\"][0][\"accumulated_fees\"]\n j[\"result\"][0][\"fee_pool\"] = j2[\"result\"][0][\"fee_pool\"]\n\n issuer = j[\"result\"][0][\"issuer\"]\n ws.send('{\"id\": 1, \"method\": \"call\", \"params\": [0, \"get_objects\", [[\"'+issuer+'\"]]]}')\n result3 = ws.recv()\n j3 = json.loads(result3)\n j[\"result\"][0][\"issuer_name\"] = j3[\"result\"][0][\"name\"]\n\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT volume, mcap FROM assets WHERE aid=%s\"\n cur.execute(query, (asset_id,))\n results = cur.fetchall()\n con.close()\n try:\n j[\"result\"][0][\"volume\"] = results[0][0]\n j[\"result\"][0][\"mcap\"] = results[0][1]\n except:\n j[\"result\"][0][\"volume\"] = 0\n j[\"result\"][0][\"mcap\"] = 0\n\n return jsonify(j[\"result\"])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_asset_and_volume", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_user(username, chat_id, last_update):\n conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\users\\\\\" + username + '.db')\n conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\\\cf.db')\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n cursor = conn.cursor()\n cursor2 = conn2.cursor()\n cursor_settings = settings.cursor()\n cursor_settings.execute(\"select last_problem from users where chat_id = ?\", (str(chat_id), ))\n update_eq = cursor_settings.fetchone()\n cursor_settings.execute(\"select * from last_update_problemset\")\n update_base = cursor_settings.fetchone()\n last_problem = update_base[0]\n if update_eq[0] != update_base[0]:\n cursor2.execute(\"SELECT * FROM problems\")\n x = cursor2.fetchone()\n while x != None:\n cursor.execute(\"select * from result where problem = ? and diff = ?\", (str(x[0]), str(x[1])))\n x2 = cursor.fetchone()\n if x2 == None:\n cursor.execute(\"insert into result values (?, ?, ? )\", (x[0], x[1], \"NULL\"))\n last_problem = x\n x = cursor2.fetchone()\n conn2.close()\n settings.close()\n if len(last_problem) == 2:\n last_problem = last_problem[0] + last_problem[1]\n\n url = 'http://codeforces.com/submissions/' + username\n r = requests.get(url)\n max_page = 1\n soup = BeautifulSoup(r.text, \"lxml\")\n\n for link in soup.find_all(attrs={\"class\": \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[4]))\n\n v = False\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')\n soup = BeautifulSoup(r.text, \"lxml\")\n last_try_new = soup.find(attrs={\"class\": \"status-small\"})\n last_try_new = str(last_try_new).split()\n last_try_new = str(last_try_new[2]) + str(last_try_new[3])\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n count = 0\n j = 0\n ver = soup.find_all(attrs={\"class\": \"submissionVerdictWrapper\"})\n last_try = soup.find_all(attrs={\"class\": \"status-small\"})\n for link in soup.find_all('a'):\n last_try_date = str(last_try[j]).split()\n last_try_date = str(last_try_date[2]) + str(last_try_date[3])\n if last_try_date == last_update:\n v = True\n break\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5:\n s2 = str(ver[count]).split()\n s2 = s2[5].split('\\\"')\n count += 1\n j += 1\n cursor.execute(\"select * from result where problem = ? and diff = ?\", (s[3], s[4]))\n x = cursor.fetchone()\n if s2[1] == 'OK' and x != None:\n cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n if x[2] != 'OK':\n cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n if v:\n break\n\n conn.commit()\n conn.close()\n\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"update users set username = ? where chat_id = ?\", (str(username), str(chat_id)))\n conn.execute(\"update users set last_update = ? where chat_id = ?\", (str(last_try_new), str(chat_id)))\n conn.execute(\"update users set last_problem = ? where chat_id = ?\", (str(last_problem), str(chat_id)))\n\n settings.commit()\n settings.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_user", "_file_name": "bases/update.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static long do_get_mempolicy(int *policy, nodemask_t *nmask,\n\t\t\t unsigned long addr, unsigned long flags)\n{\n\tint err;\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma = NULL;\n\tstruct mempolicy *pol = current->mempolicy;\n\n\tif (flags &\n\t\t~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))\n\t\treturn -EINVAL;\n\n\tif (flags & MPOL_F_MEMS_ALLOWED) {\n\t\tif (flags & (MPOL_F_NODE|MPOL_F_ADDR))\n\t\t\treturn -EINVAL;\n\t\t*policy = 0;\t/* just so it's initialized */\n\t\ttask_lock(current);\n\t\t*nmask = cpuset_current_mems_allowed;\n\t\ttask_unlock(current);\n\t\treturn 0;\n\t}\n\n\tif (flags & MPOL_F_ADDR) {\n\t\t/*\n\t\t * Do NOT fall back to task policy if the\n\t\t * vma/shared policy at addr is NULL. We\n\t\t * want to return MPOL_DEFAULT in this case.\n\t\t */\n\t\tdown_read(&mm->mmap_sem);\n\t\tvma = find_vma_intersection(mm, addr, addr+1);\n\t\tif (!vma) {\n\t\t\tup_read(&mm->mmap_sem);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\tif (vma->vm_ops && vma->vm_ops->get_policy)\n\t\t\tpol = vma->vm_ops->get_policy(vma, addr);\n\t\telse\n\t\t\tpol = vma->vm_policy;\n\t} else if (addr)\n\t\treturn -EINVAL;\n\n\tif (!pol)\n\t\tpol = &default_policy;\t/* indicates default behavior */\n\n\tif (flags & MPOL_F_NODE) {\n\t\tif (flags & MPOL_F_ADDR) {\n\t\t\terr = lookup_node(addr);\n\t\t\tif (err < 0)\n\t\t\t\tgoto out;\n\t\t\t*policy = err;\n\t\t} else if (pol == current->mempolicy &&\n\t\t\t\tpol->mode == MPOL_INTERLEAVE) {\n\t\t\t*policy = next_node_in(current->il_prev, pol->v.nodes);\n\t\t} else {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t*policy = pol == &default_policy ? MPOL_DEFAULT :\n\t\t\t\t\t\tpol->mode;\n\t\t/*\n\t\t * Internal mempolicy flags must be masked off before exposing\n\t\t * the policy to userspace.\n\t\t */\n\t\t*policy |= (pol->flags & MPOL_MODE_FLAGS);\n\t}\n\n\tif (vma) {\n\t\tup_read(¤t->mm->mmap_sem);\n\t\tvma = NULL;\n\t}\n\n\terr = 0;\n\tif (nmask) {\n\t\tif (mpol_store_user_nodemask(pol)) {\n\t\t\t*nmask = pol->w.user_nodemask;\n\t\t} else {\n\t\t\ttask_lock(current);\n\t\t\tget_policy_nodemask(pol, nmask);\n\t\t\ttask_unlock(current);\n\t\t}\n\t}\n\n out:\n\tmpol_cond_put(pol);\n\tif (vma)\n\t\tup_read(¤t->mm->mmap_sem);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1678, 1753]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1678, 1753]]}, "_func_name": "do_get_mempolicy", "_file_name": "mm/mempolicy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_NO_HOST_RET), ''])\n\n create_host_cmd = ['createhost', '-iscsi', '-add', 'fakehost',\n 'iqn.1993-08.org.debian:01:222']\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_modify_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int usbhid_parse(struct hid_device *hid)\n{\n\tstruct usb_interface *intf = to_usb_interface(hid->dev.parent);\n\tstruct usb_host_interface *interface = intf->cur_altsetting;\n\tstruct usb_device *dev = interface_to_usbdev (intf);\n\tstruct hid_descriptor *hdesc;\n\tu32 quirks = 0;\n\tunsigned int rsize = 0;\n\tchar *rdesc;\n\tint ret, n;\n\tint num_descriptors;\n\tsize_t offset = offsetof(struct hid_descriptor, desc);\n\n\tquirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),\n\t\t\tle16_to_cpu(dev->descriptor.idProduct));\n\n\tif (quirks & HID_QUIRK_IGNORE)\n\t\treturn -ENODEV;\n\n\t/* Many keyboards and mice don't like to be polled for reports,\n\t * so we will always set the HID_QUIRK_NOGET flag for them. */\n\tif (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {\n\t\tif (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||\n\t\t\tinterface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)\n\t\t\t\tquirks |= HID_QUIRK_NOGET;\n\t}\n\n\tif (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&\n\t (!interface->desc.bNumEndpoints ||\n\t usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {\n\t\tdbg_hid(\"class descriptor not present\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tif (hdesc->bLength < sizeof(struct hid_descriptor)) {\n\t\tdbg_hid(\"hid descriptor is too short\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\thid->version = le16_to_cpu(hdesc->bcdHID);\n\thid->country = hdesc->bCountryCode;\n\n\tnum_descriptors = min_t(int, hdesc->bNumDescriptors,\n\t (hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));\n\n\tfor (n = 0; n < num_descriptors; n++)\n\t\tif (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)\n\t\t\trsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);\n\n\tif (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {\n\t\tdbg_hid(\"weird size of report descriptor (%u)\\n\", rsize);\n\t\treturn -EINVAL;\n\t}\n\n\trdesc = kmalloc(rsize, GFP_KERNEL);\n\tif (!rdesc)\n\t\treturn -ENOMEM;\n\n\thid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);\n\n\tret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,\n\t\t\tHID_DT_REPORT, rdesc, rsize);\n\tif (ret < 0) {\n\t\tdbg_hid(\"reading report descriptor failed\\n\");\n\t\tkfree(rdesc);\n\t\tgoto err;\n\t}\n\n\tret = hid_parse_report(hid, rdesc, rsize);\n\tkfree(rdesc);\n\tif (ret) {\n\t\tdbg_hid(\"parsing report descriptor failed\\n\");\n\t\tgoto err;\n\t}\n\n\thid->quirks |= quirks;\n\n\treturn 0;\nerr:\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usbhid_parse", "_file_name": "drivers/hid/usbhid/hid-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void regulator_ena_gpio_free(struct regulator_dev *rdev)\n{\n\tstruct regulator_enable_gpio *pin, *n;\n\n\tif (!rdev->ena_pin)\n\t\treturn;\n\n\t/* Free the GPIO only in case of no use */\n\tlist_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {\n\t\tif (pin->gpiod == rdev->ena_pin->gpiod) {\n\t\t\tif (pin->request_count <= 1) {\n\t\t\t\tpin->request_count = 0;\n\t\t\t\tgpiod_put(pin->gpiod);\n\t\t\t\tlist_del(&pin->list);\n\t\t\t\tkfree(pin);\n\t\t\t\trdev->ena_pin = NULL;\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tpin->request_count--;\n\t\t\t}\n\t\t}\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "regulator_ena_gpio_free", "_file_name": "drivers/regulator/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def getSubmissionDateFromDatabase(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT Date FROM ChallengeRankings WHERE SubmissionID = '\" + str(submission.id) + \"'\").fetchone()[0]\n database.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[124, 252]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[124, 252]]}, "_func_name": "getSubmissionDateFromDatabase", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--\n\n#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count\n\n int\n pixel;\n\n register ssize_t\n i,\n j;\n\n size_t\n length;\n\n ssize_t\n packets;\n\n packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n CheckNumberCompactPixels;\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n compact_pixels++;\n }\n }\n return(i);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "DecodePSDPixels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route(\"//edit\")\ndef edit_page(page_name):\n query = db.query(\"select * from page where title = $1\", page_name).namedresult()\n if len(query) == 0:\n return render_template(\n \"edit.html\",\n page_name=page_name,\n query=query\n )\n else:\n return render_template(\n \"edit.html\",\n page_name=page_name,\n query=query[0]\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit_page", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def htmlvalue(self, val):\n \"\"\"\n Return an HTML representation of this block that is safe to be included\n in comparison views\n \"\"\"\n return escape(text_from_html(self.block.render_basic(val)))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "htmlvalue", "_file_name": "wagtail/admin/compare.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n error = None\n email = request.form['email'].strip()\n nickname = request.form['nickname'].strip()\n password = request.form['password'].strip()\n password2 = request.form['password2'].strip()\n\n email = email.lower()\n\n if email == \"\" or nickname == \"\" or password == \"\" or password2 == \"\":\n error = 'Please input all the information'\n elif password2 != password:\n error = 'The password is not repeated correctly'\n elif len(password) < 6:\n error = 'The password has at least 6 characters'\n elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +\n '[0-9a-zA-Z]{1,15}\\.[com,cn,net]', email):\n error = 'Please input the right email'\n\n cursor.execute(\"SELECT * FROM users where email = %s;\", (email,))\n u = cursor.fetchone()\n\n if u is not None:\n error = 'The email has already exsit'\n\n if error is not None:\n return render_template('register.html', error=error)\n else:\n password = bcrypt.generate_password_hash(password)\n cursor.execute(\"INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);\", (email, nickname, password))\n conn.commit()\n flash('Register Success!')\n return redirect(url_for('users.login'))\n\n return render_template('register.html')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "register", "_file_name": "flaskr/flaskr/views/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "str_lower_case_match(OnigEncoding enc, int case_fold_flag,\n const UChar* t, const UChar* tend,\n const UChar* p, const UChar* end)\n{\n int lowlen;\n UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];\n\n while (t < tend) {\n lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);\n q = lowbuf;\n while (lowlen > 0) {\n if (t >= tend) return 0;\n if (*t++ != *q++) return 0;\n lowlen--;\n }\n }\n\n return 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "str_lower_case_match", "_file_name": "src/regexec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int hi3660_stub_clk_probe(struct platform_device *pdev)\n{\n\tstruct device *dev = &pdev->dev;\n\tstruct resource *res;\n\tunsigned int i;\n\tint ret;\n\n\t/* Use mailbox client without blocking */\n\tstub_clk_chan.cl.dev = dev;\n\tstub_clk_chan.cl.tx_done = NULL;\n\tstub_clk_chan.cl.tx_block = false;\n\tstub_clk_chan.cl.knows_txdone = false;\n\n\t/* Allocate mailbox channel */\n\tstub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);\n\tif (IS_ERR(stub_clk_chan.mbox))\n\t\treturn PTR_ERR(stub_clk_chan.mbox);\n\n\tres = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (!res)\n\t\treturn -EINVAL;\n\tfreq_reg = devm_ioremap(dev, res->start, resource_size(res));\n\tif (!freq_reg)\n\t\treturn -ENOMEM;\n\n\tfreq_reg += HI3660_STUB_CLOCK_DATA;\n\n\tfor (i = 0; i < HI3660_CLK_STUB_NUM; i++) {\n\t\tret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,\n\t\t\t\t\t hi3660_stub_clks);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "hi3660_stub_clk_probe", "_file_name": "drivers/clk/hisilicon/clk-hi3660-stub.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def process_ranks(self, scene, urls, recent_date):\n PLAYER1 = 0\n PLAYER2 = 1\n WINNER = 2\n DATE = 3\n SCENE = 4\n\n # make sure if we already have calculated ranks for these players at this time, we do not do it again\n sql = \"SELECT * FROM ranks WHERE scene = '{}' AND date='{}';\".format(str(scene), recent_date)\n res = self.db.exec(sql)\n if len(res) > 0:\n LOG.info('We have already calculated ranks for {} on date {}. SKipping'.format(scene, recent_date))\n return\n\n matches = bracket_utils.get_matches_from_urls(self.db, urls)\n LOG.info('About to start processing ranks for scene {} on {}'.format(scene, recent_date))\n\n # Iterate through each match, and build up our dict\n win_loss_dict = {}\n for match in matches:\n p1 = match[PLAYER1]\n p2 = match[PLAYER2]\n winner = match[WINNER]\n date = match[DATE]\n\n #Add p1 to the dict\n if p1 not in win_loss_dict:\n win_loss_dict[p1] = {}\n\n if p2 not in win_loss_dict[p1]:\n win_loss_dict[p1][p2] = []\n\n # Add an entry to represent this match to p1\n win_loss_dict[p1][p2].append((date, winner == p1))\n\n # add p2 to the dict\n if p2 not in win_loss_dict:\n win_loss_dict[p2] = {}\n\n if p1 not in win_loss_dict[p2]:\n win_loss_dict[p2][p1] = []\n\n win_loss_dict[p2][p1].append((date, winner == p2))\n\n ranks = get_ranks(win_loss_dict)\n\n tag_rank_map = {}\n for i, x in enumerate(ranks):\n points, player = x\n rank = len(ranks) - i\n\n sql = \"INSERT INTO ranks (scene, player, rank, points, date) VALUES ('{}', '{}', '{}', '{}', '{}');\"\\\n .format(str(scene), str(player), int(rank), str(points), str(recent_date))\n self.db.exec(sql)\n\n # Only count this player if this is the scene he/she belongs to\n sql = \"SELECT scene FROM players WHERE tag='{}';\".format(player)\n res = self.db.exec(sql)\n\n if len(res) == 0 or res[0][0] == scene:\n # Also create a list to update the player web\n map = {'rank':rank, 'total_ranked':len(ranks)}\n tag_rank_map[player] = map\n\n player_web.update_ranks(tag_rank_map)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[260, 362], [1725, 1934], [2041, 2118]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[260, 362], [1725, 1934], [2041, 2118]]}, "_func_name": "process_ranks", "_file_name": "process_data.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _add_volume_to_volume_set(self, volume, volume_name,\n cpg, vvs_name, qos):\n if vvs_name is not None:\n # Admin has set a volume set name to add the volume to\n self._cli_run('createvvset -add %s %s' % (vvs_name,\n volume_name), None)\n else:\n vvs_name = self._get_3par_vvs_name(volume['id'])\n domain = self.get_domain(cpg)\n self._cli_run('createvvset -domain %s %s' % (domain,\n vvs_name), None)\n self._set_qos_rule(qos, vvs_name)\n self._cli_run('createvvset -add %s %s' % (vvs_name,\n volume_name), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[216, 354], [471, 610], [656, 793]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[216, 354], [471, 610], [656, 793]]}, "_func_name": "_add_volume_to_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_first_ranked_month(db, scene, player):\n sql = \"select date from ranks where scene='{}' and player='{}' order by date limit 1;\".format(scene, player)\n res = db.exec(sql)\n date = res[0][0]\n return date", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[47, 160]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[47, 160]]}, "_func_name": "get_first_ranked_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('//history/record')\ndef view_page_record(page_name):\n content_id = request.args.get('id')\n query = db.query(\"select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1\", content_id)\n page_record = query.namedresult()[0]\n\n return render_template(\n 'page_record.html',\n page_name = page_name,\n page_record = page_record\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "view_page_record", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@api.route('/items/', methods=['GET'])\ndef get_item(item_id):\n sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''\n cursor = mysql.connection.cursor()\n cursor.execute(sql, [item_id])\n data = cursor.fetchone()\n\n if data:\n item = {}\n for tup in zip([column[0] for column in cursor.description], data):\n item[tup[0]] = tup[1]\n else:\n return jsonify({\"error\": \"item not found\"}), 404\n\n return jsonify(item)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_item", "_file_name": "timf/api/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def check_if_this_project_is_in_database(self, project_id):\n self.cursor.execute(\"SELECT count(id) FROM projects where id = %s\" % project_id)\n return self.cursor.fetchall()[0][0] == 1", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[64, 153]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[64, 153]]}, "_func_name": "check_if_this_project_is_in_database", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_first_month(db, scene):\n sql = \"select date from matches where scene='{}' order by date limit 1;\".format(scene)\n res = db.exec(sql)\n date = res[0][0]\n return date", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[32, 123]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[32, 123]]}, "_func_name": "get_first_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def delete(self, email):\n \"\"\" Deletes admin with the corresponding email \"\"\"\n return database_utilities.execute_query(f\"\"\"delete from admins where email = %s\"\"\", (email, ))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete", "_file_name": "apis/admins.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "decode_bundle(bool load, const struct nx_action_bundle *nab,\n const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,\n struct ofpbuf *ofpacts)\n{\n static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);\n struct ofpact_bundle *bundle;\n uint32_t slave_type;\n size_t slaves_size, i;\n enum ofperr error;\n\n bundle = ofpact_put_BUNDLE(ofpacts);\n\n bundle->n_slaves = ntohs(nab->n_slaves);\n bundle->basis = ntohs(nab->basis);\n bundle->fields = ntohs(nab->fields);\n bundle->algorithm = ntohs(nab->algorithm);\n slave_type = ntohl(nab->slave_type);\n slaves_size = ntohs(nab->len) - sizeof *nab;\n\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n if (!flow_hash_fields_valid(bundle->fields)) {\n VLOG_WARN_RL(&rl, \"unsupported fields %d\", (int) bundle->fields);\n } else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {\n VLOG_WARN_RL(&rl, \"too many slaves\");\n } else if (bundle->algorithm != NX_BD_ALG_HRW\n && bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {\n VLOG_WARN_RL(&rl, \"unsupported algorithm %d\", (int) bundle->algorithm);\n } else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {\n VLOG_WARN_RL(&rl, \"unsupported slave type %\"PRIu16, slave_type);\n } else {\n error = 0;\n }\n\n if (!is_all_zeros(nab->zero, sizeof nab->zero)) {\n VLOG_WARN_RL(&rl, \"reserved field is nonzero\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n\n if (load) {\n bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);\n bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);\n error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,\n &bundle->dst.field, tlv_bitmap);\n if (error) {\n return error;\n }\n\n if (bundle->dst.n_bits < 16) {\n VLOG_WARN_RL(&rl, \"bundle_load action requires at least 16 bit \"\n \"destination.\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n } else {\n if (nab->ofs_nbits || nab->dst) {\n VLOG_WARN_RL(&rl, \"bundle action has nonzero reserved fields\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n }\n\n if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {\n VLOG_WARN_RL(&rl, \"Nicira action %s only has %\"PRIuSIZE\" bytes \"\n \"allocated for slaves. %\"PRIuSIZE\" bytes are required \"\n \"for %\"PRIu16\" slaves.\",\n load ? \"bundle_load\" : \"bundle\", slaves_size,\n bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);\n error = OFPERR_OFPBAC_BAD_LEN;\n } else {\n for (i = 0; i < bundle->n_slaves; i++) {\n ofp_port_t ofp_port\n = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));\n ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);\n bundle = ofpacts->header;\n }\n }\n\n ofpact_finish_BUNDLE(ofpacts, &bundle);\n if (!error) {\n error = bundle_check(bundle, OFPP_MAX, NULL);\n }\n return error;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_bundle", "_file_name": "lib/ofp-actions.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def mode_init(self, request):\n \"\"\"\n This is called by render_POST when the client requests an init\n mode operation (at startup)\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n\n remote_addr = request.getClientIP()\n host_string = \"%s (%s:%s)\" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)\n\n sess = AjaxWebClientSession()\n sess.client = self\n sess.init_session(\"ajax/comet\", remote_addr, self.sessionhandler)\n\n sess.csessid = csessid\n csession = _CLIENT_SESSIONS(session_key=sess.csessid)\n uid = csession and csession.get(\"webclient_authenticated_uid\", False)\n if uid:\n # the client session is already logged in\n sess.uid = uid\n sess.logged_in = True\n\n sess.sessionhandler.connect(sess)\n\n self.last_alive[csessid] = (time.time(), False)\n if not self.keep_alive:\n # the keepalive is not running; start it.\n self.keep_alive = LoopingCall(self._keepalive)\n self.keep_alive.start(_KEEPALIVE, now=False)\n\n return jsonify({'msg': host_string, 'csessid': csessid})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mode_init", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def userLogin(self):\n\n sqlName=\"select count(*) from users where name=%s and password=%s;\"\n params = [self.name,self.password]\n checkName=sql.queryDB(self.conn,sqlName,params)\n result=checkName[0][0]\n if result == 0:\n self.clean()\n return False\n else:\n return True", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "userLogin", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)\n{\n\tswitch (mem->type) {\n\tcase RXE_MEM_TYPE_DMA:\n\t\treturn 0;\n\n\tcase RXE_MEM_TYPE_MR:\n\tcase RXE_MEM_TYPE_FMR:\n\t\treturn ((iova < mem->iova) ||\n\t\t\t((iova + length) > (mem->iova + mem->length))) ?\n\t\t\t-EFAULT : 0;\n\n\tdefault:\n\t\treturn -EFAULT;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[174, 274]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[174, 274]]}, "_func_name": "mem_check_range", "_file_name": "drivers/infiniband/sw/rxe/rxe_mr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int string_scan_range(RList *list, const ut8 *buf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc;\n\t\t\tif ((to - needle) > 4) {\n\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\n\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r)) {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\e\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 28) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t// reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (list) {\n\t\t\t\tRBinString *new = R_NEW0 (RBinString);\n\t\t\t\tif (!new) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->type = str_type;\n\t\t\t\tnew->length = runes;\n\t\t\t\tnew->size = needle - str_start;\n\t\t\t\tnew->ordinal = count++;\n\t\t\t\t// TODO: move into adjust_offset\n\t\t\t\tswitch (str_type) {\n\t\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->paddr = new->vaddr = str_start;\n\t\t\t\tnew->string = r_str_ndup ((const char *)tmp, i);\n\t\t\t\tr_list_append (list, new);\n\t\t\t} else {\n\t\t\t\t// DUMP TO STDOUT. raw dumping for rabin2 -zzz\n\t\t\t\tprintf (\"0x%08\" PFMT64x \" %s\\n\", str_start, tmp);\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2786, 2829], [2971, 3014]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2786, 2829], [2971, 3014]]}, "_func_name": "string_scan_range", "_file_name": "libr/bin/bin.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def handle_file(u: Profile, headline: str, category: str, text: str, file):\n m: Media = Media()\n upload_base_path: str = 'uploads/' + str(date.today().year)\n high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):\n os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)\n with open(high_res_file_name, 'wb+') as destination:\n for chunk in file.chunks():\n destination.write(chunk)\n # TODO crop image\n original = Image.open(high_res_file_name)\n width, height = original.size\n diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))\n width /= diameter\n height /= diameter\n width *= IMAGE_SCALE\n height *= IMAGE_SCALE\n cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)\n cropped.save(low_res_file_name)\n m.text = text\n m.cachedText = compile_markdown(text)\n m.category = category\n m.highResFile = \"/\" + high_res_file_name\n m.lowResFile = \"/\" + low_res_file_name\n m.headline = headline\n m.save()\n mu: MediaUpload = MediaUpload()\n mu.UID = u\n mu.MID = m\n mu.save()\n logging.info(\"Uploaded file '\" + str(file.name) + \"' and cropped it. The resulting PK is \" + str(m.pk))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1021, 1107], [1195, 1221]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1021, 1107], [1195, 1221]]}, "_func_name": "handle_file", "_file_name": "c3shop/frontpage/management/mediatools/media_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)\n{\n QWriteLocker locker(&lock);\n\n Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };\n m_peers.push_back(temp);\n\n if (m_peers.size() >= MAX_LOG_MESSAGES)\n m_peers.pop_front();\n\n emit newLogPeer(temp);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[112, 210]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[112, 210]]}, "_func_name": "Logger::addPeer", "_file_name": "src/base/logger.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def _create_vdisk(self, name, size, units, opts):\n \"\"\"Create a new vdisk.\"\"\"\n\n LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)\n\n model_update = None\n easytier = 'on' if opts['easytier'] else 'off'\n\n # Set space-efficient options\n if opts['rsize'] == -1:\n ssh_cmd_se_opt = []\n else:\n ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),\n '-autoexpand', '-warning',\n '%s%%' % str(opts['warning'])]\n if not opts['autoexpand']:\n ssh_cmd_se_opt.remove('-autoexpand')\n\n if opts['compression']:\n ssh_cmd_se_opt.append('-compressed')\n else:\n ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])\n\n ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',\n self.configuration.storwize_svc_volpool_name,\n '-iogrp', '0', '-size', size, '-unit',\n units, '-easytier', easytier] + ssh_cmd_se_opt\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), '_create_vdisk',\n ssh_cmd, out, err)\n\n # Ensure that the output is as expected\n match_obj = re.search('Virtual Disk, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('_create_vdisk %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': name, 'out': str(out), 'err': str(err)})\n\n LOG.debug(_('leave: _create_vdisk: volume %s ') % name)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_create_vdisk", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void usb_serial_console_disconnect(struct usb_serial *serial)\n{\n\tif (serial->port[0] && serial->port[0] == usbcons_info.port) {\n\t\tusb_serial_console_exit();\n\t\tusb_serial_put(serial);\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usb_serial_console_disconnect", "_file_name": "drivers/usb/serial/console.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)\n{\n QCA::Initializer init;\n QByteArray temp = cipherText;\n\n //do padding ourselves\n if (direction)\n {\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n else\n {\n // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input\n if ((temp.length() % 12) != 0)\n return cipherText;\n\n temp = b64ToByte(temp);\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n\n QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;\n QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);\n QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();\n temp2 += cipher.final().toByteArray();\n\n if (!cipher.ok())\n return cipherText;\n\n if (direction) {\n // Sanity check\n if ((temp2.length() % 8) != 0)\n return cipherText;\n\n temp2 = byteToB64(temp2);\n }\n\n return temp2;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Cipher::blowfishECB", "_file_name": "src/core/cipher.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/get_all_referrers')\ndef get_all_referrers():\n account_id = request.args.get('account_id')\n\n if not isObject(account_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_account_names\",[[\"' + account_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n\n account_id = j_l[\"result\"][0][\"id\"]\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"select * from referrers where referrer='\"+account_id+\"'\"\n cur.execute(query)\n results = cur.fetchall()\n\n return jsonify(results)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[430, 500]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[430, 500]]}, "_func_name": "get_all_referrers", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def callback(recipeName):\n menu.pack_forget()\n viewRecipeFrame.pack(expand=True, fill='both')\n groceryButton.pack_forget()\n database_file = \"meal_planner.db\"\n print(recipeName)\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n selection = cursor.execute(\"\"\"SELECT * FROM recipe WHERE name = ?;\"\"\", (recipeName, ))\n for result in [selection]:\n for row in result.fetchall():\n name = row[0]\n time = row[1]\n servings = row[2]\n ingredients = row[4]\n directions = row[5]\n\n string = (\"Name: {} \\n Cook time: {} \\n Number of Servings: {} \\n \".format(name, time, servings))\n secondString = (\"Ingredients: {}\".format(ingredients))\n thirdString = (\"Directions: {}\".format(directions))\n Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [viewRecipeFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__init__.callback", "_file_name": "mealPlan.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connects()\n try:\n # The following introduces a deliberate security flaw. See section on SQL injecton below\n query = \"INSERT INTO crimes (description) VALUES (%s);\"\n with connection.cursor() as cursor:\n cursor.execute(query, data)\n connection.commit()\n finally:\n connection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def change_pass(self, new_pass, logged_user):\n update_sql = \"\"\"\n UPDATE Clients\n SET password = ?\n WHERE client_id = ?\n \"\"\"\n\n cursor = self.__conn.cursor()\n\n cursor.execute(update_sql, (new_pass, logged_user.get_client_id()))\n self.__conn.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "change_pass", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, space_id):\n \"\"\" Fetch data for space with the corresponding space_id \"\"\"\n return database_utilities.execute_query(\n f\"\"\"select * from spaces where space_id = '{space_id}'\"\"\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[147, 217]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[147, 217]]}, "_func_name": "get", "_file_name": "apis/spaces.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, email):\n \"\"\" Fetch data for admin with the corresponding email \"\"\"\n return database_utilities.execute_query(f\"\"\"select * from admins where email = '{email}'\"\"\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[92, 192]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[92, 192]]}, "_func_name": "get", "_file_name": "apis/admins.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tif (offset + 8 >= sz) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "r_bin_java_line_number_table_attr_new", "_file_name": "shlr/java/class.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _run_ssh(self, command, check_exit=True, attempts=1):\n if not self.sshpool:\n self.sshpool = utils.SSHPool(self.config.san_ip,\n self.config.san_ssh_port,\n self.config.ssh_conn_timeout,\n self.config.san_login,\n password=self.config.san_password,\n privatekey=\n self.config.san_private_key,\n min_size=\n self.config.ssh_min_pool_conn,\n max_size=\n self.config.ssh_max_pool_conn)\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return self._ssh_execute(ssh, command,\n check_exit_code=check_exit)\n except Exception as e:\n LOG.error(e)\n greenthread.sleep(randint(20, 500) / 100.0)\n msg = (_(\"SSH Command failed after '%(total_attempts)r' \"\n \"attempts : '%(command)s'\") %\n {'total_attempts': total_attempts, 'command': command})\n raise paramiko.SSHException(msg)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running ssh command: %s\") % command)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 62]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 62]]}, "_func_name": "_run_ssh", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info,\n Image *images,const char *filename,ExceptionInfo *exception)\n{\n#define WriteImageTag \"Write/Image\"\n\n ExceptionInfo\n *sans_exception;\n\n ImageInfo\n *write_info;\n\n MagickBooleanType\n proceed;\n\n MagickOffsetType\n progress;\n\n MagickProgressMonitor\n progress_monitor;\n\n MagickSizeType\n number_images;\n\n MagickStatusType\n status;\n\n register Image\n *p;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(images != (Image *) NULL);\n assert(images->signature == MagickCoreSignature);\n if (images->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",images->filename);\n assert(exception != (ExceptionInfo *) NULL);\n write_info=CloneImageInfo(image_info);\n *write_info->magick='\\0';\n images=GetFirstImageInList(images);\n if (filename != (const char *) NULL)\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n (void) CopyMagickString(p->filename,filename,MagickPathExtent);\n (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent);\n sans_exception=AcquireExceptionInfo();\n (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images),\n sans_exception);\n sans_exception=DestroyExceptionInfo(sans_exception);\n if (*write_info->magick == '\\0')\n (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent);\n p=images;\n for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p))\n {\n register Image\n *next;\n \n next=GetNextImageInList(p);\n if (next == (Image *) NULL)\n break;\n if (p->scene >= next->scene)\n {\n register ssize_t\n i;\n\n /*\n Generate consistent scene numbers.\n */\n i=(ssize_t) images->scene;\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n p->scene=(size_t) i++;\n break;\n }\n }\n /*\n Write images.\n */\n status=MagickTrue;\n progress_monitor=(MagickProgressMonitor) NULL;\n progress=0;\n number_images=GetImageListLength(images);\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n {\n if (number_images != 1)\n progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL,\n p->client_data);\n status&=WriteImage(write_info,p,exception);\n if (number_images != 1)\n (void) SetImageProgressMonitor(p,progress_monitor,p->client_data);\n if (write_info->adjoin != MagickFalse)\n break;\n if (number_images != 1)\n {\n proceed=SetImageProgress(p,WriteImageTag,progress++,number_images);\n if (proceed == MagickFalse)\n break;\n }\n }\n write_info=DestroyImageInfo(write_info);\n return(status != 0 ? MagickTrue : MagickFalse);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WriteImages", "_file_name": "MagickCore/constitute.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def update_playlist(id, name, db):\n db.execute(\"UPDATE playlist SET name=%s WHERE id=%s;\", (name, id,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,\n\tstruct dvb_diseqc_master_cmd *d)\n{\n\tstruct cx24116_state *state = fe->demodulator_priv;\n\tint i, ret;\n\n\t/* Dump DiSEqC message */\n\tif (debug) {\n\t\tprintk(KERN_INFO \"cx24116: %s(\", __func__);\n\t\tfor (i = 0 ; i < d->msg_len ;) {\n\t\t\tprintk(KERN_INFO \"0x%02x\", d->msg[i]);\n\t\t\tif (++i < d->msg_len)\n\t\t\t\tprintk(KERN_INFO \", \");\n\t\t}\n\t\tprintk(\") toneburst=%d\\n\", toneburst);\n\t}\n\n\t/* Validate length */\n\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n\t\treturn -EINVAL;\n\n\t/* DiSEqC message */\n\tfor (i = 0; i < d->msg_len; i++)\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];\n\n\t/* DiSEqC message length */\n\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;\n\n\t/* Command length */\n\tstate->dsec_cmd.len = CX24116_DISEQC_MSGOFS +\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN];\n\n\t/* DiSEqC toneburst */\n\tif (toneburst == CX24116_DISEQC_MESGCACHE)\n\t\t/* Message is cached */\n\t\treturn 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONEOFF)\n\t\t/* Message is sent without burst */\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONECACHE) {\n\t\t/*\n\t\t * Message is sent with derived else cached burst\n\t\t *\n\t\t * WRITE PORT GROUP COMMAND 38\n\t\t *\n\t\t * 0/A/A: E0 10 38 F0..F3\n\t\t * 1/B/B: E0 10 38 F4..F7\n\t\t * 2/C/A: E0 10 38 F8..FB\n\t\t * 3/D/B: E0 10 38 FC..FF\n\t\t *\n\t\t * databyte[3]= 8421:8421\n\t\t * ABCD:WXYZ\n\t\t * CLR :SET\n\t\t *\n\t\t * WX= PORT SELECT 0..3 (X=TONEBURST)\n\t\t * Y = VOLTAGE (0=13V, 1=18V)\n\t\t * Z = BAND (0=LOW, 1=HIGH(22K))\n\t\t */\n\t\tif (d->msg_len >= 4 && d->msg[2] == 0x38)\n\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] =\n\t\t\t\t((d->msg[3] & 4) >> 2);\n\t\tif (debug)\n\t\t\tdprintk(\"%s burst=%d\\n\", __func__,\n\t\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST]);\n\t}\n\n\t/* Wait for LNB ready */\n\tret = cx24116_wait_for_lnb(fe);\n\tif (ret != 0)\n\t\treturn ret;\n\n\t/* Wait for voltage/min repeat delay */\n\tmsleep(100);\n\n\t/* Command */\n\tret = cx24116_cmd_execute(fe, &state->dsec_cmd);\n\tif (ret != 0)\n\t\treturn ret;\n\t/*\n\t * Wait for send\n\t *\n\t * Eutelsat spec:\n\t * >15ms delay + (XXX determine if FW does this, see set_tone)\n\t * 13.5ms per byte +\n\t * >15ms delay +\n\t * 12.5ms burst +\n\t * >15ms delay (XXX determine if FW does this, see set_tone)\n\t */\n\tmsleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +\n\t\t((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[425, 530]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[425, 530]]}, "_func_name": "cx24116_send_diseqc_msg", "_file_name": "drivers/media/dvb-frontends/cx24116.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n size_t size)\n{\n GetBitContext gb;\n AC3HeaderInfo *hdr;\n int err;\n\n if (!*phdr)\n *phdr = av_mallocz(sizeof(AC3HeaderInfo));\n if (!*phdr)\n return AVERROR(ENOMEM);\n hdr = *phdr;\n\n init_get_bits8(&gb, buf, size);\n err = ff_ac3_parse_header(&gb, hdr);\n if (err < 0)\n return AVERROR_INVALIDDATA;\n\n return get_bits_count(&gb);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[306, 342]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[306, 342]]}, "_func_name": "avpriv_ac3_parse_header", "_file_name": "libavcodec/ac3_parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def save_accepted_transaction(self, user_id, project_id, money):\n self.cursor.execute(\"update users set money = money - %s where id = %s\", (money, user_id))\n self.cursor.execute(\"update projects set money = money + %s where id = %s\", (money, project_id))\n self.cursor.execute(\"insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, \"\n \"%s, now(), 'accepted' )\", (project_id, user_id, money))\n self.db.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "save_accepted_transaction", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)\n{\n\tstruct xc2028_data *priv = fe->tuner_priv;\n\tstruct xc2028_ctrl *p = priv_cfg;\n\tint rc = 0;\n\n\ttuner_dbg(\"%s called\\n\", __func__);\n\n\tmutex_lock(&priv->lock);\n\n\t/*\n\t * Copy the config data.\n\t * For the firmware name, keep a local copy of the string,\n\t * in order to avoid troubles during device release.\n\t */\n\tkfree(priv->ctrl.fname);\n\tmemcpy(&priv->ctrl, p, sizeof(priv->ctrl));\n\tif (p->fname) {\n\t\tpriv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);\n\t\tif (priv->ctrl.fname == NULL)\n\t\t\trc = -ENOMEM;\n\t}\n\n\t/*\n\t * If firmware name changed, frees firmware. As free_firmware will\n\t * reset the status to NO_FIRMWARE, this forces a new request_firmware\n\t */\n\tif (!firmware_name[0] && p->fname &&\n\t priv->fname && strcmp(p->fname, priv->fname))\n\t\tfree_firmware(priv);\n\n\tif (priv->ctrl.max_len < 9)\n\t\tpriv->ctrl.max_len = 13;\n\n\tif (priv->state == XC2028_NO_FIRMWARE) {\n\t\tif (!firmware_name[0])\n\t\t\tpriv->fname = priv->ctrl.fname;\n\t\telse\n\t\t\tpriv->fname = firmware_name;\n\n\t\trc = request_firmware_nowait(THIS_MODULE, 1,\n\t\t\t\t\t priv->fname,\n\t\t\t\t\t priv->i2c_props.adap->dev.parent,\n\t\t\t\t\t GFP_KERNEL,\n\t\t\t\t\t fe, load_firmware_cb);\n\t\tif (rc < 0) {\n\t\t\ttuner_err(\"Failed to request firmware %s\\n\",\n\t\t\t\t priv->fname);\n\t\t\tpriv->state = XC2028_NODEV;\n\t\t} else\n\t\t\tpriv->state = XC2028_WAITING_FIRMWARE;\n\t}\n\tmutex_unlock(&priv->lock);\n\n\treturn rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[572, 589]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[572, 589]]}, "_func_name": "xc2028_set_config", "_file_name": "drivers/media/tuners/tuner-xc2028.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "rfbHandleAuthResult(rfbClient* client)\n{\n uint32_t authResult=0;\n\n if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;\n\n authResult = rfbClientSwap32IfLE(authResult);\n\n switch (authResult) {\n case rfbVncAuthOK:\n rfbClientLog(\"VNC authentication succeeded\\n\");\n return TRUE;\n break;\n case rfbVncAuthFailed:\n if (client->major==3 && client->minor>7)\n {\n /* we have an error following */\n ReadReason(client);\n return FALSE;\n }\n rfbClientLog(\"VNC authentication failed\\n\");\n return FALSE;\n case rfbVncAuthTooMany:\n rfbClientLog(\"VNC authentication failed - too many tries\\n\");\n return FALSE;\n }\n\n rfbClientLog(\"Unknown VNC authentication result: %d\\n\",\n (int)authResult);\n return FALSE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rfbHandleAuthResult", "_file_name": "libvncclient/rfbproto.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)\n{\n\tWINPR_UNUSED(update);\n\tif (Stream_GetRemainingLength(s) < 18)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, bitmapData->destLeft);\n\tStream_Read_UINT16(s, bitmapData->destTop);\n\tStream_Read_UINT16(s, bitmapData->destRight);\n\tStream_Read_UINT16(s, bitmapData->destBottom);\n\tStream_Read_UINT16(s, bitmapData->width);\n\tStream_Read_UINT16(s, bitmapData->height);\n\tStream_Read_UINT16(s, bitmapData->bitsPerPixel);\n\tStream_Read_UINT16(s, bitmapData->flags);\n\tStream_Read_UINT16(s, bitmapData->bitmapLength);\n\n\tif (bitmapData->flags & BITMAP_COMPRESSION)\n\t{\n\t\tif (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\treturn FALSE;\n\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tbitmapData->bitmapLength = bitmapData->cbCompMainBodySize;\n\t\t}\n\n\t\tbitmapData->compressed = TRUE;\n\t}\n\telse\n\t\tbitmapData->compressed = FALSE;\n\n\tif (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)\n\t\treturn FALSE;\n\n\tif (bitmapData->bitmapLength > 0)\n\t{\n\t\tbitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);\n\n\t\tif (!bitmapData->bitmapDataStream)\n\t\t\treturn FALSE;\n\n\t\tmemcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);\n\t\tStream_Seek(s, bitmapData->bitmapLength);\n\t}\n\n\treturn TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_read_bitmap_data", "_file_name": "libfreerdp/core/update.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_article(index):\n with conn.cursor(cursor_factory=DictCursor) as cur:\n query = \"SELECT * FROM articles WHERE index=\"+str(index)\n cur.execute(query)\n article = cur.fetchone()\n return article", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[80, 145]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[80, 145]]}, "_func_name": "get_article", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int read_entry(\n\tgit_index_entry **out,\n\tsize_t *out_size,\n\tgit_index *index,\n\tconst void *buffer,\n\tsize_t buffer_size,\n\tconst char *last)\n{\n\tsize_t path_length, entry_size;\n\tconst char *path_ptr;\n\tstruct entry_short source;\n\tgit_index_entry entry = {{0}};\n\tbool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;\n\tchar *tmp_path = NULL;\n\n\tif (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)\n\t\treturn -1;\n\n\t/* buffer is not guaranteed to be aligned */\n\tmemcpy(&source, buffer, sizeof(struct entry_short));\n\n\tentry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);\n\tentry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);\n\tentry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);\n\tentry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);\n\tentry.dev = ntohl(source.dev);\n\tentry.ino = ntohl(source.ino);\n\tentry.mode = ntohl(source.mode);\n\tentry.uid = ntohl(source.uid);\n\tentry.gid = ntohl(source.gid);\n\tentry.file_size = ntohl(source.file_size);\n\tgit_oid_cpy(&entry.id, &source.oid);\n\tentry.flags = ntohs(source.flags);\n\n\tif (entry.flags & GIT_IDXENTRY_EXTENDED) {\n\t\tuint16_t flags_raw;\n\t\tsize_t flags_offset;\n\n\t\tflags_offset = offsetof(struct entry_long, flags_extended);\n\t\tmemcpy(&flags_raw, (const char *) buffer + flags_offset,\n\t\t\tsizeof(flags_raw));\n\t\tflags_raw = ntohs(flags_raw);\n\n\t\tmemcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_long, path);\n\t} else\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_short, path);\n\n\tif (!compressed) {\n\t\tpath_length = entry.flags & GIT_IDXENTRY_NAMEMASK;\n\n\t\t/* if this is a very long string, we must find its\n\t\t * real length without overflowing */\n\t\tif (path_length == 0xFFF) {\n\t\t\tconst char *path_end;\n\n\t\t\tpath_end = memchr(path_ptr, '\\0', buffer_size);\n\t\t\tif (path_end == NULL)\n\t\t\t\treturn -1;\n\n\t\t\tpath_length = path_end - path_ptr;\n\t\t}\n\n\t\tentry_size = index_entry_size(path_length, 0, entry.flags);\n\t\tentry.path = (char *)path_ptr;\n\t} else {\n\t\tsize_t varint_len;\n\t\tsize_t strip_len = git_decode_varint((const unsigned char *)path_ptr,\n\t\t\t\t\t\t &varint_len);\n\t\tsize_t last_len = strlen(last);\n\t\tsize_t prefix_len = last_len - strip_len;\n\t\tsize_t suffix_len = strlen(path_ptr + varint_len);\n\t\tsize_t path_len;\n\n\t\tif (varint_len == 0)\n\t\t\treturn index_error_invalid(\"incorrect prefix length\");\n\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);\n\t\ttmp_path = git__malloc(path_len);\n\t\tGITERR_CHECK_ALLOC(tmp_path);\n\n\t\tmemcpy(tmp_path, last, prefix_len);\n\t\tmemcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);\n\t\tentry_size = index_entry_size(suffix_len, varint_len, entry.flags);\n\t\tentry.path = tmp_path;\n\t}\n\n\tif (entry_size == 0)\n\t\treturn -1;\n\n\tif (INDEX_FOOTER_SIZE + entry_size > buffer_size)\n\t\treturn -1;\n\n\tif (index_entry_dup(out, index, &entry) < 0) {\n\t\tgit__free(tmp_path);\n\t\treturn -1;\n\t}\n\n\tgit__free(tmp_path);\n\t*out_size = entry_size;\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[2025, 2354]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2025, 2354]]}, "_func_name": "read_entry", "_file_name": "src/index.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _download_file(bucket, filename, local_dir):\n key = bucket.get_key(filename)\n local_filename = os.path.join(local_dir, filename)\n key.get_contents_to_filename(local_filename)\n return local_filename", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[110, 169]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[110, 169]]}, "_func_name": "_download_file", "_file_name": "nova/image/s3.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@hook.command(adminonly=True)\ndef openPoll(question, reply=None, db=None):\n \"\"\"Creates a new poll.\"\"\"\n if not db_ready: db_init(db)\n try:\n active = db.execute(\"SELECT pollID FROM polls WHERE active = 1\").fetchone()[0]\n if active: \n reply(\"There already is an open poll.\")\n return\n except:\n db.execute(\"INSERT INTO polls (question, active) VALUES ('{}', 1)\".format(question))\n reply(\"Opened new poll: {}\".format(question))\n #reply(\"Poll opened!\")\n return", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[337, 430]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[337, 430]]}, "_func_name": "openPoll", "_file_name": "plugins/poll.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n if \"player1\" not in form or \"player2\" not in form or \"size\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n player1 = form[\"player1\"].value\n player2 = form[\"player2\"].value\n for c in player1+player2:\n if c not in \"_-\" and not c.isdigit() and not c.isalpha():\n raise FormError(\"Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens\")\n return\n\n try:\n size = int(form[\"size\"].value)\n except:\n raise FormError(\"Invalid parameters: 'size' is not an integer.\")\n return\n\n if size < 2 or size > 9:\n raise FormError(\"The 'size' must be in the range 2-9, inclusive.\")\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n cursor = conn.cursor()\n\n # insert the new row\n cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\" % (player1,player2,size))\n\n gameID = cursor.lastrowid\n\n\n # MySQLdb has been building a transaction as we run. Commit them now, and\n # also clean up the other resources we've allocated.\n conn.commit()\n cursor.close()\n conn.close()\n\n return gameID", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1148, 1261]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1148, 1261]]}, "_func_name": "process_form", "_file_name": "cgi/create_game.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef gravatar(context, user, size=None):\n \"\"\"\n Outputs the HTML for displaying a user's gravatar.\n\n This can take an optional size of the image (defaults to 80 if not\n specified).\n\n This is also influenced by the following settings:\n\n GRAVATAR_SIZE - Default size for gravatars\n GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x)\n GRAVATAR_DEFAULT - Default image set to show if the user hasn't\n specified a gravatar (identicon, monsterid, wavatar)\n\n See http://www.gravatar.com/ for more information.\n \"\"\"\n url = get_gravatar_url(context['request'], user, size)\n\n if url:\n return ('\"%s\"' %\n (url, size, size, user.get_full_name() or user.username))\n else:\n return ''", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[698, 881]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[698, 881]]}, "_func_name": "gravatar", "_file_name": "djblets/gravatars/templatetags/gravatars.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def link_dialog(request):\n # list of wiki pages\n name = request.values.get(\"pagename\", \"\")\n name_escaped = wikiutil.escape(name)\n if name:\n from MoinMoin import search\n # XXX error handling!\n searchresult = search.searchPages(request, 't:\"%s\"' % name)\n\n pages = [p.page_name for p in searchresult.hits]\n pages.sort()\n pages[0:0] = [name]\n page_list = '''\n \n \n \n \n \n''' % \"\\n\".join(['' % (wikiutil.escape(page), wikiutil.escape(page))\n for page in pages])\n else:\n page_list = \"\"\n\n # list of interwiki names\n interwiki_list = wikiutil.load_wikimap(request)\n interwiki = interwiki_list.keys()\n interwiki.sort()\n iwpreferred = request.cfg.interwiki_preferred[:]\n if not iwpreferred or iwpreferred and iwpreferred[-1] is not None:\n resultlist = iwpreferred\n for iw in interwiki:\n if not iw in iwpreferred:\n resultlist.append(iw)\n else:\n resultlist = iwpreferred[:-1]\n interwiki = \"\\n\".join(\n ['' % (wikiutil.escape(key), wikiutil.escape(key))\n for key in resultlist])\n\n # wiki url\n url_prefix_static = request.cfg.url_prefix_static\n scriptname = request.script_root + '/'\n action = scriptname\n basepage = wikiutil.escape(request.page.page_name)\n request.write(u'''\n\n\n\n\n\n \n Link Properties\n \n \n \n \n \n \n \n
\n Link Type
\n \n
\n
\n
\n \n \n \n \n
\n
\n \n \n \n \n \n \n \n \n %(page_list)s\n
\n Page Name
\n \n
\n \n
\n
\n
\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n Wiki:PageName
\n :\n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n Protocol
\n \n
 \n URL
\n \n
\n
\n
\n
\n \n\n''' % locals())", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "link_dialog", "_file_name": "MoinMoin/action/fckdialog.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "layer_resize(int layer, int x_size, int y_size)\n{\n\tint old_height;\n\tint old_width;\n\tstruct map_tile* tile;\n\tint tile_width;\n\tint tile_height;\n\tstruct map_tile* tilemap;\n\tstruct map_trigger* trigger;\n\tstruct map_zone* zone;\n\tsize_t tilemap_size;\n\n\tint x, y, i;\n\n\told_width = s_map->layers[layer].width;\n\told_height = s_map->layers[layer].height;\n\n\t// allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc\n\t// because the tilemap is a 2D array.\n\ttilemap_size = x_size * y_size * sizeof(struct map_tile);\n\tif (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size\n\t\t|| !(tilemap = malloc(tilemap_size)))\n\t\treturn false;\n\tfor (x = 0; x < x_size; ++x) {\n\t\tfor (y = 0; y < y_size; ++y) {\n\t\t\tif (x < old_width && y < old_height) {\n\t\t\t\ttilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width];\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttile = &tilemap[x + y * x_size];\n\t\t\t\ttile->frames_left = tileset_get_delay(s_map->tileset, 0);\n\t\t\t\ttile->tile_index = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// free the old tilemap and substitute the new one\n\tfree(s_map->layers[layer].tilemap);\n\ts_map->layers[layer].tilemap = tilemap;\n\ts_map->layers[layer].width = x_size;\n\ts_map->layers[layer].height = y_size;\n\n\t// if we resize the largest layer, the overall map size will change.\n\t// recalcuate it.\n\ttileset_get_size(s_map->tileset, &tile_width, &tile_height);\n\ts_map->width = 0;\n\ts_map->height = 0;\n\tfor (i = 0; i < s_map->num_layers; ++i) {\n\t\tif (!s_map->layers[i].is_parallax) {\n\t\t\ts_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width);\n\t\t\ts_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height);\n\t\t}\n\t}\n\n\t// ensure zones and triggers remain in-bounds. if any are completely\n\t// out-of-bounds, delete them.\n\tfor (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) {\n\t\tzone = vector_get(s_map->zones, i);\n\t\tif (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height)\n\t\t\tvector_remove(s_map->zones, i);\n\t\telse {\n\t\t\tif (zone->bounds.x2 > s_map->width)\n\t\t\t\tzone->bounds.x2 = s_map->width;\n\t\t\tif (zone->bounds.y2 > s_map->height)\n\t\t\t\tzone->bounds.y2 = s_map->height;\n\t\t}\n\t}\n\tfor (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) {\n\t\ttrigger = vector_get(s_map->triggers, i);\n\t\tif (trigger->x >= s_map->width || trigger->y >= s_map->height)\n\t\t\tvector_remove(s_map->triggers, i);\n\t}\n\n\treturn true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "layer_resize", "_file_name": "src/minisphere/map_engine.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "\tdef add_input(self, data):\n\t\tconnection = self.connect()\n\t\ttry:\n\t\t\t# The following introduces a deliberate security flaw.See section on SQL injection below\n\t\t\tquery = \"INSERT INTO crimes (description) VALUES('{}');\".format(data)\n\t\t\twith connection.cursor() as cursor:\n\t\t\t\tcursor.execute(query)\n\t\t\t\tconnection.commit()\n\t\tfinally:\n\t\t\tconnection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[157, 230]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[157, 230]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)\n{\n AliasInfo *alias;\n unsigned i, num_key_aliases;\n struct xkb_key_alias *key_aliases;\n\n /*\n * Do some sanity checking on the aliases. We can't do it before\n * because keys and their aliases may be added out-of-order.\n */\n num_key_aliases = 0;\n darray_foreach(alias, info->aliases) {\n /* Check that ->real is a key. */\n if (!XkbKeyByName(keymap, alias->real, false)) {\n log_vrb(info->ctx, 5,\n \"Attempt to alias %s to non-existent key %s; Ignored\\n\",\n KeyNameText(info->ctx, alias->alias),\n KeyNameText(info->ctx, alias->real));\n alias->real = XKB_ATOM_NONE;\n continue;\n }\n\n /* Check that ->alias is not a key. */\n if (XkbKeyByName(keymap, alias->alias, false)) {\n log_vrb(info->ctx, 5,\n \"Attempt to create alias with the name of a real key; \"\n \"Alias \\\"%s = %s\\\" ignored\\n\",\n KeyNameText(info->ctx, alias->alias),\n KeyNameText(info->ctx, alias->real));\n alias->real = XKB_ATOM_NONE;\n continue;\n }\n\n num_key_aliases++;\n }\n\n /* Copy key aliases. */\n key_aliases = NULL;\n if (num_key_aliases > 0) {\n key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));\n if (!key_aliases)\n return false;\n\n i = 0;\n darray_foreach(alias, info->aliases) {\n if (alias->real != XKB_ATOM_NONE) {\n key_aliases[i].alias = alias->alias;\n key_aliases[i].real = alias->real;\n i++;\n }\n }\n }\n\n keymap->num_key_aliases = num_key_aliases;\n keymap->key_aliases = key_aliases;\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "CopyKeyAliasesToKeymap", "_file_name": "src/xkbcomp/keycodes.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)\n{\n\tdouble width_d;\n\tdouble scale_f_d = 1.0;\n\tconst double filter_width_d = DEFAULT_BOX_RADIUS;\n\tint windows_size;\n\tunsigned int u;\n\tLineContribType *res;\n\n\tif (scale_d < 1.0) {\n\t\twidth_d = filter_width_d / scale_d;\n\t\tscale_f_d = scale_d;\n\t} else {\n\t\twidth_d= filter_width_d;\n\t}\n\n\twindows_size = 2 * (int)ceil(width_d) + 1;\n\tres = _gdContributionsAlloc(line_size, windows_size);\n\n\tfor (u = 0; u < line_size; u++) {\n\t\tconst double dCenter = (double)u / scale_d;\n\t\t/* get the significant edge points affecting the pixel */\n\t\tregister int iLeft = MAX(0, (int)floor (dCenter - width_d));\n\t\tint iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);\n\t\tdouble dTotalWeight = 0.0;\n\t\tint iSrc;\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\t/* Cut edge points to fit in filter window in case of spill-off */\n\t\tif (iRight - iLeft + 1 > windows_size) {\n\t\t\tif (iLeft < ((int)src_size - 1 / 2)) {\n\t\t\t\tiLeft++;\n\t\t\t} else {\n\t\t\t\tiRight--;\n\t\t\t}\n\t\t}\n\n\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\tdTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));\n\t\t}\n\n\t\tif (dTotalWeight < 0.0) {\n\t\t\t_gdContributionsFree(res);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (dTotalWeight > 0.0) {\n\t\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\t\tres->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[847, 989]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[847, 989]]}, "_func_name": "_gdContributionsCalc", "_file_name": "src/gd_interpolation.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def mode_receive(self, request):\n \"\"\"\n This is called by render_POST when the client is telling us\n that it is ready to receive data as soon as it is available.\n This is the basis of a long-polling (comet) mechanism: the\n server will wait to reply until data is available.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n self.last_alive[csessid] = (time.time(), False)\n\n dataentries = self.databuffer.get(csessid, [])\n if dataentries:\n return dataentries.pop(0)\n request.notifyFinish().addErrback(self._responseFailed, csessid, request)\n if csessid in self.requests:\n self.requests[csessid].finish() # Clear any stale request.\n self.requests[csessid] = request\n return server.NOT_DONE_YET", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mode_receive", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "wiki_handle_rest_call(HttpRequest *req, \n\t\t HttpResponse *res,\n\t\t char *func)\n{\n\n if (func != NULL && *func != '\\0')\n {\n if (!strcmp(func, \"page/get\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && (access(page, R_OK) == 0)) \n\t {\n\t http_response_printf(res, \"%s\", file_read(page));\n\t http_response_send(res);\n\t return;\n\t } \n\t}\n else if (!strcmp(func, \"page/set\"))\n\t{\n\t char *wikitext = NULL, *page = NULL;\n\t if( ( (wikitext = http_request_param_get(req, \"text\")) != NULL)\n\t && ( (page = http_request_param_get(req, \"page\")) != NULL))\n\t {\n\t file_write(page, wikitext);\t \n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return;\n\t }\n\t}\n else if (!strcmp(func, \"page/delete\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && (unlink(page) > 0))\n\t {\n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n else if (!strcmp(func, \"page/exists\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && (access(page, R_OK) == 0)) \n\t {\n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n else if (!strcmp(func, \"pages\") || !strcmp(func, \"search\"))\n\t{\n\t WikiPageList **pages = NULL;\n\t int n_pages, i;\n\t char *expr = http_request_param_get(req, \"expr\");\n\n\t if (expr == NULL)\n\t expr = http_request_get_query_string(req);\n\t \n\t pages = wiki_get_pages(&n_pages, expr);\n\n\t if (pages)\n\t {\n\t for (i=0; imtime);\n\t\t strftime(datebuf, sizeof(datebuf), \"%Y-%m-%d %H:%M\", pTm);\n\t\t http_response_printf(res, \"%s\\t%s\\n\", pages[i]->name, datebuf);\n\t\t}\n\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n }\n\n http_response_set_status(res, 500, \"Error\");\n http_response_printf(res, \"Failed\\n\");\n http_response_send(res);\n\n return; \n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[307, 350], [699, 741], [1333, 1376]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[307, 350], [699, 741], [1333, 1376]]}, "_func_name": "wiki_handle_rest_call", "_file_name": "src/wiki.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)\n{\n\tsc_context_t *ctx;\n\tsc_apdu_t apdu;\n\tu8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tu8 sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\ttcos_data *data;\n\tint tcos3, r;\n\n\tassert(card != NULL && crgram != NULL && out != NULL);\n\tctx = card->ctx;\n\ttcos3=(card->type==SC_CARD_TYPE_TCOS_V3);\n\tdata=(tcos_data *)card->drv_data;\n\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t\t\"TCOS3:%d PKCS1:%d\\n\",tcos3,\n\t\t!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));\n\n\tsc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = crgram_len;\n\n\tapdu.data = sbuf;\n\tapdu.lc = apdu.datalen = crgram_len+1;\n\tsbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);\n\tmemcpy(sbuf+1, crgram, crgram_len);\n\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif (apdu.sw1==0x90 && apdu.sw2==0x00) {\n\t\tsize_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;\n\t\tunsigned int offset=0;\n\t\tif(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) {\n\t\t\toffset=2; while(offsetctx, SC_LOG_DEBUG_VERBOSE, len-offset);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[852, 889]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[852, 889]]}, "_func_name": "tcos_decipher", "_file_name": "src/libopensc/card-tcos.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def can_user_pass_that_amount_of_money(self, user_id, money):\n self.cursor.execute(\"SELECT count(id) FROM kickstarter.users where id = %s and money >= %s\" % (user_id, money))\n return self.cursor.fetchall()[0][0]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[66, 186]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[66, 186]]}, "_func_name": "can_user_pass_that_amount_of_money", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, char **buf, int *buf_type)\n{\n\tstruct smb_rqst rqst;\n\tint resp_buftype, rc = -EACCES;\n\tstruct smb2_read_plain_req *req = NULL;\n\tstruct smb2_read_rsp *rsp = NULL;\n\tstruct kvec iov[1];\n\tstruct kvec rsp_iov;\n\tunsigned int total_len;\n\tint flags = CIFS_LOG_ERROR;\n\tstruct cifs_ses *ses = io_parms->tcon->ses;\n\n\t*nbytes = 0;\n\trc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);\n\tif (rc)\n\t\treturn rc;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\tiov[0].iov_base = (char *)req;\n\tiov[0].iov_len = total_len;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = 1;\n\n\trc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);\n\tcifs_small_buf_release(req);\n\n\trsp = (struct smb2_read_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\tif (rc != -ENODATA) {\n\t\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);\n\t\t\tcifs_dbg(VFS, \"Send error in read = %d\\n\", rc);\n\t\t\ttrace_smb3_read_err(xid, req->PersistentFileId,\n\t\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t\t io_parms->offset, io_parms->length,\n\t\t\t\t\t rc);\n\t\t} else\n\t\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, 0);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t\treturn rc == -ENODATA ? 0 : rc;\n\t} else\n\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length);\n\n\t*nbytes = le32_to_cpu(rsp->DataLength);\n\tif ((*nbytes > CIFS_MAX_MSGSIZE) ||\n\t (*nbytes > io_parms->length)) {\n\t\tcifs_dbg(FYI, \"bad length %d for count %d\\n\",\n\t\t\t *nbytes, io_parms->length);\n\t\trc = -EIO;\n\t\t*nbytes = 0;\n\t}\n\n\tif (*buf) {\n\t\tmemcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t} else if (resp_buftype != CIFS_NO_BUFFER) {\n\t\t*buf = rsp_iov.iov_base;\n\t\tif (resp_buftype == CIFS_SMALL_BUFFER)\n\t\t\t*buf_type = CIFS_SMALL_BUFFER;\n\t\telse if (resp_buftype == CIFS_LARGE_BUFFER)\n\t\t\t*buf_type = CIFS_LARGE_BUFFER;\n\t}\n\treturn rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[802, 882]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[802, 882]]}, "_func_name": "SMB2_read", "_file_name": "fs/cifs/smb2pdu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;\n\n\t/* sanity checking for parameters. */\n\tif (g->sect <= 0 ||\n\t g->head <= 0 ||\n\t /* check for zero in F_SECT_PER_TRACK */\n\t (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;\n\n\t\tif (lock_fdc(drive))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[177, 219]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[177, 219]]}, "_func_name": "set_geometry", "_file_name": "drivers/block/floppy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp)\n{\n ExceptionInfo\n *exception;\n\n int\n bit;\n\n ssize_t\n x;\n\n register PixelPacket\n *q;\n\n IndexPacket\n index;\n\n register IndexPacket\n *indexes;\n\n exception=(&image->exception);\n switch (bpp)\n {\n case 1: /* Convert bitmap scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)\n {\n index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n p++;\n }\n if (!SyncAuthenticPixels(image,exception))\n break;\n break;\n }\n case 2: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p) & 0x3);\n SetPixelIndex(indexes+x+1,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if ((image->columns % 4) != 0)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n if ((image->columns % 4) >= 1)\n\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n if ((image->columns % 4) >= 2)\n\n {\n index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n break;\n }\n\n case 4: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p) & 0x0f);\n SetPixelIndex(indexes+x+1,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if ((image->columns % 2) != 0)\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n break;\n }\n case 8: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL) break;\n indexes=GetAuthenticIndexQueue(image);\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ConstrainColormapIndex(image,*p);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n break;\n\n case 24: /* Convert DirectColor scanline. */\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n q++;\n }\n if (!SyncAuthenticPixels(image,exception))\n break;\n break;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1585, 1643]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1585, 1643]]}, "_func_name": "InsertRow", "_file_name": "coders/wpg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_recvmsg(int sockfd, struct msghdr *msg, int flags) {\n size_t total_buffer_size = CalculateTotalMessageSize(msg);\n\n MessageWriter input;\n input.Push(sockfd);\n input.Push(msg->msg_namelen);\n input.Push(total_buffer_size);\n input.Push(msg->msg_controllen);\n input.Push(msg->msg_flags);\n input.Push(flags);\n\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvMsgHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvmsg\", 2,\n /*match_exact_params=*/false);\n\n ssize_t result = output.next();\n int klinux_errno = output.next();\n\n // recvmsg() returns the number of characters received. On error, -1 is\n // returned, with errno set to indicate the cause of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n if (result > total_buffer_size) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_recvmsg: result exceeds requested\");\n }\n\n auto msg_name_extent = output.next();\n // The returned |msg_namelen| should not exceed the buffer size.\n if (msg_name_extent.size() <= msg->msg_namelen) {\n msg->msg_namelen = msg_name_extent.size();\n }\n memcpy(msg->msg_name, msg_name_extent.As(), msg->msg_namelen);\n\n // A single buffer is passed from the untrusted side, copy it into the\n // scattered buffers inside the enclave.\n auto msg_iov_extent = output.next();\n size_t total_bytes = msg_iov_extent.size();\n size_t bytes_copied = 0;\n for (int i = 0; i < msg->msg_iovlen && bytes_copied < total_bytes; ++i) {\n size_t bytes_to_copy =\n std::min(msg->msg_iov[i].iov_len, total_bytes - bytes_copied);\n memcpy(msg->msg_iov[i].iov_base, msg_iov_extent.As() + bytes_copied,\n bytes_to_copy);\n bytes_copied += bytes_to_copy;\n }\n\n auto msg_control_extent = output.next();\n // The returned |msg_controllen| should not exceed the buffer size.\n if (msg_control_extent.size() <= msg->msg_controllen) {\n msg->msg_controllen = msg_control_extent.size();\n }\n memcpy(msg->msg_control, msg_control_extent.As(), msg->msg_controllen);\n\n return result;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_recvmsg", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/summary', methods=['GET'])\ndef summary():\n\tif 'username' in session:\n\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor()\n\n\t\t#select the maximum score from the results table\n\t\tcursor.execute(\"SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount='\" + session['username'] + \"'\");\n\t\tcourseConcentration = cursor.fetchone()\n\n\t\treturn render_template('summary.html', courseConcentration = courseConcentration[0])\n\treturn redirect(url_for('login'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[185, 397]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[185, 397]]}, "_func_name": "summary", "_file_name": "src/tech_track.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {\n\tstruct r_bin_t *rbin = arch->rbin;\n\tint i;\n\tint *methods = NULL;\n\tint sym_count = 0;\n\n\t// doublecheck??\n\tif (!bin || bin->methods_list) {\n\t\treturn false;\n\t}\n\tbin->code_from = UT64_MAX;\n\tbin->code_to = 0;\n\tbin->methods_list = r_list_newf ((RListFree)free);\n\tif (!bin->methods_list) {\n\t\treturn false;\n\t}\n\tbin->imports_list = r_list_newf ((RListFree)free);\n\tif (!bin->imports_list) {\n\t\tr_list_free (bin->methods_list);\n\t\treturn false;\n\t}\n\tbin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);\n\tif (!bin->classes_list) {\n\t\tr_list_free (bin->methods_list);\n\t\tr_list_free (bin->imports_list);\n\t\treturn false;\n\t}\n\n\tif (bin->header.method_size>bin->size) {\n\t\tbin->header.method_size = 0;\n\t\treturn false;\n\t}\n\n\t/* WrapDown the header sizes to avoid huge allocations */\n\tbin->header.method_size = R_MIN (bin->header.method_size, bin->size);\n\tbin->header.class_size = R_MIN (bin->header.class_size, bin->size);\n\tbin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);\n\n\t// TODO: is this posible after R_MIN ??\n\tif (bin->header.strings_size > bin->size) {\n\t\teprintf (\"Invalid strings size\\n\");\n\t\treturn false;\n\t}\n\n\tif (bin->classes) {\n\t\tut64 amount = sizeof (int) * bin->header.method_size;\n\t\tif (amount > UT32_MAX || amount < bin->header.method_size) {\n\t\t\treturn false;\n\t\t}\n\t\tmethods = calloc (1, amount + 1);\n\t\tfor (i = 0; i < bin->header.class_size; i++) {\n\t\t\tchar *super_name, *class_name;\n\t\t\tstruct dex_class_t *c = &bin->classes[i];\n\t\t\tclass_name = dex_class_name (bin, c);\n\t\t\tsuper_name = dex_class_super_name (bin, c);\n\t\t\tif (dexdump) { \n\t\t\t\trbin->cb_printf (\"Class #%d -\\n\", i);\n\t\t\t}\n\t\t\tparse_class (arch, bin, c, i, methods, &sym_count);\n\t\t\tfree (class_name);\n\t\t\tfree (super_name);\n\t\t}\n\t}\n\n\tif (methods) {\n\t\tint import_count = 0;\n\t\tint sym_count = bin->methods_list->length;\n\n\t\tfor (i = 0; i < bin->header.method_size; i++) {\n\t\t\tint len = 0;\n\t\t\tif (methods[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (bin->methods[i].class_id > bin->header.types_size - 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchar *class_name = getstr (\n\t\t\t\tbin, bin->types[bin->methods[i].class_id]\n\t\t\t\t\t\t.descriptor_id);\n\t\t\tif (!class_name) {\n\t\t\t\tfree (class_name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlen = strlen (class_name);\n\t\t\tif (len < 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tclass_name[len - 1] = 0; // remove last char \";\"\n\t\t\tchar *method_name = dex_method_name (bin, i);\n\t\t\tchar *signature = dex_method_signature (bin, i);\n\t\t\tif (method_name && *method_name) {\n\t\t\t\tRBinImport *imp = R_NEW0 (RBinImport);\n\t\t\t\timp->name = r_str_newf (\"%s.method.%s%s\", class_name, method_name, signature);\n\t\t\t\timp->type = r_str_const (\"FUNC\");\n\t\t\t\timp->bind = r_str_const (\"NONE\");\n\t\t\t\timp->ordinal = import_count++;\n\t\t\t\tr_list_append (bin->imports_list, imp);\n\n\t\t\t\tRBinSymbol *sym = R_NEW0 (RBinSymbol);\n\t\t\t\tsym->name = r_str_newf (\"imp.%s\", imp->name);\n\t\t\t\tsym->type = r_str_const (\"FUNC\");\n\t\t\t\tsym->bind = r_str_const (\"NONE\");\n\t\t\t\t//XXX so damn unsafe check buffer boundaries!!!!\n\t\t\t\t//XXX use r_buf API!!\n\t\t\t\tsym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;\n\t\t\t\tsym->ordinal = sym_count++;\n\t\t\t\tr_list_append (bin->methods_list, sym);\n\t\t\t\tsdb_num_set (mdb, sdb_fmt (0, \"method.%d\", i), sym->paddr, 0);\n\t\t\t}\n\t\t\tfree (method_name);\n\t\t\tfree (signature);\n\t\t\tfree (class_name);\n\t\t}\n\t\tfree (methods);\n\t}\n\treturn true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1978, 2042]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1978, 2042]]}, "_func_name": "dex_loadcode", "_file_name": "libr/bin/p/bin_dex.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n enum mrb_fiber_state status;\n mrb_value value;\n\n fiber_check_cfunc(mrb, c);\n status = c->status;\n if (resume && status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n if (status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n fiber_switch_context(mrb, c);\n if (status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n\n mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n b = c->stack+1;\n e = b + len;\n while (bcibase->argc = (int)len;\n value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];\n }\n else {\n value = fiber_result(mrb, a, len);\n }\n\n if (vmexec) {\n c->vmexec = TRUE;\n value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);\n mrb->c = old_c;\n }\n else {\n MARK_CONTEXT_MODIFY(c);\n }\n return value;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fiber_switch", "_file_name": "mrbgems/mruby-fiber/src/fiber.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)\n{\n int i, j, len;\n UChar *p;\n\n for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {\n len = enclen(enc, p);\n if (i + len >= OPT_EXACT_MAXLEN) break;\n for (j = 0; j < len && p < end; j++)\n to->s[i++] = *p++;\n }\n\n to->len = i;\n\n if (p >= end)\n to->reach_end = 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "concat_opt_exact_str", "_file_name": "src/regcomp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def insertNPC(name, race,classe,sex,level,image,legit):\n\tc, conn = getConnection()\n\tdate = now()\n\tc.execute(\"INSERT INTO npc VALUES (?,?,?,?,?,?,?,?)\",(date,str(name),race,classe,sex,str(level),image,str(legit)))\n\tconn.commit()\n\tconn.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "insertNPC", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/', methods=['POST'])\ndef login():\n print('login')\n user = str(request.form['username'])\n password = str(request.form['password'])\n cur.execute('SELECT * FROM users WHERE name = \\'{}\\' AND password = \\'{}\\';'.format(user, password))\n response = cur.fetchone()\n if response != None:\n print(response, 'OK')\n return redirect(url_for('enter_test_point'))\n else:\n print(response, 'not OK')\n flash('Invalid login or password')\n return render_template('login.html')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[152, 257]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[152, 257]]}, "_func_name": "login", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/wins\")\ndef wins():\n if db == None:\n init()\n\n player = request.args.get('tag', default=\"christmasmike\")\n sql = \"SELECT * FROM matches WHERE winner = '\"+str(player)+\"' ORDER BY date DESC;\"\n result = db.exec(sql)\n\n result = [str(x) for x in result]\n result = '\\n'.join(result)\n return json.dumps(result)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[135, 222]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[135, 222]]}, "_func_name": "wins", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):\n # Ensure vdisk has no FlashCopy mappings\n mapping_ids = self._get_vdisk_fc_mappings(name)\n while len(mapping_ids):\n wait_for_copy = False\n for map_id in mapping_ids:\n attrs = self._get_flashcopy_mapping_attributes(map_id)\n if not attrs:\n continue\n source = attrs['source_vdisk_name']\n target = attrs['target_vdisk_name']\n copy_rate = attrs['copy_rate']\n status = attrs['status']\n\n if copy_rate == '0':\n # Case #2: A vdisk that has snapshots\n if source == name:\n if not allow_snaps:\n return False\n ssh_cmd = ('svctask chfcmap -copyrate 50 '\n '-autodelete on %s' % map_id)\n out, err = self._run_ssh(ssh_cmd)\n wait_for_copy = True\n # Case #3: A snapshot\n else:\n msg = (_('Vdisk %(name)s not involved in '\n 'mapping %(src)s -> %(tgt)s') %\n {'name': name, 'src': source, 'tgt': target})\n self._driver_assert(target == name, msg)\n if status in ['copying', 'prepared']:\n self._run_ssh('svctask stopfcmap %s' % map_id)\n elif status in ['stopping', 'preparing']:\n wait_for_copy = True\n else:\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n # Case 4: Copy in progress - wait and will autodelete\n else:\n if status == 'prepared':\n self._run_ssh('svctask stopfcmap %s' % map_id)\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n elif status == 'idle_or_copied':\n # Prepare failed\n self._run_ssh('svctask rmfcmap -force %s' % map_id)\n else:\n wait_for_copy = True\n if wait_for_copy:\n time.sleep(5)\n mapping_ids = self._get_vdisk_fc_mappings(name)\n return True", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[820, 952], [1459, 1534], [1679, 1759], [1896, 2043], [2137, 2213]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[820, 952], [1459, 1534], [1679, 1759], [1896, 2043], [2137, 2213]]}, "_func_name": "_ensure_vdisk_no_fc_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "matchCurrentInput(\n\t\tconst InString *input, int pos, const widechar *passInstructions, int passIC) {\n\tint k;\n\tint kk = pos;\n\tfor (k = passIC + 2;\n\t\t\t((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));\n\t\t\tk++)\n\t\tif (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])\n\t\t\treturn 0;\n\treturn 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "matchCurrentInput", "_file_name": "liblouis/lou_translateString.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret)\n{\n\tMD5_CTX md5_secret, my_md5;\n\tunsigned char misc[AUTH_VECTOR_LEN];\n\tint i;\n\tint length = strlen(password);\n\tunsigned char hashed[256 + AUTH_PASS_LEN];\t/* can't be longer than this */\n\tunsigned char *vector;\n\tattribute_t *attr;\n\n\tif (length > MAXPASS) {\t\t\t\t/* shorten the password for now */\n\t\tlength = MAXPASS;\n\t}\n\n\tif (length == 0) {\n\t\tlength = AUTH_PASS_LEN;\t\t\t/* 0 maps to 16 */\n\t} if ((length & (AUTH_PASS_LEN - 1)) != 0) {\n\t\tlength += (AUTH_PASS_LEN - 1);\t\t/* round it up */\n\t\tlength &= ~(AUTH_PASS_LEN - 1);\t\t/* chop it off */\n\t}\t\t\t\t\t\t/* 16*N maps to itself */\n\n\tmemset(hashed, 0, length);\n\tmemcpy(hashed, password, length);\n\n\tattr = find_attribute(request, PW_PASSWORD);\n\n\tif (type == PW_PASSWORD) {\n\t\tvector = request->vector;\n\t} else {\n\t\tvector = attr->data;\t\t\t/* attr CANNOT be NULL here. */\n\t}\n\n\t/* ************************************************************ */\n\t/* encrypt the password */\n\t/* password : e[0] = p[0] ^ MD5(secret + vector) */\n\tMD5Init(&md5_secret);\n\tMD5Update(&md5_secret, (unsigned char *) secret, strlen(secret));\n\tmy_md5 = md5_secret;\t\t\t\t/* so we won't re-do the hash later */\n\tMD5Update(&my_md5, vector, AUTH_VECTOR_LEN);\n\tMD5Final(misc, &my_md5);\t\t\t/* set the final vector */\n\txor(hashed, misc, AUTH_PASS_LEN);\n\n\t/* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */\n\tfor (i = 1; i < (length >> 4); i++) {\n\t\tmy_md5 = md5_secret;\t\t\t/* grab old value of the hash */\n\t\tMD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN);\n\t\tMD5Final(misc, &my_md5);\t\t\t/* set the final vector */\n\t\txor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN);\n\t}\n\n\tif (type == PW_OLD_PASSWORD) {\n\t\tattr = find_attribute(request, PW_OLD_PASSWORD);\n\t}\n\n\tif (!attr) {\n\t\tadd_attribute(request, type, hashed, length);\n\t} else {\n\t\tmemcpy(attr->data, hashed, length); /* overwrite the packet */\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_password", "_file_name": "src/pam_radius_auth.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/h2h\")\ndef h2h():\n if db == None:\n init()\n\n player1 = request.args.get('tag1', default=\"christmasmike\")\n player2 = request.args.get('tag2', default=\"christmasmike\")\n sql = \"SELECT * FROM matches WHERE (player1 = '{player1}' OR \"\\\n +\"player2 = '{player1}') AND (player1 = '{player2}' OR \"\\\n +\"player2 = '{player2}') ORDER BY date DESC;\"\n args = {'player1': player1, 'player2': player2}\n result = db.exec(sql, args)\n return json.dumps(result)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "h2h", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)\n{\n\tstruct sockaddr_rc sa;\n\tstruct sock *sk = sock->sk;\n\tint len, err = 0;\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tmemset(&sa, 0, sizeof(sa));\n\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n\tmemcpy(&sa, addr, len);\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa.rc_bdaddr);\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_OPEN) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tif (sk->sk_type != SOCK_STREAM) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\twrite_lock(&rfcomm_sk_list.lock);\n\n\tif (sa.rc_channel &&\n\t __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {\n\t\terr = -EADDRINUSE;\n\t} else {\n\t\t/* Save source address */\n\t\tbacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);\n\t\trfcomm_pi(sk)->channel = sa.rc_channel;\n\t\tsk->sk_state = BT_BOUND;\n\t}\n\n\twrite_unlock(&rfcomm_sk_list.lock);\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rfcomm_sock_bind", "_file_name": "net/bluetooth/rfcomm/sock.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/', methods=['POST'])\ndef login():\n print('login')\n user = str(request.form['username'])\n password = str(request.form['password'])\n cur.execute(\"SELECT * FROM users WHERE name = ? AND password = ?;\", [user, password])\n response = cur.fetchone()\n if response != None:\n print(response, 'OK')\n return redirect(url_for('enter_test_point'))\n else:\n print(response, 'not OK')\n flash('Invalid login or password')\n return render_template('login.html')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "login", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)\n{\n WavpackHeader *wphdr = (WavpackHeader *) buffer;\n uint32_t checksum_passed = 0, bcount, meta_bc;\n unsigned char *dp, meta_id, c1, c2;\n\n if (strncmp (wphdr->ckID, \"wvpk\", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))\n return FALSE;\n\n bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;\n dp = (unsigned char *)(wphdr + 1);\n\n while (bcount >= 2) {\n meta_id = *dp++;\n c1 = *dp++;\n\n meta_bc = c1 << 1;\n bcount -= 2;\n\n if (meta_id & ID_LARGE) {\n if (bcount < 2)\n return FALSE;\n\n c1 = *dp++;\n c2 = *dp++;\n meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);\n bcount -= 2;\n }\n\n if (bcount < meta_bc)\n return FALSE;\n\n if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {\n#ifdef BITSTREAM_SHORTS\n uint16_t *csptr = (uint16_t*) buffer;\n#else\n unsigned char *csptr = buffer;\n#endif\n int wcount = (int)(dp - 2 - buffer) >> 1;\n uint32_t csum = (uint32_t) -1;\n\n if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)\n return FALSE;\n\n#ifdef BITSTREAM_SHORTS\n while (wcount--)\n csum = (csum * 3) + *csptr++;\n#else\n WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);\n\n while (wcount--) {\n csum = (csum * 3) + csptr [0] + (csptr [1] << 8);\n csptr += 2;\n }\n\n WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);\n#endif\n\n if (meta_bc == 4) {\n if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))\n return FALSE;\n }\n else {\n csum ^= csum >> 16;\n\n if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))\n return FALSE;\n }\n\n checksum_passed++;\n }\n\n bcount -= meta_bc;\n dp += meta_bc;\n }\n\n return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1724, 1869], [1973, 2050]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1724, 1869], [1973, 2050]]}, "_func_name": "WavpackVerifySingleBlock", "_file_name": "src/open_utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def handle_message(self, ch, method, properties, body):\n \"\"\"\n this is a pika.basic_consumer callback\n handles client inputs, runs appropriate workflows and views\n\n Args:\n ch: amqp channel\n method: amqp method\n properties:\n body: message body\n \"\"\"\n input = {}\n headers = {}\n try:\n self.sessid = method.routing_key\n\n input = json_decode(body)\n data = input['data']\n\n # since this comes as \"path\" we dont know if it's view or workflow yet\n # TODO: just a workaround till we modify ui to\n if 'path' in data:\n if data['path'] in settings.VIEW_URLS:\n data['view'] = data['path']\n else:\n data['wf'] = data['path']\n session = Session(self.sessid)\n\n headers = {'remote_ip': input['_zops_remote_ip'],\n 'source': input['_zops_source']}\n\n if 'wf' in data:\n output = self._handle_workflow(session, data, headers)\n elif 'job' in data:\n\n self._handle_job(session, data, headers)\n return\n else:\n output = self._handle_view(session, data, headers)\n\n except HTTPError as e:\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), \"code\": e.code}\n log.exception(\"Http error occurred\")\n except:\n self.current = Current(session=session, input=data)\n self.current.headers = headers\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n err = traceback.format_exc()\n output = {'error': self._prepare_error_msg(err), \"code\": 500}\n log.exception(\"Worker error occurred with messsage body:\\n%s\" % body)\n if 'callbackID' in input:\n output['callbackID'] = input['callbackID']\n log.info(\"OUTPUT for %s: %s\" % (self.sessid, output))\n output['reply_timestamp'] = time()\n self.send_output(output)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle_message", "_file_name": "zengine/wf_daemon.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('//history/record')\ndef view_page_record(page_name):\n content_id = request.args.get('id')\n query = db.query(\"select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = '%s'\" % content_id)\n page_record = query.namedresult()[0]\n\n return render_template(\n 'page_record.html',\n page_name = page_name,\n page_record = page_record\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[115, 292]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[115, 292]]}, "_func_name": "view_page_record", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _normalize(self, metaerrors):\n \"\"\"Normalize output format to be usable by Anaconda's linting frontend\n \"\"\"\n\n errors = []\n for error in metaerrors:\n if self.filepath not in error.get('path', ''):\n continue\n\n error_type = error.get('severity', 'X').capitalize()[0]\n if error_type == 'X':\n continue\n if error_type not in ['E', 'W']:\n error_type = 'V'\n errors.append({\n 'underline_range': True,\n 'lineno': error.get('line', 0),\n 'offset': error.get('col', 0),\n 'raw_message': error.get('message', ''),\n 'code': 0,\n 'level': error_type,\n 'message': '[{0}] {1} ({2}): {3}'.format(\n error_type,\n error.get('linter', 'none'),\n error.get('severity', 'none'),\n error.get('message')\n )\n })\n\n return errors", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[183, 242]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[183, 242]]}, "_func_name": "_normalize", "_file_name": "plugin/handlers_go/anagonda/context/gometalinter.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def span(self, key):\n path = os.path.join(self.namespace, key)\n try:\n self.etcd.write(path, None, dir=True, prevExist=False)\n except etcd.EtcdAlreadyExist as err:\n raise CSStoreExists(str(err))\n except etcd.EtcdException as err:\n log_error(\"Error storing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to store key')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[25, 74]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[25, 74]]}, "_func_name": "span", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):\n \"\"\"Create a 3PAR host.\n\n Create a 3PAR host, if there is already a host on the 3par using\n the same iqn but with a different hostname, return the hostname\n used by 3PAR.\n \"\"\"\n cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain',\n domain, hostname, iscsi_iqn]\n out = self.common._cli_run(cmd)\n if out and len(out) > 1:\n return self.common.parse_create_host_error(hostname, out)\n return hostname", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_create_3par_iscsi_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def deletePost(self,postid):\n sqlText=\"delete from post where post.postid=%s\"\n params=[postid]\n result=sql.deleteDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "deletePost", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_requested_day(self, date):\n\n data = dict()\n\n day_start, day_end = self.get_epoch_day(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}\n\n query = '''\n SELECT TimeStamp, SUM(Power) AS Power \n FROM DayData \n WHERE TimeStamp BETWEEN %s AND %s \n GROUP BY TimeStamp;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query % (day_start, day_end)):\n data['data'].append({ 'time': row[0], 'power': row[1] })\n\n\n if self.get_datetime(date).date() == datetime.today().date():\n query = '''\n SELECT SUM(EToday) as EToday\n FROM Inverters;\n '''\n else:\n query = '''\n SELECT SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN %s AND %s\n GROUP BY TimeStamp\n ''' % (day_start, day_end)\n self.c.execute(query)\n row = self.c.fetchone()\n if row and row[0]: data['total'] = row[0]\n else: data['total'] = 0\n\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if (first_data): data['hasPrevious'] = (first_data < day_start)\n else: data['hasPrevious'] = False\n\n if (last_data): data['hasNext'] = (last_data > day_end)\n else: data['hasNext'] = False\n\n #print(json.dumps(data, indent=4))\n return data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[379, 426], [501, 566], [945, 995], [1030, 1073]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[379, 426], [501, 566], [945, 995], [1030, 1073]]}, "_func_name": "get_requested_day", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):\n \"\"\"\n Get all the old sourcebyinstitution number from the SQLite database.\n \"\"\"\n query = \"\"\"\n SELECT\n titles\n FROM\n history\n WHERE\n sourcebyinstitution = ?\n ORDER BY\n titles DESC\n LIMIT 1\n \"\"\"\n\n sqlite.execute(query, (sourcebyinstitution,))\n for record in sqlite:\n old_sourcebyinstitution_number = record[0]\n return old_sourcebyinstitution_number", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_old_sourcebyinstitution_number", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_chap_secret_for_host(self, host_name):\n \"\"\"Return the CHAP secret for the given host.\"\"\"\n\n LOG.debug(_('enter: _get_chap_secret_for_host: host name %s')\n % host_name)\n\n ssh_cmd = ['svcinfo', 'lsiscsiauth', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines), '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header, '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n self._assert_ssh_return('iscsi_auth_method' in header,\n '_get_chap_secret_for_host', ssh_cmd, out, err)\n self._assert_ssh_return('iscsi_chap_secret' in header,\n '_get_chap_secret_for_host', ssh_cmd, out, err)\n name_index = header.index('name')\n method_index = header.index('iscsi_auth_method')\n secret_index = header.index('iscsi_chap_secret')\n\n chap_secret = None\n host_found = False\n for line in host_lines:\n info = line.split('!')\n if info[name_index] == host_name:\n host_found = True\n if info[method_index] == 'chap':\n chap_secret = info[secret_index]\n\n self._assert_ssh_return(host_found, '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n\n LOG.debug(_('leave: _get_chap_secret_for_host: host name '\n '%(host_name)s with secret %(chap_secret)s')\n % {'host_name': host_name, 'chap_secret': chap_secret})\n\n return chap_secret", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_chap_secret_for_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)\n{\n\tunsigned int first = 0;\n\tunsigned int last = ARR_SIZE(insn_regs_intel) - 1;\n\tunsigned int mid = ARR_SIZE(insn_regs_intel) / 2;\n\n\tif (!intel_regs_sorted) {\n\t\tmemcpy(insn_regs_intel_sorted, insn_regs_intel,\n\t\t\t\tsizeof(insn_regs_intel_sorted));\n\t\tqsort(insn_regs_intel_sorted,\n\t\t\t\tARR_SIZE(insn_regs_intel_sorted),\n\t\t\t\tsizeof(struct insn_reg), regs_cmp);\n\t\tintel_regs_sorted = true;\n\t}\n\n\twhile (first <= last) {\n\t\tif (insn_regs_intel_sorted[mid].insn < id) {\n\t\t\tfirst = mid + 1;\n\t\t} else if (insn_regs_intel_sorted[mid].insn == id) {\n\t\t\tif (access) {\n\t\t\t\t*access = insn_regs_intel_sorted[mid].access;\n\t\t\t}\n\t\t\treturn insn_regs_intel_sorted[mid].reg;\n\t\t} else {\n\t\t\tif (mid == 0)\n\t\t\t\tbreak;\n\t\t\tlast = mid - 1;\n\t\t}\n\t\tmid = (first + last) / 2;\n\t}\n\n\t// not found\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[148, 199], [776, 808]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[148, 199], [776, 808]]}, "_func_name": "X86_insn_reg_intel", "_file_name": "arch/X86/X86Mapping.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def save_accepted_transaction(self, user_id, project_id, money):\n self.cursor.execute(\"update users set money = money - %s where id = %s\"%(money, user_id))\n self.cursor.execute(\"update projects set money = money + %s where id = %s\" % (money, project_id))\n self.cursor.execute(\"insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), 'accepted' )\" % (project_id, user_id, money))\n self.db.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[69, 447]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[69, 447]]}, "_func_name": "save_accepted_transaction", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n try:\n int(winner)\n int(loser)\n except ValueError:\n raise ValueError(\n \"\\\"winner\\\" and/or \\\"loser\\\" input are not integers.\\n\"\n \"Please use the id number of each player to report match results.\"\n )\n w = str(winner)\n l = str(loser)\n db = connect()\n c = db.cursor()\n statement = \"INSERT INTO matches values ({w}, {l})\".format(w=w, l=l)\n c.execute(statement)\n db.commit()\n db.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[551, 649]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[551, 649]]}, "_func_name": "reportMatch", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def index(request, is_mobile=False):\n hue_collections = DashboardController(request.user).get_search_collections()\n collection_id = request.GET.get('collection')\n\n if not hue_collections or not collection_id:\n return admin_collections(request, True, is_mobile)\n\n try:\n collection_doc = Document2.objects.get(id=collection_id)\n if USE_NEW_EDITOR.get():\n collection_doc.can_read_or_exception(request.user)\n else:\n collection_doc.doc.get().can_read_or_exception(request.user)\n collection = Collection2(request.user, document=collection_doc)\n except Exception, e:\n raise PopupException(e, title=_(\"Dashboard does not exist or you don't have the permission to access it.\"))\n\n query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}\n\n if request.method == 'GET':\n if 'q' in request.GET:\n query['qs'][0]['q'] = antixss(request.GET.get('q', ''))\n if 'qd' in request.GET:\n query['qd'] = antixss(request.GET.get('qd', ''))\n\n template = 'search.mako'\n if is_mobile:\n template = 'search_m.mako'\n\n return render(template, request, {\n 'collection': collection,\n 'query': json.dumps(query),\n 'initial': json.dumps({\n 'collections': [],\n 'layout': DEFAULT_LAYOUT,\n 'is_latest': LATEST.get(),\n 'engines': get_engines(request.user)\n }),\n 'is_owner': collection_doc.can_write(request.user) if USE_NEW_EDITOR.get() else collection_doc.doc.get().can_write(request.user),\n 'can_edit_index': can_edit_index(request.user),\n 'is_embeddable': request.GET.get('is_embeddable', False),\n 'mobile': is_mobile,\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "index", "_file_name": "desktop/libs/dashboard/src/dashboard/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/movies/add', methods=['GET', 'POST'])\ndef add_movie():\n form = MovieForm()\n if not form.validate_on_submit():\n return render_template('new_movie.html', title='Add New Movie', form=form)\n lang_id = add_language(form.data['language'])\n movie = {\n 'title': '',\n 'description': '',\n 'release_year': 0,\n 'rental_duration': 0,\n 'rental_rate': 0.00,\n 'length': 0,\n 'replacement_cost': 0.00\n }\n for k, v in movie.items():\n movie[k] = form.data[k]\n movie['language_id'] = movie.get('language_id', lang_id)\n cur.execute(\n \"\"\"\n INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)\n VALUES ('{}', '{}', {}, {}, {}, {}, {}, {})\n \"\"\".format(*[v for k, v in movie.items()])\n )\n try:\n cur.execute(f\"SELECT * FROM film where fulltext @@ to_tsquery('Dark Knight')\")\n res = cur.fetchall()\n conn.commit()\n return redirect(url_for('movies'))\n except Exception as e:\n return redirect(url_for('index'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[784, 887], [902, 989]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[784, 887], [902, 989]]}, "_func_name": "add_movie", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(commands =['login'])\ndef get_login(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n name = conn.fetchone()\n if name != None:\n bot.send_message(message.chat.id, \"Previous handle: \" + str(name[1]))\n else:\n bot.send_message(message.chat.id, \"Previous handle: None\")\n settings.close()\n bot.send_message(message.chat.id, \"Type new handle: \")\n set_state(message.chat.id, config.States.S_LOGIN.value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[195, 282]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[195, 282]]}, "_func_name": "get_login", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def check(current_num):\n try:\n cursor.execute('SELECT * FROM comics WHERE num=\"%s\"' % current_num)\n except sqlite3.OperationalError:\n cursor.execute('CREATE TABLE comics (num text)')\n return False\n else:\n return False if cursor.fetchone() is None else True", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[33, 109]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[33, 109]]}, "_func_name": "check", "_file_name": "comics/check_comics.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "bool WddxPacket::recursiveAddVar(const String& varName,\n const Variant& varVariant,\n bool hasVarTag) {\n\n bool isArray = varVariant.isArray();\n bool isObject = varVariant.isObject();\n\n if (isArray || isObject) {\n if (hasVarTag) {\n m_packetString += \"\";\n }\n\n Array varAsArray;\n Object varAsObject = varVariant.toObject();\n if (isArray) varAsArray = varVariant.toArray();\n if (isObject) varAsArray = varAsObject.toArray();\n\n int length = varAsArray.length();\n if (length > 0) {\n ArrayIter it = ArrayIter(varAsArray);\n if (it.first().isString()) isObject = true;\n if (isObject) {\n m_packetString += \"\";\n if (!isArray) {\n m_packetString += \"\";\n m_packetString += varAsObject->o_getClassName().c_str();\n m_packetString += \"\";\n }\n } else {\n m_packetString += \"\";\n }\n for (ArrayIter it(varAsArray); it; ++it) {\n Variant key = it.first();\n Variant value = it.second();\n recursiveAddVar(key.toString(), value, isObject);\n }\n if (isObject) {\n m_packetString += \"\";\n }\n else {\n m_packetString += \"\";\n }\n }\n else {\n //empty object\n if (isObject) {\n m_packetString += \"\";\n if (!isArray) {\n m_packetString += \"\";\n m_packetString += varAsObject->o_getClassName().c_str();\n m_packetString += \"\";\n }\n m_packetString += \"\";\n }\n }\n if (hasVarTag) {\n m_packetString += \"\";\n }\n return true;\n }\n\n std::string varType = getDataTypeString(varVariant.getType()).data();\n if (!getWddxEncoded(varType, \"\", varName, false).empty()) {\n std::string varValue = varVariant.toString().data();\n if (varType.compare(\"boolean\") == 0) {\n varValue = varVariant.toBoolean() ? \"true\" : \"false\";\n }\n m_packetString += getWddxEncoded(varType, varValue, varName, hasVarTag);\n return true;\n }\n\n return false;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[2068, 2125]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2068, 2125]]}, "_func_name": "HPHP::WddxPacket::recursiveAddVar", "_file_name": "hphp/runtime/ext/wddx/ext_wddx.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def get_user(self):\n if not hasattr(self, '_user'):\n qs = \"select * from account_access where access_token = '%s'\" % self.access_token\n result = self.db.get(qs)\n if result:\n self._user = result\n else:\n self._user = None\n \n return self._user", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[63, 157]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[63, 157]]}, "_func_name": "get_user", "_file_name": "src/auth.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "TiledInputFile::rawTileData (int &dx, int &dy,\n\t\t\t int &lx, int &ly,\n const char *&pixelData,\n\t\t\t int &pixelDataSize)\n{\n try\n {\n Lock lock (*_data->_streamData);\n\n if (!isValidTile (dx, dy, lx, ly))\n throw IEX_NAMESPACE::ArgExc (\"Tried to read a tile outside \"\n\t\t\t \"the image file's data window.\");\n\n TileBuffer *tileBuffer = _data->getTileBuffer (0);\n\n //\n // if file is a multipart file, we have to seek to the required tile\n // since we don't know where the file pointer is\n //\n int old_dx=dx;\n int old_dy=dy;\n int old_lx=lx;\n int old_ly=ly;\n if(isMultiPart(version()))\n {\n _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly));\n }\n readNextTileData (_data->_streamData, _data, dx, dy, lx, ly,\n\t\t\t tileBuffer->buffer,\n pixelDataSize);\n if(isMultiPart(version()))\n {\n if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly)\n {\n throw IEX_NAMESPACE::ArgExc (\"rawTileData read the wrong tile\");\n }\n }\n pixelData = tileBuffer->buffer;\n }\n catch (IEX_NAMESPACE::BaseExc &e)\n {\n REPLACE_EXC (e, \"Error reading pixel data from image \"\n \"file \\\"\" << fileName() << \"\\\". \" << e.what());\n throw;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1183, 1223]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1183, 1223]]}, "_func_name": "TiledInputFile::rawTileData", "_file_name": "OpenEXR/IlmImf/ImfTiledInputFile.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "std::string TarFileReader::extract(const string &_path) {\n if (_path.empty()) THROW(\"path cannot be empty\");\n if (!hasMore()) THROW(\"No more tar files\");\n\n string path = _path;\n if (SystemUtilities::isDirectory(path)) path += \"/\" + getFilename();\n\n LOG_DEBUG(5, \"Extracting: \" << path);\n\n return extract(*SystemUtilities::oopen(path));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[180, 251], [293, 342]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[180, 251], [293, 342]]}, "_func_name": "TarFileReader::extract", "_file_name": "src/cbang/tar/TarFileReader.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def karma_sub(name):\n karma = karma_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if karma is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES(%(name)s,-1,0)\n ''', (name, ))\n db.commit()\n logger.debug('Inserted into karmadb -1 karma for {}'.format(name))\n db.close()\n return -1\n\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n else:\n karma = karma - 1\n try:\n cursor.execute('''\n UPDATE people SET karma = %(karma)s WHERE name = %(name)s\n ''', (\n karma,\n name,\n ))\n db.commit()\n logger.debug('Inserted into karmadb -1 karma for {}'.format(name))\n db.close()\n return karma\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "karma_sub", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _normalize(self, metaerrors):\n \"\"\"Normalize output format to be usable by Anaconda's linting frontend\n \"\"\"\n\n errors = []\n for error in metaerrors:\n last_path = os.path.join(\n os.path.basename(os.path.dirname(self.filepath)),\n os.path.basename(self.filepath)\n )\n if last_path not in error.get('path', ''):\n continue\n\n error_type = error.get('severity', 'X').capitalize()[0]\n if error_type == 'X':\n continue\n if error_type not in ['E', 'W']:\n error_type = 'V'\n errors.append({\n 'underline_range': True,\n 'lineno': error.get('line', 0),\n 'offset': error.get('col', 0),\n 'raw_message': error.get('message', ''),\n 'code': 0,\n 'level': error_type,\n 'message': '[{0}] {1} ({2}): {3}'.format(\n error_type,\n error.get('linter', 'none'),\n error.get('severity', 'none'),\n error.get('message')\n )\n })\n\n return errors", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_normalize", "_file_name": "plugin/handlers_go/anagonda/context/gometalinter.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void set_fdc(int drive)\n{\n\tunsigned int new_fdc = fdc;\n\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tnew_fdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (new_fdc >= N_FDC) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tfdc = new_fdc;\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set_fdc", "_file_name": "drivers/block/floppy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,\n packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ndpi_reset_packet_line_info", "_file_name": "src/lib/ndpi_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int usb_get_bos_descriptor(struct usb_device *dev)\n{\n\tstruct device *ddev = &dev->dev;\n\tstruct usb_bos_descriptor *bos;\n\tstruct usb_dev_cap_header *cap;\n\tunsigned char *buffer;\n\tint length, total_len, num, i;\n\tint ret;\n\n\tbos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);\n\tif (!bos)\n\t\treturn -ENOMEM;\n\n\t/* Get BOS descriptor */\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);\n\tif (ret < USB_DT_BOS_SIZE) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tkfree(bos);\n\t\treturn ret;\n\t}\n\n\tlength = bos->bLength;\n\ttotal_len = le16_to_cpu(bos->wTotalLength);\n\tnum = bos->bNumDeviceCaps;\n\tkfree(bos);\n\tif (total_len < length)\n\t\treturn -EINVAL;\n\n\tdev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);\n\tif (!dev->bos)\n\t\treturn -ENOMEM;\n\n\t/* Now let's get the whole BOS descriptor set */\n\tbuffer = kzalloc(total_len, GFP_KERNEL);\n\tif (!buffer) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\tdev->bos->desc = (struct usb_bos_descriptor *)buffer;\n\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);\n\tif (ret < total_len) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor set\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tgoto err;\n\t}\n\ttotal_len -= length;\n\n\tfor (i = 0; i < num; i++) {\n\t\tbuffer += length;\n\t\tcap = (struct usb_dev_cap_header *)buffer;\n\n\t\tif (total_len < sizeof(*cap) || total_len < cap->bLength) {\n\t\t\tdev->bos->desc->bNumDeviceCaps = i;\n\t\t\tbreak;\n\t\t}\n\t\tlength = cap->bLength;\n\t\ttotal_len -= length;\n\n\t\tif (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {\n\t\t\tdev_warn(ddev, \"descriptor type invalid, skip\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (cap->bDevCapabilityType) {\n\t\tcase USB_CAP_TYPE_WIRELESS_USB:\n\t\t\t/* Wireless USB cap descriptor is handled by wusb */\n\t\t\tbreak;\n\t\tcase USB_CAP_TYPE_EXT:\n\t\t\tdev->bos->ext_cap =\n\t\t\t\t(struct usb_ext_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SS_CAP_TYPE:\n\t\t\tdev->bos->ss_cap =\n\t\t\t\t(struct usb_ss_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SSP_CAP_TYPE:\n\t\t\tdev->bos->ssp_cap =\n\t\t\t\t(struct usb_ssp_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase CONTAINER_ID_TYPE:\n\t\t\tdev->bos->ss_id =\n\t\t\t\t(struct usb_ss_container_id_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_PTM_CAP_TYPE:\n\t\t\tdev->bos->ptm_cap =\n\t\t\t\t(struct usb_ptm_cap_descriptor *)buffer;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\nerr:\n\tusb_release_bos_descriptor(dev);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usb_get_bos_descriptor", "_file_name": "drivers/usb/core/config.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def span(self, key):\n path = self._absolute_key(key)\n try:\n self.etcd.write(path, None, dir=True, prevExist=False)\n except etcd.EtcdAlreadyExist as err:\n raise CSStoreExists(str(err))\n except etcd.EtcdException as err:\n log_error(\"Error storing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to store key')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "span", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _get_degree_2(user_id, cnx):\n \"\"\"Get all users of degree 2 follow that are not currently followed.\n Example:\n this user (follows) user B (follows) user B\n AND user (does NOT follow) user B\n means that user B will be in the list\n Args:\n user_id (int): id of user\n cnx: DB connection\n Returns:\n list: list of user_ids\n \"\"\"\n sql = 'WITH tmp_suggest (followed_id) AS ' \\\n '(' \\\n 'SELECT b.followed_id AS followed_id ' \\\n 'FROM ' \\\n 'tbl_follow a INNER JOIN tbl_follow b ' \\\n 'ON a.followed_id = b.follower_id ' \\\n 'WHERE a.follower_id = %s ' \\\n 'AND b.followed_id NOT IN ' \\\n '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \\\n 'AND b.followed_id != %s ' \\\n ') ' \\\n 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \\\n 'GROUP BY followed_id ' \\\n 'ORDER BY num_mutual DESC'\n with cnx.cursor() as cursor:\n cursor.execute(sql, (user_id, user_id, user_id))\n res = cursor.fetchall()\n return list(map(lambda x: x[0], res))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_degree_2", "_file_name": "server/ygoons/modules/user/follow_suggest.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @property\n async def html_content(self):\n content = await self.content\n if not content:\n return ''\n return markdown(content)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[48, 85]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[48, 85]]}, "_func_name": "html_content", "_file_name": "models/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _add_chapsecret_to_host(self, host_name):\n \"\"\"Generate and store a randomly-generated CHAP secret for the host.\"\"\"\n\n chap_secret = utils.generate_password()\n ssh_cmd = ('svctask chhost -chapsecret \"%(chap_secret)s\" %(host_name)s'\n % {'chap_secret': chap_secret, 'host_name': host_name})\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from chhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_add_chapsecret_to_host', ssh_cmd, out, err)\n return chap_secret", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[179, 334]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[179, 334]]}, "_func_name": "_add_chapsecret_to_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_conn_fc_wwpns(self, host_name):\n wwpns = []\n cmd = ['svcinfo', 'lsfabric', '-host', host_name]\n generator = self._port_conf_generator(cmd)\n header = next(generator, None)\n if not header:\n return wwpns\n\n for port_data in generator:\n try:\n wwpns.append(port_data['local_wwpn'])\n except KeyError as e:\n self._handle_keyerror('lsfabric', header)\n\n return wwpns", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_conn_fc_wwpns", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n{\n#define MaxDirectoryStack 16\n#define EXIF_DELIMITER \"\\n\"\n#define EXIF_NUM_FORMATS 12\n#define TAG_EXIF_OFFSET 0x8769\n#define TAG_INTEROP_OFFSET 0xa005\n\n typedef struct _DirectoryInfo\n {\n unsigned char\n *directory;\n\n size_t\n entry;\n } DirectoryInfo;\n\n DirectoryInfo\n directory_stack[MaxDirectoryStack];\n\n EndianType\n endian;\n\n size_t\n entry,\n length,\n number_entries;\n\n ssize_t\n id,\n level,\n offset;\n\n static int\n format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};\n\n unsigned char\n *directory,\n *exif;\n\n /*\n Set EXIF resolution tag.\n */\n length=GetStringInfoLength(profile);\n exif=GetStringInfoDatum(profile);\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadProfileShort(LSBEndian,exif);\n if ((id != 0x4949) && (id != 0x4D4D))\n {\n while (length != 0)\n {\n if (ReadProfileByte(&exif,&length) != 0x45)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x78)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x69)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x66)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x00)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x00)\n continue;\n break;\n }\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadProfileShort(LSBEndian,exif);\n }\n endian=LSBEndian;\n if (id == 0x4949)\n endian=LSBEndian;\n else\n if (id == 0x4D4D)\n endian=MSBEndian;\n else\n return(MagickFalse);\n if (ReadProfileShort(endian,exif+2) != 0x002a)\n return(MagickFalse);\n /*\n This the offset to the first IFD.\n */\n offset=(ssize_t) ReadProfileLong(endian,exif+4);\n if ((offset < 0) || (size_t) offset >= length)\n return(MagickFalse);\n directory=exif+offset;\n level=0;\n entry=0;\n do\n {\n if (level > 0)\n {\n level--;\n directory=directory_stack[level].directory;\n entry=directory_stack[level].entry;\n }\n if ((directory < exif) || (directory > (exif+length-2)))\n break;\n /*\n Determine how many entries there are in the current IFD.\n */\n number_entries=ReadProfileShort(endian,directory);\n for ( ; entry < number_entries; entry++)\n {\n int\n components;\n\n register unsigned char\n *p,\n *q;\n\n size_t\n number_bytes;\n\n ssize_t\n format,\n tag_value;\n\n q=(unsigned char *) (directory+2+(12*entry));\n if (q > (exif+length-12))\n break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n if ((format-1) >= EXIF_NUM_FORMATS)\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n if (components < 0)\n break; /* corrupt EXIF */\n number_bytes=(size_t) components*format_bytes[format];\n if ((ssize_t) number_bytes < components)\n break; /* prevent overflow */\n if (number_bytes <= 4)\n p=q+8;\n else\n {\n /*\n The directory entry contains an offset.\n */\n offset=(ssize_t) ReadProfileLong(endian,q+8);\n if ((size_t) (offset+number_bytes) > length)\n continue;\n if (~length < number_bytes)\n continue; /* prevent overflow */\n p=(unsigned char *) (exif+offset);\n }\n switch (tag_value)\n {\n case 0x011a:\n {\n (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);\n (void) WriteProfileLong(endian,1UL,p+4);\n break;\n }\n case 0x011b:\n {\n (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);\n (void) WriteProfileLong(endian,1UL,p+4);\n break;\n }\n case 0x0112:\n {\n if (number_bytes == 4)\n {\n (void) WriteProfileLong(endian,(size_t) image->orientation,p);\n break;\n }\n (void) WriteProfileShort(endian,(unsigned short) image->orientation,\n p);\n break;\n }\n case 0x0128:\n {\n if (number_bytes == 4)\n {\n (void) WriteProfileLong(endian,(size_t) (image->units+1),p);\n break;\n }\n (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);\n break;\n }\n default:\n break;\n }\n if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))\n {\n offset=(ssize_t) ReadProfileLong(endian,p);\n if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=directory;\n entry++;\n directory_stack[level].entry=entry;\n level++;\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n level++;\n if ((directory+2+(12*number_entries)) > (exif+length))\n break;\n offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*\n number_entries));\n if ((offset != 0) && ((size_t) offset < length) &&\n (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n level++;\n }\n }\n break;\n }\n }\n } while (level > 0);\n return(MagickTrue);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2750, 2792]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2750, 2792]]}, "_func_name": "SyncExifProfile", "_file_name": "MagickCore/profile.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void MAPIPrint(MAPIProps *p) {\n int j, i, index, h, x;\n DDWORD *ddword_ptr;\n DDWORD ddword_tmp;\n dtr thedate;\n MAPIProperty *mapi;\n variableLength *mapidata;\n variableLength vlTemp;\n int found;\n\n for (j = 0; j < p->count; j++) {\n mapi = &(p->properties[j]);\n printf(\" #%i: Type: [\", j);\n switch (PROP_TYPE(mapi->id)) {\n case PT_UNSPECIFIED:\n printf(\" NONE \"); break;\n case PT_NULL:\n printf(\" NULL \"); break;\n case PT_I2:\n printf(\" I2 \"); break;\n case PT_LONG:\n printf(\" LONG \"); break;\n case PT_R4:\n printf(\" R4 \"); break;\n case PT_DOUBLE:\n printf(\" DOUBLE \"); break;\n case PT_CURRENCY:\n printf(\"CURRENCY \"); break;\n case PT_APPTIME:\n printf(\"APP TIME \"); break;\n case PT_ERROR:\n printf(\" ERROR \"); break;\n case PT_BOOLEAN:\n printf(\" BOOLEAN \"); break;\n case PT_OBJECT:\n printf(\" OBJECT \"); break;\n case PT_I8:\n printf(\" I8 \"); break;\n case PT_STRING8:\n printf(\" STRING8 \"); break;\n case PT_UNICODE:\n printf(\" UNICODE \"); break;\n case PT_SYSTIME:\n printf(\"SYS TIME \"); break;\n case PT_CLSID:\n printf(\"OLE GUID \"); break;\n case PT_BINARY:\n printf(\" BINARY \"); break;\n default:\n printf(\"<%x>\", PROP_TYPE(mapi->id)); break;\n }\n\n printf(\"] Code: [\");\n if (mapi->custom == 1) {\n printf(\"UD:x%04x\", PROP_ID(mapi->id));\n } else {\n found = 0;\n for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {\n if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {\n printf(\"%s\", MPList[index].name);\n found = 1;\n }\n }\n if (found == 0) {\n printf(\"0x%04x\", PROP_ID(mapi->id));\n }\n }\n printf(\"]\\n\");\n if (mapi->namedproperty > 0) {\n for (i = 0; i < mapi->namedproperty; i++) {\n printf(\" Name: %s\\n\", mapi->propnames[i].data);\n }\n }\n for (i = 0; i < mapi->count; i++) {\n mapidata = &(mapi->data[i]);\n if (mapi->count > 1) {\n printf(\" [%i/%u] \", i, mapi->count);\n } else {\n printf(\" \");\n }\n printf(\"Size: %i\", mapidata->size);\n switch (PROP_TYPE(mapi->id)) {\n case PT_SYSTIME:\n MAPISysTimetoDTR(mapidata->data, &thedate);\n printf(\" Value: \");\n ddword_tmp = *((DDWORD *)mapidata->data);\n TNEFPrintDate(thedate);\n printf(\" [HEX: \");\n for (x = 0; x < sizeof(ddword_tmp); x++) {\n printf(\" %02x\", (BYTE)mapidata->data[x]);\n }\n printf(\"] (%llu)\\n\", ddword_tmp);\n break;\n case PT_LONG:\n printf(\" Value: %li\\n\", *((long*)mapidata->data));\n break;\n case PT_I2:\n printf(\" Value: %hi\\n\", *((short int*)mapidata->data));\n break;\n case PT_BOOLEAN:\n if (mapi->data->data[0] != 0) {\n printf(\" Value: True\\n\");\n } else {\n printf(\" Value: False\\n\");\n }\n break;\n case PT_OBJECT:\n printf(\"\\n\");\n break;\n case PT_BINARY:\n if (IsCompressedRTF(mapidata) == 1) {\n printf(\" Detected Compressed RTF. \");\n printf(\"Decompressed text follows\\n\");\n printf(\"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\n\");\n if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {\n printf(\"%s\\n\", vlTemp.data);\n free(vlTemp.data);\n }\n printf(\"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\n\");\n } else {\n printf(\" Value: [\");\n for (h = 0; h < mapidata->size; h++) {\n if (isprint(mapidata->data[h])) {\n printf(\"%c\", mapidata->data[h]);\n } else {\n printf(\".\");\n }\n\n }\n printf(\"]\\n\");\n }\n break;\n case PT_STRING8:\n printf(\" Value: [%s]\\n\", mapidata->data);\n if (strlen((char*)mapidata->data) != mapidata->size - 1) {\n printf(\"Detected Hidden data: [\");\n for (h = 0; h < mapidata->size; h++) {\n if (isprint(mapidata->data[h])) {\n printf(\"%c\", mapidata->data[h]);\n } else {\n printf(\".\");\n }\n\n }\n printf(\"]\\n\");\n }\n break;\n case PT_CLSID:\n printf(\" Value: \");\n printf(\"[HEX: \");\n for(x=0; x< 16; x++) {\n printf(\" %02x\", (BYTE)mapidata->data[x]);\n }\n printf(\"]\\n\");\n break;\n default:\n printf(\" Value: [%s]\\n\", mapidata->data);\n }\n }\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2731, 2795]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2731, 2795]]}, "_func_name": "MAPIPrint", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _checkPairing():\n if winner == loser:\n raise ValueError('Attempt to match player against self')\n\n q = '''\n SELECT COUNT(*) FROM matches\n WHERE (matches.winner_id = %s AND matches.loser_id = %s)\n OR (matches.winner_id = %s AND matches.loser_id = %s);\n ''' % (winner, loser, loser, winner)\n cur.execute(q)\n if cur.fetchone()[0] > 0:\n raise ValueError('Pairing %s, %s already played' % (winner, loser))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[310, 378]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[310, 378]]}, "_func_name": "reportMatch._checkPairing", "_file_name": "vagrant/tournament/tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def retrieve_videos_from_playlist(playlist_id, db):\n db.execute(\"SELECT id, title, thumbnail, position from video WHERE playlist_id={playlist_id} ORDER BY position ASC;\".format(\n playlist_id=playlist_id))\n rows = db.fetchall()\n return rows", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[52, 215]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[52, 215]]}, "_func_name": "retrieve_videos_from_playlist", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)\n{\n\tbee_t *bee = ic->bee;\n\tbee_user_t *bu = bee_user_by_handle(bee, ic, handle);\n\n\tif (bee->ui->ft_in_start) {\n\t\treturn bee->ui->ft_in_start(bee, bu, file_name, file_size);\n\t} else {\n\t\treturn NULL;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[194, 223]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[194, 223]]}, "_func_name": "imcb_file_send_start", "_file_name": "protocols/bee_ft.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "PlayerGeneric::~PlayerGeneric()\n{\n\tif (mixer)\n\t\tdelete mixer;\n\n\tif (player)\n\t{\n\t\tif (mixer->isActive() && !mixer->isDeviceRemoved(player))\n\t\t\tmixer->removeDevice(player);\n\t\tdelete player;\n\t}\n\n\tdelete[] audioDriverName;\n\t\n\tdelete listener;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[34, 62]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[34, 62]]}, "_func_name": "PlayerGeneric::~PlayerGeneric", "_file_name": "src/milkyplay/PlayerGeneric.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "xdp_umem_reg", "_file_name": "net/xdp/xdp_umem.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _modify_3par_fibrechan_host(self, hostname, wwns):\n # when using -add, you can not send the persona or domain options\n command = ['createhost', '-add', hostname]\n for wwn in wwns:\n command.append(wwn)\n\n out = self.common._cli_run(command)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_modify_3par_fibrechan_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_fc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_sources(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the source table.\n \"\"\"\n current_sources = get_all_current_sources(k10plus, ai)\n old_sources = get_all_old_sources(conn, sqlite)\n\n # Check if the source table is allready filled and this is not the first checkup\n source_table_is_filled = len(old_sources) > 100\n\n for old_source in old_sources:\n if source_table_is_filled and old_source not in current_sources:\n message = \"Die SID %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die SID aus der Datenbank loeschen.\" % old_source\n send_message(message)\n\n for current_source in current_sources:\n if current_source not in old_sources:\n message = \"The source %s is new in Solr.\" % current_source\n if source_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO source (source) VALUES (?)\"\n sqlite.execute(sql, (current_source,))\n conn.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_sources", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def getQueue(self, numberOfLinks=10):\n self.cursor.execute(\"SELECT url FROM queue WHERE visited = '0' LIMIT ?;\", numberOfLinks)\n result = self.cursor.fetchall()\n self.remove(result)\n return result", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getQueue", "_file_name": "beta/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tstruct ahash_request *req = &ctx->req;\n\tchar state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];\n\tstruct sock *sk2;\n\tstruct alg_sock *ask2;\n\tstruct hash_ctx *ctx2;\n\tint err;\n\n\terr = crypto_ahash_export(req, state);\n\tif (err)\n\t\treturn err;\n\n\terr = af_alg_accept(ask->parent, newsock);\n\tif (err)\n\t\treturn err;\n\n\tsk2 = newsock->sk;\n\task2 = alg_sk(sk2);\n\tctx2 = ask2->private;\n\tctx2->more = 1;\n\n\terr = crypto_ahash_import(&ctx2->req, state);\n\tif (err) {\n\t\tsock_orphan(sk2);\n\t\tsock_put(sk2);\n\t}\n\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[563, 580]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[563, 580]]}, "_func_name": "hash_accept", "_file_name": "crypto/algif_hash.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@then(parsers.parse(\"the hostname '{hostname}' should be resolved\"))\ndef resolve_hostname(busybox_pod, host, hostname):\n with host.sudo():\n # test dns resolve\n cmd_nslookup = (\"kubectl --kubeconfig=/etc/kubernetes/admin.conf\"\n \" exec -ti {0} nslookup {1}\".format(\n pod_name,\n hostname))\n res = host.run(cmd_nslookup)\n assert res.rc == 0, \"Cannot resolve {}\".format(hostname)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[120, 514]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[120, 514]]}, "_func_name": "resolve_hostname", "_file_name": "tests/post/steps/test_dns.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/quiz')\ndef quiz():\n\n varga = request.args.get('varga')\n\n try:\n rows =[]\n\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = ? order by random() limit 1;\", [varga])\n rows = cur.fetchall();\n\n artha = rows[0][\"artha\"];\n cur.execute(\"select pada from pada where varga = ? and artha = ? order by id\", [varga, artha]);\n paryaya = cur.fetchall();\n\n return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)\n finally:\n con.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "quiz", "_file_name": "docker/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/ranks\")\ndef ranks():\n if db == None:\n init()\n\n scene = request.args.get('scene', default='austin')\n date = request.args.get('date')\n \n # If no date was provided, pick the date of the latest tournament\n if date == None:\n sql = \"SELECT distinct date FROM ranks WHERE scene='{}' ORDER BY date DESC LIMIT 1;\".format(scene)\n res = db.exec(sql)\n date = res[0][0]\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, date)\n res = db.exec(sql)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n cur_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n cur_ranks[tag] = rank\n\n # Now get the ranks from last month, so we know if these players went up or down\n y, m, d = date.split('-')\n prev_date = bracket_utils.get_previous_month(date)\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{}' and date='{}'\".format(scene, prev_date)\n res = db.exec(sql)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n prev_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n prev_ranks[tag] = rank\n\n return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[260, 367], [480, 565], [994, 1084]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[260, 367], [480, 565], [994, 1084]]}, "_func_name": "ranks", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/placings\")\ndef placings():\n if db == None:\n init()\n\n tag = request.args.get('tag', default='christmas mike')\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM placings WHERE player = '{tag}'\"\n args = {'tag': tag}\n results = list(db.exec(sql, args))\n results.sort(key=lambda x: int(x[2]))\n\n return json.dumps(results)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "placings", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n auto const ch2 = *p++;\n auto const dch3 = dehexchar(*p++);\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n return false;\n }\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[646, 760]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[646, 760]]}, "_func_name": "HPHP::SimpleParser::handleBackslash", "_file_name": "hphp/runtime/ext/json/JSON_parser.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static void copyIPv6IfDifferent(void * dest, const void * src)\n{\n\tif(dest != src) {\n\t\tmemcpy(dest, src, sizeof(struct in6_addr));\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[65, 84]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[65, 84]]}, "_func_name": "copyIPv6IfDifferent", "_file_name": "miniupnpd/pcpserver.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n if \"player1\" not in form or \"player2\" not in form or \"size\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n player1 = form[\"player1\"].value\n player2 = form[\"player2\"].value\n for c in player1+player2:\n if c not in \"_-\" and not c.isdigit() and not c.isalpha():\n raise FormError(\"Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens\")\n return\n\n try:\n size = int(form[\"size\"].value)\n except:\n raise FormError(\"Invalid parameters: 'size' is not an integer.\")\n return\n\n if size < 2 or size > 9:\n raise FormError(\"The 'size' must be in the range 2-9, inclusive.\")\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n cursor = conn.cursor()\n\n # insert the new row\n cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\", (player1,player2,size))\n\n gameID = cursor.lastrowid\n\n\n # MySQLdb has been building a transaction as we run. Commit them now, and\n # also clean up the other resources we've allocated.\n conn.commit()\n cursor.close()\n conn.close()\n\n return gameID", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_form", "_file_name": "cgi/create_game.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int usb_console_setup(struct console *co, char *options)\n{\n\tstruct usbcons_info *info = &usbcons_info;\n\tint baud = 9600;\n\tint bits = 8;\n\tint parity = 'n';\n\tint doflow = 0;\n\tint cflag = CREAD | HUPCL | CLOCAL;\n\tchar *s;\n\tstruct usb_serial *serial;\n\tstruct usb_serial_port *port;\n\tint retval;\n\tstruct tty_struct *tty = NULL;\n\tstruct ktermios dummy;\n\n\tif (options) {\n\t\tbaud = simple_strtoul(options, NULL, 10);\n\t\ts = options;\n\t\twhile (*s >= '0' && *s <= '9')\n\t\t\ts++;\n\t\tif (*s)\n\t\t\tparity = *s++;\n\t\tif (*s)\n\t\t\tbits = *s++ - '0';\n\t\tif (*s)\n\t\t\tdoflow = (*s++ == 'r');\n\t}\n\t\n\t/* Sane default */\n\tif (baud == 0)\n\t\tbaud = 9600;\n\n\tswitch (bits) {\n\tcase 7:\n\t\tcflag |= CS7;\n\t\tbreak;\n\tdefault:\n\tcase 8:\n\t\tcflag |= CS8;\n\t\tbreak;\n\t}\n\tswitch (parity) {\n\tcase 'o': case 'O':\n\t\tcflag |= PARODD;\n\t\tbreak;\n\tcase 'e': case 'E':\n\t\tcflag |= PARENB;\n\t\tbreak;\n\t}\n\tco->cflag = cflag;\n\n\t/*\n\t * no need to check the index here: if the index is wrong, console\n\t * code won't call us\n\t */\n\tport = usb_serial_port_get_by_minor(co->index);\n\tif (port == NULL) {\n\t\t/* no device is connected yet, sorry :( */\n\t\tpr_err(\"No USB device connected to ttyUSB%i\\n\", co->index);\n\t\treturn -ENODEV;\n\t}\n\tserial = port->serial;\n\n\tretval = usb_autopm_get_interface(serial->interface);\n\tif (retval)\n\t\tgoto error_get_interface;\n\n\ttty_port_tty_set(&port->port, NULL);\n\n\tinfo->port = port;\n\n\t++port->port.count;\n\tif (!tty_port_initialized(&port->port)) {\n\t\tif (serial->type->set_termios) {\n\t\t\t/*\n\t\t\t * allocate a fake tty so the driver can initialize\n\t\t\t * the termios structure, then later call set_termios to\n\t\t\t * configure according to command line arguments\n\t\t\t */\n\t\t\ttty = kzalloc(sizeof(*tty), GFP_KERNEL);\n\t\t\tif (!tty) {\n\t\t\t\tretval = -ENOMEM;\n\t\t\t\tgoto reset_open_count;\n\t\t\t}\n\t\t\tkref_init(&tty->kref);\n\t\t\ttty->driver = usb_serial_tty_driver;\n\t\t\ttty->index = co->index;\n\t\t\tinit_ldsem(&tty->ldisc_sem);\n\t\t\tspin_lock_init(&tty->files_lock);\n\t\t\tINIT_LIST_HEAD(&tty->tty_files);\n\t\t\tkref_get(&tty->driver->kref);\n\t\t\t__module_get(tty->driver->owner);\n\t\t\ttty->ops = &usb_console_fake_tty_ops;\n\t\t\ttty_init_termios(tty);\n\t\t\ttty_port_tty_set(&port->port, tty);\n\t\t}\n\n\t\t/* only call the device specific open if this\n\t\t * is the first time the port is opened */\n\t\tretval = serial->type->open(NULL, port);\n\t\tif (retval) {\n\t\t\tdev_err(&port->dev, \"could not open USB console port\\n\");\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif (serial->type->set_termios) {\n\t\t\ttty->termios.c_cflag = cflag;\n\t\t\ttty_termios_encode_baud_rate(&tty->termios, baud, baud);\n\t\t\tmemset(&dummy, 0, sizeof(struct ktermios));\n\t\t\tserial->type->set_termios(tty, port, &dummy);\n\n\t\t\ttty_port_tty_set(&port->port, NULL);\n\t\t\ttty_kref_put(tty);\n\t\t}\n\t\ttty_port_set_initialized(&port->port, 1);\n\t}\n\t/* Now that any required fake tty operations are completed restore\n\t * the tty port count */\n\t--port->port.count;\n\t/* The console is special in terms of closing the device so\n\t * indicate this port is now acting as a system console. */\n\tport->port.console = 1;\n\n\tmutex_unlock(&serial->disc_mutex);\n\treturn retval;\n\n fail:\n\ttty_port_tty_set(&port->port, NULL);\n\ttty_kref_put(tty);\n reset_open_count:\n\tport->port.count = 0;\n\tinfo->port = NULL;\n\tusb_autopm_put_interface(serial->interface);\n error_get_interface:\n\tusb_serial_put(serial);\n\tmutex_unlock(&serial->disc_mutex);\n\treturn retval;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usb_console_setup", "_file_name": "drivers/usb/serial/console.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _remove_volume_from_volume_set(self, volume_name, vvs_name):\n self._cli_run('removevvset -f %s %s' % (vvs_name, volume_name), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[69, 146]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[69, 146]]}, "_func_name": "_remove_volume_from_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost', '123456789012345',\n '123456789054321'])\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int __init big_key_init(void)\n{\n\treturn register_key_type(&key_type_big_key);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[39, 86]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[39, 86]]}, "_func_name": "big_key_init", "_file_name": "security/keys/big_key.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)\n{\n bool ok;\n XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };\n enum xkb_file_type type;\n struct xkb_context *ctx = keymap->ctx;\n\n /* Collect section files and check for duplicates. */\n for (file = (XkbFile *) file->defs; file;\n file = (XkbFile *) file->common.next) {\n if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||\n file->file_type > LAST_KEYMAP_FILE_TYPE) {\n if (file->file_type == FILE_TYPE_GEOMETRY) {\n log_vrb(ctx, 1,\n \"Geometry sections are not supported; ignoring\\n\");\n } else {\n log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n xkb_file_type_to_string(file->file_type));\n }\n continue;\n }\n\n if (files[file->file_type]) {\n log_err(ctx,\n \"More than one %s section in keymap file; \"\n \"All sections after the first ignored\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n files[file->file_type] = file;\n }\n\n /*\n * Check that all required section were provided.\n * Report everything before failing.\n */\n ok = true;\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n if (files[type] == NULL) {\n log_err(ctx, \"Required section %s missing from keymap\\n\",\n xkb_file_type_to_string(type));\n ok = false;\n }\n }\n if (!ok)\n return false;\n\n /* Compile sections. */\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n log_dbg(ctx, \"Compiling %s \\\"%s\\\"\\n\",\n xkb_file_type_to_string(type), files[type]->name);\n\n ok = compile_file_fns[type](files[type], keymap, merge);\n if (!ok) {\n log_err(ctx, \"Failed to compile %s\\n\",\n xkb_file_type_to_string(type));\n return false;\n }\n }\n\n return UpdateDerivedKeymapFields(keymap);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "CompileKeymap", "_file_name": "src/xkbcomp/keymap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def fetch_page_name(self, page_id):\n '''\n Returns the page name corresponding to the provided page ID.\n\n Args:\n page_id: The page ID whose ID to fetch.\n\n Returns:\n str: The page name corresponding to the provided page ID.\n\n Raises:\n ValueError: If the provided page ID is invalid or does not exist.\n '''\n helpers.validate_page_id(page_id)\n\n query = 'SELECT name FROM pages WHERE id=\"{0}\"'.format(page_id)\n self.cursor.execute(query)\n\n page_name = self.cursor.fetchone()\n\n if not page_name:\n raise ValueError('Invalid page ID \"{0}\" provided. Page ID does not exist.'.format(page_id))\n\n return page_name[0].encode('utf-8').replace('_', ' ')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[378, 446]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[378, 446]]}, "_func_name": "fetch_page_name", "_file_name": "sdow/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_top_popular(top_num):\r\n \"\"\" query the top(top_num) popular articles\r\n top_num => list of [title, count]\r\n \"\"\"\r\n cmd = \"\"\"SELECT title, views FROM articles\r\n INNER JOIN (\r\n SELECT path, count(path) AS views\r\n FROM log GROUP BY log.path\r\n ) AS log\r\n ON log.path = '/article/' || articles.slug\r\n ORDER BY views DESC\r\n LIMIT %s\"\"\"\r\n data = [top_num, ]\r\n return execute_query(cmd, data)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_top_popular", "_file_name": "logAnalyzerDb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_top_author(top_num):\r\n \"\"\" query the top(top_num) popular author\r\n top_num => list of [author, count]\r\n \"\"\"\r\n cmd = \"\"\"SELECT authors.name,author_result.num\r\n FROM authors JOIN\r\n (SELECT SUM(article_result.num) as num,\r\n article_result.author\r\n from (SELECT articles.title, articles.author,\r\n SUM(log.views) AS num\r\n FROM articles\r\n INNER JOIN (\r\n SELECT path, count(path) AS views\r\n FROM log GROUP BY log.path\r\n ) AS log ON log.path = '/article/'\r\n || articles.slug\r\n GROUP BY articles.title, articles.author)\r\n AS article_result\r\n GROUP BY article_result.author) as author_result\r\n ON authors.id = author_result.author\r\n ORDER BY num DESC LIMIT %s\"\"\"\r\n data = [top_num, ]\r\n return execute_query(cmd, data)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_top_author", "_file_name": "logAnalyzerDb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tconst char *section_name = \"\";\n\tconst char *link_section_name = \"\";\n\tchar *end = NULL;\n\tElf_(Shdr) *link_shdr = NULL;\n\tut8 dfs[sizeof (Elf_(Verdef))] = {0};\n\tSdb *sdb;\n\tint cnt, i;\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn false;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (shdr->sh_size < 1) {\n\t\treturn false;\n\t}\n\tElf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));\n\tif (!defs) {\n\t\treturn false;\n\t}\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!defs) {\n\t\tbprintf (\"Warning: Cannot allocate memory (Check Elf_(Verdef))\\n\");\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tend = (char *)defs + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {\n\t\tSdb *sdb_verdef = sdb_new0 ();\n\t\tchar *vstart = ((char*)defs) + i;\n\t\tchar key[32] = {0};\n\t\tElf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;\n\t\tElf_(Verdaux) aux = {0};\n\t\tint j = 0;\n\t\tint isum = 0;\n\n\t\tr_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));\n\t\tverdef->vd_version = READ16 (dfs, j)\n\t\tverdef->vd_flags = READ16 (dfs, j)\n\t\tverdef->vd_ndx = READ16 (dfs, j)\n\t\tverdef->vd_cnt = READ16 (dfs, j)\n\t\tverdef->vd_hash = READ32 (dfs, j)\n\t\tverdef->vd_aux = READ32 (dfs, j)\n\t\tverdef->vd_next = READ32 (dfs, j)\n\t\tint vdaux = verdef->vd_aux;\n\t\tif (vdaux < 1) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tvstart += vdaux;\n\t\tif (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tj = 0;\n\t\taux.vda_name = READ32 (vstart, j)\n\t\taux.vda_next = READ32 (vstart, j)\n\n\t\tisum = i + verdef->vd_aux;\n\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tsdb_num_set (sdb_verdef, \"idx\", i, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_version\", verdef->vd_version, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_ndx\", verdef->vd_ndx, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_cnt\", verdef->vd_cnt, 0);\n\t\tsdb_set (sdb_verdef, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\tsdb_set (sdb_verdef, \"flags\", get_ver_flags (verdef->vd_flags), 0);\n\n\t\tfor (j = 1; j < verdef->vd_cnt; ++j) {\n\t\t\tint k;\n\t\t\tSdb *sdb_parent = sdb_new0 ();\n\t\t\tisum += aux.vda_next;\n\t\t\tvstart += aux.vda_next;\n\t\t\tif (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tk = 0;\n\t\t\taux.vda_name = READ32 (vstart, k)\n\t\t\taux.vda_next = READ32 (vstart, k)\n\t\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_parent, \"idx\", isum, 0);\n\t\t\tsdb_num_set (sdb_parent, \"parent\", j, 0);\n\t\t\tsdb_set (sdb_parent, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\t\tsnprintf (key, sizeof (key), \"parent%d\", j - 1);\n\t\t\tsdb_ns_set (sdb_verdef, key, sdb_parent);\n\t\t}\n\n\t\tsnprintf (key, sizeof (key), \"verdef%d\", cnt);\n\t\tsdb_ns_set (sdb, key, sdb_verdef);\n\t\tif (!verdef->vd_next) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tif ((st32)verdef->vd_next < 1) {\n\t\t\teprintf (\"Warning: Invalid vd_next in the ELF version\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += verdef->vd_next;\n\t}\n\tfree (defs);\n\treturn sdb;\nout_error:\n\tfree (defs);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "store_versioninfo_gnu_verdef", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "lexer_process_char_literal (parser_context_t *context_p, /**< context */\n const uint8_t *char_p, /**< characters */\n size_t length, /**< length of string */\n uint8_t literal_type, /**< final literal type */\n bool has_escape) /**< has escape sequences */\n{\n parser_list_iterator_t literal_iterator;\n lexer_literal_t *literal_p;\n uint32_t literal_index = 0;\n\n JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL\n || literal_type == LEXER_STRING_LITERAL);\n\n JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);\n JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);\n\n parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);\n\n while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (literal_p->type == literal_type\n && literal_p->prop.length == length\n && memcmp (literal_p->u.char_p, char_p, length) == 0)\n {\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);\n return;\n }\n\n literal_index++;\n }\n\n JERRY_ASSERT (literal_index == context_p->literal_count);\n\n if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)\n {\n parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);\n }\n\n literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);\n literal_p->prop.length = (uint16_t) length;\n literal_p->type = literal_type;\n literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;\n\n if (has_escape)\n {\n literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);\n memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);\n }\n else\n {\n literal_p->u.char_p = char_p;\n }\n\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n context_p->literal_count++;\n} /* lexer_process_char_literal */", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1556, 1648]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1556, 1648]]}, "_func_name": "lexer_process_char_literal", "_file_name": "jerry-core/parser/js/js-lexer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int mailimf_group_parse(const char * message, size_t length,\n\t\t\t size_t * indx,\n\t\t\t struct mailimf_group ** result)\n{\n size_t cur_token;\n char * display_name;\n struct mailimf_mailbox_list * mailbox_list;\n struct mailimf_group * group;\n int r;\n int res;\n\n cur_token = * indx;\n\n mailbox_list = NULL;\n\n r = mailimf_display_name_parse(message, length, &cur_token, &display_name);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto err;\n }\n\n r = mailimf_colon_parse(message, length, &cur_token);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto free_display_name;\n }\n\n r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);\n switch (r) {\n case MAILIMF_NO_ERROR:\n break;\n case MAILIMF_ERROR_PARSE:\n r = mailimf_cfws_parse(message, length, &cur_token);\n if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {\n res = r;\n goto free_display_name;\n }\n break;\n default:\n res = r;\n goto free_display_name;\n }\n\n r = mailimf_semi_colon_parse(message, length, &cur_token);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto free_mailbox_list;\n }\n\n group = mailimf_group_new(display_name, mailbox_list);\n if (group == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n goto free_mailbox_list;\n }\n\n * indx = cur_token;\n * result = group;\n\n return MAILIMF_NO_ERROR;\n\n free_mailbox_list:\n if (mailbox_list != NULL) {\n mailimf_mailbox_list_free(mailbox_list);\n }\n free_display_name:\n mailimf_display_name_free(display_name);\n err:\n return res;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[278, 279]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[278, 279]]}, "_func_name": "mailimf_group_parse", "_file_name": "src/low-level/imf/mailimf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/quiz')\ndef quiz():\n\n varga = request.args.get('varga')\n\n try:\n rows =[]\n\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from pada inner join mula on pada.sloka_line = mula.sloka_line where pada.varga = '%s' order by random() limit 1;\" % varga)\n rows = cur.fetchall();\n\n artha = rows[0][\"artha\"];\n cur.execute(\"select pada from pada where varga = '%s' and artha = '%s' order by id\" % (varga, artha));\n paryaya = cur.fetchall();\n\n return render_template('quiz.html', rows=rows, paryaya=paryaya, varga=varga)\n finally:\n con.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[213, 371], [445, 560]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[213, 371], [445, 560]]}, "_func_name": "quiz", "_file_name": "docker/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "autodetect_recv_bandwidth_measure_results", "_file_name": "libfreerdp/core/autodetect.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _cliq_run(self, verb, cliq_args, check_exit_code=True):\n \"\"\"Runs a CLIQ command over SSH, without doing any result parsing\"\"\"\n cmd_list = [verb]\n for k, v in cliq_args.items():\n cmd_list.append(\"%s=%s\" % (k, v))\n\n return self._run_ssh(cmd_list, check_exit_code)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_cliq_run", "_file_name": "cinder/volume/drivers/san/hp_lefthand.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@hook.command(adminonly=True)\ndef openPoll(question, reply=None, db=None):\n \"\"\"Creates a new poll.\"\"\"\n if not db_ready: db_init(db)\n try:\n active = db.execute(\"SELECT pollID FROM polls WHERE active = 1\").fetchone()[0]\n if active: \n reply(\"There already is an open poll.\")\n return\n except:\n db.execute(\"INSERT INTO polls (question, active) VALUES (?, 1)\", (question,))\n reply(\"Opened new poll: {}\".format(question))\n #reply(\"Poll opened!\")\n return", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "openPoll", "_file_name": "plugins/poll.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def new_category(category_name):\n try:\n conn = check_heroku_db()\n cur = conn.cursor()\n\n query = \"INSERT INTO categories (cat_name) VALUES (%s);\"\n data = (category_name,)\n cur.execute(query, data)\n\n conn.commit()\n conn.close()\n\n except psycopg2.DatabaseError as e:\n print('Error %s' % e)\n sys.exit(1)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "new_category", "_file_name": "db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def shame_ask(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n SELECT shame FROM people WHERE name='{}'\n '''.format(name))\n shame = cursor.fetchone()\n db.close()\n if shame is None:\n logger.debug('No shame found for name {}'.format(name))\n return shame\n else:\n shame = shame[0]\n logger.debug('shame of {} found for name {}'.format(shame, name))\n return shame\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[104, 187]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[104, 187]]}, "_func_name": "shame_ask", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void copyIPv6IfDifferent(void * dest, const void * src)\n{\n\tif(dest != src && src != NULL) {\n\t\tmemcpy(dest, src, sizeof(struct in6_addr));\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "copyIPv6IfDifferent", "_file_name": "miniupnpd/pcpserver.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):\n # Ensure vdisk has no FlashCopy mappings\n mapping_ids = self._get_vdisk_fc_mappings(name)\n while len(mapping_ids):\n wait_for_copy = False\n for map_id in mapping_ids:\n attrs = self._get_flashcopy_mapping_attributes(map_id)\n if not attrs:\n continue\n source = attrs['source_vdisk_name']\n target = attrs['target_vdisk_name']\n copy_rate = attrs['copy_rate']\n status = attrs['status']\n\n if copy_rate == '0':\n # Case #2: A vdisk that has snapshots\n if source == name:\n if not allow_snaps:\n return False\n ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',\n '-autodelete', 'on', map_id]\n out, err = self._run_ssh(ssh_cmd)\n wait_for_copy = True\n # Case #3: A snapshot\n else:\n msg = (_('Vdisk %(name)s not involved in '\n 'mapping %(src)s -> %(tgt)s') %\n {'name': name, 'src': source, 'tgt': target})\n self._driver_assert(target == name, msg)\n if status in ['copying', 'prepared']:\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n elif status in ['stopping', 'preparing']:\n wait_for_copy = True\n else:\n self._run_ssh(['svctask', 'rmfcmap', '-force',\n map_id])\n # Case 4: Copy in progress - wait and will autodelete\n else:\n if status == 'prepared':\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n elif status == 'idle_or_copied':\n # Prepare failed\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n else:\n wait_for_copy = True\n if wait_for_copy:\n time.sleep(5)\n mapping_ids = self._get_vdisk_fc_mappings(name)\n return True", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_ensure_vdisk_no_fc_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mkdir(self, data, path):\n credentials = self._formatCredentials(data, name='current')\n\n command = (\n '{credentials} '\n 'rclone touch current:{path}/.keep'\n ).format(\n credentials=credentials,\n path=path,\n )\n\n try:\n result = self._execute(command)\n return {\n 'message': 'Success',\n }\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[101, 287]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[101, 287]]}, "_func_name": "mkdir", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,\n\t\t UChar* range, UChar** low, UChar** high, UChar** low_prev)\n{\n UChar *p, *pprev = (UChar* )NULL;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"forward_search_range: str: %d, end: %d, s: %d, range: %d\\n\",\n\t (int )str, (int )end, (int )s, (int )range);\n#endif\n\n p = s;\n if (reg->dmin > 0) {\n if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {\n p += reg->dmin;\n }\n else {\n UChar *q = p + reg->dmin;\n\n if (q >= end) return 0; /* fail */\n while (p < q) p += enclen(reg->enc, p);\n }\n }\n\n retry:\n switch (reg->optimize) {\n case ONIG_OPTIMIZE_EXACT:\n p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);\n break;\n case ONIG_OPTIMIZE_EXACT_IC:\n p = slow_search_ic(reg->enc, reg->case_fold_flag,\n reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM:\n p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:\n p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_MAP:\n p = map_search(reg->enc, reg->map, p, range);\n break;\n }\n\n if (p && p < range) {\n if (p - reg->dmin < s) {\n retry_gate:\n pprev = p;\n p += enclen(reg->enc, p);\n goto retry;\n }\n\n if (reg->sub_anchor) {\n UChar* prev;\n\n switch (reg->sub_anchor) {\n case ANCHOR_BEGIN_LINE:\n if (!ON_STR_BEGIN(p)) {\n prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n }\n break;\n\n case ANCHOR_END_LINE:\n if (ON_STR_END(p)) {\n#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE\n prev = (UChar* )onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n#endif\n }\n else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)\n#ifdef USE_CRNL_AS_LINE_TERMINATOR\n && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)\n#endif\n )\n goto retry_gate;\n break;\n }\n }\n\n if (reg->dmax == 0) {\n *low = p;\n if (low_prev) {\n if (*low > s)\n *low_prev = onigenc_get_prev_char_head(reg->enc, s, p);\n else\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n }\n }\n else {\n if (reg->dmax != ONIG_INFINITE_DISTANCE) {\n *low = p - reg->dmax;\n if (*low > s) {\n *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,\n *low, (const UChar** )low_prev);\n if (low_prev && IS_NULL(*low_prev))\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : s), *low);\n }\n else {\n if (low_prev)\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), *low);\n }\n }\n }\n /* no needs to adjust *high, *high is used as range check only */\n *high = p - reg->dmin;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr,\n \"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\\n\",\n\t (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);\n#endif\n return 1; /* success */\n }\n\n return 0; /* fail */\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "forward_search_range", "_file_name": "src/regexec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def analyze_smashgg(self, urls, name):\n LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls)))\n for url in urls:\n # Before we process this URL, check to see if we already have\n sql = \"SELECT * FROM analyzed where base_url='{url}'\"\n args = {'url':url}\n res = self.db.exec(sql, args)\n if len(res) == 0:\n\n display_name = bracket_utils.get_display_base(url)\n\n # We don't care about doubles tournaments\n if 'doubles' in display_name.lower() or 'dubs' in display_name.lower():\n LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name))\n continue\n\n LOG.info('About to process pro bracket {}'.format(url))\n self.data_processor.process(url, name, display_name)\n else:\n LOG.info(\"Skpping pro bracket because it has already been analyzed: {}\".format(url))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "analyze_smashgg", "_file_name": "validURLs.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit/', methods=['GET', 'POST'])\ndef edit(msg_id):\n m = None\n if request.method == 'GET':\n cursor.execute(\"SELECT * FROM message where msg_id = %s;\", (msg_id,))\n m = cursor.fetchone()\n return render_template('message/edit.html', m=m, msg_id=msg_id)\n\n if request.method == 'POST':\n content = request.form['content']\n cursor.execute(\"UPDATE message SET content = %s where msg_id = %s;\", (content, msg_id))\n conn.commit()\n flash('Edit Success!')\n return redirect(url_for('show_entries'))\n\n return render_template('message/edit.html', m=m, msg_id=msg_id)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def cut(self, key):\n try:\n self.etcd.delete(self._absolute_key(key))\n except etcd.EtcdKeyNotFound:\n return False\n except etcd.EtcdException as err:\n log_error(\"Error removing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to cut key')\n return True", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cut", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpc_pi_nextrpcl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tint compno;\n\tjpc_picomp_t *picomp;\n\tint xstep;\n\tint ystep;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->xstep = 0;\n\t\tpi->ystep = 0;\n\t\tfor (compno = 0, picomp = pi->picomps; compno < pi->numcomps;\n\t\t ++compno, ++picomp) {\n\t\t\tfor (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <\n\t\t\t picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\t\t// Check for the potential for overflow problems.\n\t\t\t\tif (pirlvl->prcwidthexpn + picomp->numrlvls >\n\t\t\t\t JAS_UINTFAST32_NUMBITS - 2 ||\n\t\t\t\t pirlvl->prcheightexpn + picomp->numrlvls >\n\t\t\t\t JAS_UINTFAST32_NUMBITS - 2) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\txstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t\t\t (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));\n\t\t\t\tystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t\t\t (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));\n\t\t\t\tpi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);\n\t\t\t\tpi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);\n\t\t\t}\n\t\t}\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&\n\t pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {\n\t\tfor (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=\n\t\t pi->ystep - (pi->y % pi->ystep)) {\n\t\t\tfor (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=\n\t\t\t pi->xstep - (pi->x % pi->xstep)) {\n\t\t\t\tfor (pi->compno = pchg->compnostart,\n\t\t\t\t pi->picomp = &pi->picomps[pi->compno];\n\t\t\t\t pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <\n\t\t\t\t pi->numcomps; ++pi->compno, ++pi->picomp) {\n\t\t\t\t\tif (pi->rlvlno >= pi->picomp->numrlvls) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\tif (((pi->x == pi->xstart &&\n\t\t\t\t\t ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))\n\t\t\t\t\t || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart &&\n\t\t\t\t\t ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))\n\t\t\t\t\t || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,\n\t\t\t\t\t\t pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -\n\t\t\t\t\t\t JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,\n\t\t\t\t\t\t pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -\n\t\t\t\t\t\t JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;\n\n\t\t\t\t\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno <\n\t\t\t\t\t\t pi->numlyrs && pi->lyrno < JAS_CAST(int,\n\t\t\t\t\t\t pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jpc_pi_nextrpcl", "_file_name": "src/libjasper/jpc/jpc_t2cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " */\nstatic void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)\n{\n\tst_entry ent;\n\twddx_stack *stack = (wddx_stack *)user_data;\n\n\tif (!strcmp(name, EL_PACKET)) {\n\t\tint i;\n\n\t\tif (atts) for (i=0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_VERSION)) {\n\t\t\t\t/* nothing for now */\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_STRING)) {\n\t\tent.type = ST_STRING;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_STRING;\n\t\tZ_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();\n\t\tZ_STRLEN_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_BINARY)) {\n\t\tent.type = ST_BINARY;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_STRING;\n\t\tZ_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();\n\t\tZ_STRLEN_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_CHAR)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tchar tmp_buf[2];\n\n\t\t\t\tsnprintf(tmp_buf, sizeof(tmp_buf), \"%c\", (char)strtol(atts[i+1], NULL, 16));\n\t\t\t\tphp_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_NUMBER)) {\n\t\tent.type = ST_NUMBER;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_LONG;\n\t\tZ_LVAL_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_BOOLEAN)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tent.type = ST_BOOLEAN;\n\t\t\t\tSET_STACK_VARNAME;\n\n\t\t\t\tALLOC_ZVAL(ent.data);\n\t\t\t\tINIT_PZVAL(ent.data);\n\t\t\t\tZ_TYPE_P(ent.data) = IS_BOOL;\n\t\t\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t\t\t\tphp_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tent.type = ST_BOOLEAN;\n\t\t\tSET_STACK_VARNAME;\n\t\t\tZVAL_FALSE(&ent.data);\n\t\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t\t}\n\t} else if (!strcmp(name, EL_NULL)) {\n\t\tent.type = ST_NULL;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZVAL_NULL(ent.data);\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_ARRAY)) {\n\t\tent.type = ST_ARRAY;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_STRUCT)) {\n\t\tent.type = ST_STRUCT;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_VAR)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tif (stack->varname) efree(stack->varname);\n\t\t\t\tstack->varname = estrdup(atts[i+1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_RECORDSET)) {\n\t\tint i;\n\n\t\tent.type = ST_RECORDSET;\n\t\tSET_STACK_VARNAME;\n\t\tMAKE_STD_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], \"fieldNames\") && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tzval *tmp;\n\t\t\t\tchar *key;\n\t\t\t\tchar *p1, *p2, *endp;\n\n\t\t\t\ti++;\n\t\t\t\tendp = (char *)atts[i] + strlen(atts[i]);\n\t\t\t\tp1 = (char *)atts[i];\n\t\t\t\twhile ((p2 = php_memnstr(p1, \",\", sizeof(\",\")-1, endp)) != NULL) {\n\t\t\t\t\tkey = estrndup(p1, p2 - p1);\n\t\t\t\t\tMAKE_STD_ZVAL(tmp);\n\t\t\t\t\tarray_init(tmp);\n\t\t\t\t\tadd_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);\n\t\t\t\t\tp1 = p2 + sizeof(\",\")-1;\n\t\t\t\t\tefree(key);\n\t\t\t\t}\n\n\t\t\t\tif (p1 <= endp) {\n\t\t\t\t\tMAKE_STD_ZVAL(tmp);\n\t\t\t\t\tarray_init(tmp);\n\t\t\t\t\tadd_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tint i;\n\t\tst_entry ent;\n\n\t\tent.type = ST_FIELD;\n\t\tent.varname = NULL;\n\t\tent.data = NULL;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tst_entry *recordset;\n\t\t\t\tzval **field;\n\n\t\t\t\tif (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&\n\t\t\t\t\trecordset->type == ST_RECORDSET &&\n\t\t\t\t\tzend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {\n\t\t\t\t\tent.data = *field;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_DATETIME)) {\n\t\tent.type = ST_DATETIME;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_LONG;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "php_wddx_push_element", "_file_name": "ext/wddx/wddx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def mode_keepalive(self, request):\n \"\"\"\n This is called by render_POST when the\n client is replying to the keepalive.\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n self.last_alive[csessid] = (time.time(), False)\n return '\"\"'", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mode_keepalive", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connect()\n try:\n # The following introduces a deliberate security flaw. \n # See section on SQL injection below\n query = \"INSERT INTO crimes (description) VALUES('{}');\".format(data)\n with connection.cursor() as cursor:\n cursor.execute(query)\n connection.commit()\n finally:\n connection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[197, 279]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[197, 279]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def poll(self, poll_input):\n username = poll_input.credentials.username\n password = poll_input.credentials.password\n domain = poll_input.credentials.domain\n \n if domain is None:\n opt_str = '--ignore-certificate --authonly -u \\'{}\\' -p \\'{}\\' {}:{}'\n options = opt_str.format(\n username, password,\n poll_input.server, poll_input.port)\n else:\n opt_str = '--ignore-certificate --authonly -d {} -u \\'{}\\' -p \\'{}\\' {}:{}'\n options = opt_str.format(\n domain.domain, username, password,\n poll_input.server, poll_input.port)\n\n try:\n output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)\n result = RdpPollResult(True)\n return result\n except Exception as e:\n if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):\n result = RdpPollResult(True)\n return result\n print(\"{{{{%s}}}}\" % e.output)\n result = RdpPollResult(False, e)\n return result", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "poll", "_file_name": "polling/poll_rdp.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "async def save(request):\n # TODO csrf\n data = await request.post()\n item = Item(data['src'])\n\n # Update name\n new_src = data.get('new_src')\n if new_src:\n new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src)\n if not new_abspath.startswith(settings.STORAGE_DIR):\n return web.Response(status=400, body=b'Invalid Request')\n\n if new_abspath != item.abspath:\n shutil.move(item.abspath, new_abspath)\n old_backup_abspath = item.backup_abspath\n item = Item(new_src)\n if os.path.isfile(old_backup_abspath):\n shutil.move(old_backup_abspath, item.backup_abspath)\n\n # Update meta\n for field in item.FORM:\n # TODO handle .repeatable (keywords)\n item.meta[field] = [data.get(field, '')]\n\n if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):\n shutil.copyfile(item.abspath, item.backup_abspath)\n\n # WISHLIST don't write() if nothing changed\n item.meta.write()\n\n return web.Response(\n status=200,\n body=json.dumps(item.get_form_fields()).encode('utf8'),\n content_type='application/json',\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "save", "_file_name": "gallery/gallery.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/overview/')\ndef overview(classNum):\n\tif 'username' in session:\n\t\tclassNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]\n\n\t\t#Save the current course as a session variable.\n\t\tsession['currentCourse'] = classNoSpace\n\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor()\n\n\t\tcursor.execute(\"SELECT courseName,courseOverview from courses where courseAbbreviation='\" + classNoSpace + \"'\")\n\t\tdata = cursor.fetchone()\n\n\t\treturn render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])\n\n\treturn redirect(url_for('index'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[294, 408]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[294, 408]]}, "_func_name": "overview", "_file_name": "src/tech_track.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tops->destroy(dev);\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[823, 870]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[823, 870]]}, "_func_name": "kvm_ioctl_create_device", "_file_name": "virt/kvm/kvm_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static inline void get_conn_text(const conn *c, const int af,\n char* addr, struct sockaddr *sock_addr) {\n char addr_text[MAXPATHLEN];\n addr_text[0] = '\\0';\n const char *protoname = \"?\";\n unsigned short port = 0;\n size_t pathlen = 0;\n\n switch (af) {\n case AF_INET:\n (void) inet_ntop(af,\n &((struct sockaddr_in *)sock_addr)->sin_addr,\n addr_text,\n sizeof(addr_text) - 1);\n port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port);\n protoname = IS_UDP(c->transport) ? \"udp\" : \"tcp\";\n break;\n\n case AF_INET6:\n addr_text[0] = '[';\n addr_text[1] = '\\0';\n if (inet_ntop(af,\n &((struct sockaddr_in6 *)sock_addr)->sin6_addr,\n addr_text + 1,\n sizeof(addr_text) - 2)) {\n strcat(addr_text, \"]\");\n }\n port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port);\n protoname = IS_UDP(c->transport) ? \"udp6\" : \"tcp6\";\n break;\n\n case AF_UNIX:\n // this strncpy call originally could piss off an address\n // sanitizer; we supplied the size of the dest buf as a limiter,\n // but optimized versions of strncpy could read past the end of\n // *src while looking for a null terminator. Since buf and\n // sun_path here are both on the stack they could even overlap,\n // which is \"undefined\". In all OSS versions of strncpy I could\n // find this has no effect; it'll still only copy until the first null\n // terminator is found. Thus it's possible to get the OS to\n // examine past the end of sun_path but it's unclear to me if this\n // can cause any actual problem.\n //\n // We need a safe_strncpy util function but I'll punt on figuring\n // that out for now.\n pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path);\n if (MAXPATHLEN <= pathlen) {\n pathlen = MAXPATHLEN - 1;\n }\n strncpy(addr_text,\n ((struct sockaddr_un *)sock_addr)->sun_path,\n pathlen);\n addr_text[pathlen] = '\\0';\n protoname = \"unix\";\n break;\n }\n\n if (strlen(addr_text) < 2) {\n /* Most likely this is a connected UNIX-domain client which\n * has no peer socket address, but there's no portable way\n * to tell for sure.\n */\n sprintf(addr_text, \"\", af);\n }\n\n if (port) {\n sprintf(addr, \"%s:%s:%u\", protoname, addr_text, port);\n } else {\n sprintf(addr, \"%s:%s\", protoname, addr_text);\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_conn_text", "_file_name": "memcached.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "size_t jsuGetFreeStack() {\n#ifdef ARM\n void *frame = __builtin_frame_address(0);\n size_t stackPos = (size_t)((char*)frame);\n size_t stackEnd = (size_t)((char*)&LINKER_END_VAR);\n if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow!\n return stackPos - stackEnd;\n#elif defined(LINUX)\n // On linux, we set STACK_BASE from `main`.\n char ptr; // this is on the stack\n extern void *STACK_BASE;\n uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr);\n const uint32_t max_stack = 1000000; // give it 1 megabyte of stack\n if (count>max_stack) return 0;\n return max_stack - count;\n#else\n // stack depth seems pretty platform-specific :( Default to a value that disables it\n return 1000000; // no stack depth check on this platform\n#endif\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jsuGetFreeStack", "_file_name": "src/jsutils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void MAPIPrint(MAPIProps *p) {\n int j, i, index, h, x;\n DDWORD *ddword_ptr;\n DDWORD ddword_tmp;\n dtr thedate;\n MAPIProperty *mapi;\n variableLength *mapidata;\n variableLength vlTemp;\n int found;\n\n for (j = 0; j < p->count; j++) {\n mapi = &(p->properties[j]);\n printf(\" #%i: Type: [\", j);\n switch (PROP_TYPE(mapi->id)) {\n case PT_UNSPECIFIED:\n printf(\" NONE \"); break;\n case PT_NULL:\n printf(\" NULL \"); break;\n case PT_I2:\n printf(\" I2 \"); break;\n case PT_LONG:\n printf(\" LONG \"); break;\n case PT_R4:\n printf(\" R4 \"); break;\n case PT_DOUBLE:\n printf(\" DOUBLE \"); break;\n case PT_CURRENCY:\n printf(\"CURRENCY \"); break;\n case PT_APPTIME:\n printf(\"APP TIME \"); break;\n case PT_ERROR:\n printf(\" ERROR \"); break;\n case PT_BOOLEAN:\n printf(\" BOOLEAN \"); break;\n case PT_OBJECT:\n printf(\" OBJECT \"); break;\n case PT_I8:\n printf(\" I8 \"); break;\n case PT_STRING8:\n printf(\" STRING8 \"); break;\n case PT_UNICODE:\n printf(\" UNICODE \"); break;\n case PT_SYSTIME:\n printf(\"SYS TIME \"); break;\n case PT_CLSID:\n printf(\"OLE GUID \"); break;\n case PT_BINARY:\n printf(\" BINARY \"); break;\n default:\n printf(\"<%x>\", PROP_TYPE(mapi->id)); break;\n }\n\n printf(\"] Code: [\");\n if (mapi->custom == 1) {\n printf(\"UD:x%04x\", PROP_ID(mapi->id));\n } else {\n found = 0;\n for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {\n if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {\n printf(\"%s\", MPList[index].name);\n found = 1;\n }\n }\n if (found == 0) {\n printf(\"0x%04x\", PROP_ID(mapi->id));\n }\n }\n printf(\"]\\n\");\n if (mapi->namedproperty > 0) {\n for (i = 0; i < mapi->namedproperty; i++) {\n printf(\" Name: %s\\n\", mapi->propnames[i].data);\n }\n }\n for (i = 0; i < mapi->count; i++) {\n mapidata = &(mapi->data[i]);\n if (mapi->count > 1) {\n printf(\" [%i/%u] \", i, mapi->count);\n } else {\n printf(\" \");\n }\n printf(\"Size: %i\", mapidata->size);\n switch (PROP_TYPE(mapi->id)) {\n case PT_SYSTIME:\n MAPISysTimetoDTR(mapidata->data, &thedate);\n printf(\" Value: \");\n ddword_tmp = *((DDWORD *)mapidata->data);\n TNEFPrintDate(thedate);\n printf(\" [HEX: \");\n for (x = 0; x < sizeof(ddword_tmp); x++) {\n printf(\" %02x\", (BYTE)mapidata->data[x]);\n }\n printf(\"] (%llu)\\n\", ddword_tmp);\n break;\n case PT_LONG:\n printf(\" Value: %i\\n\", *((int*)mapidata->data));\n break;\n case PT_I2:\n printf(\" Value: %hi\\n\", *((short int*)mapidata->data));\n break;\n case PT_BOOLEAN:\n if (mapi->data->data[0] != 0) {\n printf(\" Value: True\\n\");\n } else {\n printf(\" Value: False\\n\");\n }\n break;\n case PT_OBJECT:\n printf(\"\\n\");\n break;\n case PT_BINARY:\n if (IsCompressedRTF(mapidata) == 1) {\n printf(\" Detected Compressed RTF. \");\n printf(\"Decompressed text follows\\n\");\n printf(\"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\n\");\n if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {\n printf(\"%s\\n\", vlTemp.data);\n free(vlTemp.data);\n }\n printf(\"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\\n\");\n } else {\n printf(\" Value: [\");\n for (h = 0; h < mapidata->size; h++) {\n if (isprint(mapidata->data[h])) {\n printf(\"%c\", mapidata->data[h]);\n } else {\n printf(\".\");\n }\n\n }\n printf(\"]\\n\");\n }\n break;\n case PT_STRING8:\n printf(\" Value: [%s]\\n\", mapidata->data);\n if (strlen((char*)mapidata->data) != mapidata->size - 1) {\n printf(\"Detected Hidden data: [\");\n for (h = 0; h < mapidata->size; h++) {\n if (isprint(mapidata->data[h])) {\n printf(\"%c\", mapidata->data[h]);\n } else {\n printf(\".\");\n }\n\n }\n printf(\"]\\n\");\n }\n break;\n case PT_CLSID:\n printf(\" Value: \");\n printf(\"[HEX: \");\n for(x=0; x< 16; x++) {\n printf(\" %02x\", (BYTE)mapidata->data[x]);\n }\n printf(\"]\\n\");\n break;\n default:\n printf(\" Value: [%s]\\n\", mapidata->data);\n }\n }\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "MAPIPrint", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def on_save(self):\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(\n \"insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values (%s, %s, %s, %s, %s);\",\n (str(self.ip_address), str(self.user_agent), str(self.referrer), str(self.full_path), self.visit_time))\n connection.commit()\n connection.close()\n return 0", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "on_save", "_file_name": "experimental/python/buford/model/visitor.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def process_as_reply(email_obj):\n job_number = email_obj['subject'].split(': #')[1]\n feedback = re.findall(\"^[\\W]*([Oo\\d]){1}(?=[\\W]*)\", email_obj['content'].replace('#','').replace('link', ''))[0]\n feedback = int(0 if feedback == ('O' or 'o') else feedback)\n dcn_key = re.findall('\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}', email_obj['content'])[0]\n logger.info(f\"got feedback `{feedback}` for job #`{job_number}`\")\n with create_connection() as conn:\n was_prev_closed = pd.read_sql(\"SELECT * FROM df_dilfo WHERE job_number=?\", conn, params=[job_number]).iloc[0].closed\n if was_prev_closed:\n logger.info(f\"job was already matched successfully and logged as `closed`... skipping.\")\n return\n if feedback == 1:\n logger.info(f\"got feeback that DCN key {dcn_key} was correct\")\n update_status_query = \"UPDATE df_dilfo SET closed = 1 WHERE job_number = ?\"\n with create_connection() as conn:\n conn.cursor().execute(update_status_query, [job_number])\n logger.info(f\"updated df_dilfo to show `closed` status for job #{job_number}\")\n with create_connection() as conn:\n df = pd.read_sql(\"SELECT * FROM df_matched\", conn)\n match_dict_input = {\n 'job_number': job_number,\n 'dcn_key': dcn_key,\n 'ground_truth': 1 if feedback == 1 else 0,\n 'multi_phase': 1 if feedback == 2 else 0,\n 'verifier': email_obj[\"sender\"],\n 'source': 'feedback',\n 'log_date': str(datetime.datetime.now().date()),\n 'validate': 0,\n }\n df = df.append(match_dict_input, ignore_index=True)\n df = df.drop_duplicates(subset=[\"job_number\", \"dcn_key\"], keep='last')\n df.to_sql('df_matched', conn, if_exists='replace', index=False)\n logger.info(\n f\"DCN key `{dcn_key}` was a \"\n f\"{'successful match' if feedback == 1 else 'mis-match'} for job \"\n f\"#{job_number}\"\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_as_reply", "_file_name": "inbox_scanner.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "updateDevice(const struct header * headers, time_t t)\n{\n\tstruct device ** pp = &devlist;\n\tstruct device * p = *pp;\t/* = devlist; */\n\twhile(p)\n\t{\n\t\tif( p->headers[HEADER_NT].l == headers[HEADER_NT].l\n\t\t && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))\n\t\t && p->headers[HEADER_USN].l == headers[HEADER_USN].l\n\t\t && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )\n\t\t{\n\t\t\t/*printf(\"found! %d\\n\", (int)(t - p->t));*/\n\t\t\tsyslog(LOG_DEBUG, \"device updated : %.*s\", headers[HEADER_USN].l, headers[HEADER_USN].p);\n\t\t\tp->t = t;\n\t\t\t/* update Location ! */\n\t\t\tif(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)\n\t\t\t{\n\t\t\t\tstruct device * tmp;\n\t\t\t\ttmp = realloc(p, sizeof(struct device)\n\t\t\t\t + headers[0].l+headers[1].l+headers[2].l);\n\t\t\t\tif(!tmp)\t/* allocation error */\n\t\t\t\t{\n\t\t\t\t\tsyslog(LOG_ERR, \"updateDevice() : memory allocation error\");\n\t\t\t\t\tfree(p);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tp = tmp;\n\t\t\t\t*pp = p;\n\t\t\t}\n\t\t\tmemcpy(p->data + p->headers[0].l + p->headers[1].l,\n\t\t\t headers[2].p, headers[2].l);\n\t\t\t/* TODO : check p->headers[HEADER_LOCATION].l */\n\t\t\treturn 0;\n\t\t}\n\t\tpp = &p->next;\n\t\tp = *pp;\t/* p = p->next; */\n\t}\n\tsyslog(LOG_INFO, \"new device discovered : %.*s\",\n\t headers[HEADER_USN].l, headers[HEADER_USN].p);\n\t/* add */\n\t{\n\t\tchar * pc;\n\t\tint i;\n\t\tp = malloc( sizeof(struct device)\n\t\t + headers[0].l+headers[1].l+headers[2].l );\n\t\tif(!p) {\n\t\t\tsyslog(LOG_ERR, \"updateDevice(): cannot allocate memory\");\n\t\t\treturn -1;\n\t\t}\n\t\tp->next = devlist;\n\t\tp->t = t;\n\t\tpc = p->data;\n\t\tfor(i = 0; i < 3; i++)\n\t\t{\n\t\t\tp->headers[i].p = pc;\n\t\t\tp->headers[i].l = headers[i].l;\n\t\t\tmemcpy(pc, headers[i].p, headers[i].l);\n\t\t\tpc += headers[i].l;\n\t\t}\n\t\tdevlist = p;\n\t\tsendNotifications(NOTIF_NEW, p, NULL);\n\t}\n\treturn 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[920, 934]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[920, 934]]}, "_func_name": "updateDevice", "_file_name": "minissdpd/minissdpd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int decode_zbuf(AVBPrint *bp, const uint8_t *data,\n const uint8_t *data_end)\n{\n z_stream zstream;\n unsigned char *buf;\n unsigned buf_size;\n int ret;\n\n zstream.zalloc = ff_png_zalloc;\n zstream.zfree = ff_png_zfree;\n zstream.opaque = NULL;\n if (inflateInit(&zstream) != Z_OK)\n return AVERROR_EXTERNAL;\n zstream.next_in = (unsigned char *)data;\n zstream.avail_in = data_end - data;\n av_bprint_init(bp, 0, -1);\n\n while (zstream.avail_in > 0) {\n av_bprint_get_buffer(bp, 2, &buf, &buf_size);\n if (buf_size < 2) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n zstream.next_out = buf;\n zstream.avail_out = buf_size - 1;\n ret = inflate(&zstream, Z_PARTIAL_FLUSH);\n if (ret != Z_OK && ret != Z_STREAM_END) {\n ret = AVERROR_EXTERNAL;\n goto fail;\n }\n bp->len += zstream.next_out - buf;\n if (ret == Z_STREAM_END)\n break;\n }\n inflateEnd(&zstream);\n bp->str[bp->len] = 0;\n return 0;\n\nfail:\n inflateEnd(&zstream);\n av_bprint_finalize(bp, NULL);\n return ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_zbuf", "_file_name": "libavcodec/pngdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "mrb_class_real(struct RClass* cl)\n{\n if (cl == 0)\n return NULL;\n while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {\n cl = cl->super;\n }\n return cl;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[36, 68]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[36, 68]]}, "_func_name": "mrb_class_real", "_file_name": "src/class.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)\n{\n\tint i;\n\tint ch;\n\tchar id[5];\n\tt_chunk_info *cidx;\n\tint sidx;\n\tint nc;\n\n\tGD2_DBG(php_gd_error(\"Reading gd2 header info\"));\n\n\tfor (i = 0; i < 4; i++) {\n\t\tch = gdGetC(in);\n\t\tif (ch == EOF) {\n\t\t\tgoto fail1;\n\t\t}\n\t\tid[i] = ch;\n\t}\n\tid[4] = 0;\n\n\tGD2_DBG(php_gd_error(\"Got file code: %s\", id));\n\n\t/* Equiv. of 'magick'. */\n\tif (strcmp(id, GD2_ID) != 0) {\n\t\tGD2_DBG(php_gd_error(\"Not a valid gd2 file\"));\n\t\tgoto fail1;\n\t}\n\n\t/* Version */\n\tif (gdGetWord(vers, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Version: %d\", *vers));\n\n\tif ((*vers != 1) && (*vers != 2)) {\n\t\tGD2_DBG(php_gd_error(\"Bad version: %d\", *vers));\n\t\tgoto fail1;\n\t}\n\n\t/* Image Size */\n\tif (!gdGetWord(sx, in)) {\n\t\tGD2_DBG(php_gd_error(\"Could not get x-size\"));\n\t\tgoto fail1;\n\t}\n\tif (!gdGetWord(sy, in)) {\n\t\tGD2_DBG(php_gd_error(\"Could not get y-size\"));\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Image is %dx%d\", *sx, *sy));\n\n\t/* Chunk Size (pixels, not bytes!) */\n\tif (gdGetWord(cs, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"ChunkSize: %d\", *cs));\n\n\tif ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {\n\t\tGD2_DBG(php_gd_error(\"Bad chunk size: %d\", *cs));\n\t\tgoto fail1;\n\t}\n\n\t/* Data Format */\n\tif (gdGetWord(fmt, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Format: %d\", *fmt));\n\n\tif ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {\n\t\tGD2_DBG(php_gd_error(\"Bad data format: %d\", *fmt));\n\t\tgoto fail1;\n\t}\n\n\t/* # of chunks wide */\n\tif (gdGetWord(ncx, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"%d Chunks Wide\", *ncx));\n\n\t/* # of chunks high */\n\tif (gdGetWord(ncy, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"%d Chunks vertically\", *ncy));\n\n\tif (gd2_compressed(*fmt)) {\n\t\tnc = (*ncx) * (*ncy);\n\t\tGD2_DBG(php_gd_error(\"Reading %d chunk index entries\", nc));\n\t\tif (overflow2(sidx, nc)) {\n\t\t\tgoto fail1;\n\t\t}\n\t\tsidx = sizeof(t_chunk_info) * nc;\n\t\tif (sidx <= 0) {\n\t\t\tgoto fail1;\n\t\t}\n\t\tcidx = gdCalloc(sidx, 1);\n\t\tif (cidx == NULL) {\n\t\t\tgoto fail1;\n\t\t}\n\n\t\tfor (i = 0; i < nc; i++) {\n\t\t\tif (gdGetInt(&cidx[i].offset, in) != 1) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t\tif (gdGetInt(&cidx[i].size, in) != 1) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t\tif (cidx[i].offset < 0 || cidx[i].size < 0) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t}\n\t\t*chunkIdx = cidx;\n\t}\n\n\tGD2_DBG(php_gd_error(\"gd2 header complete\"));\n\n\treturn 1;\n\nfail1:\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_gd2GetHeader", "_file_name": "ext/gd/libgd/gd_gd2.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,\n struct sockaddr *src_addr, socklen_t *addrlen) {\n int klinux_flags = TokLinuxRecvSendFlag(flags);\n if (klinux_flags == 0 && flags != 0) {\n errno = EINVAL;\n return -1;\n }\n\n MessageWriter input;\n input.Push(sockfd);\n input.Push(len);\n input.Push(klinux_flags);\n MessageReader output;\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvFromHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvfrom\", 4);\n\n int result = output.next();\n int klinux_errno = output.next();\n // recvfrom() returns -1 on failure, with errno set to indicate the cause\n // of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n auto buffer_received = output.next();\n memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size()));\n\n // If |src_addr| is not NULL, and the underlying protocol provides the source\n // address, this source address is filled in. When |src_addr| is NULL, nothing\n // is filled in; in this case, |addrlen| is not used, and should also be NULL.\n if (src_addr != nullptr && addrlen != nullptr) {\n auto klinux_sockaddr_buf = output.next();\n const struct klinux_sockaddr *klinux_addr =\n klinux_sockaddr_buf.As();\n FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,\n addrlen, TrustedPrimitives::BestEffortAbort);\n }\n\n return result;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[873, 913]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[873, 913]]}, "_func_name": "enc_untrusted_recvfrom", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def add_language(self, language):\n \"\"\"\"Add new language for item translations.\"\"\"\n if self.connection:\n self.cursor.execute('insert into itemlanguage (language) values (\"%s\")' % language[0])\n self.connection.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[121, 220]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[121, 220]]}, "_func_name": "add_language", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tag_to_tag_num(self, tag):\n ''' Returns tag_num given tag. '''\n\n q = \"SELECT rowid FROM tags WHERE tag = '\" + tag + \"'\"\n self.query(q)\n return self.c.fetchone()[0]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[79, 142]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[79, 142]]}, "_func_name": "tag_to_tag_num", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, email):\n \"\"\" Fetch data for admin with the corresponding email \"\"\"\n return database_utilities.execute_query(f\"\"\"select * from admins where email = %s\"\"\", (email, ))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "apis/admins.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/delete/', methods=['GET', 'POST'])\ndef delete(msg_id):\n if request.method == 'GET':\n sql = \"DELETE FROM message where msg_id = '%d';\" % (msg_id)\n cursor.execute(sql)\n conn.commit()\n flash('Delete Success!')\n return redirect(url_for('show_entries'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[112, 208]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[112, 208]]}, "_func_name": "delete", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) \n{\n\tVipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );\n\tGifFileType *file = gif->file;\n\n\tColorMapObject *map;\n\tGifByteType *extension;\n\n\tif( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {\n\t\tvips_foreign_load_gif_error( gif ); \n\t\treturn( -1 );\n\t}\n\n\t/* Check that the frame looks sane. Perhaps giflib checks\n\t * this for us.\n\t */\n\tif( file->Image.Left < 0 ||\n\t\tfile->Image.Width < 1 ||\n\t\tfile->Image.Width > 10000 ||\n\t\tfile->Image.Left + file->Image.Width > file->SWidth ||\n\t\tfile->Image.Top < 0 ||\n\t\tfile->Image.Height < 1 ||\n\t\tfile->Image.Height > 10000 ||\n\t\tfile->Image.Top + file->Image.Height > file->SHeight ) {\n\t\tvips_error( class->nickname, \"%s\", _( \"bad frame size\" ) ); \n\t\treturn( -1 ); \n\t}\n\n\t/* Test for a non-greyscale colourmap for this frame.\n\t */\n\tmap = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap;\n\tif( !gif->has_colour &&\n\t\tmap ) {\n\t\tint i;\n\n\t\tfor( i = 0; i < map->ColorCount; i++ ) \n\t\t\tif( map->Colors[i].Red != map->Colors[i].Green ||\n\t\t\t\tmap->Colors[i].Green != map->Colors[i].Blue ) {\n\t\t\t\tgif->has_colour = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t/* Step over compressed image data.\n\t */\n\tdo {\n\t\tif( vips_foreign_load_gif_code_next( gif, &extension ) ) \n\t\t\treturn( -1 );\n\t} while( extension != NULL );\n\n\treturn( 0 );\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "vips_foreign_load_gif_scan_image", "_file_name": "libvips/foreign/gifload.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "generatePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D &previewPixels)\n{\n //\n // Read the input file\n //\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D pixels (h, w);\n in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n //\n // Make a preview image\n //\n\n previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;\n float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;\n float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);\n\t}\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "generatePreview", "_file_name": "OpenEXR/exrmakepreview/makePreview.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,\n\t\t\t\t struct srpt_recv_ioctx *recv_ioctx,\n\t\t\t\t struct srpt_send_ioctx *send_ioctx)\n{\n\tstruct srp_tsk_mgmt *srp_tsk;\n\tstruct se_cmd *cmd;\n\tstruct se_session *sess = ch->sess;\n\tuint64_t unpacked_lun;\n\tuint32_t tag = 0;\n\tint tcm_tmr;\n\tint rc;\n\n\tBUG_ON(!send_ioctx);\n\n\tsrp_tsk = recv_ioctx->ioctx.buf;\n\tcmd = &send_ioctx->cmd;\n\n\tpr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\"\n\t\t \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func,\n\t\t srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);\n\n\tsrpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);\n\tsend_ioctx->cmd.tag = srp_tsk->tag;\n\ttcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);\n\tif (tcm_tmr < 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\tTMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;\n\t\tgoto fail;\n\t}\n\tunpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,\n\t\t\t\t sizeof(srp_tsk->lun));\n\n\tif (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {\n\t\trc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);\n\t\tif (rc < 0) {\n\t\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\t\t\tTMR_TASK_DOES_NOT_EXIST;\n\t\t\tgoto fail;\n\t\t}\n\t\ttag = srp_tsk->task_tag;\n\t}\n\trc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,\n\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, tag,\n\t\t\t\tTARGET_SCF_ACK_KREF);\n\tif (rc != 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;\n\t\tgoto fail;\n\t}\n\treturn;\nfail:\n\ttransport_send_check_condition_and_sense(cmd, 0, 0); // XXX:\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[255, 288], [695, 1154]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[255, 288], [695, 1154]]}, "_func_name": "srpt_handle_tsk_mgmt", "_file_name": "drivers/infiniband/ulp/srpt/ib_srpt.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def cancelFollow(self,userid,friendid):\n sqlText=\"delete from friends where userid=%d and friendid=%s;\"\n params=[userid,friendid]\n result=sql.deleteDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cancelFollow", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def update_title(self, title = None):\n if (not self.title):\n self.title = title\n\n quote_tuple = self.title, self.entry_id\n\n # This will fall to a sql injection \n sql = \"UPDATE jdk_entries SET title = ?\" + \\\n \"WHERE jdk_entries.id = ?;\" \n\n db_execute(sql, quote_tuple)\n \n self.update_date_modified()\n\n return None", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_title", "_file_name": "entry.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/delete/', methods=['GET', 'POST'])\ndef delete(cmt_id):\n if request.method == 'GET':\n sql = \"SELECT msg_id FROM comment where cmt_id = %d;\" % (cmt_id)\n cursor.execute(sql)\n m = cursor.fetchone()\n sql = \"DELETE FROM comment where cmt_id = '%d';\" % (cmt_id)\n cursor.execute(sql)\n conn.commit()\n flash('Delete Success!')\n return redirect(url_for('comment.show', msg_id=m[0]))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[112, 213], [243, 339]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[112, 213], [243, 339]]}, "_func_name": "delete", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data)\n\t{\n\tconst u_char* data_start = data;\n\n\tif ( len <= 0 )\n\t\treturn 0;\n\n\tfor ( ; len > 0; --len, ++data )\n\t\t{\n\t\tif ( offset >= buf_len )\n\t\t\tInitBuffer(buf_len * 2);\n\n\t\tint c = data[0];\n\n#define EMIT_LINE \\\n\t{ \\\n\tbuf[offset] = '\\0'; \\\n\tint seq_len = data + 1 - data_start; \\\n\tseq_delivered_in_lines = seq + seq_len; \\\n\tlast_char = c; \\\n\tForwardStream(offset, buf, IsOrig()); \\\n\toffset = 0; \\\n\treturn seq_len; \\\n\t}\n\n\t\tswitch ( c ) {\n\t\tcase '\\r':\n\t\t\t// Look ahead for '\\n'.\n\t\t\tif ( len > 1 && data[1] == '\\n' )\n\t\t\t\t{\n\t\t\t\t--len; ++data;\n\t\t\t\tlast_char = c;\n\t\t\t\tc = data[0];\n\t\t\t\tEMIT_LINE\n\t\t\t\t}\n\n\t\t\telse if ( CR_LF_as_EOL & CR_as_EOL )\n\t\t\t\tEMIT_LINE\n\n\t\t\telse\n\t\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\n\t\tcase '\\n':\n\t\t\tif ( last_char == '\\r' )\n\t\t\t\t{\n\t\t\t\t--offset; // remove '\\r'\n\t\t\t\tEMIT_LINE\n\t\t\t\t}\n\n\t\t\telse if ( CR_LF_as_EOL & LF_as_EOL )\n\t\t\t\tEMIT_LINE\n\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tif ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) )\n\t\t\t\t\tConn()->Weird(\"line_terminated_with_single_LF\");\n\t\t\t\tbuf[offset++] = c;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase '\\0':\n\t\t\tif ( flag_NULs )\n\t\t\t\tCheckNUL();\n\t\t\telse\n\t\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( last_char == '\\r' )\n\t\t\tif ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) )\n\t\t\t\tConn()->Weird(\"line_terminated_with_single_CR\");\n\n\t\tlast_char = c;\n\t\t}\n\n\treturn data - data_start;\n\t}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[799, 828]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[799, 828]]}, "_func_name": "ContentLine_Analyzer::DoDeliverOnce", "_file_name": "src/analyzer/protocol/tcp/ContentLine.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def get_monthly_ranks_for_scene(db, scene, tag):\n\n sql = \"SELECT date, rank FROM ranks WHERE scene='{scene}' AND player='{tag}'\"\n args = {'scene': scene, 'tag': tag}\n res = db.exec(sql, args)\n\n res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]\n\n # Build up a dict of {date: rank}\n ranks = {}\n for r in res:\n ranks[r[0]] = r[1]\n\n return ranks", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_monthly_ranks_for_scene", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def check(current_num):\n try:\n cursor.execute('SELECT * FROM comics WHERE num=?', (current_num,))\n except sqlite3.OperationalError:\n cursor.execute('CREATE TABLE comics (num text)')\n return False\n else:\n return False if cursor.fetchone() is None else True", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "check", "_file_name": "comics/check_comics.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self,data):\n connection = self.connect()\n\n try:\n query = \"INSERT INTO crimes (description) VALUES (%s);\"\n with connection.cursor() as cursor:\n cursor.execute(query,data)\n connection.commit()\n finally:\n connection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def valid_id(opts, id_):\n '''\n Returns if the passed id is valid\n '''\n try:\n if any(x in id_ for x in ('/', '\\\\', '\\0')):\n return False\n return bool(clean_path(opts['pki_dir'], id_))\n except (AttributeError, KeyError, TypeError):\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "valid_id", "_file_name": "salt/utils/verify.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,\n\t\t\tint cpu_id)\n{\n\tstruct ring_buffer_per_cpu *cpu_buffer;\n\tunsigned long nr_pages;\n\tint cpu, err = 0;\n\n\t/*\n\t * Always succeed at resizing a non-existent buffer:\n\t */\n\tif (!buffer)\n\t\treturn size;\n\n\t/* Make sure the requested buffer exists */\n\tif (cpu_id != RING_BUFFER_ALL_CPUS &&\n\t !cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\treturn size;\n\n\tnr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\n\t/* we need a minimum of two pages */\n\tif (nr_pages < 2)\n\t\tnr_pages = 2;\n\n\tsize = nr_pages * BUF_PAGE_SIZE;\n\n\t/*\n\t * Don't succeed if resizing is disabled, as a reader might be\n\t * manipulating the ring buffer and is expecting a sane state while\n\t * this is true.\n\t */\n\tif (atomic_read(&buffer->resize_disabled))\n\t\treturn -EBUSY;\n\n\t/* prevent another thread from changing buffer sizes */\n\tmutex_lock(&buffer->mutex);\n\n\tif (cpu_id == RING_BUFFER_ALL_CPUS) {\n\t\t/* calculate the pages to update */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\n\t\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\t\tcpu_buffer->nr_pages;\n\t\t\t/*\n\t\t\t * nothing more to do for removing pages or no update\n\t\t\t */\n\t\t\tif (cpu_buffer->nr_pages_to_update <= 0)\n\t\t\t\tcontinue;\n\t\t\t/*\n\t\t\t * to add pages, make sure all new pages can be\n\t\t\t * allocated without receiving ENOMEM\n\t\t\t */\n\t\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\t\tif (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t\t&cpu_buffer->new_pages, cpu)) {\n\t\t\t\t/* not enough memory for new pages */\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out_err;\n\t\t\t}\n\t\t}\n\n\t\tget_online_cpus();\n\t\t/*\n\t\t * Fire off all the required work handlers\n\t\t * We can't schedule on offline CPUs, but it's not necessary\n\t\t * since we can change their buffer sizes without any race.\n\t\t */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\t/* Can't run something on an offline CPU. */\n\t\t\tif (!cpu_online(cpu)) {\n\t\t\t\trb_update_pages(cpu_buffer);\n\t\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t\t} else {\n\t\t\t\tschedule_work_on(cpu,\n\t\t\t\t\t\t&cpu_buffer->update_pages_work);\n\t\t\t}\n\t\t}\n\n\t\t/* wait for all the updates to complete */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\tif (cpu_online(cpu))\n\t\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t}\n\n\t\tput_online_cpus();\n\t} else {\n\t\t/* Make sure this CPU has been intitialized */\n\t\tif (!cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\t\tgoto out;\n\n\t\tcpu_buffer = buffer->buffers[cpu_id];\n\n\t\tif (nr_pages == cpu_buffer->nr_pages)\n\t\t\tgoto out;\n\n\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\tcpu_buffer->nr_pages;\n\n\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\tif (cpu_buffer->nr_pages_to_update > 0 &&\n\t\t\t__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t &cpu_buffer->new_pages, cpu_id)) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_err;\n\t\t}\n\n\t\tget_online_cpus();\n\n\t\t/* Can't run something on an offline CPU. */\n\t\tif (!cpu_online(cpu_id))\n\t\t\trb_update_pages(cpu_buffer);\n\t\telse {\n\t\t\tschedule_work_on(cpu_id,\n\t\t\t\t\t &cpu_buffer->update_pages_work);\n\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t}\n\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\tput_online_cpus();\n\t}\n\n out:\n\t/*\n\t * The ring buffer resize can happen with the ring buffer\n\t * enabled, so that the update disturbs the tracing as little\n\t * as possible. But if the buffer is disabled, we do not need\n\t * to worry about that, and we can take the time to verify\n\t * that the buffer is not corrupt.\n\t */\n\tif (atomic_read(&buffer->record_disabled)) {\n\t\tatomic_inc(&buffer->record_disabled);\n\t\t/*\n\t\t * Even though the buffer was disabled, we must make sure\n\t\t * that it is truly disabled before calling rb_check_pages.\n\t\t * There could have been a race between checking\n\t\t * record_disable and incrementing it.\n\t\t */\n\t\tsynchronize_sched();\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\trb_check_pages(cpu_buffer);\n\t\t}\n\t\tatomic_dec(&buffer->record_disabled);\n\t}\n\n\tmutex_unlock(&buffer->mutex);\n\treturn size;\n\n out_err:\n\tfor_each_buffer_cpu(buffer, cpu) {\n\t\tstruct buffer_page *bpage, *tmp;\n\n\t\tcpu_buffer = buffer->buffers[cpu];\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\n\t\tif (list_empty(&cpu_buffer->new_pages))\n\t\t\tcontinue;\n\n\t\tlist_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,\n\t\t\t\t\tlist) {\n\t\t\tlist_del_init(&bpage->list);\n\t\t\tfree_buffer_page(bpage);\n\t\t}\n\t}\n\tmutex_unlock(&buffer->mutex);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ring_buffer_resize", "_file_name": "kernel/trace/ring_buffer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int exif_scan_JPEG_header(image_info_type *ImageInfo) {\n int section, sn;\n int marker = 0, last_marker = M_PSEUDO, comment_correction=1;\n int ll, lh;\n unsigned char *Data;\n size_t fpos, size, got, itemlen;\n jpeg_sof_info sof_info;\n\n for(section=0;;section++) {\n // get marker byte, swallowing possible padding\n // some software does not count the length bytes of COM section\n // one company doing so is very much envolved in JPEG...\n // so we accept too\n if (last_marker==M_COM && comment_correction) {\n comment_correction = 2;\n }\n do {\n if ((marker = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n if (last_marker==M_COM && comment_correction>0) {\n if (marker!=0xFF) {\n marker = 0xff;\n comment_correction--;\n } else {\n last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */\n }\n }\n } while (marker == 0xff);\n if (last_marker==M_COM && !comment_correction) {\n raise_notice(\"Image has corrupt COM section: some software set \"\n \"wrong length information\");\n }\n if (last_marker==M_COM && comment_correction)\n return M_EOI; /* ah illegal: char after COM section not 0xFF */\n\n fpos = ImageInfo->infile->tell();\n\n if (marker == 0xff) {\n // 0xff is legal padding, but if we get that many, something's wrong.\n raise_warning(\"To many padding bytes\");\n return 0;\n }\n\n /* Read the length of the section. */\n\n if ((lh = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n if ((ll = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n itemlen = (lh << 8) | ll;\n\n if (itemlen < 2) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr);\n if (sn == -1) return 0;\n Data = ImageInfo->file.list[sn].data;\n\n /* Store first two pre-read bytes. */\n Data[0] = (unsigned char)lh;\n Data[1] = (unsigned char)ll;\n\n String str = ImageInfo->infile->read(itemlen-2);\n got = str.length();\n if (got != itemlen-2) {\n raise_warning(\"Error reading from file: \"\n \"got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)\",\n got, got, itemlen-2, itemlen-2);\n return 0;\n }\n memcpy(Data+2, str.c_str(), got);\n switch(marker) {\n case M_SOS: /* stop before hitting compressed data */\n // If reading entire image is requested, read the rest of the data.\n if (ImageInfo->read_all) {\n /* Determine how much file is left. */\n fpos = ImageInfo->infile->tell();\n size = ImageInfo->FileSize - fpos;\n sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr);\n if (sn == -1) return 0;\n Data = ImageInfo->file.list[sn].data;\n str = ImageInfo->infile->read(size);\n got = str.length();\n if (got != size) {\n raise_warning(\"Unexpected end of file reached\");\n return 0;\n }\n memcpy(Data, str.c_str(), got);\n }\n return 1;\n\n case M_EOI: /* in case it's a tables-only JPEG stream */\n raise_warning(\"No image in jpeg!\");\n return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0;\n\n case M_COM: /* Comment section */\n exif_process_COM(ImageInfo, (char *)Data, itemlen);\n break;\n\n case M_EXIF:\n if (!(ImageInfo->sections_found&FOUND_IFD0)) {\n /*ImageInfo->sections_found |= FOUND_EXIF;*/\n /* Seen files from some 'U-lead' software with Vivitar scanner\n that uses marker 31 later in the file (no clue what for!) */\n exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos);\n }\n break;\n\n case M_APP12:\n exif_process_APP12(ImageInfo, (char *)Data, itemlen);\n break;\n\n\n case M_SOF0:\n case M_SOF1:\n case M_SOF2:\n case M_SOF3:\n case M_SOF5:\n case M_SOF6:\n case M_SOF7:\n case M_SOF9:\n case M_SOF10:\n case M_SOF11:\n case M_SOF13:\n case M_SOF14:\n case M_SOF15:\n exif_process_SOFn(Data, marker, &sof_info);\n ImageInfo->Width = sof_info.width;\n ImageInfo->Height = sof_info.height;\n if (sof_info.num_components == 3) {\n ImageInfo->IsColor = 1;\n } else {\n ImageInfo->IsColor = 0;\n }\n break;\n default:\n /* skip any other marker silently. */\n break;\n }\n\n /* keep track of last marker */\n last_marker = marker;\n }\n return 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[4277, 4329]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[4277, 4329]]}, "_func_name": "HPHP::exif_scan_JPEG_header", "_file_name": "hphp/runtime/ext/gd/ext_gd.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef gravatar(context, user, size=None):\n \"\"\"\n Outputs the HTML for displaying a user's gravatar.\n\n This can take an optional size of the image (defaults to 80 if not\n specified).\n\n This is also influenced by the following settings:\n\n GRAVATAR_SIZE - Default size for gravatars\n GRAVATAR_RATING - Maximum allowed rating (g, pg, r, x)\n GRAVATAR_DEFAULT - Default image set to show if the user hasn't\n specified a gravatar (identicon, monsterid, wavatar)\n\n See http://www.gravatar.com/ for more information.\n \"\"\"\n url = get_gravatar_url(context['request'], user, size)\n\n if url:\n return format_html(\n '\"{2}\"',\n url, size, user.get_full_name() or user.username)\n else:\n return ''", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "gravatar", "_file_name": "djblets/gravatars/templatetags/gravatars.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const size_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;\n\n register const unsigned char\n *p;\n\n register Quantum\n *q;\n\n register ssize_t\n x;\n\n size_t\n packet_size;\n\n unsigned short\n nibble;\n\n p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n switch (type)\n {\n case -1:\n {\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case -2:\n case 0:\n {\n SetPixelRed(image,pixel,q);\n if (channels == 1 || type == -2)\n SetPixelGray(image,pixel,q);\n if (image->storage_class == PseudoClass)\n {\n if (packet_size == 1)\n SetPixelIndex(image,ScaleQuantumToChar(pixel),q);\n else\n SetPixelIndex(image,ScaleQuantumToShort(pixel),q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);\n if (image->depth == 1)\n {\n ssize_t\n bit,\n number_bits;\n \n number_bits=image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit=0; bit < number_bits; bit++)\n {\n SetPixelIndex(image,(((unsigned char) pixel) &\n (0x01 << (7-bit))) != 0 ? 0 : 255,q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n ConstrainColormapIndex(image,GetPixelIndex(image,q),\n exception),q);\n q+=GetPixelChannels(image);\n x++;\n }\n x--;\n continue;\n }\n }\n break;\n }\n case 1:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelGreen(image,pixel,q);\n break;\n }\n case 2:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelBlue(image,pixel,q);\n break;\n }\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,pixel,q);\n else\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case 4:\n {\n if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&\n (channels > 3))\n break;\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n default:\n break;\n }\n q+=GetPixelChannels(image);\n }\n return(SyncAuthenticPixels(image,exception));\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ReadPSDChannelPixels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int usb_get_bos_descriptor(struct usb_device *dev)\n{\n\tstruct device *ddev = &dev->dev;\n\tstruct usb_bos_descriptor *bos;\n\tstruct usb_dev_cap_header *cap;\n\tunsigned char *buffer;\n\tint length, total_len, num, i;\n\tint ret;\n\n\tbos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);\n\tif (!bos)\n\t\treturn -ENOMEM;\n\n\t/* Get BOS descriptor */\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);\n\tif (ret < USB_DT_BOS_SIZE) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tkfree(bos);\n\t\treturn ret;\n\t}\n\n\tlength = bos->bLength;\n\ttotal_len = le16_to_cpu(bos->wTotalLength);\n\tnum = bos->bNumDeviceCaps;\n\tkfree(bos);\n\tif (total_len < length)\n\t\treturn -EINVAL;\n\n\tdev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);\n\tif (!dev->bos)\n\t\treturn -ENOMEM;\n\n\t/* Now let's get the whole BOS descriptor set */\n\tbuffer = kzalloc(total_len, GFP_KERNEL);\n\tif (!buffer) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\tdev->bos->desc = (struct usb_bos_descriptor *)buffer;\n\n\tret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);\n\tif (ret < total_len) {\n\t\tdev_err(ddev, \"unable to get BOS descriptor set\\n\");\n\t\tif (ret >= 0)\n\t\t\tret = -ENOMSG;\n\t\tgoto err;\n\t}\n\ttotal_len -= length;\n\n\tfor (i = 0; i < num; i++) {\n\t\tbuffer += length;\n\t\tcap = (struct usb_dev_cap_header *)buffer;\n\t\tlength = cap->bLength;\n\n\t\tif (total_len < length)\n\t\t\tbreak;\n\t\ttotal_len -= length;\n\n\t\tif (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {\n\t\t\tdev_warn(ddev, \"descriptor type invalid, skip\\n\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (cap->bDevCapabilityType) {\n\t\tcase USB_CAP_TYPE_WIRELESS_USB:\n\t\t\t/* Wireless USB cap descriptor is handled by wusb */\n\t\t\tbreak;\n\t\tcase USB_CAP_TYPE_EXT:\n\t\t\tdev->bos->ext_cap =\n\t\t\t\t(struct usb_ext_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SS_CAP_TYPE:\n\t\t\tdev->bos->ss_cap =\n\t\t\t\t(struct usb_ss_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_SSP_CAP_TYPE:\n\t\t\tdev->bos->ssp_cap =\n\t\t\t\t(struct usb_ssp_cap_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase CONTAINER_ID_TYPE:\n\t\t\tdev->bos->ss_id =\n\t\t\t\t(struct usb_ss_container_id_descriptor *)buffer;\n\t\t\tbreak;\n\t\tcase USB_PTM_CAP_TYPE:\n\t\t\tdev->bos->ptm_cap =\n\t\t\t\t(struct usb_ptm_cap_descriptor *)buffer;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n\nerr:\n\tusb_release_bos_descriptor(dev);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1313, 1365]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1313, 1365]]}, "_func_name": "usb_get_bos_descriptor", "_file_name": "drivers/usb/core/config.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def also_add(name, also):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n INSERT INTO isalso(name,also) VALUES('{}','{}')\n '''.format(name, also))\n db.commit()\n logger.debug('added to isalso name {} with value {}'.format(\n name, also))\n db.close()\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[109, 205]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[109, 205]]}, "_func_name": "also_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _download_file(bucket, filename, local_dir):\n key = bucket.get_key(filename)\n local_filename = os.path.join(local_dir, os.path.basename(filename))\n key.get_contents_to_filename(local_filename)\n return local_filename", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_download_file", "_file_name": "nova/image/s3.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_vdisk_attributes(self, vdisk_name):\n \"\"\"Return vdisk attributes, or None if vdisk does not exist\n\n Exception is raised if the information from system can not be\n parsed/matched to a single vdisk.\n \"\"\"\n\n ssh_cmd = 'svcinfo lsvdisk -bytes -delim ! %s ' % vdisk_name\n return self._execute_command_and_parse_attributes(ssh_cmd)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[243, 312]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[243, 312]]}, "_func_name": "_get_vdisk_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 1;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len + 1 + len/255;\n }\n\n ret = ff_alloc_extradata(st->codecpar, xd_size);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n av_assert0(delta <= xd_size - offset);\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n av_assert0(data_len[j] <= xd_size - offset);\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "track_header", "_file_name": "libavformat/vividas.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "daemon_AuthUserPwd(char *username, char *password, char *errbuf)\n{\n#ifdef _WIN32\n\t/*\n\t * Warning: the user which launches the process must have the\n\t * SE_TCB_NAME right.\n\t * This corresponds to have the \"Act as part of the Operating System\"\n\t * turned on (administrative tools, local security settings, local\n\t * policies, user right assignment)\n\t * However, it seems to me that if you run it as a service, this\n\t * right should be provided by default.\n\t *\n\t * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,\n\t * which merely indicates that the user name or password is\n\t * incorrect, not whether it's the user name or the password\n\t * that's incorrect, so a client that's trying to brute-force\n\t * accounts doesn't know whether it's the user name or the\n\t * password that's incorrect, so it doesn't know whether to\n\t * stop trying to log in with a given user name and move on\n\t * to another user name.\n\t */\n\tHANDLE Token;\n\tif (LogonUser(username, \".\", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"LogonUser() failed\");\n\t\treturn -1;\n\t}\n\n\t// This call should change the current thread to the selected user.\n\t// I didn't test it.\n\tif (ImpersonateLoggedOnUser(Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"ImpersonateLoggedOnUser() failed\");\n\t\tCloseHandle(Token);\n\t\treturn -1;\n\t}\n\n\tCloseHandle(Token);\n\treturn 0;\n\n#else\n\t/*\n\t * See\n\t *\n\t *\thttp://www.unixpapa.com/incnote/passwd.html\n\t *\n\t * We use the Solaris/Linux shadow password authentication if\n\t * we have getspnam(), otherwise we just do traditional\n\t * authentication, which, on some platforms, might work, even\n\t * with shadow passwords, if we're running as root. Traditional\n\t * authenticaion won't work if we're not running as root, as\n\t * I think these days all UN*Xes either won't return the password\n\t * at all with getpwnam() or will only do so if you're root.\n\t *\n\t * XXX - perhaps what we *should* be using is PAM, if we have\n\t * it. That might hide all the details of username/password\n\t * authentication, whether it's done with a visible-to-root-\n\t * only password database or some other authentication mechanism,\n\t * behind its API.\n\t */\n\tstruct passwd *user;\n\tchar *user_password;\n#ifdef HAVE_GETSPNAM\n\tstruct spwd *usersp;\n#endif\n\tchar *crypt_password;\n\n\t// This call is needed to get the uid\n\tif ((user = getpwnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n#ifdef HAVE_GETSPNAM\n\t// This call is needed to get the password; otherwise 'x' is returned\n\tif ((usersp = getspnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\tuser_password = usersp->sp_pwdp;\n#else\n\t/*\n\t * XXX - what about other platforms?\n\t * The unixpapa.com page claims this Just Works on *BSD if you're\n\t * running as root - it's from 2000, so it doesn't indicate whether\n\t * macOS (which didn't come out until 2001, under the name Mac OS\n\t * X) behaves like the *BSDs or not, and might also work on AIX.\n\t * HP-UX does something else.\n\t *\n\t * Again, hopefully PAM hides all that.\n\t */\n\tuser_password = user->pw_passwd;\n#endif\n\n\tcrypt_password = crypt(password, user_password);\n\tif (crypt_password == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed\");\n\t\treturn -1;\n\t}\n\tif (strcmp(user_password, crypt_password) != 0)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n\tif (setuid(user->pw_uid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setuid\");\n\t\treturn -1;\n\t}\n\n/*\tif (setgid(user->pw_gid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setgid\");\n\t\treturn -1;\n\t}\n*/\n\treturn 0;\n\n#endif\n\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "daemon_AuthUserPwd", "_file_name": "rpcapd/daemon.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getQueue(self, numberOfLinks=10):\n self.cursor.execute(\"SELECT url FROM queue WHERE visited = '0' LIMIT {};\".format(numberOfLinks))\n result = self.cursor.fetchall()\n self.remove(result)\n return result", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[42, 147]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[42, 147]]}, "_func_name": "getQueue", "_file_name": "beta/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)\ndef get_login2(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n if bases.createuserbase.check_username(message.text):\n bot.send_message(message.chat.id, \"Invalid handle.\")\n set_state(message.chat.id, config.States.S_START.value)\n return 0\n\n conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n name = conn.fetchone()\n settings.close()\n bases.update.cf_update()\n bases.createuserbase.clean_base(name[1])\n bases.createuserbase.clean_base(message.text)\n bot.send_message(message.chat.id, \"Creating base...\")\n bases.createuserbase.init_user(message.text, message.chat.id)\n bot.send_message(message.chat.id, \"Done!\")\n set_state(message.chat.id, config.States.S_START.value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[465, 553]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[465, 553]]}, "_func_name": "get_login2", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _inject_file_into_fs(fs, path, contents, append=False):\n absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/'))\n\n parent_dir = os.path.dirname(absolute_path)\n utils.execute('mkdir', '-p', parent_dir, run_as_root=True)\n\n args = []\n if append:\n args.append('-a')\n args.append(absolute_path)\n\n kwargs = dict(process_input=contents, run_as_root=True)\n\n utils.execute('tee', *args, **kwargs)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_inject_file_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(commands =['login'])\ndef get_login(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n name = conn.fetchone()\n if name != None:\n bot.send_message(message.chat.id, \"Previous handle: \" + str(name[1]))\n else:\n bot.send_message(message.chat.id, \"Previous handle: None\")\n settings.close()\n bot.send_message(message.chat.id, \"Type new handle: \")\n set_state(message.chat.id, config.States.S_LOGIN.value)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_login", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def is_cgi(self):\n \"\"\"Test whether self.path corresponds to a CGI script.\n\n Returns True and updates the cgi_info attribute to the tuple\n (dir, rest) if self.path requires running a CGI script.\n Returns False otherwise.\n\n The default implementation tests whether the normalized url\n path begins with one of the strings in self.cgi_directories\n (and the next character is a '/' or the end of the string).\n \"\"\"\n splitpath = _url_collapse_path_split(self.path)\n if splitpath[0] in self.cgi_directories:\n self.cgi_info = splitpath\n return True\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "is_cgi", "_file_name": "Lib/CGIHTTPServer.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_history_and_sourcebyinstitution(conn, sqlite, k10plus, ai):\n \"\"\"\n Get all current sources and title numbers from Solr and log them into database.\n \"\"\"\n current_sources = get_all_current_sources(k10plus, ai)\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_sourcebyinstitutions = get_all_old_sourcebyinstitutions(conn, sqlite)\n current_sourcebyinstitutions = []\n\n for source in current_sources:\n\n for institution in current_institutions:\n\n if not institution or institution == \" \" or '\"' in institution:\n continue\n\n sourcebyinstitution = \"SID \" + str(source) + \" (\" + institution + \")\"\n current_sourcebyinstitutions.append(sourcebyinstitution)\n\n params = {\n \"q\": 'source_id:%s AND institution:\"%s\"' % (source, institution),\n \"rows\": 0,\n \"wt\": \"json\"\n }\n\n # check k10plus\n result = get_solr_result(k10plus, params)\n number = result[\"response\"][\"numFound\"]\n if number != 0:\n sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (\"%s\", %s)' % (sourcebyinstitution, number)\n sqlite.execute(sql)\n conn.commit()\n else:\n # check ai\n result = get_solr_result(ai, params)\n number = result[\"response\"][\"numFound\"]\n if number != 0:\n # TODO: escape via sqlite\n sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (\"%s\", %s)' % (sourcebyinstitution, number)\n sqlite.execute(sql)\n conn.commit()\n\n if sourcebyinstitution not in old_sourcebyinstitutions:\n logging.info(\"The %s is now connected to SID %s.\", institution, source)\n sql = \"INSERT INTO sourcebyinstitution (sourcebyinstitution) VALUES ('%s')\" % sourcebyinstitution\n sqlite.execute(sql)\n conn.commit()\n\n if number != 0:\n old_sourcebyinstitution_number = get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution)\n if number < old_sourcebyinstitution_number:\n message = \"Die Anzahl der Titel hat sich bei %s gegenueber einem frueheren Import verringert.\" % (sourcebyinstitution)\n send_message(message)\n\n # requests.exceptions.ConnectionError: HTTPConnectionPool(XXXXXX): Max retries exceeded\n time.sleep(0.25)\n\n for old_sourcebyinstitution in old_sourcebyinstitutions:\n if old_sourcebyinstitution not in current_sourcebyinstitutions:\n message = \"Die %s ist nicht laenger für die SID %s angesigelt.\" % (institution, source)\n send_message(message)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1094, 1218], [1516, 1644], [1875, 1989]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1094, 1218], [1516, 1644], [1875, 1989]]}, "_func_name": "update_history_and_sourcebyinstitution", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _remove_volume_from_volume_set(self, volume_name, vvs_name):\n self._cli_run(['removevvset', '-f', vvs_name, volume_name])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_remove_volume_from_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,\n\t\t enum CCSTATE* state, ScanEnv* env)\n{\n int r;\n\n if (*state == CCS_RANGE)\n return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;\n\n if (*state == CCS_VALUE && *type != CCV_CLASS) {\n if (*type == CCV_SB)\n BITSET_SET_BIT(cc->bs, (int )(*vs));\n else if (*type == CCV_CODE_POINT) {\n r = add_code_range(&(cc->mbuf), env, *vs, *vs);\n if (r < 0) return r;\n }\n }\n\n *state = CCS_VALUE;\n *type = CCV_CLASS;\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[456, 478]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[456, 478]]}, "_func_name": "next_state_class", "_file_name": "src/regparse.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search ORACLE\\n\");\n\n if(packet->tcp != NULL) {\n sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n\t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n\t && (packet->payload[1] != 0x00)\n\t && (packet->payload[2] == 0x00)\n\t\t && (packet->payload[3] == 0x00)))) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&\n packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&\n packet->payload[3] == 0x00 ) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n }\n } else {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ndpi_search_oracle", "_file_name": "src/lib/protocols/oracle.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "authDigestNonceLink(digest_nonce_h * nonce)\n{\n assert(nonce != NULL);\n ++nonce->references;\n debugs(29, 9, \"nonce '\" << nonce << \"' now at '\" << nonce->references << \"'.\");\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[98, 182]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[98, 182]]}, "_func_name": "authDigestNonceLink", "_file_name": "src/auth/digest/Config.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def redirect(self, url, **kwargs):\n \"\"\"Explicitly converts url to 'str', because webapp2.RequestHandler.redirect\n strongly requires 'str' but url might be an unicode string.\"\"\"\n url = str(url)\n check_redirect_url(url)\n super(Handler, self).redirect(url, **kwargs)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "redirect", "_file_name": "src/appengine/handlers/base_handler.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def initialize_connection(self, volume, connector):\n \"\"\"Restrict access to a volume.\"\"\"\n try:\n cmd = ['volume', 'select', volume['name'], 'access', 'create',\n 'initiator', connector['initiator']]\n if self.configuration.eqlx_use_chap:\n cmd.extend(['authmethod chap', 'username',\n self.configuration.eqlx_chap_login])\n self._eql_execute(*cmd)\n iscsi_properties = self._get_iscsi_properties(volume)\n return {\n 'driver_volume_type': 'iscsi',\n 'data': iscsi_properties\n }\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_('Failed to initialize connection to volume %s'),\n volume['name'])", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[292, 351]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[292, 351]]}, "_func_name": "initialize_connection", "_file_name": "cinder/volume/drivers/eqlx.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static inline void get_conn_text(const conn *c, const int af,\n char* addr, struct sockaddr *sock_addr) {\n char addr_text[MAXPATHLEN];\n addr_text[0] = '\\0';\n const char *protoname = \"?\";\n unsigned short port = 0;\n\n switch (af) {\n case AF_INET:\n (void) inet_ntop(af,\n &((struct sockaddr_in *)sock_addr)->sin_addr,\n addr_text,\n sizeof(addr_text) - 1);\n port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port);\n protoname = IS_UDP(c->transport) ? \"udp\" : \"tcp\";\n break;\n\n case AF_INET6:\n addr_text[0] = '[';\n addr_text[1] = '\\0';\n if (inet_ntop(af,\n &((struct sockaddr_in6 *)sock_addr)->sin6_addr,\n addr_text + 1,\n sizeof(addr_text) - 2)) {\n strcat(addr_text, \"]\");\n }\n port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port);\n protoname = IS_UDP(c->transport) ? \"udp6\" : \"tcp6\";\n break;\n\n case AF_UNIX:\n strncpy(addr_text,\n ((struct sockaddr_un *)sock_addr)->sun_path,\n sizeof(addr_text) - 1);\n addr_text[sizeof(addr_text)-1] = '\\0';\n protoname = \"unix\";\n break;\n }\n\n if (strlen(addr_text) < 2) {\n /* Most likely this is a connected UNIX-domain client which\n * has no peer socket address, but there's no portable way\n * to tell for sure.\n */\n sprintf(addr_text, \"\", af);\n }\n\n if (port) {\n sprintf(addr, \"%s:%s:%u\", protoname, addr_text, port);\n } else {\n sprintf(addr, \"%s:%s\", protoname, addr_text);\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1203, 1298]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1203, 1298]]}, "_func_name": "get_conn_text", "_file_name": "memcached.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_output(command: str) -> bytes:\n \"\"\"\n Run a command and return raw output\n\n :param str command: the command to run\n :returns: the stdout output of the command\n \"\"\"\n return subprocess.check_output(command.split())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 39], [186, 237]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 39], [186, 237]]}, "_func_name": "get_output", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,\n const Quantum pixel,const MagickEvaluateOperator op,\n const MagickRealType value)\n{\n MagickRealType\n result;\n\n result=0.0;\n switch (op)\n {\n case UndefinedEvaluateOperator:\n break;\n case AbsEvaluateOperator:\n {\n result=(MagickRealType) fabs((double) (pixel+value));\n break;\n }\n case AddEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case AddModulusEvaluateOperator:\n {\n /*\n This returns a 'floored modulus' of the addition which is a\n positive result. It differs from % or fmod() which returns a\n 'truncated modulus' result, where floor() is replaced by trunc()\n and could return a negative result (which is clipped).\n */\n result=pixel+value;\n result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));\n break;\n }\n case AndEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));\n break;\n }\n case CosineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case DivideEvaluateOperator:\n {\n result=pixel/(value == 0.0 ? 1.0 : value);\n break;\n }\n case ExponentialEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*\n pixel)));\n break;\n }\n case GaussianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n GaussianNoise,value);\n break;\n }\n case ImpulseNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n ImpulseNoise,value);\n break;\n }\n case LaplacianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n LaplacianNoise,value);\n break;\n }\n case LeftShiftEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));\n break;\n }\n case LogEvaluateOperator:\n {\n if ((QuantumScale*pixel) >= MagickEpsilon)\n result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*\n pixel+1.0))/log((double) (value+1.0)));\n break;\n }\n case MaxEvaluateOperator:\n {\n result=(MagickRealType) EvaluateMax((double) pixel,value);\n break;\n }\n case MeanEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MedianEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MinEvaluateOperator:\n {\n result=(MagickRealType) MagickMin((double) pixel,value);\n break;\n }\n case MultiplicativeNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n MultiplicativeGaussianNoise,value);\n break;\n }\n case MultiplyEvaluateOperator:\n {\n result=(MagickRealType) (value*pixel);\n break;\n }\n case OrEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));\n break;\n }\n case PoissonNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n PoissonNoise,value);\n break;\n }\n case PowEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),\n (double) value));\n break;\n }\n case RightShiftEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));\n break;\n }\n case RootMeanSquareEvaluateOperator:\n {\n result=(MagickRealType) (pixel*pixel+value);\n break;\n }\n case SetEvaluateOperator:\n {\n result=value;\n break;\n }\n case SineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case SubtractEvaluateOperator:\n {\n result=(MagickRealType) (pixel-value);\n break;\n }\n case SumEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case ThresholdEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :\n QuantumRange);\n break;\n }\n case ThresholdBlackEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);\n break;\n }\n case ThresholdWhiteEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :\n pixel);\n break;\n }\n case UniformNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n UniformNoise,value);\n break;\n }\n case XorEvaluateOperator:\n {\n result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));\n break;\n }\n }\n return(result);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[975, 1046], [2060, 2132], [3157, 3228], [3618, 3690], [4948, 5019]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[975, 1046], [2060, 2132], [3157, 3228], [3618, 3690], [4948, 5019]]}, "_func_name": "ApplyEvaluateOperator", "_file_name": "magick/statistic.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "BYTE *DecompressRTF(variableLength *p, int *size) {\n BYTE *dst; // destination for uncompressed bytes\n BYTE *src;\n unsigned int in;\n unsigned int out;\n variableLength comp_Prebuf;\n ULONG compressedSize, uncompressedSize, magic;\n\n comp_Prebuf.size = strlen(RTF_PREBUF);\n comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);\n ALLOCCHECK_CHAR(comp_Prebuf.data);\n memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);\n\n src = p->data;\n in = 0;\n\n if (p->size < 20) {\n printf(\"File too small\\n\");\n return(NULL);\n }\n compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);\n in += 4;\n uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);\n in += 4;\n magic = SwapDWord((BYTE*)src + in, 4);\n in += 4;\n in += 4;\n\n // check size excluding the size field itself\n if (compressedSize != p->size - 4) {\n printf(\" Size Mismatch: %u != %i\\n\", compressedSize, p->size - 4);\n free(comp_Prebuf.data);\n return NULL;\n }\n\n // process the data\n if (magic == 0x414c454d) {\n // magic number that identifies the stream as a uncompressed stream\n dst = calloc(uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, src + 4, uncompressedSize);\n } else if (magic == 0x75465a4c) {\n // magic number that identifies the stream as a compressed stream\n int flagCount = 0;\n int flags = 0;\n // Prevent overflow on 32 Bit Systems\n if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {\n printf(\"Corrupted file\\n\");\n exit(-1);\n }\n dst = calloc(comp_Prebuf.size + uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);\n out = comp_Prebuf.size;\n while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) {\n // each flag byte flags 8 literals/references, 1 per bit\n flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;\n if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal\n unsigned int offset = src[in++];\n unsigned int length = src[in++];\n unsigned int end;\n offset = (offset << 4) | (length >> 4); // the offset relative to block start\n length = (length & 0xF) + 2; // the number of bytes to copy\n // the decompression buffer is supposed to wrap around back\n // to the beginning when the end is reached. we save the\n // need for such a buffer by pointing straight into the data\n // buffer, and simulating this behaviour by modifying the\n // pointers appropriately.\n offset = (out / 4096) * 4096 + offset;\n if (offset >= out) // take from previous block\n offset -= 4096;\n // note: can't use System.arraycopy, because the referenced\n // bytes can cross through the current out position.\n end = offset + length;\n while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))\n && (offset < (comp_Prebuf.size + uncompressedSize)))\n dst[out++] = dst[offset++];\n } else { // literal\n if ((out >= (comp_Prebuf.size + uncompressedSize)) ||\n (in >= p->size)) {\n printf(\"Corrupted stream\\n\");\n exit(-1);\n }\n dst[out++] = src[in++];\n }\n }\n // copy it back without the prebuffered data\n src = dst;\n dst = calloc(uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, src + comp_Prebuf.size, uncompressedSize);\n free(src);\n *size = uncompressedSize;\n free(comp_Prebuf.data);\n return dst;\n } else { // unknown magic number\n printf(\"Unknown compression type (magic number %x)\\n\", magic);\n }\n free(comp_Prebuf.data);\n return NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "DecompressRTF", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {\n\tint name_end = -1;\n\tint j = *idx;\n\tint ptr_count = 0;\n#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)\n#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)\n#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)\n\n\tchar *cp = name_out;\n\tconst char *const end = name_out + name_out_len;\n\n\t/* Normally, names are a series of length prefixed strings terminated */\n\t/* with a length of 0 (the lengths are u8's < 63). */\n\t/* However, the length can start with a pair of 1 bits and that */\n\t/* means that the next 14 bits are a pointer within the current */\n\t/* packet. */\n\n\tfor (;;) {\n\t\tu8 label_len;\n\t\tGET8(label_len);\n\t\tif (!label_len) break;\n\t\tif (label_len & 0xc0) {\n\t\t\tu8 ptr_low;\n\t\t\tGET8(ptr_low);\n\t\t\tif (name_end < 0) name_end = j;\n\t\t\tj = (((int)label_len & 0x3f) << 8) + ptr_low;\n\t\t\t/* Make sure that the target offset is in-bounds. */\n\t\t\tif (j < 0 || j >= length) return -1;\n\t\t\t/* If we've jumped more times than there are characters in the\n\t\t\t * message, we must have a loop. */\n\t\t\tif (++ptr_count > length) return -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (label_len > 63) return -1;\n\t\tif (cp != name_out) {\n\t\t\tif (cp + 1 >= end) return -1;\n\t\t\t*cp++ = '.';\n\t\t}\n\t\tif (cp + label_len >= end) return -1;\n\t\tif (j + label_len > length) return -1;\n\t\tmemcpy(cp, packet + j, label_len);\n\t\tcp += label_len;\n\t\tj += label_len;\n\t}\n\tif (cp >= end) return -1;\n\t*cp = '\\0';\n\tif (name_end < 0)\n\t\t*idx = j;\n\telse\n\t\t*idx = name_end;\n\treturn 0;\n err:\n\treturn -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "name_parse", "_file_name": "evdns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void dd_save_text(struct dump_dir *dd, const char *name, const char *data)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot save text. '%s' is not a valid file name\", name);\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);\n free(full_path);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_save_text", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getPostsByPostid(self,postid):\n sqlText=\"select users.name,post.comment from users,post where \\\n users.userid=post.userid and post.postid=%d\"%(postid)\n result=sql.queryDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[111, 181]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[111, 181]]}, "_func_name": "getPostsByPostid", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 curpos, offset = 0;\n\tRBinJavaLineNumberAttribute *lnattr;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;\n\tattr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->info.line_number_table_attr.line_number_table = r_list_newf (free);\n\n\tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n\tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n\tif (linenum_len > sz) {\n\t\tfree (attr);\n\t\treturn NULL;\n\t}\n\tfor (i = 0; i < linenum_len; i++) {\n\t\tcurpos = buf_offset + offset;\n\t\t// printf (\"%llx %llx \\n\", curpos, sz);\n\t\t// XXX if (curpos + 8 >= sz) break;\n\t\tlnattr = R_NEW0 (RBinJavaLineNumberAttribute);\n\t\tif (!lnattr) {\n\t\t\tbreak;\n\t\t}\n\t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tlnattr->file_offset = curpos;\n\t\tlnattr->size = 4;\n\t\tr_list_append (linenum_list, lnattr);\n\t}\n\tattr->size = offset;\n\treturn attr;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[996, 1053]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[996, 1053]]}, "_func_name": "r_bin_java_line_number_table_attr_new", "_file_name": "shlr/java/class.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def retrieve_playlist_by_id(id, db):\n db.execute(\n \"SELECT id, name, video_position from playlist WHERE id={id};\".format(id=id))\n row = db.fetchone()\n return row", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[53, 139]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[53, 139]]}, "_func_name": "retrieve_playlist_by_id", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void usb_sg_cancel(struct usb_sg_request *io)\n{\n\tunsigned long flags;\n\tint i, retval;\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tif (io->status || io->count == 0) {\n\t\tspin_unlock_irqrestore(&io->lock, flags);\n\t\treturn;\n\t}\n\t/* shut everything down */\n\tio->status = -ECONNRESET;\n\tio->count++;\t\t/* Keep the request alive until we're done */\n\tspin_unlock_irqrestore(&io->lock, flags);\n\n\tfor (i = io->entries - 1; i >= 0; --i) {\n\t\tusb_block_urb(io->urbs[i]);\n\n\t\tretval = usb_unlink_urb(io->urbs[i]);\n\t\tif (retval != -EINPROGRESS\n\t\t && retval != -ENODEV\n\t\t && retval != -EBUSY\n\t\t && retval != -EIDRM)\n\t\t\tdev_warn(&io->dev->dev, \"%s, unlink --> %d\\n\",\n\t\t\t\t __func__, retval);\n\t}\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tio->count--;\n\tif (!io->count)\n\t\tcomplete(&io->complete);\n\tspin_unlock_irqrestore(&io->lock, flags);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usb_sg_cancel", "_file_name": "drivers/usb/core/message.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n{\n\tbool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;\n\tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n\tunsigned int chunks, chunks_per_page;\n\tu64 addr = mr->addr, size = mr->len;\n\tint size_chk, err;\n\n\tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n\t\t/* Strictly speaking we could support this, if:\n\t\t * - huge pages, or*\n\t\t * - using an IOMMU, or\n\t\t * - making sure the memory area is consecutive\n\t\t * but for now, we simply say \"computer says no\".\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |\n\t\t\tXDP_UMEM_USES_NEED_WAKEUP))\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks && !is_power_of_2(chunk_size))\n\t\treturn -EINVAL;\n\n\tif (!PAGE_ALIGNED(addr)) {\n\t\t/* Memory area has to be page size aligned. For\n\t\t * simplicity, this might change.\n\t\t */\n\t\treturn -EINVAL;\n\t}\n\n\tif ((addr + size) < addr)\n\t\treturn -EINVAL;\n\n\tchunks = (unsigned int)div_u64(size, chunk_size);\n\tif (chunks == 0)\n\t\treturn -EINVAL;\n\n\tif (!unaligned_chunks) {\n\t\tchunks_per_page = PAGE_SIZE / chunk_size;\n\t\tif (chunks < chunks_per_page || chunks % chunks_per_page)\n\t\t\treturn -EINVAL;\n\t}\n\n\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n\tif (size_chk < 0)\n\t\treturn -EINVAL;\n\n\tumem->address = (unsigned long)addr;\n\tumem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK\n\t\t\t\t\t : ~((u64)chunk_size - 1);\n\tumem->size = size;\n\tumem->headroom = headroom;\n\tumem->chunk_size_nohr = chunk_size - headroom;\n\tumem->npgs = size / PAGE_SIZE;\n\tumem->pgs = NULL;\n\tumem->user = NULL;\n\tumem->flags = mr->flags;\n\tINIT_LIST_HEAD(&umem->xsk_list);\n\tspin_lock_init(&umem->xsk_list_lock);\n\n\trefcount_set(&umem->users, 1);\n\n\terr = xdp_umem_account_pages(umem);\n\tif (err)\n\t\treturn err;\n\n\terr = xdp_umem_pin_pages(umem);\n\tif (err)\n\t\tgoto out_account;\n\n\tumem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),\n\t\t\t GFP_KERNEL_ACCOUNT);\n\tif (!umem->pages) {\n\t\terr = -ENOMEM;\n\t\tgoto out_pin;\n\t}\n\n\terr = xdp_umem_map_pages(umem);\n\tif (!err)\n\t\treturn 0;\n\n\tkvfree(umem->pages);\n\nout_pin:\n\txdp_umem_unpin_pages(umem);\nout_account:\n\txdp_umem_unaccount_pages(umem);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[278, 298], [1202, 1278]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[278, 298], [1202, 1278]]}, "_func_name": "xdp_umem_reg", "_file_name": "net/xdp/xdp_umem.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int hci_uart_set_proto(struct hci_uart *hu, int id)\n{\n\tconst struct hci_uart_proto *p;\n\tint err;\n\n\tp = hci_uart_get_proto(id);\n\tif (!p)\n\t\treturn -EPROTONOSUPPORT;\n\n\thu->proto = p;\n\n\terr = hci_uart_register_dev(hu);\n\tif (err) {\n\t\treturn err;\n\t}\n\n\tset_bit(HCI_UART_PROTO_READY, &hu->flags);\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "hci_uart_set_proto", "_file_name": "drivers/bluetooth/hci_ldisc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_recvmsg(int sockfd, struct msghdr *msg, int flags) {\n size_t total_buffer_size = CalculateTotalMessageSize(msg);\n\n MessageWriter input;\n input.Push(sockfd);\n input.Push(msg->msg_namelen);\n input.Push(total_buffer_size);\n input.Push(msg->msg_controllen);\n input.Push(msg->msg_flags);\n input.Push(flags);\n\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvMsgHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvmsg\", 2,\n /*match_exact_params=*/false);\n\n ssize_t result = output.next();\n int klinux_errno = output.next();\n\n // recvmsg() returns the number of characters received. On error, -1 is\n // returned, with errno set to indicate the cause of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n auto msg_name_extent = output.next();\n // The returned |msg_namelen| should not exceed the buffer size.\n if (msg_name_extent.size() <= msg->msg_namelen) {\n msg->msg_namelen = msg_name_extent.size();\n }\n memcpy(msg->msg_name, msg_name_extent.As(), msg->msg_namelen);\n\n // A single buffer is passed from the untrusted side, copy it into the\n // scattered buffers inside the enclave.\n auto msg_iov_extent = output.next();\n size_t total_bytes = msg_iov_extent.size();\n size_t bytes_copied = 0;\n for (int i = 0; i < msg->msg_iovlen && bytes_copied < total_bytes; ++i) {\n size_t bytes_to_copy =\n std::min(msg->msg_iov[i].iov_len, total_bytes - bytes_copied);\n memcpy(msg->msg_iov[i].iov_base, msg_iov_extent.As() + bytes_copied,\n bytes_to_copy);\n bytes_copied += bytes_to_copy;\n }\n\n auto msg_control_extent = output.next();\n // The returned |msg_controllen| should not exceed the buffer size.\n if (msg_control_extent.size() <= msg->msg_controllen) {\n msg->msg_controllen = msg_control_extent.size();\n }\n memcpy(msg->msg_control, msg_control_extent.As(), msg->msg_controllen);\n\n return result;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[947, 987]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[947, 987]]}, "_func_name": "enc_untrusted_recvmsg", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)\n{\n\tGF_M2TS_Program *prog;\n\tGF_M2TS_SECTION_ES *pmt;\n\tu32 i, nb_progs, evt_type;\n\tu32 nb_sections;\n\tu32 data_size;\n\tunsigned char *data;\n\tGF_M2TS_Section *section;\n\n\t/*wait for the last section */\n\tif (!(status&GF_M2TS_TABLE_END)) return;\n\n\t/*skip if already received*/\n\tif (status&GF_M2TS_TABLE_REPEAT) {\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL);\n\t\treturn;\n\t}\n\n\tnb_sections = gf_list_count(sections);\n\tif (nb_sections > 1) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"PAT on multiple sections not supported\\n\"));\n\t}\n\n\tsection = (GF_M2TS_Section *)gf_list_get(sections, 0);\n\tdata = section->data;\n\tdata_size = section->data_size;\n\n\tif (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) {\n\t\tif (ts->pat->demux_restarted) {\n\t\t\tts->pat->demux_restarted = 0;\n\t\t} else {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\\n\", table_id, ex_table_id));\n\t\t}\n\t\treturn;\n\t}\n\tnb_progs = data_size / 4;\n\n\tfor (i=0; init) {\n\t\t\t\tts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);\n\t\t\t}\n\t\t} else if (!pid) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Broken PAT found reserved PID 0, ignoring\\n\", pid));\n\t\t} else if (! ts->ess[pid]) {\n\t\t\tGF_SAFEALLOC(prog, GF_M2TS_Program);\n\t\t\tif (!prog) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate program for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprog->streams = gf_list_new();\n\t\t\tprog->pmt_pid = pid;\n\t\t\tprog->number = number;\n\t\t\tprog->ts = ts;\n\t\t\tgf_list_add(ts->programs, prog);\n\t\t\tGF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);\n\t\t\tif (!pmt) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate pmt filter for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpmt->flags = GF_M2TS_ES_IS_SECTION;\n\t\t\tgf_list_add(prog->streams, pmt);\n\t\t\tpmt->pid = prog->pmt_pid;\n\t\t\tpmt->program = prog;\n\t\t\tts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;\n\t\t\tpmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);\n\t\t}\n\t}\n\n\tevt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND;\n\tif (ts->on_event) ts->on_event(ts, evt_type, NULL);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "gf_m2ts_process_pat", "_file_name": "src/media_tools/mpegts.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);\n free(full_path);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[179, 241]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[179, 241]]}, "_func_name": "dd_save_binary", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def process_as_reply(email_obj):\n job_number = email_obj['subject'].split(': #')[1]\n feedback = re.findall(\"^[\\W]*([Oo\\d]){1}(?=[\\W]*)\", email_obj['content'].replace('#','').replace('link', ''))[0]\n feedback = int(0 if feedback == ('O' or 'o') else feedback)\n dcn_key = re.findall('\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}', email_obj['content'])[0]\n logger.info(f\"got feedback `{feedback}` for job #`{job_number}`\")\n with create_connection() as conn:\n was_prev_closed = pd.read_sql(f\"SELECT * FROM df_dilfo WHERE job_number={job_number}\", conn).iloc[0].closed\n if was_prev_closed:\n logger.info(f\"job was already matched successfully and logged as `closed`... skipping.\")\n return\n if feedback == 1:\n logger.info(f\"got feeback that DCN key {dcn_key} was correct\")\n update_status_query = \"UPDATE df_dilfo SET closed = 1 WHERE job_number = {}\"\n with create_connection() as conn:\n conn.cursor().execute(update_status_query.format(job_number))\n logger.info(f\"updated df_dilfo to show `closed` status for job #{job_number}\")\n with create_connection() as conn:\n df = pd.read_sql(\"SELECT * FROM df_matched\", conn)\n match_dict_input = {\n 'job_number': job_number,\n 'dcn_key': dcn_key,\n 'ground_truth': 1 if feedback == 1 else 0,\n 'multi_phase': 1 if feedback == 2 else 0,\n 'verifier': email_obj[\"sender\"],\n 'source': 'feedback',\n 'log_date': str(datetime.datetime.now().date()),\n 'validate': 0,\n }\n df = df.append(match_dict_input, ignore_index=True)\n df = df.drop_duplicates(subset=[\"job_number\", \"dcn_key\"], keep='last')\n df.to_sql('df_matched', conn, if_exists='replace', index=False)\n logger.info(\n f\"DCN key `{dcn_key}` was a \"\n f\"{'successful match' if feedback == 1 else 'mis-match'} for job \"\n f\"#{job_number}\"\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[460, 576], [805, 890], [932, 1006]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[460, 576], [805, 890], [932, 1006]]}, "_func_name": "process_as_reply", "_file_name": "inbox_scanner.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def makeJudge(judge):\n\tdb.execute(\"UPDATE players SET Judge = 1 WHERE Name = '%s' COLLATE NOCASE\" % (judge)) \n\tdatabase.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[22, 110]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[22, 110]]}, "_func_name": "makeJudge", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)\n{\n QWriteLocker locker(&lock);\n\n Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) };\n m_peers.push_back(temp);\n\n if (m_peers.size() >= MAX_LOG_MESSAGES)\n m_peers.pop_front();\n\n emit newLogPeer(temp);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Logger::addPeer", "_file_name": "src/base/logger.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def new_goal():\n \"\"\"\n new goal\n \"\"\"\n\n goals_dir_check()\n\n goal_name_not_ok = True\n\n click.echo(chalk.blue('Input a single-word name of the goal:'))\n while goal_name_not_ok:\n goal_name = input().strip()\n if goal_name.isalnum():\n goal_name_not_ok = False\n else:\n click.echo(chalk.red('Only alphanumeric characters can be used! Please input the goal name:'))\n\n if goal_name_exists(goal_name):\n click.echo(chalk.red(\n 'A goal with this name already exists. Please type \"yoda goals view\" to see a list of existing goals'))\n else:\n click.echo(chalk.blue('Input description of the goal:'))\n text = input().strip()\n\n click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))\n incorrect_date_format = True\n while incorrect_date_format:\n deadline = input().strip()\n try:\n date_str = datetime.datetime.strptime(deadline, '%Y-%m-%d').strftime('%Y-%m-%d')\n if date_str != deadline:\n raise ValueError\n incorrect_date_format = False\n except ValueError:\n click.echo(chalk.red(\"Incorrect data format, should be YYYY-MM-DD. Please repeat:\"))\n\n if os.path.isfile(GOALS_CONFIG_FILE_PATH):\n setup_data = dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)\n else:\n setup_data = dict(\n entries=[\n dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n ]\n )\n input_data(setup_data, GOALS_CONFIG_FILE_PATH)\n\n input_data(dict(entries=[]), get_goal_file_path(goal_name))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "new_goal", "_file_name": "modules/goals.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n unsigned char **p,\n unsigned char *end )\n{\n int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n size_t len;\n ((void) ssl);\n\n /*\n * PSK parameters:\n *\n * opaque psk_identity_hint<0..2^16-1>;\n */\n if( (*p) > end - 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n len = (*p)[0] << 8 | (*p)[1];\n *p += 2;\n\n if( (*p) + len > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n /*\n * Note: we currently ignore the PKS identity hint, as we only allow one\n * PSK to be provisionned on the client. This could be changed later if\n * someone needs that feature.\n */\n *p += len;\n ret = 0;\n\n return( ret );\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[646, 673]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[646, 673]]}, "_func_name": "ssl_parse_server_psk_hint", "_file_name": "library/ssl_cli.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "set_interface_var(const char *iface,\n\t\t const char *var, const char *name,\n\t\t uint32_t val)\n{\n\tFILE *fp;\n\tchar spath[64+IFNAMSIZ];\t/* XXX: magic constant */\n\tif (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))\n\t\treturn -1;\n\n\tif (access(spath, F_OK) != 0)\n\t\treturn -1;\n\n\tfp = fopen(spath, \"w\");\n\tif (!fp) {\n\t\tif (name)\n\t\t\tflog(LOG_ERR, \"failed to set %s (%u) for %s: %s\",\n\t\t\t name, val, iface, strerror(errno));\n\t\treturn -1;\n\t}\n\tfprintf(fp, \"%u\", val);\n\tfclose(fp);\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[239, 270]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[239, 270]]}, "_func_name": "set_interface_var", "_file_name": "device-linux.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def fetch(url):\n '''Download and verify a package url.'''\n base = os.path.basename(url)\n print('Fetching %s...' % base)\n fetch_file(url + '.asc')\n fetch_file(url)\n fetch_file(url + '.sha256')\n fetch_file(url + '.asc.sha256')\n print('Verifying %s...' % base)\n # TODO: check for verification failure.\n subprocess.check_call(['shasum', '-c', base + '.sha256'])\n subprocess.check_call(['shasum', '-c', base + '.asc.sha256'])\n subprocess.check_call(['gpg', '--verify', base + '.asc', base])\n subprocess.check_call(['keybase', 'verify', base + '.asc'])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fetch", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n\tstruct user_namespace *user_ns)\n{\n\tmm->mmap = NULL;\n\tmm->mm_rb = RB_ROOT;\n\tmm->vmacache_seqnum = 0;\n\tatomic_set(&mm->mm_users, 1);\n\tatomic_set(&mm->mm_count, 1);\n\tinit_rwsem(&mm->mmap_sem);\n\tINIT_LIST_HEAD(&mm->mmlist);\n\tmm->core_state = NULL;\n\tatomic_long_set(&mm->nr_ptes, 0);\n\tmm_nr_pmds_init(mm);\n\tmm->map_count = 0;\n\tmm->locked_vm = 0;\n\tmm->pinned_vm = 0;\n\tmemset(&mm->rss_stat, 0, sizeof(mm->rss_stat));\n\tspin_lock_init(&mm->page_table_lock);\n\tmm_init_cpumask(mm);\n\tmm_init_aio(mm);\n\tmm_init_owner(mm, p);\n\tRCU_INIT_POINTER(mm->exe_file, NULL);\n\tmmu_notifier_mm_init(mm);\n\tinit_tlb_flush_pending(mm);\n#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS\n\tmm->pmd_huge_pte = NULL;\n#endif\n\n\tif (current->mm) {\n\t\tmm->flags = current->mm->flags & MMF_INIT_MASK;\n\t\tmm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;\n\t} else {\n\t\tmm->flags = default_dump_filter;\n\t\tmm->def_flags = 0;\n\t}\n\n\tif (mm_alloc_pgd(mm))\n\t\tgoto fail_nopgd;\n\n\tif (init_new_context(p, mm))\n\t\tgoto fail_nocontext;\n\n\tmm->user_ns = get_user_ns(user_ns);\n\treturn mm;\n\nfail_nocontext:\n\tmm_free_pgd(mm);\nfail_nopgd:\n\tfree_mm(mm);\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mm_init", "_file_name": "kernel/fork.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)\n{\n\tstruct snd_pcm_runtime *runtime;\n\tunsigned long flags;\n\n\tif (PCM_RUNTIME_CHECK(substream))\n\t\treturn;\n\truntime = substream->runtime;\n\n\tsnd_pcm_stream_lock_irqsave(substream, flags);\n\tif (!snd_pcm_running(substream) ||\n\t snd_pcm_update_hw_ptr0(substream, 1) < 0)\n\t\tgoto _end;\n\n#ifdef CONFIG_SND_PCM_TIMER\n\tif (substream->timer_running)\n\t\tsnd_timer_interrupt(substream->timer, 1);\n#endif\n _end:\n\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n\tkill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[463, 564]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[463, 564]]}, "_func_name": "snd_pcm_period_elapsed", "_file_name": "sound/core/pcm_lib.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tconst char *section_name = \"\";\n\tconst char *link_section_name = \"\";\n\tchar *end = NULL;\n\tElf_(Shdr) *link_shdr = NULL;\n\tut8 dfs[sizeof (Elf_(Verdef))] = {0};\n\tSdb *sdb;\n\tint cnt, i;\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn false;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {\n\t\treturn false;\n\t}\n\tElf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));\n\tif (!defs) {\n\t\treturn false;\n\t}\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!defs) {\n\t\tbprintf (\"Warning: Cannot allocate memory (Check Elf_(Verdef))\\n\");\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tend = (char *)defs + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) {\n\t\tSdb *sdb_verdef = sdb_new0 ();\n\t\tchar *vstart = ((char*)defs) + i;\n\t\tchar key[32] = {0};\n\t\tElf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;\n\t\tElf_(Verdaux) aux = {0};\n\t\tint j = 0;\n\t\tint isum = 0;\n\n\t\tr_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));\n\t\tverdef->vd_version = READ16 (dfs, j)\n\t\tverdef->vd_flags = READ16 (dfs, j)\n\t\tverdef->vd_ndx = READ16 (dfs, j)\n\t\tverdef->vd_cnt = READ16 (dfs, j)\n\t\tverdef->vd_hash = READ32 (dfs, j)\n\t\tverdef->vd_aux = READ32 (dfs, j)\n\t\tverdef->vd_next = READ32 (dfs, j)\n\t\tint vdaux = verdef->vd_aux;\n\t\tif (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tvstart += vdaux;\n\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tj = 0;\n\t\taux.vda_name = READ32 (vstart, j)\n\t\taux.vda_next = READ32 (vstart, j)\n\n\t\tisum = i + verdef->vd_aux;\n\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tsdb_num_set (sdb_verdef, \"idx\", i, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_version\", verdef->vd_version, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_ndx\", verdef->vd_ndx, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_cnt\", verdef->vd_cnt, 0);\n\t\tsdb_set (sdb_verdef, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\tsdb_set (sdb_verdef, \"flags\", get_ver_flags (verdef->vd_flags), 0);\n\n\t\tfor (j = 1; j < verdef->vd_cnt; ++j) {\n\t\t\tint k;\n\t\t\tSdb *sdb_parent = sdb_new0 ();\n\t\t\tisum += aux.vda_next;\n\t\t\tvstart += aux.vda_next;\n\t\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tk = 0;\n\t\t\taux.vda_name = READ32 (vstart, k)\n\t\t\taux.vda_next = READ32 (vstart, k)\n\t\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_parent, \"idx\", isum, 0);\n\t\t\tsdb_num_set (sdb_parent, \"parent\", j, 0);\n\t\t\tsdb_set (sdb_parent, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\t\tsnprintf (key, sizeof (key), \"parent%d\", j - 1);\n\t\t\tsdb_ns_set (sdb_verdef, key, sdb_parent);\n\t\t}\n\n\t\tsnprintf (key, sizeof (key), \"verdef%d\", cnt);\n\t\tsdb_ns_set (sdb, key, sdb_verdef);\n\t\tif (!verdef->vd_next) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tif ((st32)verdef->vd_next < 1) {\n\t\t\teprintf (\"Warning: Invalid vd_next in the ELF version\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += verdef->vd_next;\n\t}\n\tfree (defs);\n\treturn sdb;\nout_error:\n\tfree (defs);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "store_versioninfo_gnu_verdef", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,\n xkb_mod_mask_t *mods_rtrn, CompatInfo *info)\n{\n if (expr == NULL) {\n *pred_rtrn = MATCH_ANY_OR_NONE;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n *pred_rtrn = MATCH_EXACTLY;\n if (expr->expr.op == EXPR_ACTION_DECL) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);\n if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {\n log_err(info->ctx,\n \"Illegal modifier predicate \\\"%s\\\"; Ignored\\n\", pred_txt);\n return false;\n }\n expr = expr->action.args;\n }\n else if (expr->expr.op == EXPR_IDENT) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);\n if (pred_txt && istreq(pred_txt, \"any\")) {\n *pred_rtrn = MATCH_ANY;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n }\n\n return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,\n mods_rtrn);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[434, 512]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[434, 512]]}, "_func_name": "ResolveStateAndPredicate", "_file_name": "src/xkbcomp/compat.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "mrb_obj_clone(mrb_state *mrb, mrb_value self)\n{\n struct RObject *p;\n mrb_value clone;\n\n if (mrb_immediate_p(self)) {\n mrb_raisef(mrb, E_TYPE_ERROR, \"can't clone %S\", self);\n }\n if (mrb_type(self) == MRB_TT_SCLASS) {\n mrb_raise(mrb, E_TYPE_ERROR, \"can't clone singleton class\");\n }\n p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));\n p->c = mrb_singleton_class_clone(mrb, self);\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);\n clone = mrb_obj_value(p);\n init_copy(mrb, clone, self);\n p->flags = mrb_obj_ptr(self)->flags;\n\n return clone;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[557, 596]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[557, 596]]}, "_func_name": "mrb_obj_clone", "_file_name": "src/kernel.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/summary', methods=['GET'])\ndef summary():\n\tif 'username' in session:\n\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor()\n\n\t\t#select the maximum score from the results table\n\t\tcursor.execute(\"SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s\", (session['username']));\n\t\tcourseConcentration = cursor.fetchone()\n\n\t\treturn render_template('summary.html', courseConcentration = courseConcentration[0])\n\treturn redirect(url_for('login'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "summary", "_file_name": "src/tech_track.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def delete_playlists_videos(playlist_id, db):\n db.execute(\"DELETE FROM video where playlist_id={playlist_id};\".format(\n playlist_id=playlist_id))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[46, 155]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[46, 155]]}, "_func_name": "delete_playlists_videos", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def zmi_page_request(self, *args, **kwargs):\r\n request = self.REQUEST\r\n RESPONSE = request.RESPONSE\r\n SESSION = request.SESSION\r\n self._zmi_page_request()\r\n RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822())\r\n RESPONSE.setHeader('Cache-Control', 'no-cache')\r\n RESPONSE.setHeader('Pragma', 'no-cache')\r\n RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET'])\r\n if not request.get( 'preview'):\r\n request.set( 'preview','preview')\r\n langs = self.getLanguages(request)\r\n if request.get('lang') not in langs:\r\n request.set('lang',langs[0])\r\n if request.get('manage_lang') not in self.getLocale().get_manage_langs():\r\n request.set('manage_lang',self.get_manage_lang())\r\n if not request.get('manage_tabs_message'):\r\n request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message',''))\r\n # manage_system\r\n if request.form.has_key('zmi-manage-system'):\r\n request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system')))\r\n # avoid declarative urls\r\n physical_path = self.getPhysicalPath()\r\n path_to_handle = request['URL0'][len(request['BASE0']):].split('/')\r\n path = path_to_handle[:-1]\r\n if len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n for i in range(len(path)):\r\n if path[:-(i+1)] != physical_path[:-(i+1)]:\r\n path[:-(i+1)] = physical_path[:-(i+1)]\r\n new_path = path+[path_to_handle[-1]]\r\n if path_to_handle != new_path:\r\n request.RESPONSE.redirect('/'.join(new_path))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1313, 1395]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1313, 1395]]}, "_func_name": "zmi_page_request", "_file_name": "ZMSItem.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void gps_tracker( void )\n{\n\tssize_t unused;\n int gpsd_sock;\n char line[256], *temp;\n struct sockaddr_in gpsd_addr;\n int ret, is_json, pos;\n fd_set read_fd;\n struct timeval timeout;\n\n /* attempt to connect to localhost, port 2947 */\n\n pos = 0;\n gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 );\n\n if( gpsd_sock < 0 ) {\n return;\n }\n\n gpsd_addr.sin_family = AF_INET;\n gpsd_addr.sin_port = htons( 2947 );\n gpsd_addr.sin_addr.s_addr = inet_addr( \"127.0.0.1\" );\n\n if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr,\n sizeof( gpsd_addr ) ) < 0 ) {\n return;\n }\n\n // Check if it's GPSd < 2.92 or the new one\n // 2.92+ immediately send stuff\n // < 2.92 requires to send PVTAD command\n FD_ZERO(&read_fd);\n FD_SET(gpsd_sock, &read_fd);\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout);\n if (is_json) {\n \t/*\n\t\t\t{\"class\":\"VERSION\",\"release\":\"2.95\",\"rev\":\"2010-11-16T21:12:35\",\"proto_major\":3,\"proto_minor\":3}\n\t\t\t?WATCH={\"json\":true};\n\t\t\t{\"class\":\"DEVICES\",\"devices\":[]}\n \t */\n\n\n \t// Get the crap and ignore it: {\"class\":\"VERSION\",\"release\":\"2.95\",\"rev\":\"2010-11-16T21:12:35\",\"proto_major\":3,\"proto_minor\":3}\n \tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n \t\treturn;\n\n \tis_json = (line[0] == '{');\n \tif (is_json) {\n\t\t\t// Send ?WATCH={\"json\":true};\n\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\tstrcpy(line, \"?WATCH={\\\"json\\\":true};\\n\");\n\t\t\tif( send( gpsd_sock, line, 22, 0 ) != 22 )\n\t\t\t\treturn;\n\n\t\t\t// Check that we have devices\n\t\t\tmemset(line, 0, sizeof(line));\n\t\t\tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n\t\t\t\treturn;\n\n\t\t\t// Stop processing if there is no device\n\t\t\tif (strncmp(line, \"{\\\"class\\\":\\\"DEVICES\\\",\\\"devices\\\":[]}\", 32) == 0) {\n\t\t\t\tclose(gpsd_sock);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tpos = strlen(line);\n\t\t\t}\n \t}\n }\n\n /* loop reading the GPS coordinates */\n\n while( G.do_exit == 0 )\n {\n usleep( 500000 );\n memset( G.gps_loc, 0, sizeof( float ) * 5 );\n\n /* read position, speed, heading, altitude */\n if (is_json) {\n \t// Format definition: http://catb.org/gpsd/gpsd_json.html\n\n \tif (pos == sizeof( line )) {\n \t\tmemset(line, 0, sizeof(line));\n \t\tpos = 0;\n \t}\n\n \t// New version, JSON\n \tif( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 )\n \t\treturn;\n\n \t// search for TPV class: {\"class\":\"TPV\"\n \ttemp = strstr(line, \"{\\\"class\\\":\\\"TPV\\\"\");\n \tif (temp == NULL) {\n \t\tcontinue;\n \t}\n\n \t// Make sure the data we have is complete\n \tif (strchr(temp, '}') == NULL) {\n \t\t// Move the data at the beginning of the buffer;\n \t\tpos = strlen(temp);\n \t\tif (temp != line) {\n \t\t\tmemmove(line, temp, pos);\n \t\t\tmemset(line + pos, 0, sizeof(line) - pos);\n \t\t}\n \t}\n\n\t\t\t// Example line: {\"class\":\"TPV\",\"tag\":\"MID2\",\"device\":\"/dev/ttyUSB0\",\"time\":1350957517.000,\"ept\":0.005,\"lat\":46.878936576,\"lon\":-115.832602964,\"alt\":1968.382,\"track\":0.0000,\"speed\":0.000,\"climb\":0.000,\"mode\":3}\n\n \t// Latitude\n \ttemp = strstr(temp, \"\\\"lat\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[0]);\n\n\t\t\t// Longitude\n\t\t\ttemp = strstr(temp, \"\\\"lon\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[1]);\n\n\t\t\t// Altitude\n\t\t\ttemp = strstr(temp, \"\\\"alt\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[4]);\n\n\t\t\t// Speed\n\t\t\ttemp = strstr(temp, \"\\\"speed\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[2]);\n\n\t\t\t// No more heading\n\n\t\t\t// Get the next TPV class\n\t\t\ttemp = strstr(temp, \"{\\\"class\\\":\\\"TPV\\\"\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\t\tpos = 0;\n\t\t\t} else {\n\t\t\t\tpos = strlen(temp);\n\t\t\t\tmemmove(line, temp, pos);\n\t\t\t\tmemset(line + pos, 0, sizeof(line) - pos);\n\t\t\t}\n\n } else {\n \tmemset( line, 0, sizeof( line ) );\n\n\t\t\tsnprintf( line, sizeof( line ) - 1, \"PVTAD\\r\\n\" );\n\t\t\tif( send( gpsd_sock, line, 7, 0 ) != 7 )\n\t\t\t\treturn;\n\n\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n\t\t\t\treturn;\n\n\t\t\tif( memcmp( line, \"GPSD,P=\", 7 ) != 0 )\n\t\t\t\tcontinue;\n\n\t\t\t/* make sure the coordinates are present */\n\n\t\t\tif( line[7] == '?' )\n\t\t\t\tcontinue;\n\n\t\t\tret = sscanf( line + 7, \"%f %f\", &G.gps_loc[0], &G.gps_loc[1] );\n\n\t\t\tif( ( temp = strstr( line, \"V=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[2] ); /* speed */\n\n\t\t\tif( ( temp = strstr( line, \"T=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[3] ); /* heading */\n\n\t\t\tif( ( temp = strstr( line, \"A=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[4] ); /* altitude */\n }\n\n if (G.record_data)\n\t\t\tfputs( line, G.f_gps );\n\n\t\tG.save_gps = 1;\n\n if (G.do_exit == 0)\n\t\t{\n\t\t\tunused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 );\n\t\t\tkill( getppid(), SIGUSR2 );\n\t\t}\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[2379, 2452]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2379, 2452]]}, "_func_name": "gps_tracker", "_file_name": "src/airodump-ng.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def update_video_positions(removed_position, db):\n db.execute(\"UPDATE video SET position = position - 1 WHERE position > {removed_position}\".format(\n removed_position=removed_position))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[50, 195]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[50, 195]]}, "_func_name": "update_video_positions", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,\n\t\toidc_session_t *session, const char *client_id,\n\t\tconst char *check_session_iframe) {\n\n\toidc_debug(r, \"enter\");\n\n\tconst char *java_script =\n\t\t\t\" \\n\";\n\n\t/* determine the origin for the check_session_iframe endpoint */\n\tchar *origin = apr_pstrdup(r->pool, check_session_iframe);\n\tapr_uri_t uri;\n\tapr_uri_parse(r->pool, check_session_iframe, &uri);\n\tchar *p = strstr(origin, uri.path);\n\t*p = '\\0';\n\n\t/* the element identifier for the OP iframe */\n\tconst char *op_iframe_id = \"openidc-op\";\n\n\t/* restore the OP session_state from the session */\n\tconst char *session_state = oidc_session_get_session_state(r, session);\n\tif (session_state == NULL) {\n\t\toidc_warn(r,\n\t\t\t\t\"no session_state found in the session; the OP does probably not support session management!?\");\n\t\treturn DONE;\n\t}\n\n\tchar *s_poll_interval = NULL;\n\toidc_util_get_request_parameter(r, \"poll\", &s_poll_interval);\n\tif (s_poll_interval == NULL)\n\t\ts_poll_interval = \"3000\";\n\n\tconst char *redirect_uri = oidc_get_redirect_uri(r, c);\n\tjava_script = apr_psprintf(r->pool, java_script, origin, client_id,\n\t\t\tsession_state, op_iframe_id, s_poll_interval, redirect_uri,\n\t\t\tredirect_uri);\n\n\treturn oidc_util_html_send(r, NULL, java_script, \"setTimer\", NULL, DONE);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[743, 803], [2273, 2331], [2458, 2521]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[743, 803], [2273, 2331], [2458, 2521]]}, "_func_name": "oidc_handle_session_management_iframe_rp", "_file_name": "src/mod_auth_openidc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int string_scan_range(RList *list, const ut8 *buf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc;\n\t\t\tif ((to - needle) > 4) {\n\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\n\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r)) {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\e\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 28) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t// reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (list) {\n\t\t\t\tRBinString *new = R_NEW0 (RBinString);\n\t\t\t\tif (!new) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->type = str_type;\n\t\t\t\tnew->length = runes;\n\t\t\t\tnew->size = needle - str_start;\n\t\t\t\tnew->ordinal = count++;\n\t\t\t\t// TODO: move into adjust_offset\n\t\t\t\tswitch (str_type) {\n\t\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\t\tif (str_start > 1) {\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\t\tif (str_start > 3) {\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->paddr = new->vaddr = str_start;\n\t\t\t\tnew->string = r_str_ndup ((const char *)tmp, i);\n\t\t\t\tr_list_append (list, new);\n\t\t\t} else {\n\t\t\t\t// DUMP TO STDOUT. raw dumping for rabin2 -zzz\n\t\t\t\tprintf (\"0x%08\" PFMT64x \" %s\\n\", str_start, tmp);\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "string_scan_range", "_file_name": "libr/bin/bin.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n{\n int i, j, v;\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = v;\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* chroma_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n /* chroma_non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n next_start_code_studio(gb);\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "read_quant_matrix_ext", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_rank(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n SELECT (SELECT COUNT(*) FROM people AS t2 WHERE t2.karma > t1.karma)\n AS row_Num FROM people AS t1 WHERE name=%(name)s\n ''', (name, ))\n rank = cursor.fetchone()[0] + 1\n logger.debug('Rank of {} found for name {}'.format(rank, name))\n db.close()\n return rank\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "karma_rank", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def list_editor_workflows(request): \n workflows = [d.content_object.to_dict() for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n return render('editor/list_editor_workflows.mako', request, {\n 'workflows_json': json.dumps(workflows)\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[225, 271]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[225, 271]]}, "_func_name": "list_editor_workflows", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/get_asset_and_volume')\ndef get_asset_and_volume():\n asset_id = request.args.get('asset_id')\n\n if not isObject(asset_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_asset_symbols\",[[\"' + asset_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n asset_id = j_l[\"result\"][0][\"id\"]\n\n #print asset_id\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"get_assets\",[[\"' + asset_id + '\"], 0]]}')\n result = ws.recv()\n j = json.loads(result)\n\n dynamic_asset_data_id = j[\"result\"][0][\"dynamic_asset_data_id\"]\n\n ws.send('{\"id\": 1, \"method\": \"call\", \"params\": [0, \"get_objects\", [[\"'+dynamic_asset_data_id+'\"]]]}')\n result2 = ws.recv()\n j2 = json.loads(result2)\n #print j2[\"result\"][0][\"current_supply\"]\n\n j[\"result\"][0][\"current_supply\"] = j2[\"result\"][0][\"current_supply\"]\n j[\"result\"][0][\"confidential_supply\"] = j2[\"result\"][0][\"confidential_supply\"]\n #print j[\"result\"]\n\n j[\"result\"][0][\"accumulated_fees\"] = j2[\"result\"][0][\"accumulated_fees\"]\n j[\"result\"][0][\"fee_pool\"] = j2[\"result\"][0][\"fee_pool\"]\n\n issuer = j[\"result\"][0][\"issuer\"]\n ws.send('{\"id\": 1, \"method\": \"call\", \"params\": [0, \"get_objects\", [[\"'+issuer+'\"]]]}')\n result3 = ws.recv()\n j3 = json.loads(result3)\n j[\"result\"][0][\"issuer_name\"] = j3[\"result\"][0][\"name\"]\n\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT volume, mcap FROM assets WHERE aid='\"+asset_id+\"'\"\n cur.execute(query)\n results = cur.fetchall()\n con.close()\n try:\n j[\"result\"][0][\"volume\"] = results[0][0]\n j[\"result\"][0][\"mcap\"] = results[0][1]\n except:\n j[\"result\"][0][\"volume\"] = 0\n j[\"result\"][0][\"mcap\"] = 0\n\n return jsonify(j[\"result\"])", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1428, 1499]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1428, 1499]]}, "_func_name": "get_asset_and_volume", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static long do_get_mempolicy(int *policy, nodemask_t *nmask,\n\t\t\t unsigned long addr, unsigned long flags)\n{\n\tint err;\n\tstruct mm_struct *mm = current->mm;\n\tstruct vm_area_struct *vma = NULL;\n\tstruct mempolicy *pol = current->mempolicy;\n\n\tif (flags &\n\t\t~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))\n\t\treturn -EINVAL;\n\n\tif (flags & MPOL_F_MEMS_ALLOWED) {\n\t\tif (flags & (MPOL_F_NODE|MPOL_F_ADDR))\n\t\t\treturn -EINVAL;\n\t\t*policy = 0;\t/* just so it's initialized */\n\t\ttask_lock(current);\n\t\t*nmask = cpuset_current_mems_allowed;\n\t\ttask_unlock(current);\n\t\treturn 0;\n\t}\n\n\tif (flags & MPOL_F_ADDR) {\n\t\t/*\n\t\t * Do NOT fall back to task policy if the\n\t\t * vma/shared policy at addr is NULL. We\n\t\t * want to return MPOL_DEFAULT in this case.\n\t\t */\n\t\tdown_read(&mm->mmap_sem);\n\t\tvma = find_vma_intersection(mm, addr, addr+1);\n\t\tif (!vma) {\n\t\t\tup_read(&mm->mmap_sem);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\tif (vma->vm_ops && vma->vm_ops->get_policy)\n\t\t\tpol = vma->vm_ops->get_policy(vma, addr);\n\t\telse\n\t\t\tpol = vma->vm_policy;\n\t} else if (addr)\n\t\treturn -EINVAL;\n\n\tif (!pol)\n\t\tpol = &default_policy;\t/* indicates default behavior */\n\n\tif (flags & MPOL_F_NODE) {\n\t\tif (flags & MPOL_F_ADDR) {\n\t\t\terr = lookup_node(addr);\n\t\t\tif (err < 0)\n\t\t\t\tgoto out;\n\t\t\t*policy = err;\n\t\t} else if (pol == current->mempolicy &&\n\t\t\t\tpol->mode == MPOL_INTERLEAVE) {\n\t\t\t*policy = next_node_in(current->il_prev, pol->v.nodes);\n\t\t} else {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\t*policy = pol == &default_policy ? MPOL_DEFAULT :\n\t\t\t\t\t\tpol->mode;\n\t\t/*\n\t\t * Internal mempolicy flags must be masked off before exposing\n\t\t * the policy to userspace.\n\t\t */\n\t\t*policy |= (pol->flags & MPOL_MODE_FLAGS);\n\t}\n\n\terr = 0;\n\tif (nmask) {\n\t\tif (mpol_store_user_nodemask(pol)) {\n\t\t\t*nmask = pol->w.user_nodemask;\n\t\t} else {\n\t\t\ttask_lock(current);\n\t\t\tget_policy_nodemask(pol, nmask);\n\t\t\ttask_unlock(current);\n\t\t}\n\t}\n\n out:\n\tmpol_cond_put(pol);\n\tif (vma)\n\t\tup_read(¤t->mm->mmap_sem);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "do_get_mempolicy", "_file_name": "mm/mempolicy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_day_data_row(self, ts, data, prev_etotal):\n\n if data['power'] > 0:\n\n inv_serial = data['source']['serial_id']\n query = '''\n INSERT INTO DayData (\n TimeStamp,\n Serial,\n Power,\n TotalYield\n ) VALUES (\n %s,\n %s,\n %s,\n %s\n );\n ''' % (ts, inv_serial, data['power'], prev_etotal + data['energy'])\n self.c.execute(query)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[340, 431], [449, 563]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[340, 431], [449, 563]]}, "_func_name": "add_day_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void *__ns_get_path(struct path *path, struct ns_common *ns)\n{\n\tstruct vfsmount *mnt = nsfs_mnt;\n\tstruct qstr qname = { .name = \"\", };\n\tstruct dentry *dentry;\n\tstruct inode *inode;\n\tunsigned long d;\n\n\trcu_read_lock();\n\td = atomic_long_read(&ns->stashed);\n\tif (!d)\n\t\tgoto slow;\n\tdentry = (struct dentry *)d;\n\tif (!lockref_get_not_dead(&dentry->d_lockref))\n\t\tgoto slow;\n\trcu_read_unlock();\n\tns->ops->put(ns);\ngot_it:\n\tpath->mnt = mntget(mnt);\n\tpath->dentry = dentry;\n\treturn NULL;\nslow:\n\trcu_read_unlock();\n\tinode = new_inode_pseudo(mnt->mnt_sb);\n\tif (!inode) {\n\t\tns->ops->put(ns);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\tinode->i_ino = ns->inum;\n\tinode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);\n\tinode->i_flags |= S_IMMUTABLE;\n\tinode->i_mode = S_IFREG | S_IRUGO;\n\tinode->i_fop = &ns_file_operations;\n\tinode->i_private = ns;\n\n\tdentry = d_alloc_pseudo(mnt->mnt_sb, &qname);\n\tif (!dentry) {\n\t\tiput(inode);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\td_instantiate(dentry, inode);\n\tdentry->d_fsdata = (void *)ns->ops;\n\td = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry);\n\tif (d) {\n\t\td_delete(dentry);\t/* make sure ->d_prune() does nothing */\n\t\tdput(dentry);\n\t\tcpu_relax();\n\t\treturn ERR_PTR(-EAGAIN);\n\t}\n\tgoto got_it;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[985, 1022]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[985, 1022]]}, "_func_name": "__ns_get_path", "_file_name": "fs/nsfs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def start():\n print(\"[*] Starting backdoor process\")\n print(\"[*] Decompressing target to tmp directory...\")\n #subprocess.call(\"jar -x %s\" % target, shell=True)\n with zipfile.ZipFile(target, 'r') as zip:\n zip.extractall(\"tmp\")\n print(\"[*] Target dumped to tmp directory\")\n\n print(\"[*] Modifying manifest file...\")\n oldmain=\"\"\n man = open(\"tmp/META-INF/MANIFEST.MF\",\"r\").read()\n with open(\"tmp/META-INF/MANIFEST.MF\",\"w\") as f:\n for l in man.split(\"\\n\"):\n if \"Main-Class\" in l:\n oldmain=l[12:]\n f.write(\"Main-Class: %s\\n\" % \"Backdoor\")\n else:\n f.write(\"%s\\n\" % l)\n print(\"[*] Manifest file modified\")\n \n print(\"[*] Modifying provided backdoor...\")\n inmain=False\n level=0\n bd=open(backdoor, \"r\").read()\n with open(\"tmp/%s\" % backdoor,'w') as f:\n for l in bd.split(\"\\n\"):\n if \"main(\" in l:\n inmain=True\n f.write(l)\n elif \"}\" in l and level<2 and inmain:\n f.write(\"%s.main(args);}\" % oldmain)\n inmain=False\n elif \"}\" in l and level>1 and inmain:\n level-=1\n f.write(l)\n elif \"{\" in l and inmain:\n level+=1\n f.write(l)\n else:\n f.write(l)\n print(\"[*] Provided backdoor successfully modified\")\n\n print(\"[*] Compiling modified backdoor...\")\n if subprocess.call(\"javac -cp tmp/ tmp/%s\" % backdoor, shell=True) != 0:\n print(\"[!] Error compiling %s\" % backdoor)\n print(\"[*] Compiled modified backdoor\")\n \n if(len(oldmain)<1):\n print(\"[!] Main-Class manifest attribute not found\")\n else:\n print(\"[*] Repackaging target jar file...\")\n createZip(\"tmp\",outfile)\n print(\"[*] Target jar successfully repackaged\")\n shutil.rmtree('tmp/')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1462, 1539]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1462, 1539]]}, "_func_name": "start", "_file_name": "ajar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {\n\tRASN1Object *object;\n\tRCMS *container;\n\tif (!buffer || !length) {\n\t\treturn NULL;\n\t}\n\tcontainer = R_NEW0 (RCMS);\n\tif (!container) {\n\t\treturn NULL;\n\t}\n\tobject = r_asn1_create_object (buffer, length);\n\tif (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {\n\t\tr_asn1_free_object (object);\n\t\tfree (container);\n\t\treturn NULL;\n\t}\n\tcontainer->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);\n\tr_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);\n\tr_asn1_free_object (object);\n\treturn container;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[258, 375]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[258, 375]]}, "_func_name": "r_pkcs7_parse_cms", "_file_name": "libr/util/r_pkcs7.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def process_vote(target,action,chan,mask,db,notice,conn):\n if ' ' in target: \n notice('Invalid nick')\n return\n\n try: votes2kick = database.get(db,'channels','votekick','chan',chan)\n except: votes2kick = 10\n try: votes2ban = database.get(db,'channels','voteban','chan',chan)\n except: votes2ban = 10\n\n if len(target) is 0:\n if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick))\n elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban))\n return\n\n votefinished = False\n global db_ready\n if not db_ready: db_init(db)\n chan = chan.lower()\n target = target.lower()\n voter = user.format_hostmask(mask)\n voters = db.execute(\"SELECT voters FROM votes where chan=? and action=? and target like ?\", chan, action, target).fetchone()\n\n if conn.nick.lower() in target: return \"I dont think so Tim.\"\n\n if voters: \n voters = voters[0]\n if voter in voters: \n notice(\"You have already voted.\")\n return\n else:\n voters = '{} {}'.format(voters,voter).strip()\n notice(\"Thank you for your vote!\")\n else: \n voters = voter\n\n votecount = len(voters.split(' '))\n\n if 'kick' in action: \n votemax = int(votes2kick)\n if votecount >= votemax:\n votefinished = True\n conn.send(\"KICK {} {} :{}\".format(chan, target, \"You have been voted off the island.\"))\n if 'ban' in action:\n votemax = int(votes2ban)\n if votecount >= votemax:\n votefinished = True\n conn.send(\"MODE {} +b {}\".format(chan, user.get_hostmask(target,db)))\n conn.send(\"KICK {} {} :\".format(chan, target, \"You have been voted off the island.\"))\n \n if votefinished: db.execute(\"DELETE FROM votes where chan=? and action=? and target like ?\", chan, action, target)\n else: db.execute(\"insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)\", (chan, action, target, voters, time.time()))\n \n db.commit()\n return (\"Votes to {} {}: {}/{}\".format(action, target, votecount,votemax))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_vote", "_file_name": "plugins/vote.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "INST_HANDLER (lds) {\t// LDS Rd, k\n\tif (len < 4) {\n\t\treturn;\n\t}\n\tint d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);\n\tint k = (buf[3] << 8) | buf[2];\n\top->ptr = k;\n\n\t// load value from RAMPD:k\n\t__generic_ld_st (op, \"ram\", 0, 1, 0, k, 0);\n\tESIL_A (\"r%d,=,\", d);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "INST_HANDLER", "_file_name": "libr/anal/p/anal_avr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _find_host_from_wwpn(self, connector):\n for wwpn in connector['wwpns']:\n ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n # This WWPN is not in use\n continue\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('remote_wwpn' in header and\n 'name' in header,\n '_find_host_from_wwpn',\n ssh_cmd, out, err)\n rmt_wwpn_idx = header.index('remote_wwpn')\n name_idx = header.index('name')\n\n wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)\n\n if wwpn in wwpns:\n # All the wwpns will be the mapping for the same\n # host from this WWPN-based query. Just pick\n # the name from first line.\n hostname = host_lines[0].split('!')[name_idx]\n return hostname\n\n # Didn't find a host\n return None", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_find_host_from_wwpn", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)\ndef get_task(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n name = conn.fetchone()\n settings.close()\n if name == None:\n bot.send_message(message.chat.id, \"You should login before get tasks.\")\n else:\n bases.update.update_user(name[1], name[0], name[2])\n bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))\n set_state(message.chat.id, config.States.S_START.value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[266, 353]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[266, 353]]}, "_func_name": "get_task", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@login_required(redirect_field_name='', login_url='/403')\n@require_POST\n@require_AJAX\n@transaction.atomic\ndef batch_edit_translations(request):\n \"\"\"Perform an action on a list of translations.\n\n Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view\n are defined in `models.BatchActionsForm`.\n\n \"\"\"\n form = forms.BatchActionsForm(request.POST)\n if not form.is_valid():\n return HttpResponseBadRequest(form.errors.as_json())\n\n locale = get_object_or_404(Locale, code=form.cleaned_data['locale'])\n entities = Entity.objects.filter(pk__in=form.cleaned_data['entities'])\n\n if not entities.exists():\n return JsonResponse({'count': 0})\n\n # Batch editing is only available to translators. Check if user has\n # translate permissions for all of the projects in passed entities.\n # Also make sure projects are not enabled in read-only mode for a locale.\n projects_pk = entities.values_list('resource__project__pk', flat=True)\n projects = Project.objects.filter(pk__in=projects_pk.distinct())\n\n for project in projects:\n if (\n not request.user.can_translate(project=project, locale=locale)\n or readonly_exists(projects, locale)\n ):\n return HttpResponseForbidden(\n \"Forbidden: You don't have permission for batch editing\"\n )\n\n # Find all impacted active translations, including plural forms.\n active_translations = Translation.objects.filter(\n active=True,\n locale=locale,\n entity__in=entities,\n )\n\n # Execute the actual action.\n action_function = ACTIONS_FN_MAP[form.cleaned_data['action']]\n action_status = action_function(\n form,\n request.user,\n active_translations,\n locale,\n )\n\n if action_status.get('error'):\n return JsonResponse(action_status)\n\n invalid_translation_count = len(action_status.get('invalid_translation_pks', []))\n if action_status['count'] == 0:\n return JsonResponse({\n 'count': 0,\n 'invalid_translation_count': invalid_translation_count,\n })\n\n update_stats(action_status['translated_resources'], locale)\n mark_changed_translation(action_status['changed_entities'], locale)\n\n # Update latest translation.\n if action_status['latest_translation_pk']:\n Translation.objects.get(\n pk=action_status['latest_translation_pk']\n ).update_latest_translation()\n\n update_translation_memory(\n action_status['changed_translation_pks'],\n project,\n locale\n )\n\n return JsonResponse({\n 'count': action_status['count'],\n 'invalid_translation_count': invalid_translation_count,\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[406, 467]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[406, 467]]}, "_func_name": "batch_edit_translations", "_file_name": "pontoon/batch/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def take_bug_report(self, test_name, begin_time):\n \"\"\"Takes a bug report on the device and stores it in a file.\n\n Args:\n test_name: Name of the test case that triggered this bug report.\n begin_time: Logline format timestamp taken when the test started.\n \"\"\"\n new_br = True\n try:\n stdout = self.adb.shell('bugreportz -v').decode('utf-8')\n # This check is necessary for builds before N, where adb shell's ret\n # code and stderr are not propagated properly.\n if 'not found' in stdout:\n new_br = False\n except adb.AdbError:\n new_br = False\n br_path = os.path.join(self.log_path, 'BugReports')\n utils.create_dir(br_path)\n base_name = ',%s,%s.txt' % (begin_time, self.serial)\n if new_br:\n base_name = base_name.replace('.txt', '.zip')\n test_name_len = utils.MAX_FILENAME_LEN - len(base_name)\n out_name = test_name[:test_name_len] + base_name\n full_out_path = os.path.join(br_path, out_name.replace(' ', r'\\ '))\n # in case device restarted, wait for adb interface to return\n self.wait_for_boot_completion()\n self.log.info('Taking bugreport for %s.', test_name)\n if new_br:\n out = self.adb.shell('bugreportz').decode('utf-8')\n if not out.startswith('OK'):\n raise DeviceError(self, 'Failed to take bugreport: %s' % out)\n br_out_path = out.split(':')[1].strip()\n self.adb.pull('%s %s' % (br_out_path, full_out_path))\n else:\n self.adb.bugreport(' > %s' % full_out_path)\n self.log.info('Bugreport for %s taken at %s.', test_name,\n full_out_path)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1526, 1592]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1526, 1592]]}, "_func_name": "take_bug_report", "_file_name": "mobly/controllers/android_device.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @classmethod\n def simple_search(cls, query, using=None, index=None):\n \"\"\"\n Do a search without facets.\n\n This is used in:\n\n * The Docsearch API\n * The Project Admin Search page\n \"\"\"\n\n es_search = cls.search(using=using, index=index)\n es_search = es_search.highlight_options(encoder='html')\n\n es_query = cls.get_es_query(query=query)\n highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]\n es_search = es_search.query(es_query).highlight(*highlighted_fields)\n\n return es_search", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "simple_search", "_file_name": "readthedocs/search/documents.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def likeComments(self,commentid,userid):\n sqlText=\"insert into comment_like values(%d,%d);\"%(userid,commentid)\n result=sql.insertDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[45, 122]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[45, 122]]}, "_func_name": "likeComments", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def update_date_modified(self):\n quote_tuple = CURRENT_DATESTAMP, self.entry_id\n\n sql = \"UPDATE jdk_entries \" + \\\n \"SET date_last_modified = ? \" + \\\n \"WHERE jdk_entries.id = ?;\"\n \n db_execute(sql, quote_tuple)\n\n return None", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_date_modified", "_file_name": "entry.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def check_and_update_ranks(self, scene):\n # There are 2 cases here:\n # 1) Ranks have never been calculated for this scene before\n # - This means we need to calculate what the ranks were every month of this scenes history\n # - We should only do this if ranks don't already exist for this scene\n # 2) Ranks have been calculated for this scene before\n # - We already have bulk ranks. We should check if it has been more than 1 month since we last\n # calculated ranks. If so, calculate again with the brackets that have come out this month\n\n LOG.info('About to check if ranks need updating for {}'.format(scene))\n # First, do we have any ranks for this scene already?\n sql = 'select count(*) from ranks where scene=\"{}\";'.format(scene)\n res = self.db.exec(sql)\n count = res[0][0]\n\n n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK\n if count == 0:\n LOG.info('Detected that we need to bulk update ranks for {}'.format(scene))\n # Alright, we have nothing. Bulk update ranks\n first_month = bracket_utils.get_first_month(self.db, scene)\n last_month = bracket_utils.get_last_month(self.db, scene)\n \n # Iterate through all tournaments going month by month, and calculate ranks\n months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True)\n for month in months:\n urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)\n self.process_ranks(scene, urls, month)\n else:\n\n # Get the date of the last time we calculated ranks\n sql = \"select date from ranks where scene='{}' order by date desc limit 1;\".format(scene)\n res = self.db.exec(sql)\n last_rankings_date = res[0][0]\n\n # Check to see if it's been more than 1 month since we last calculated ranks\n more_than_one_month = bracket_utils.has_month_passed(last_rankings_date)\n if more_than_one_month:\n # Get only the last n tournaments, so it doesn't take too long to process\n today = datetime.datetime.today().strftime('%Y-%m-%d')\n msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today)\n LOG.info(msg)\n\n # We should only ever calculate ranks on the 1st. If today is not the first, log error\n if not today.split('-')[-1] == '1':\n LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today))\n\n months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True)\n for month in months:\n # Make sure that we actually have matches during this month\n # Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30\n prev_date = bracket_utils.get_previous_month(month)\n brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date)\n\n if len(brackets_during_month) > 0:\n tweet('Calculating {} ranks for {}'.format(month, scene))\n urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)\n self.process_ranks(scene, urls, month)\n\n else:\n LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[763, 838], [1777, 1879]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[763, 838], [1777, 1879]]}, "_func_name": "check_and_update_ranks", "_file_name": "process_data.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)\n{\n\tstatic const char module[] = \"NeXTDecode\";\n\tunsigned char *bp, *op;\n\ttmsize_t cc;\n\tuint8* row;\n\ttmsize_t scanline, n;\n\n\t(void) s;\n\t/*\n\t * Each scanline is assumed to start off as all\n\t * white (we assume a PhotometricInterpretation\n\t * of ``min-is-black'').\n\t */\n\tfor (op = (unsigned char*) buf, cc = occ; cc-- > 0;)\n\t\t*op++ = 0xff;\n\n\tbp = (unsigned char *)tif->tif_rawcp;\n\tcc = tif->tif_rawcc;\n\tscanline = tif->tif_scanlinesize;\n\tif (occ % scanline)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata, module, \"Fractional scanlines cannot be read\");\n\t\treturn (0);\n\t}\n\tfor (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {\n\t\tn = *bp++, cc--;\n\t\tswitch (n) {\n\t\tcase LITERALROW:\n\t\t\t/*\n\t\t\t * The entire scanline is given as literal values.\n\t\t\t */\n\t\t\tif (cc < scanline)\n\t\t\t\tgoto bad;\n\t\t\t_TIFFmemcpy(row, bp, scanline);\n\t\t\tbp += scanline;\n\t\t\tcc -= scanline;\n\t\t\tbreak;\n\t\tcase LITERALSPAN: {\n\t\t\ttmsize_t off;\n\t\t\t/*\n\t\t\t * The scanline has a literal span that begins at some\n\t\t\t * offset.\n\t\t\t */\n\t\t\tif( cc < 4 )\n\t\t\t\tgoto bad;\n\t\t\toff = (bp[0] * 256) + bp[1];\n\t\t\tn = (bp[2] * 256) + bp[3];\n\t\t\tif (cc < 4+n || off+n > scanline)\n\t\t\t\tgoto bad;\n\t\t\t_TIFFmemcpy(row+off, bp+4, n);\n\t\t\tbp += 4+n;\n\t\t\tcc -= 4+n;\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tuint32 npixels = 0, grey;\n\t\t\tuint32 imagewidth = tif->tif_dir.td_imagewidth;\n if( isTiled(tif) )\n imagewidth = tif->tif_dir.td_tilewidth;\n\n\t\t\t/*\n\t\t\t * The scanline is composed of a sequence of constant\n\t\t\t * color ``runs''. We shift into ``run mode'' and\n\t\t\t * interpret bytes as codes of the form\n\t\t\t * until we've filled the scanline.\n\t\t\t */\n\t\t\top = row;\n\t\t\tfor (;;) {\n\t\t\t\tgrey = (uint32)((n>>6) & 0x3);\n\t\t\t\tn &= 0x3f;\n\t\t\t\t/*\n\t\t\t\t * Ensure the run does not exceed the scanline\n\t\t\t\t * bounds, potentially resulting in a security\n\t\t\t\t * issue.\n\t\t\t\t */\n\t\t\t\twhile (n-- > 0 && npixels < imagewidth)\n\t\t\t\t\tSETPIXEL(op, grey);\n\t\t\t\tif (npixels >= imagewidth)\n\t\t\t\t\tbreak;\n\t\t\t\tif (cc == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tn = *bp++, cc--;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t}\n\ttif->tif_rawcp = (uint8*) bp;\n\ttif->tif_rawcc = cc;\n\treturn (1);\nbad:\n\tTIFFErrorExt(tif->tif_clientdata, module, \"Not enough data for scanline %ld\",\n\t (long) tif->tif_row);\n\treturn (0);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1882, 1926]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1882, 1926]]}, "_func_name": "NeXTDecode", "_file_name": "libtiff/tif_next.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void youngcollection (lua_State *L, global_State *g) {\n GCObject **psurvival; /* to point to first non-dead survival object */\n lua_assert(g->gcstate == GCSpropagate);\n markold(g, g->allgc, g->reallyold);\n markold(g, g->finobj, g->finobjrold);\n atomic(L);\n\n /* sweep nursery and get a pointer to its last live element */\n psurvival = sweepgen(L, g, &g->allgc, g->survival);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->reallyold);\n g->reallyold = g->old;\n g->old = *psurvival; /* 'survival' survivals are old now */\n g->survival = g->allgc; /* all news are survivals */\n\n /* repeat for 'finobj' lists */\n psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->finobjrold);\n g->finobjrold = g->finobjold;\n g->finobjold = *psurvival; /* 'survival' survivals are old now */\n g->finobjsur = g->finobj; /* all news are survivals */\n\n sweepgen(L, g, &g->tobefnz, NULL);\n\n finishgencycle(L, g);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "youngcollection", "_file_name": "lgc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _port_conf_generator(self, cmd):\n ssh_cmd = cmd + ['-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return\n port_lines = out.strip().split('\\n')\n if not len(port_lines):\n return\n\n header = port_lines.pop(0)\n yield header\n for portip_line in port_lines:\n try:\n port_data = self._get_hdr_dic(header, portip_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('_port_conf_generator',\n ssh_cmd, out, err)\n yield port_data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_port_conf_generator", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "layer_resize(int layer, int x_size, int y_size)\n{\n\tint old_height;\n\tint old_width;\n\tstruct map_tile* tile;\n\tint tile_width;\n\tint tile_height;\n\tstruct map_tile* tilemap;\n\tstruct map_trigger* trigger;\n\tstruct map_zone* zone;\n\n\tint x, y, i;\n\n\told_width = s_map->layers[layer].width;\n\told_height = s_map->layers[layer].height;\n\n\t// allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc\n\t// because the tilemap is a 2D array.\n\tif (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile))))\n\t\treturn false;\n\tfor (x = 0; x < x_size; ++x) {\n\t\tfor (y = 0; y < y_size; ++y) {\n\t\t\tif (x < old_width && y < old_height) {\n\t\t\t\ttilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width];\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttile = &tilemap[x + y * x_size];\n\t\t\t\ttile->frames_left = tileset_get_delay(s_map->tileset, 0);\n\t\t\t\ttile->tile_index = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// free the old tilemap and substitute the new one\n\tfree(s_map->layers[layer].tilemap);\n\ts_map->layers[layer].tilemap = tilemap;\n\ts_map->layers[layer].width = x_size;\n\ts_map->layers[layer].height = y_size;\n\n\t// if we resize the largest layer, the overall map size will change.\n\t// recalcuate it.\n\ttileset_get_size(s_map->tileset, &tile_width, &tile_height);\n\ts_map->width = 0;\n\ts_map->height = 0;\n\tfor (i = 0; i < s_map->num_layers; ++i) {\n\t\tif (!s_map->layers[i].is_parallax) {\n\t\t\ts_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width);\n\t\t\ts_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height);\n\t\t}\n\t}\n\n\t// ensure zones and triggers remain in-bounds. if any are completely\n\t// out-of-bounds, delete them.\n\tfor (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) {\n\t\tzone = vector_get(s_map->zones, i);\n\t\tif (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height)\n\t\t\tvector_remove(s_map->zones, i);\n\t\telse {\n\t\t\tif (zone->bounds.x2 > s_map->width)\n\t\t\t\tzone->bounds.x2 = s_map->width;\n\t\t\tif (zone->bounds.y2 > s_map->height)\n\t\t\t\tzone->bounds.y2 = s_map->height;\n\t\t}\n\t}\n\tfor (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) {\n\t\ttrigger = vector_get(s_map->triggers, i);\n\t\tif (trigger->x >= s_map->width || trigger->y >= s_map->height)\n\t\t\tvector_remove(s_map->triggers, i);\n\t}\n\n\treturn true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[526, 595]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[526, 595]]}, "_func_name": "layer_resize", "_file_name": "src/minisphere/map_engine.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_last_active_users(limit):\n \"\"\"\n Get from the database a tuple of users who have been recently using\n the bot\n :param limit: integer that specifies how much users to get\n :return: tuple of tuples with users info\n \"\"\"\n log.info('Evaluating last active users with date of '\n 'last time when they used bot...')\n\n # From photo_queries_table2 we take chat_id of the last\n # active users and from 'users' table we take info about these\n # users by chat_id which is a foreign key\n query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'FROM photo_queries_table2 p '\n 'INNER JOIN users u '\n 'ON p.chat_id = u.chat_id '\n 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'ORDER BY MAX(time)'\n f'DESC LIMIT {limit}')\n\n try:\n cursor = db.execute_query(query)\n except DatabaseConnectionError:\n log.error(\"Cannot get the last active users because of some \"\n \"problems with the database\")\n raise\n\n last_active_users = cursor.fetchall()\n return last_active_users", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[976, 1016]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[976, 1016]]}, "_func_name": "get_last_active_users", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_byte = data[0];\n\tut64 offset = addr - java_get_method_start ();\n\tut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;\n\n\tif (op_byte == 0xaa) {\n\t\t// handle a table switch condition\n\t\tif (pos + 8 + 8 > len) {\n\t\t\treturn op->size;\n\t\t}\n\t\tconst int min_val = (ut32)(UINT (data, pos + 4));\n\t\tconst int max_val = (ut32)(UINT (data, pos + 8));\n\n\t\tut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;\n\t\top->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);\n\t\tRAnalCaseOp *caseop = NULL;\n\t\tpos += 12;\n\t\tif (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {\n\t\t\t//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);\n\t\t\tfor (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {\n\t\t\t\t//ut32 value = (ut32)(UINT (data, pos));\n\t\t\t\tif (pos + 4 >= len) {\n\t\t\t\t\t// switch is too big cant read further\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));\n\t\t\t\tcaseop = r_anal_switch_op_add_case (op->switch_op,\n\t\t\t\t\taddr + pos, cur_case + min_val, addr + offset);\n\t\t\t\tif (caseop) {\n\t\t\t\t\tcaseop->bb_ref_to = addr+offset;\n\t\t\t\t\tcaseop->bb_ref_from = addr; // TODO figure this one out\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid switch boundaries at 0x%\"PFMT64x\"\\n\", addr);\n\t\t}\n\t}\n\top->size = pos;\n\treturn op->size;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "java_switch_op", "_file_name": "libr/anal/p/anal_java.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _keyify(key):\n key = escape(key.lower(), quote=True)\n return _key_pattern.sub(' ', key)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_keyify", "_file_name": "mistune.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_coordinator(request):\n coordinator_id = request.GET.get('coordinator')\n doc = None\n \n if coordinator_id:\n doc = Document2.objects.get(id=coordinator_id)\n coordinator = Coordinator(document=doc)\n else:\n coordinator = Coordinator()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):\n raise PopupException(_('You don\\'t have access to the workflow of this coordinator.'))\n\n return render('editor/coordinator_editor.mako', request, {\n 'coordinator_json': coordinator.json,\n 'credentials_json': json.dumps(credentials.credentials.keys()),\n 'workflows_json': json.dumps(workflows),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[915, 1076]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[915, 1076]]}, "_func_name": "edit_coordinator", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def top_karma(bot, trigger):\n \"\"\"\n Show karma status for the top n number of IRC users.\n \"\"\"\n try:\n top_limit = int(trigger.group(2).strip())\n except ValueError:\n top_limit = 5\n\n query = \"SELECT slug, value FROM nick_values NATURAL JOIN nicknames \\\n WHERE key = 'karma' ORDER BY value DESC LIMIT ?\"\n karmalist = bot.db.execute(query, str(top_limit)).fetchall()\n for user in karmalist:\n bot.say(\"%s == %s\" % (user[0], user[1]))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "top_karma", "_file_name": "sopel_modules/karma/karma.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "mapi_attr_read (size_t len, unsigned char *buf)\n{\n size_t idx = 0;\n uint32 i,j;\n assert(len > 4);\n uint32 num_properties = GETINT32(buf+idx);\n MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));\n\n idx += 4;\n\n if (!attrs) return NULL;\n for (i = 0; i < num_properties; i++)\n {\n\tMAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);\n\tMAPI_Value* v = NULL;\n\n\tCHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;\n\tCHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;\n\n\t/* handle special case of GUID prefixed properties */\n\tif (a->name & GUID_EXISTS_FLAG)\n\t{\n\t /* copy GUID */\n\t a->guid = CHECKED_XMALLOC(GUID, 1);\n\t copy_guid_from_buf(a->guid, buf+idx, len);\n\t idx += sizeof (GUID);\n\n\t CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;\n\t if (a->num_names > 0)\n\t {\n\t\t/* FIXME: do something useful here! */\n\t\tsize_t i;\n\n\t\ta->names = CHECKED_XCALLOC(VarLenData, a->num_names);\n\n\t\tfor (i = 0; i < a->num_names; i++)\n\t\t{\n\t\t size_t j;\n\n\t\t CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;\n\n\t\t /* read the data into a buffer */\n\t\t a->names[i].data \n\t\t\t= CHECKED_XMALLOC(unsigned char, a->names[i].len);\n\t\t for (j = 0; j < (a->names[i].len >> 1); j++)\n\t\t\ta->names[i].data[j] = (buf+idx)[j*2];\n\n\t\t /* But what are we going to do with it? */\n\t\t \n\t\t idx += pad_to_4byte(a->names[i].len);\n\t\t}\n\t }\n\t else\n\t {\n\t\t/* get the 'real' name */\n\t\tCHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;\n\t }\n\t}\n\n\t/* \n\t * Multi-value types and string/object/binary types have\n\t * multiple values \n\t */\n\tif (a->type & MULTI_VALUE_FLAG ||\n\t a->type == szMAPI_STRING ||\n\t a->type == szMAPI_UNICODE_STRING ||\n\t a->type == szMAPI_OBJECT ||\n\t a->type == szMAPI_BINARY)\n\t{\n\t CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);\n\t idx += 4;\n\t}\n else\n {\n\t a->num_values = 1;\n }\n\n\t/* Amend the type in case of multi-value type */\n\tif (a->type & MULTI_VALUE_FLAG)\n\t{\n\t a->type -= MULTI_VALUE_FLAG;\n\t}\n\n\n\tv = alloc_mapi_values (a);\n\n\tfor (j = 0; j < a->num_values; j++) \n\t{\n\t switch (a->type)\n\t {\n\t case szMAPI_SHORT:\t/* 2 bytes */\n\t\tv->len = 2;\n\t\tCHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);\n\t\tidx += 4;\t/* assume padding of 2, advance by 4! */\n\t\tbreak;\n\n\t case szMAPI_INT:\t/* 4 bytes */\n\t\tv->len = 4;\n\t\tCHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);\n\t\tidx += 4;\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_FLOAT:\t/* 4 bytes */\n\t case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */\n\t\tv->len = 4;\n\t\tCHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_SYSTIME: /* 8 bytes */\n\t\tv->len = 8;\n\t\tCHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);\n\t\tCHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);\n\t\tidx += 8;\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_DOUBLE:\t/* 8 bytes */\n\t case szMAPI_APPTIME:\n\t case szMAPI_CURRENCY:\n\t case szMAPI_INT8BYTE:\n\t\tv->len = 8;\n\t\tCHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);\n\t\tCHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_CLSID:\n\t\tv->len = sizeof (GUID);\n\t\tcopy_guid_from_buf(&v->data.guid, buf+idx, len);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_STRING:\n\t case szMAPI_UNICODE_STRING:\n\t case szMAPI_OBJECT:\n\t case szMAPI_BINARY:\n\t\tCHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;\n\n\t\tif (a->type == szMAPI_UNICODE_STRING)\n\t\t{\n\t\t v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);\n\t\t}\n\t\telse\n\t\t{\n\t\t v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);\n\t\t memmove (v->data.buf, buf+idx, v->len);\n\t\t}\n\n\t\tidx += pad_to_4byte(v->len);\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_NULL:\t/* illegal in input tnef streams */\n\t case szMAPI_ERROR:\n\t case szMAPI_UNSPECIFIED:\n\t\tfprintf (stderr,\n\t\t\t \"Invalid attribute, input file may be corrupted\\n\");\n\t\tif (!ENCODE_SKIP) exit (1);\n\n\t\treturn NULL;\n\n\t default:\t\t/* should never get here */\n\t\tfprintf (stderr,\n\t\t\t \"Undefined attribute, input file may be corrupted\\n\");\n\t\tif (!ENCODE_SKIP) exit (1);\n\n\t\treturn NULL;\n\n\t }\n\t if (DEBUG_ON) mapi_attr_dump (attrs[i]);\n\t}\n }\n attrs[i] = NULL;\n\n return attrs;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[154, 230]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[154, 230]]}, "_func_name": "mapi_attr_read", "_file_name": "src/mapi_attr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "archive_read_format_rar_read_data(struct archive_read *a, const void **buff,\n size_t *size, int64_t *offset)\n{\n struct rar *rar = (struct rar *)(a->format->data);\n int ret;\n\n if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {\n\t rar->has_encrypted_entries = 0;\n }\n\n if (rar->bytes_unconsumed > 0) {\n /* Consume as much as the decompressor actually used. */\n __archive_read_consume(a, rar->bytes_unconsumed);\n rar->bytes_unconsumed = 0;\n }\n\n *buff = NULL;\n if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {\n *size = 0;\n *offset = rar->offset;\n if (*offset < rar->unp_size)\n *offset = rar->unp_size;\n return (ARCHIVE_EOF);\n }\n\n switch (rar->compression_method)\n {\n case COMPRESS_METHOD_STORE:\n ret = read_data_stored(a, buff, size, offset);\n break;\n\n case COMPRESS_METHOD_FASTEST:\n case COMPRESS_METHOD_FAST:\n case COMPRESS_METHOD_NORMAL:\n case COMPRESS_METHOD_GOOD:\n case COMPRESS_METHOD_BEST:\n ret = read_data_compressed(a, buff, size, offset);\n if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);\n break;\n\n default:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unsupported compression method for RAR file.\");\n ret = ARCHIVE_FATAL;\n break;\n }\n return (ret);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1072, 1122]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1072, 1122]]}, "_func_name": "archive_read_format_rar_read_data", "_file_name": "libarchive/archive_read_support_format_rar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def is_cgi(self):\n \"\"\"Test whether self.path corresponds to a CGI script,\n and return a boolean.\n\n This function sets self.cgi_info to a tuple (dir, rest)\n when it returns True, where dir is the directory part before\n the CGI script name. Note that rest begins with a\n slash if it is not empty.\n\n The default implementation tests whether the path\n begins with one of the strings in the list\n self.cgi_directories (and the next character is a '/'\n or the end of the string).\n \"\"\"\n\n path = self.path\n\n for x in self.cgi_directories:\n i = len(x)\n if path[:i] == x and (not path[i:] or path[i] == '/'):\n self.cgi_info = path[:i], path[i+1:]\n return True\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[22, 342], [343, 549], [561, 587], [588, 798]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[22, 342], [343, 549], [561, 587], [588, 798]]}, "_func_name": "is_cgi", "_file_name": "Lib/CGIHTTPServer.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n conn = connect()\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO playsRecord (winner, loser) VALUES ('%s', '%s')\" % (winner, loser));\n conn.commit()\n conn.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[267, 368]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[267, 368]]}, "_func_name": "reportMatch", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/delete_crawl', methods=['POST'])\n@is_logged_in\ndef delete_crawl():\n\n # Get Form Fields\n cid = request.form['cid']\n\n # Create cursor\n cur = mysql.connection.cursor()\n\n # Get user by username\n result = cur.execute(\"\"\"DELETE FROM Crawls WHERE cid = %s\"\"\" (cid,))\n\n # Commit to DB\n mysql.connection.commit()\n\n # Close connection\n cur.close()\n\n # FIXME check if successfull first, return message\n flash('Crawl successfully removed', 'success')\n\n return redirect(url_for('dashboard'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_crawl", "_file_name": "bar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getSubmissionDateFromDatabase(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT Date FROM ChallengeRankings WHERE SubmissionID = ?\", [str(submission.id)]).fetchone()[0]\n database.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getSubmissionDateFromDatabase", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1137, 1165]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1137, 1165]]}, "_func_name": "asylo::primitives::TrustedPrimitives::UntrustedCall", "_file_name": "asylo/platform/primitives/sgx/trusted_sgx.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)\n{\n\t/* OpenSc Operation values for each command operation-type */\n\tconst int df_idx[8] = {\t /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/\n\t\tSC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\tSC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};\n\tconst int ef_idx[8] = {\n\t\tSC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\tconst int efi_idx[8] = { /* internal EF used for RSA keys */\n\t\tSC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\n\tu8\t\tbValue;\n\tint\t\ti;\n\tint\t\tiKeyRef = 0;\n\tint\t\tiMethod;\n\tint\t\tiPinCount;\n\tint\t\tiOffset = 0;\n\tint\t\tiOperation;\n\tconst int*\tp_idx;\n\n\t/* Check all sub-AC definitions within the total AC */\n\twhile (len > 1) {\t\t\t\t/* minimum length = 2 */\n\t\tsize_t iACLen = buf[iOffset] & 0x0F;\n\t\tif (iACLen > len)\n\t\t\tbreak;\n\n\t\tiMethod = SC_AC_NONE;\t\t/* default no authentication required */\n\n\t\tif (buf[iOffset] & 0X80) { /* AC in adaptive coding */\n\t\t\t/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */\n\t\t\tsize_t\tiParmLen = 1;\t\t\t/* command-byte is always present */\n\t\t\tsize_t\tiKeyLen = 0;\t\t\t/* Encryption key is optional */\n\n\t\t\tif (buf[iOffset] & 0x20) iKeyLen++;\n\t\t\tif (buf[iOffset+1] & 0x40) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x20) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x10) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x08) iParmLen++;\n\n\t\t\t/* Get KeyNumber if available */\n\t\t\tif(iKeyLen) {\n\t\t\t\tint iSC;\n\t\t\t\tif (len < 1+(size_t)iACLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiSC = buf[iOffset+iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ){\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\t\t\t}\n\n\t\t\t/* Get PinNumber if available */\n\t\t\tif (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */\n\t\t\t\tif (len < 1+1+1+(size_t)iParmLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Convert SETCOS command to OpenSC command group */\n\t\t\tif (len < 1+2)\n\t\t\t\tbreak;\n\t\t\tswitch(buf[iOffset+2]){\n\t\t\tcase 0x2A:\t\t\t/* crypto operation */\n\t\t\t\tiOperation = SC_AC_OP_CRYPTO;\n\t\t\t\tbreak;\n\t\t\tcase 0x46:\t\t\t/* key-generation operation */\n\t\t\t\tiOperation = SC_AC_OP_UPDATE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tiOperation = SC_AC_OP_SELECT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);\n\t\t}\n\t\telse { /* AC in simple coding */\n\t\t\t /* Initial AC is treated as an operational AC */\n\n\t\t\t/* Get specific Cmd groups for specified file-type */\n\t\t\tswitch (file->type) {\n\t\t\tcase SC_FILE_TYPE_DF: /* DF */\n\t\t\t\tp_idx = df_idx;\n\t\t\t\tbreak;\n\t\t\tcase SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */\n\t\t\t\tp_idx = efi_idx;\n\t\t\t\tbreak;\n\t\t\tdefault: /* EF */\n\t\t\t\tp_idx = ef_idx;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Encryption key present ? */\n\t\t\tiPinCount = iACLen - 1;\t\t\n\n\t\t\tif (buf[iOffset] & 0x20) {\n\t\t\t\tint iSC;\n\t\t\t\tif (len < 1 + (size_t)iACLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiSC = buf[iOffset + iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ) {\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\n\t\t\t\tiPinCount--;\t\t\t\t/* one byte used for keyReference */\n\t\t\t}\n\n\t\t\t/* Pin present ? */\n\t\t\tif ( iPinCount > 0 ) {\n\t\t\t\tif (len < 1 + 2)\n\t\t\t\t\tbreak;\n\t\t\t\tiKeyRef = buf[iOffset + 2];\t/* pin ref */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Add AC for each command-operationType into OpenSc structure */\n\t\t\tbValue = buf[iOffset + 1];\n\t\t\tfor (i = 0; i < 8; i++) {\n\t\t\t\tif((bValue & 1) && (p_idx[i] >= 0))\n\t\t\t\t\tsc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);\n\t\t\t\tbValue >>= 1;\n\t\t\t}\n\t\t}\n\t\t/* Current field treated, get next AC sub-field */\n\t\tiOffset += iACLen +1;\t\t/* AC + PTL-byte */\n\t\tlen -= iACLen +1;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[3184, 3213]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3184, 3213]]}, "_func_name": "parse_sec_attr_44", "_file_name": "src/libopensc/card-setcos.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int nfc_genl_deactivate_target(struct sk_buff *skb,\n\t\t\t\t struct genl_info *info)\n{\n\tstruct nfc_dev *dev;\n\tu32 device_idx, target_idx;\n\tint rc;\n\n\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX])\n\t\treturn -EINVAL;\n\n\tdevice_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);\n\n\tdev = nfc_get_device(device_idx);\n\tif (!dev)\n\t\treturn -ENODEV;\n\n\ttarget_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);\n\n\trc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);\n\n\tnfc_put_device(dev);\n\treturn rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[156, 198]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[156, 198]]}, "_func_name": "nfc_genl_deactivate_target", "_file_name": "net/nfc/netlink.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def verify_rno(self, rno):\n self.cursor.execute(\"SELECT COUNT(rno) FROM rides WHERE rno = :rno\", {'rno': rno})\n result = self.cursor.fetchone()\n if (int(result[0]) > 0):\n return True \n else:\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "verify_rno", "_file_name": "book_rides/book_rides.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _inject_net_into_fs(net, fs, execute=None):\n \"\"\"Inject /etc/network/interfaces into the filesystem rooted at fs.\n\n net is the contents of /etc/network/interfaces.\n \"\"\"\n netdir = os.path.join(os.path.join(fs, 'etc'), 'network')\n utils.execute('mkdir', '-p', netdir, run_as_root=True)\n utils.execute('chown', 'root:root', netdir, run_as_root=True)\n utils.execute('chmod', 755, netdir, run_as_root=True)\n netfile = os.path.join(netdir, 'interfaces')\n utils.execute('tee', netfile, process_input=net, run_as_root=True)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[181, 243], [426, 545]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[181, 243], [426, 545]]}, "_func_name": "_inject_net_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "cleanup_pathname(struct archive_write_disk *a)\n{\n\tchar *dest, *src;\n\tchar separator = '\\0';\n\n\tdest = src = a->name;\n\tif (*src == '\\0') {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Invalid empty pathname\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n#if defined(__CYGWIN__)\n\tcleanup_pathname_win(a);\n#endif\n\t/* Skip leading '/'. */\n\tif (*src == '/') {\n\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Path is absolute\");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\n\t\tseparator = *src++;\n\t}\n\n\t/* Scan the pathname one element at a time. */\n\tfor (;;) {\n\t\t/* src points to first char after '/' */\n\t\tif (src[0] == '\\0') {\n\t\t\tbreak;\n\t\t} else if (src[0] == '/') {\n\t\t\t/* Found '//', ignore second one. */\n\t\t\tsrc++;\n\t\t\tcontinue;\n\t\t} else if (src[0] == '.') {\n\t\t\tif (src[1] == '\\0') {\n\t\t\t\t/* Ignore trailing '.' */\n\t\t\t\tbreak;\n\t\t\t} else if (src[1] == '/') {\n\t\t\t\t/* Skip './'. */\n\t\t\t\tsrc += 2;\n\t\t\t\tcontinue;\n\t\t\t} else if (src[1] == '.') {\n\t\t\t\tif (src[2] == '/' || src[2] == '\\0') {\n\t\t\t\t\t/* Conditionally warn about '..' */\n\t\t\t\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_MISC,\n\t\t\t\t\t\t \"Path contains '..'\");\n\t\t\t\t\t\treturn (ARCHIVE_FAILED);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Note: Under no circumstances do we\n\t\t\t\t * remove '..' elements. In\n\t\t\t\t * particular, restoring\n\t\t\t\t * '/foo/../bar/' should create the\n\t\t\t\t * 'foo' dir as a side-effect.\n\t\t\t\t */\n\t\t\t}\n\t\t}\n\n\t\t/* Copy current element, including leading '/'. */\n\t\tif (separator)\n\t\t\t*dest++ = '/';\n\t\twhile (*src != '\\0' && *src != '/') {\n\t\t\t*dest++ = *src++;\n\t\t}\n\n\t\tif (*src == '\\0')\n\t\t\tbreak;\n\n\t\t/* Skip '/' separator. */\n\t\tseparator = *src++;\n\t}\n\t/*\n\t * We've just copied zero or more path elements, not including the\n\t * final '/'.\n\t */\n\tif (dest == a->name) {\n\t\t/*\n\t\t * Nothing got copied. The path must have been something\n\t\t * like '.' or '/' or './' or '/././././/./'.\n\t\t */\n\t\tif (separator)\n\t\t\t*dest++ = '/';\n\t\telse\n\t\t\t*dest++ = '.';\n\t}\n\t/* Terminate the result. */\n\t*dest = '\\0';\n\treturn (ARCHIVE_OK);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cleanup_pathname", "_file_name": "libarchive/archive_write_disk_posix.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _modify_3par_fibrechan_host(self, hostname, wwn):\n # when using -add, you can not send the persona or domain options\n out = self.common._cli_run('createhost -add %s %s'\n % (hostname, \" \".join(wwn)), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[132, 260]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[132, 260]]}, "_func_name": "_modify_3par_fibrechan_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_fc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def check_if_this_project_is_in_database(self, project_id):\n self.cursor.execute(\"SELECT count(id) FROM projects where id = %s\", (project_id,))\n return self.cursor.fetchall()[0][0] == 1", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "check_if_this_project_is_in_database", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None,\n tpvv=True):\n # Virtual volume sets are not supported with the -online option\n cmd = 'createvvcopy -p %s -online ' % src_name\n if snap_cpg:\n cmd += '-snp_cpg %s ' % snap_cpg\n if tpvv:\n cmd += '-tpvv '\n if cpg:\n cmd += cpg + ' '\n cmd += dest_name\n LOG.debug('Creating clone of a volume with %s' % cmd)\n self._cli_run(cmd, None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[178, 233], [254, 299], [316, 344], [360, 414], [476, 508]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[178, 233], [254, 299], [316, 344], [360, 414], [476, 508]]}, "_func_name": "_copy_volume", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def create_playlist(name):\n db = connect_to_database()\n cursor = db.cursor()\n cursor.execute(\n \"INSERT INTO playlist (name, video_position) VALUES(%s, 0);\", (name,))\n db.commit()\n db.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_playlist", "_file_name": "main_test.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _port_conf_generator(self, cmd):\n ssh_cmd = '%s -delim !' % cmd\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return\n port_lines = out.strip().split('\\n')\n if not len(port_lines):\n return\n\n header = port_lines.pop(0)\n yield header\n for portip_line in port_lines:\n try:\n port_data = self._get_hdr_dic(header, portip_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('_port_conf_generator',\n ssh_cmd, out, err)\n yield port_data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[41, 79]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[41, 79]]}, "_func_name": "_port_conf_generator", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[435, 476]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[435, 476]]}, "_func_name": "enc_untrusted_create_wait_queue", "_file_name": "asylo/platform/host_call/trusted/concurrency.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,\n\t\toidc_session_t *session, const char *client_id,\n\t\tconst char *check_session_iframe) {\n\n\toidc_debug(r, \"enter\");\n\n\tconst char *java_script =\n\t\t\t\" \\n\";\n\n\t/* determine the origin for the check_session_iframe endpoint */\n\tchar *origin = apr_pstrdup(r->pool, check_session_iframe);\n\tapr_uri_t uri;\n\tapr_uri_parse(r->pool, check_session_iframe, &uri);\n\tchar *p = strstr(origin, uri.path);\n\t*p = '\\0';\n\n\t/* the element identifier for the OP iframe */\n\tconst char *op_iframe_id = \"openidc-op\";\n\n\t/* restore the OP session_state from the session */\n\tconst char *session_state = oidc_session_get_session_state(r, session);\n\tif (session_state == NULL) {\n\t\toidc_warn(r,\n\t\t\t\t\"no session_state found in the session; the OP does probably not support session management!?\");\n\t\treturn DONE;\n\t}\n\n\tchar *s_poll_interval = NULL;\n\toidc_util_get_request_parameter(r, \"poll\", &s_poll_interval);\n\tint poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;\n\tif ((poll_interval <= 0) || (poll_interval > 3600 * 24))\n\t\tpoll_interval = 3000;\n\n\tconst char *redirect_uri = oidc_get_redirect_uri(r, c);\n\tjava_script = apr_psprintf(r->pool, java_script, origin, client_id,\n\t\t\tsession_state, op_iframe_id, poll_interval, redirect_uri,\n\t\t\tredirect_uri);\n\n\treturn oidc_util_html_send(r, NULL, java_script, \"setTimer\", NULL, DONE);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "oidc_handle_session_management_iframe_rp", "_file_name": "src/mod_auth_openidc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def save(self):\n # copy the user's input from plain text to description to be processed\n self.description = self.description_plain_text\n if CE.settings.auto_cross_reference:\n self.auto_cross_ref()\n else:\n self.find_tag()\n self.slug = slugify(self.title)\n super().save()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[99, 154]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[99, 154]]}, "_func_name": "save", "_file_name": "CE/models.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('//history')\ndef view_page_history(page_name):\n query = db.query(\"select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = $1\", page_name)\n page_histories = query.namedresult()\n\n return render_template(\n 'page_history.html',\n page_name = page_name,\n page_histories = page_histories\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "view_page_history", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def store_metadata(self, session, key, mType, value):\n if (self.idNormalizer is not None):\n id = self.idNormalizer.process_string(session, id)\n elif type(id) == unicode:\n id = id.encode('utf-8')\n else:\n id = str(id)\n self._openContainer(session)\n query = (\"UPDATE %s SET %s = %r WHERE identifier = '%s';\" %\n (self.table, mType, value, id)\n )\n try:\n self._query(query)\n except:\n return None\n return value", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[311, 446]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[311, 446]]}, "_func_name": "store_metadata", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char *compose_path(ctrl_t *ctrl, char *path)\n{\n\tstruct stat st;\n\tstatic char rpath[PATH_MAX];\n\tchar *name, *ptr;\n\tchar dir[PATH_MAX] = { 0 };\n\n\tstrlcpy(dir, ctrl->cwd, sizeof(dir));\n\tDBG(\"Compose path from cwd: %s, arg: %s\", ctrl->cwd, path ?: \"\");\n\tif (!path || !strlen(path))\n\t\tgoto check;\n\n\tif (path) {\n\t\tif (path[0] != '/') {\n\t\t\tif (dir[strlen(dir) - 1] != '/')\n\t\t\t\tstrlcat(dir, \"/\", sizeof(dir));\n\t\t}\n\t\tstrlcat(dir, path, sizeof(dir));\n\t}\n\ncheck:\n\twhile ((ptr = strstr(dir, \"//\")))\n\t\tmemmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);\n\n\tif (!chrooted) {\n\t\tsize_t len = strlen(home);\n\n\t\tDBG(\"Server path from CWD: %s\", dir);\n\t\tif (len > 0 && home[len - 1] == '/')\n\t\t\tlen--;\n\t\tmemmove(dir + len, dir, strlen(dir) + 1);\n\t\tmemcpy(dir, home, len);\n\t\tDBG(\"Resulting non-chroot path: %s\", dir);\n\t}\n\n\t/*\n\t * Handle directories slightly differently, since dirname() on a\n\t * directory returns the parent directory. So, just squash ..\n\t */\n\tif (!stat(dir, &st) && S_ISDIR(st.st_mode)) {\n\t\tif (!realpath(dir, rpath))\n\t\t\treturn NULL;\n\t} else {\n\t\t/*\n\t\t * Check realpath() of directory containing the file, a\n\t\t * STOR may want to save a new file. Then append the\n\t\t * file and return it.\n\t\t */\n\t\tname = basename(path);\n\t\tptr = dirname(dir);\n\n\t\tmemset(rpath, 0, sizeof(rpath));\n\t\tif (!realpath(ptr, rpath)) {\n\t\t\tINFO(\"Failed realpath(%s): %m\", ptr);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (rpath[1] != 0)\n\t\t\tstrlcat(rpath, \"/\", sizeof(rpath));\n\t\tstrlcat(rpath, name, sizeof(rpath));\n\t}\n\n\tif (!chrooted && strncmp(rpath, home, strlen(home))) {\n\t\tDBG(\"Failed non-chroot dir:%s vs home:%s\", dir, home);\n\t\treturn NULL;\n\t}\n\n\treturn rpath;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "compose_path", "_file_name": "src/common.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def create_event(self, title, start_time, time_zone, server_id, description):\n sql = \"\"\"INSERT INTO events (title, start_time, time_zone, server_id, description)\n VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')\n \"\"\".format(title, start_time, time_zone, server_id, description)\n self.cur.execute(sql)\n self.conn.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[173, 345]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[173, 345]]}, "_func_name": "create_event", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getOptions(poll_name):\n conn, c = connectDB()\n req = \"SELECT options FROM {} WHERE name=?\".format(CFG(\"poll_table_name\"))\n options_str = queryOne(c, req, (poll_name,))\n if options_str == None:\n return None\n options = options_str.split(\",\")\n closeDB(conn)\n return options", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getOptions", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_conn_fc_wwpns(self, host_name):\n wwpns = []\n cmd = 'svcinfo lsfabric -host %s' % host_name\n generator = self._port_conf_generator(cmd)\n header = next(generator, None)\n if not header:\n return wwpns\n\n for port_data in generator:\n try:\n wwpns.append(port_data['local_wwpn'])\n except KeyError as e:\n self._handle_keyerror('lsfabric', header)\n\n return wwpns", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[64, 118]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[64, 118]]}, "_func_name": "_get_conn_fc_wwpns", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t))) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[322, 365]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[322, 365]]}, "_func_name": "ecall_restore", "_file_name": "asylo/platform/primitives/sgx/ecalls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "void Magick::Image::read(MagickCore::Image *image,\n MagickCore::ExceptionInfo *exceptionInfo)\n{\n // Ensure that multiple image frames were not read.\n if (image != (MagickCore::Image *) NULL &&\n image->next != (MagickCore::Image *) NULL)\n {\n MagickCore::Image\n *next;\n\n // Destroy any extra image frames\n next=image->next;\n image->next=(MagickCore::Image *) NULL;\n next->previous=(MagickCore::Image *) NULL;\n DestroyImageList(next);\n }\n replaceImage(image);\n if (exceptionInfo->severity == MagickCore::UndefinedException &&\n image == (MagickCore::Image *) NULL)\n {\n (void) MagickCore::DestroyExceptionInfo(exceptionInfo);\n if (!quiet())\n throwExceptionExplicit(MagickCore::ImageWarning,\n \"No image was loaded.\");\n return;\n }\n ThrowImageException;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Magick::Image::read", "_file_name": "Magick++/lib/Image.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def incrementOption(cursor, poll_name, option):\n key = poll_name+\"-\"+option\n req = \"UPDATE {} SET count=count+1 WHERE name_option=?\".format(CFG(\"options_table_name\"))\n cursor.execute(req, (key,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "incrementOption", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "\tdef get_secrets(self, from_date_added=0):\n\t\tsecrets = []\n\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added):\n\t\t\taes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]\n\t\t\tif aes_key != None:\n\t\t\t\tsecrets.append([aes_key, json_id])\n\t\t\tfrom_date_added = max(from_date_added, date_added)\n\t\treturn (secrets, from_date_added)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[58, 210]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[58, 210]]}, "_func_name": "get_secrets", "_file_name": "zeromail.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_vdisk_fc_mappings(self, vdisk_name):\n \"\"\"Return FlashCopy mappings that this vdisk is associated with.\"\"\"\n\n ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_name]\n out, err = self._run_ssh(ssh_cmd)\n\n mapping_ids = []\n if (len(out.strip())):\n lines = out.strip().split('\\n')\n mapping_ids = [line.split()[0] for line in lines]\n return mapping_ids", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_vdisk_fc_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int usbhid_parse(struct hid_device *hid)\n{\n\tstruct usb_interface *intf = to_usb_interface(hid->dev.parent);\n\tstruct usb_host_interface *interface = intf->cur_altsetting;\n\tstruct usb_device *dev = interface_to_usbdev (intf);\n\tstruct hid_descriptor *hdesc;\n\tu32 quirks = 0;\n\tunsigned int rsize = 0;\n\tchar *rdesc;\n\tint ret, n;\n\n\tquirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),\n\t\t\tle16_to_cpu(dev->descriptor.idProduct));\n\n\tif (quirks & HID_QUIRK_IGNORE)\n\t\treturn -ENODEV;\n\n\t/* Many keyboards and mice don't like to be polled for reports,\n\t * so we will always set the HID_QUIRK_NOGET flag for them. */\n\tif (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {\n\t\tif (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||\n\t\t\tinterface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)\n\t\t\t\tquirks |= HID_QUIRK_NOGET;\n\t}\n\n\tif (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&\n\t (!interface->desc.bNumEndpoints ||\n\t usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {\n\t\tdbg_hid(\"class descriptor not present\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\thid->version = le16_to_cpu(hdesc->bcdHID);\n\thid->country = hdesc->bCountryCode;\n\n\tfor (n = 0; n < hdesc->bNumDescriptors; n++)\n\t\tif (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)\n\t\t\trsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);\n\n\tif (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {\n\t\tdbg_hid(\"weird size of report descriptor (%u)\\n\", rsize);\n\t\treturn -EINVAL;\n\t}\n\n\trdesc = kmalloc(rsize, GFP_KERNEL);\n\tif (!rdesc)\n\t\treturn -ENOMEM;\n\n\thid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);\n\n\tret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,\n\t\t\tHID_DT_REPORT, rdesc, rsize);\n\tif (ret < 0) {\n\t\tdbg_hid(\"reading report descriptor failed\\n\");\n\t\tkfree(rdesc);\n\t\tgoto err;\n\t}\n\n\tret = hid_parse_report(hid, rdesc, rsize);\n\tkfree(rdesc);\n\tif (ret) {\n\t\tdbg_hid(\"parsing report descriptor failed\\n\");\n\t\tgoto err;\n\t}\n\n\thid->quirks |= quirks;\n\n\treturn 0;\nerr:\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1218, 1264]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1218, 1264]]}, "_func_name": "usbhid_parse", "_file_name": "drivers/hid/usbhid/hid-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def post(self):\n \"\"\" Returns JWT upon login verification \"\"\"\n json_data = request.get_json()\n if not json_data['email']:\n return jsonify({\"msg\": \"Missing email\"}), 400\n\n data = database_utilities.execute_query(\n f\"\"\"select * from admins where email = %s\"\"\", (json_data['email'], ))\n if data:\n email = data[0]['email']\n access_token = create_access_token(identity=email)\n refresh_token = create_refresh_token(identity=email)\n\n resp = jsonify({\"login\": True})\n set_access_cookies(resp, access_token)\n set_refresh_cookies(resp, refresh_token)\n return resp\n else:\n return jsonify({\"msg\": \"User is not an admin\"})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "post", "_file_name": "apis/login.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def verify_email(self, member):\n query = \"SELECT COUNT(email) FROM members WHERE email = '{email}'\".format(email = member)\n self.cursor.execute(query)\n result = self.cursor.fetchone()\n if (int(result[0]) > 0):\n return True \n else:\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[36, 169]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[36, 169]]}, "_func_name": "verify_email", "_file_name": "book_rides/book_rides.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):\n \"\"\"Set the root password to admin_passwd\n\n admin_password is a root password\n fs is the path to the base of the filesystem into which to inject\n the key.\n\n This method modifies the instance filesystem directly,\n and does not require a guest agent running in the instance.\n\n \"\"\"\n # The approach used here is to copy the password and shadow\n # files from the instance filesystem to local files, make any\n # necessary changes, and then copy them back.\n\n admin_user = 'root'\n\n fd, tmp_passwd = tempfile.mkstemp()\n os.close(fd)\n fd, tmp_shadow = tempfile.mkstemp()\n os.close(fd)\n\n passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd')\n shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow')\n\n utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True)\n utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True)\n _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)\n utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True)\n os.unlink(tmp_passwd)\n utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True)\n os.unlink(tmp_shadow)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_inject_admin_password_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {\n packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,\n packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,\n packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,\n packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,\n packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,\n packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,\n packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,\n packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,\n packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,\n packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[688, 793]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[688, 793]]}, "_func_name": "ndpi_reset_packet_line_info", "_file_name": "src/lib/ndpi_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)\n{\n return snprintf(dest, destlen, \"%s.hcache\", path);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[77, 130]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[77, 130]]}, "_func_name": "nntp_hcache_namer", "_file_name": "newsrc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;\n\n\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;\n\n\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;\n\n\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;\n\n\t\ttot_pages += nr_pages;\n\n\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}\n\n\treturn tot_pages * sizeof(struct scatterlist);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[255, 307]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[255, 307]]}, "_func_name": "rds_rdma_extra_size", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def insertData(self,userid,post):\n sqlText=\"insert into post(userid,date,comment) \\\n values(%s,current_timestamp(0),%s);\"\n params=[userid,post];\n result=sql.insertDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "insertData", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void exif_process_APP12(image_info_type *ImageInfo,\n char *buffer, size_t length) {\n size_t l1, l2=0;\n if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Company\",\n TAG_NONE, TAG_FMT_STRING, l1, buffer+2);\n if (length > 2+l1+1) {\n l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Info\",\n TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);\n }\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::exif_process_APP12", "_file_name": "hphp/runtime/ext/gd/ext_gd.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " static bool TryParse(const char* inp, int length,\n TypedValue* buf, Variant& out,\n JSONContainerType container_type, bool is_tsimplejson) {\n SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);\n bool ok = parser.parseValue();\n parser.skipSpace();\n if (!ok || parser.p != inp + length) {\n // Unsupported, malformed, or trailing garbage. Release entire stack.\n tvDecRefRange(buf, parser.top);\n return false;\n }\n out = Variant::attach(*--parser.top);\n return true;\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[296, 363]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[296, 363]]}, "_func_name": "HPHP::SimpleParser::TryParse", "_file_name": "hphp/runtime/ext/json/JSON_parser.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int uas_switch_interface(struct usb_device *udev,\n\t\t\t\tstruct usb_interface *intf)\n{\n\tint alt;\n\n\talt = uas_find_uas_alt_setting(intf);\n\tif (alt < 0)\n\t\treturn alt;\n\n\treturn usb_set_interface(udev,\n\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[141, 169], [170, 254]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[141, 169], [170, 254]]}, "_func_name": "uas_switch_interface", "_file_name": "drivers/usb/storage/uas.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[890, 910]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[890, 910]]}, "_func_name": "voutf", "_file_name": "src/tool_msgs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def addTags(tag_list, listing_id):\n \"\"\"\n Adds a list of tags tag_list for a given listing with listing_id to the database\n \"\"\"\n cur = conn.cursor()\n for x in tag_list:\n sql = \"INSERT INTO %s VALUES (%s %s)\"\n cur.execute(sql, (listing_tags_table_name, listing_id, x))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "addTags", "_file_name": "backend-api/backend-api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_requested_day(self, date):\n\n data = dict()\n\n day_start, day_end = self.get_epoch_day(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}\n\n query = '''\n SELECT TimeStamp, SUM(Power) AS Power \n FROM DayData \n WHERE TimeStamp BETWEEN ? AND ?\n GROUP BY TimeStamp;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query, (day_start, day_end)):\n data['data'].append({ 'time': row[0], 'power': row[1] })\n\n\n if self.get_datetime(date).date() == datetime.today().date():\n query = '''\n SELECT SUM(EToday) as EToday\n FROM Inverters;\n '''\n self.c.execute(query)\n else:\n query = '''\n SELECT SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN ? AND ?\n GROUP BY TimeStamp;\n '''\n self.c.execute(query, (day_start, day_end))\n\n row = self.c.fetchone()\n if row and row[0]: data['total'] = row[0]\n else: data['total'] = 0\n\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if (first_data): data['hasPrevious'] = (first_data < day_start)\n else: data['hasPrevious'] = False\n\n if (last_data): data['hasNext'] = (last_data > day_end)\n else: data['hasNext'] = False\n\n #print(json.dumps(data, indent=4))\n return data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_requested_day", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n\n\n if \"user\" not in form or \"game\" not in form:\n raise FormError(\"Invalid parameters.\")\n if \"pos\" not in form and \"resign\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n game = int(form[\"game\"].value)\n\n\n (players,size,state) = get_game_info(conn, game)\n\n user = form[\"user\"].value\n if user not in players:\n raise FormError(\"Invalid player ID - player is not part of this game\")\n\n\n if \"resign\" in form:\n resign = True\n else:\n resign = False\n pos = form[\"pos\"].value.split(\",\")\n assert len(pos) == 2\n x = int(pos[0])\n y = int(pos[1])\n\n\n (board,nextPlayer,letter) = build_board(conn, game,size)\n\n if user != players[nextPlayer]:\n raise FormError(\"Internal error, incorrect player is attempting to move.\")\n\n\n if resign:\n # this user is choosing to resign. Update the game state to reflect that.\n other_player_name = players[1-nextPlayer]\n\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE games SET state=\"%s:resignation\" WHERE id=%d;\"\"\" % (other_player_name,game))\n cursor.close()\n\n else:\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert board[x][y] == \"\"\n board[x][y] = \"XO\"[nextPlayer]\n\n # we've done all of our sanity checks. We now know enough to say that\n # it's safe to add a new move.\n cursor = conn.cursor()\n cursor.execute(\"\"\"INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,\"%s\",NOW());\"\"\" % (game,x,y,letter))\n\n if cursor.rowcount != 1:\n raise FormError(\"Could not make move, reason unknown.\")\n\n cursor.close()\n\n result = analyze_board(board)\n if result != \"\":\n if result == \"win\":\n result = players[nextPlayer]+\":win\"\n\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE games SET state=\"%s\" WHERE id=%d;\"\"\" % (result,game))\n cursor.close()\n\n # we've made changes, make sure to commit them!\n conn.commit()\n conn.close()\n\n\n # return the parms to the caller, so that they can build a good redirect\n return (user,game)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1369, 1479], [1806, 1927], [2237, 2328]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1369, 1479], [1806, 1927], [2237, 2328]]}, "_func_name": "process_form", "_file_name": "cgi/move.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)\n{\n INITIALIZE_LIBREPORT();\n\n char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);\n\n if (!type)\n {\n error_msg(_(\"Missing required item: '%s'\"), FILENAME_ANALYZER);\n return NULL;\n }\n\n uid_t uid = (uid_t)-1L;\n char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);\n\n if (uid_str)\n {\n char *endptr;\n errno = 0;\n long val = strtol(uid_str, &endptr, 10);\n\n if (errno != 0 || endptr == uid_str || *endptr != '\\0' || INT_MAX < val)\n {\n error_msg(_(\"uid value is not valid: '%s'\"), uid_str);\n return NULL;\n }\n\n uid = (uid_t)val;\n }\n\n struct timeval tv;\n if (gettimeofday(&tv, NULL) < 0)\n {\n perror_msg(\"gettimeofday()\");\n return NULL;\n }\n\n char *problem_id = xasprintf(\"%s-%s.%ld-%lu\"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());\n\n log_info(\"Saving to %s/%s with uid %d\", base_dir_name, problem_id, uid);\n\n struct dump_dir *dd;\n if (base_dir_name)\n dd = try_dd_create(base_dir_name, problem_id, uid);\n else\n {\n /* Try /var/run/abrt */\n dd = try_dd_create(LOCALSTATEDIR\"/run/abrt\", problem_id, uid);\n /* Try $HOME/tmp */\n if (!dd)\n {\n char *home = getenv(\"HOME\");\n if (home && home[0])\n {\n home = concat_path_file(home, \"tmp\");\n /*mkdir(home, 0777); - do we want this? */\n dd = try_dd_create(home, problem_id, uid);\n free(home);\n }\n }\n//TODO: try user's home dir obtained by getpwuid(getuid())?\n /* Try system temporary directory */\n if (!dd)\n dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);\n }\n\n if (!dd) /* try_dd_create() already emitted the error message */\n goto ret;\n\n GHashTableIter iter;\n char *name;\n struct problem_item *value;\n g_hash_table_iter_init(&iter, problem_data);\n while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))\n {\n if (value->flags & CD_FLAG_BIN)\n {\n char *dest = concat_path_file(dd->dd_dirname, name);\n log_info(\"copying '%s' to '%s'\", value->content, dest);\n off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);\n if (copied < 0)\n error_msg(\"Can't copy %s to %s\", value->content, dest);\n else\n log_info(\"copied %li bytes\", (unsigned long)copied);\n free(dest);\n\n continue;\n }\n\n /* only files should contain '/' and those are handled earlier */\n if (name[0] == '.' || strchr(name, '/'))\n {\n error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n continue;\n }\n\n dd_save_text(dd, name, value->content);\n }\n\n /* need to create basic files AFTER we save the pd to dump_dir\n * otherwise we can't skip already created files like in case when\n * reporting from anaconda where we can't read /etc/{system,redhat}-release\n * and os_release is taken from anaconda\n */\n dd_create_basic_files(dd, uid, NULL);\n\n problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\\0';\n char* new_path = concat_path_file(base_dir_name, problem_id);\n log_info(\"Renaming from '%s' to '%s'\", dd->dd_dirname, new_path);\n dd_rename(dd, new_path);\n\n ret:\n free(problem_id);\n return dd;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[2709, 2964]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2709, 2964]]}, "_func_name": "create_dump_dir_from_problem_data", "_file_name": "src/lib/create_dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def do_setup(self, ctxt):\n \"\"\"Check that we have all configuration details from the storage.\"\"\"\n\n LOG.debug(_('enter: do_setup'))\n self._context = ctxt\n\n # Validate that the pool exists\n ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-delim', '!', '-nohdr']\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n search_text = '!%s!' % self.configuration.storwize_svc_volpool_name\n if search_text not in out:\n raise exception.InvalidInput(\n reason=(_('pool %s doesn\\'t exist')\n % self.configuration.storwize_svc_volpool_name))\n\n # Check if compression is supported\n self._compression_enabled = False\n try:\n ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n license_lines = out.strip().split('\\n')\n for license_line in license_lines:\n name, foo, value = license_line.partition('!')\n if name in ('license_compression_enclosures',\n 'license_compression_capacity') and value != '0':\n self._compression_enabled = True\n break\n except exception.ProcessExecutionError:\n LOG.exception(_('Failed to get license information.'))\n\n # Get the iSCSI and FC names of the Storwize/SVC nodes\n ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n\n nodes = out.strip().split('\\n')\n self._assert_ssh_return(len(nodes),\n 'do_setup', ssh_cmd, out, err)\n header = nodes.pop(0)\n for node_line in nodes:\n try:\n node_data = self._get_hdr_dic(header, node_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('do_setup',\n ssh_cmd, out, err)\n node = {}\n try:\n node['id'] = node_data['id']\n node['name'] = node_data['name']\n node['IO_group'] = node_data['IO_group_id']\n node['iscsi_name'] = node_data['iscsi_name']\n node['WWNN'] = node_data['WWNN']\n node['status'] = node_data['status']\n node['WWPN'] = []\n node['ipv4'] = []\n node['ipv6'] = []\n node['enabled_protocols'] = []\n if node['status'] == 'online':\n self._storage_nodes[node['id']] = node\n except KeyError:\n self._handle_keyerror('lsnode', header)\n\n # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes\n self._get_iscsi_ip_addrs()\n self._get_fc_wwpns()\n\n # For each node, check what connection modes it supports. Delete any\n # nodes that do not support any types (may be partially configured).\n to_delete = []\n for k, node in self._storage_nodes.iteritems():\n if ((len(node['ipv4']) or len(node['ipv6']))\n and len(node['iscsi_name'])):\n node['enabled_protocols'].append('iSCSI')\n self._enabled_protocols.add('iSCSI')\n if len(node['WWPN']):\n node['enabled_protocols'].append('FC')\n self._enabled_protocols.add('FC')\n if not len(node['enabled_protocols']):\n to_delete.append(k)\n\n for delkey in to_delete:\n del self._storage_nodes[delkey]\n\n # Make sure we have at least one node configured\n self._driver_assert(len(self._storage_nodes),\n _('do_setup: No configured nodes'))\n\n LOG.debug(_('leave: do_setup'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "do_setup", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n // Segment ids should be of same cardinality as first input dimension and they\n // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)\n const int segment_id_size = segment_ids->dims->data[0];\n TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n int previous_segment_id = -1;\n for (int i = 0; i < segment_id_size; i++) {\n const int current_segment_id = GetTensorData(segment_ids)[i];\n if (i == 0) {\n TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n } else {\n int delta = current_segment_id - previous_segment_id;\n TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n }\n previous_segment_id = current_segment_id;\n }\n\n const int max_index = previous_segment_id;\n\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tflite::ops::builtin::segment_sum::ResizeOutputTensor", "_file_name": "tensorflow/lite/kernels/segment_sum.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "sctp_disposition_t sctp_sf_ootb(struct net *net,\n\t\t\t\tconst struct sctp_endpoint *ep,\n\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\tconst sctp_subtype_t type,\n\t\t\t\tvoid *arg,\n\t\t\t\tsctp_cmd_seq_t *commands)\n{\n\tstruct sctp_chunk *chunk = arg;\n\tstruct sk_buff *skb = chunk->skb;\n\tsctp_chunkhdr_t *ch;\n\tsctp_errhdr_t *err;\n\t__u8 *ch_end;\n\tint ootb_shut_ack = 0;\n\tint ootb_cookie_ack = 0;\n\n\tSCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);\n\n\tch = (sctp_chunkhdr_t *) chunk->chunk_hdr;\n\tdo {\n\t\t/* Report violation if the chunk is less then minimal */\n\t\tif (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* Now that we know we at least have a chunk header,\n\t\t * do things that are type appropriate.\n\t\t */\n\t\tif (SCTP_CID_SHUTDOWN_ACK == ch->type)\n\t\t\tootb_shut_ack = 1;\n\n\t\t/* RFC 2960, Section 3.3.7\n\t\t * Moreover, under any circumstances, an endpoint that\n\t\t * receives an ABORT MUST NOT respond to that ABORT by\n\t\t * sending an ABORT of its own.\n\t\t */\n\t\tif (SCTP_CID_ABORT == ch->type)\n\t\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\n\t\t/* RFC 8.4, 7) If the packet contains a \"Stale cookie\" ERROR\n\t\t * or a COOKIE ACK the SCTP Packet should be silently\n\t\t * discarded.\n\t\t */\n\n\t\tif (SCTP_CID_COOKIE_ACK == ch->type)\n\t\t\tootb_cookie_ack = 1;\n\n\t\tif (SCTP_CID_ERROR == ch->type) {\n\t\t\tsctp_walk_errors(err, ch) {\n\t\t\t\tif (SCTP_ERROR_STALE_COOKIE == err->cause) {\n\t\t\t\t\tootb_cookie_ack = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tch = (sctp_chunkhdr_t *) ch_end;\n\t} while (ch_end < skb_tail_pointer(skb));\n\n\tif (ootb_shut_ack)\n\t\treturn sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);\n\telse if (ootb_cookie_ack)\n\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\telse\n\t\treturn sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "sctp_sf_ootb", "_file_name": "net/sctp/sm_statefuns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def make_eb_config(application_name, default_region):\n # Capture our current directory\n UTILS_DIR = os.path.dirname(os.path.abspath(__file__))\n # Create the jinja2 environment.\n # Notice the use of trim_blocks, which greatly helps control whitespace.\n j2_env = Environment(loader=FileSystemLoader(UTILS_DIR))\n return j2_env.get_template('templates/eb/config.yml').render(\n APPLICATION_NAME=application_name,\n DEFAULT_REGION=default_region\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[263, 324]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[263, 324]]}, "_func_name": "make_eb_config", "_file_name": "utils/make_eb_config.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):\n \"\"\"\n Get all the old sourcebyinstitution number from the SQLite database.\n \"\"\"\n query = \"\"\"\n SELECT\n titles\n FROM\n history\n WHERE\n sourcebyinstitution = \"%s\"\n ORDER BY\n titles DESC\n LIMIT 1\n \"\"\" % sourcebyinstitution\n\n sqlite.execute(query)\n for record in sqlite:\n old_sourcebyinstitution_number = record[0]\n return old_sourcebyinstitution_number", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[261, 300], [357, 387]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[261, 300], [357, 387]]}, "_func_name": "get_old_sourcebyinstitution_number", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "xfs_attr_shortform_to_leaf(\n\tstruct xfs_da_args\t*args,\n\tstruct xfs_buf\t\t**leaf_bp)\n{\n\txfs_inode_t *dp;\n\txfs_attr_shortform_t *sf;\n\txfs_attr_sf_entry_t *sfe;\n\txfs_da_args_t nargs;\n\tchar *tmpbuffer;\n\tint error, i, size;\n\txfs_dablk_t blkno;\n\tstruct xfs_buf *bp;\n\txfs_ifork_t *ifp;\n\n\ttrace_xfs_attr_sf_to_leaf(args);\n\n\tdp = args->dp;\n\tifp = dp->i_afp;\n\tsf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;\n\tsize = be16_to_cpu(sf->hdr.totsize);\n\ttmpbuffer = kmem_alloc(size, KM_SLEEP);\n\tASSERT(tmpbuffer != NULL);\n\tmemcpy(tmpbuffer, ifp->if_u1.if_data, size);\n\tsf = (xfs_attr_shortform_t *)tmpbuffer;\n\n\txfs_idata_realloc(dp, -size, XFS_ATTR_FORK);\n\txfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);\n\n\tbp = NULL;\n\terror = xfs_da_grow_inode(args, &blkno);\n\tif (error) {\n\t\t/*\n\t\t * If we hit an IO error middle of the transaction inside\n\t\t * grow_inode(), we may have inconsistent data. Bail out.\n\t\t */\n\t\tif (error == -EIO)\n\t\t\tgoto out;\n\t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n\t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */\n\t\tgoto out;\n\t}\n\n\tASSERT(blkno == 0);\n\terror = xfs_attr3_leaf_create(args, blkno, &bp);\n\tif (error) {\n\t\t/* xfs_attr3_leaf_create may not have instantiated a block */\n\t\tif (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))\n\t\t\tgoto out;\n\t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n\t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */\n\t\tgoto out;\n\t}\n\n\tmemset((char *)&nargs, 0, sizeof(nargs));\n\tnargs.dp = dp;\n\tnargs.geo = args->geo;\n\tnargs.firstblock = args->firstblock;\n\tnargs.dfops = args->dfops;\n\tnargs.total = args->total;\n\tnargs.whichfork = XFS_ATTR_FORK;\n\tnargs.trans = args->trans;\n\tnargs.op_flags = XFS_DA_OP_OKNOENT;\n\n\tsfe = &sf->list[0];\n\tfor (i = 0; i < sf->hdr.count; i++) {\n\t\tnargs.name = sfe->nameval;\n\t\tnargs.namelen = sfe->namelen;\n\t\tnargs.value = &sfe->nameval[nargs.namelen];\n\t\tnargs.valuelen = sfe->valuelen;\n\t\tnargs.hashval = xfs_da_hashname(sfe->nameval,\n\t\t\t\t\t\tsfe->namelen);\n\t\tnargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);\n\t\terror = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */\n\t\tASSERT(error == -ENOATTR);\n\t\terror = xfs_attr3_leaf_add(bp, &nargs);\n\t\tASSERT(error != -ENOSPC);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tsfe = XFS_ATTR_SF_NEXTENTRY(sfe);\n\t}\n\terror = 0;\n\t*leaf_bp = bp;\nout:\n\tkmem_free(tmpbuffer);\n\treturn error;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "xfs_attr_shortform_to_leaf", "_file_name": "fs/xfs/libxfs/xfs_attr_leaf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n QStandardItem *item = m_peerItems.value(ip);\n int row = item->row();\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n m_missingFlags.remove(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1126, 1218]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1126, 1218]]}, "_func_name": "PeerListWidget::updatePeer", "_file_name": "src/gui/properties/peerlistwidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def getOptions(poll_name):\n conn, c = connectDB()\n options_str = queryOne(c, \"SELECT options FROM {} WHERE name='{}'\".format(CFG(\"poll_table_name\"), poll_name))\n if options_str == None:\n return None\n options = options_str.split(\",\")\n closeDB(conn)\n return options", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[53, 167]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[53, 167]]}, "_func_name": "getOptions", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "http_error_t::make_body (int n, const str &si, const str &aux)\n{\n strbuf b;\n str ldesc;\n const str sdesc = http_status.get_desc (n, &ldesc);\n b << \"\\n\"\n << \" \\n\"\n << \" \" << n << \" \" << sdesc << \"\\n\"\n << \" \\n\"\n << \" \\n\"\n << \"

Error \" << n << \" \" << sdesc << \"



\\n\"\n ;\n if (n == HTTP_NOT_FOUND && aux) {\n b << \"The file \" << aux \n << \" was not found on this server.

\\n\\n\";\n }\n b << \"
\\n\"\n << \" \" << si << \"\\n\"\n << \"
\\n\"\n << \" \\n\"\n << \"\\n\"\n ;\n return b;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[381, 414]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[381, 414]]}, "_func_name": "http_error_t::make_body", "_file_name": "libahttp/err.C", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_vvset_from_3par(self, volume_name):\n \"\"\"Get Virtual Volume Set from 3PAR.\n\n The only way to do this currently is to try and delete the volume\n to get the error message.\n\n NOTE(walter-boring): don't call this unless you know the volume is\n already in a vvset!\n \"\"\"\n cmd = \"removevv -f %s\" % volume_name\n LOG.debug(\"Issuing remove command to find vvset name %s\" % cmd)\n out = self._cli_run(cmd, None)\n vvset_name = None\n if out and len(out) > 1:\n if out[1].startswith(\"Attempt to delete \"):\n words = out[1].split(\" \")\n vvset_name = words[len(words) - 1]\n\n return vvset_name", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[319, 364], [436, 475]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[319, 364], [436, 475]]}, "_func_name": "_get_vvset_from_3par", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def system_search(self, search):\r\n search = search.lower()\r\n conn = sqlite3.connect('data/ed.db').cursor()\r\n table = conn.execute(f\"select * from populated where lower(name) = '{search}'\")\r\n results = table.fetchone()\r\n if not results:\r\n table = conn.execute(f\"select * from systems where lower(name) = '{search}'\")\r\n results = table.fetchone()\r\n if results:\r\n keys = tuple(i[0] for i in table.description) \r\n return '\\n'.join(f'{key.replace(\"_\", \" \").title()}: {field}'\r\n for key, field in zip(keys[1:], results[1:]) if field)\r\n else:\r\n return 'No systems found.'", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[126, 215], [276, 367]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[126, 215], [276, 367]]}, "_func_name": "system_search", "_file_name": "eddb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_MSB,op_LSB;\n\tint ret;\n\tif (!data)\n\t\treturn 0;\n\tmemset (op, '\\0', sizeof (RAnalOp));\n\top->addr = addr;\n\top->type = R_ANAL_OP_TYPE_UNK;\n\top->jump = op->fail = -1;\n\top->ptr = op->val = -1;\n\n\top->size = 2;\n\n\top_MSB = anal->big_endian? data[0]: data[1];\n\top_LSB = anal->big_endian? data[1]: data[0];\n\tret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[112, 124]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[112, 124]]}, "_func_name": "sh_op", "_file_name": "libr/anal/p/anal_sh.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def create_playlist(name, db):\n db.execute(\n \"INSERT INTO playlist (name, video_position) VALUES(%s, 0);\", (name,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _add_volume_to_volume_set(self, volume, volume_name,\n cpg, vvs_name, qos):\n if vvs_name is not None:\n # Admin has set a volume set name to add the volume to\n self._cli_run(['createvvset', '-add', vvs_name, volume_name])\n else:\n vvs_name = self._get_3par_vvs_name(volume['id'])\n domain = self.get_domain(cpg)\n self._cli_run(['createvvset', '-domain', domain, vvs_name])\n self._set_qos_rule(qos, vvs_name)\n self._cli_run(['createvvset', '-add', vvs_name, volume_name])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_add_volume_to_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PyImaging_MapBuffer(PyObject* self, PyObject* args)\n{\n Py_ssize_t y, size;\n Imaging im;\n\n PyObject* target;\n Py_buffer view;\n char* mode;\n char* codec;\n PyObject* bbox;\n Py_ssize_t offset;\n int xsize, ysize;\n int stride;\n int ystep;\n\n if (!PyArg_ParseTuple(args, \"O(ii)sOn(sii)\", &target, &xsize, &ysize,\n &codec, &bbox, &offset, &mode, &stride, &ystep))\n return NULL;\n\n if (!PyImaging_CheckBuffer(target)) {\n PyErr_SetString(PyExc_TypeError, \"expected string or buffer\");\n return NULL;\n }\n\n if (stride <= 0) {\n if (!strcmp(mode, \"L\") || !strcmp(mode, \"P\"))\n stride = xsize;\n else if (!strncmp(mode, \"I;16\", 4))\n stride = xsize * 2;\n else\n stride = xsize * 4;\n }\n\n size = (Py_ssize_t) ysize * stride;\n\n /* check buffer size */\n if (PyImaging_GetBuffer(target, &view) < 0)\n return NULL;\n\n if (view.len < 0) {\n PyErr_SetString(PyExc_ValueError, \"buffer has negative size\");\n return NULL;\n }\n if (offset + size > view.len) {\n PyErr_SetString(PyExc_ValueError, \"buffer is not large enough\");\n return NULL;\n }\n\n im = ImagingNewPrologueSubtype(\n mode, xsize, ysize, sizeof(ImagingBufferInstance)\n );\n if (!im)\n return NULL;\n\n /* setup file pointers */\n if (ystep > 0)\n for (y = 0; y < ysize; y++)\n im->image[y] = (char*)view.buf + offset + y * stride;\n else\n for (y = 0; y < ysize; y++)\n im->image[ysize-y-1] = (char*)view.buf + offset + y * stride;\n\n im->destroy = mapping_destroy_buffer;\n\n Py_INCREF(target);\n ((ImagingBufferInstance*) im)->target = target;\n ((ImagingBufferInstance*) im)->view = view;\n\n if (!ImagingNewEpilogue(im))\n return NULL;\n\n return PyImagingNew(im);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[812, 852]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[812, 852]]}, "_func_name": "PyImaging_MapBuffer", "_file_name": "map.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {\n\tstruct r_bin_t *rbin = arch->rbin;\n\tint i;\n\tint *methods = NULL;\n\tint sym_count = 0;\n\n\t// doublecheck??\n\tif (!bin || bin->methods_list) {\n\t\treturn false;\n\t}\n\tbin->code_from = UT64_MAX;\n\tbin->code_to = 0;\n\tbin->methods_list = r_list_newf ((RListFree)free);\n\tif (!bin->methods_list) {\n\t\treturn false;\n\t}\n\tbin->imports_list = r_list_newf ((RListFree)free);\n\tif (!bin->imports_list) {\n\t\tr_list_free (bin->methods_list);\n\t\treturn false;\n\t}\n\tbin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);\n\tif (!bin->classes_list) {\n\t\tr_list_free (bin->methods_list);\n\t\tr_list_free (bin->imports_list);\n\t\treturn false;\n\t}\n\n\tif (bin->header.method_size>bin->size) {\n\t\tbin->header.method_size = 0;\n\t\treturn false;\n\t}\n\n\t/* WrapDown the header sizes to avoid huge allocations */\n\tbin->header.method_size = R_MIN (bin->header.method_size, bin->size);\n\tbin->header.class_size = R_MIN (bin->header.class_size, bin->size);\n\tbin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);\n\n\t// TODO: is this posible after R_MIN ??\n\tif (bin->header.strings_size > bin->size) {\n\t\teprintf (\"Invalid strings size\\n\");\n\t\treturn false;\n\t}\n\n\tif (bin->classes) {\n\t\tut64 amount = sizeof (int) * bin->header.method_size;\n\t\tif (amount > UT32_MAX || amount < bin->header.method_size) {\n\t\t\treturn false;\n\t\t}\n\t\tmethods = calloc (1, amount + 1);\n\t\tfor (i = 0; i < bin->header.class_size; i++) {\n\t\t\tchar *super_name, *class_name;\n\t\t\tstruct dex_class_t *c = &bin->classes[i];\n\t\t\tclass_name = dex_class_name (bin, c);\n\t\t\tsuper_name = dex_class_super_name (bin, c);\n\t\t\tif (dexdump) { \n\t\t\t\trbin->cb_printf (\"Class #%d -\\n\", i);\n\t\t\t}\n\t\t\tparse_class (arch, bin, c, i, methods, &sym_count);\n\t\t\tfree (class_name);\n\t\t\tfree (super_name);\n\t\t}\n\t}\n\n\tif (methods) {\n\t\tint import_count = 0;\n\t\tint sym_count = bin->methods_list->length;\n\n\t\tfor (i = 0; i < bin->header.method_size; i++) {\n\t\t\tint len = 0;\n\t\t\tif (methods[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (bin->methods[i].class_id > bin->header.types_size) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchar *class_name = getstr (\n\t\t\t\tbin, bin->types[bin->methods[i].class_id]\n\t\t\t\t\t\t.descriptor_id);\n\t\t\tif (!class_name) {\n\t\t\t\tfree (class_name);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlen = strlen (class_name);\n\t\t\tif (len < 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tclass_name[len - 1] = 0; // remove last char \";\"\n\t\t\tchar *method_name = dex_method_name (bin, i);\n\t\t\tchar *signature = dex_method_signature (bin, i);\n\t\t\tif (method_name && *method_name) {\n\t\t\t\tRBinImport *imp = R_NEW0 (RBinImport);\n\t\t\t\timp->name = r_str_newf (\"%s.method.%s%s\", class_name, method_name, signature);\n\t\t\t\timp->type = r_str_const (\"FUNC\");\n\t\t\t\timp->bind = r_str_const (\"NONE\");\n\t\t\t\timp->ordinal = import_count++;\n\t\t\t\tr_list_append (bin->imports_list, imp);\n\n\t\t\t\tRBinSymbol *sym = R_NEW0 (RBinSymbol);\n\t\t\t\tsym->name = r_str_newf (\"imp.%s\", imp->name);\n\t\t\t\tsym->type = r_str_const (\"FUNC\");\n\t\t\t\tsym->bind = r_str_const (\"NONE\");\n\t\t\t\t//XXX so damn unsafe check buffer boundaries!!!!\n\t\t\t\t//XXX use r_buf API!!\n\t\t\t\tsym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;\n\t\t\t\tsym->ordinal = sym_count++;\n\t\t\t\tr_list_append (bin->methods_list, sym);\n\t\t\t\tsdb_num_set (mdb, sdb_fmt (0, \"method.%d\", i), sym->paddr, 0);\n\t\t\t}\n\t\t\tfree (method_name);\n\t\t\tfree (signature);\n\t\t\tfree (class_name);\n\t\t}\n\t\tfree (methods);\n\t}\n\treturn true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dex_loadcode", "_file_name": "libr/bin/p/bin_dex.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "rfbHandleAuthResult(rfbClient* client)\n{\n uint32_t authResult=0, reasonLen=0;\n char *reason=NULL;\n\n if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;\n\n authResult = rfbClientSwap32IfLE(authResult);\n\n switch (authResult) {\n case rfbVncAuthOK:\n rfbClientLog(\"VNC authentication succeeded\\n\");\n return TRUE;\n break;\n case rfbVncAuthFailed:\n if (client->major==3 && client->minor>7)\n {\n /* we have an error following */\n if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE;\n reasonLen = rfbClientSwap32IfLE(reasonLen);\n reason = malloc((uint64_t)reasonLen+1);\n if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; }\n reason[reasonLen]=0;\n rfbClientLog(\"VNC connection failed: %s\\n\",reason);\n free(reason);\n return FALSE;\n }\n rfbClientLog(\"VNC authentication failed\\n\");\n return FALSE;\n case rfbVncAuthTooMany:\n rfbClientLog(\"VNC authentication failed - too many tries\\n\");\n return FALSE;\n }\n\n rfbClientLog(\"Unknown VNC authentication result: %d\\n\",\n (int)authResult);\n return FALSE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[41, 104], [489, 868]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[41, 104], [489, 868]]}, "_func_name": "rfbHandleAuthResult", "_file_name": "libvncclient/rfbproto.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef commentcounts(context, filediff, interfilediff=None):\n \"\"\"\n Returns a JSON array of current comments for a filediff, sorted by\n line number.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n comment_id The ID of the comment\n text The text of the comment\n line The first line number\n num_lines The number of lines this comment spans\n user A dictionary containing \"username\" and \"name\" keys\n for the user\n url The URL to the comment\n localdraft True if this is the current user's draft comment\n =========== ==================================================\n \"\"\"\n comment_dict = {}\n user = context.get('user', None)\n\n if interfilediff:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff=interfilediff)\n else:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff__isnull=True)\n\n for comment in query:\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n key = (comment.first_line, comment.num_lines)\n\n comment_dict.setdefault(key, []).append({\n 'comment_id': comment.id,\n 'text': escape(comment.text),\n 'line': comment.first_line,\n 'num_lines': comment.num_lines,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n #'timestamp': comment.timestamp,\n 'url': comment.get_review_url(),\n 'localdraft': review.user == user and \\\n not review.public,\n })\n\n comments_array = []\n\n for key, value in comment_dict.iteritems():\n comments_array.append({\n 'linenum': key[0],\n 'num_lines': key[1],\n 'comments': value,\n })\n\n comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or\n cmp(x['num_lines'], y['num_lines'])))\n\n return simplejson.dumps(comments_array)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "commentcounts", "_file_name": "reviewboard/reviews/templatetags/reviewtags.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_error_days(cur, error_percent):\n \"\"\"Fetches the days in which requests led to errors.\n\n Fetches the days in which the specified percentage\n of requests led to errors.\n\n Args:\n cur(obj): The cursor to execute the query.\n error_percent(int): The percentage of requests that led to errors.\n\n Return:\n True if success, False otherwise.\n \"\"\"\n data = (error_percent, )\n query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),\n round((log_errors.errors * 100\n / log_requests.total::numeric), 2) as percent\n FROM log_errors, log_requests\n WHERE log_errors.date = log_requests.date AND\n log_errors.errors * 100\n / log_requests.total::numeric > %s\n ORDER BY log_errors.date'''\n rows = get_data(cur, query, data)\n\n # Write data to txt file.\n if rows is not None:\n file = open(\"error_report.txt\", \"w\")\n for row in rows:\n file.write(\"{} - {}% errors \\n\".format(row[0], row[1]))\n file.close()\n\n return True\n else:\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_error_days", "_file_name": "news_data_analysis.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/view/')\ndef view(sid):\n if utils.sid_is_valid(sid):\n path = join(app.config['UPLOAD_FOLDER'], sid)\n if os.path.isdir(path):\n using_firebase = 'true' if app.config['FIREBASE'] else 'false'\n return render_template('view.html', sid=sid,\n title=\"Progress for %s\" % sid,\n using_firebase=using_firebase)\n else:\n abort(404)\n else:\n abort(403)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "view", "_file_name": "app/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)\n{\n int i;\n GlyphInfo *cur, *s1, *e1, *s2, *s3;\n int last_space;\n int break_type;\n int exit;\n double pen_shift_x;\n double pen_shift_y;\n int cur_line;\n int run_offset;\n TextInfo *text_info = &render_priv->text_info;\n\n last_space = -1;\n text_info->n_lines = 1;\n break_type = 0;\n s1 = text_info->glyphs; // current line start\n for (i = 0; i < text_info->length; ++i) {\n int break_at = -1;\n double s_offset, len;\n cur = text_info->glyphs + i;\n s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);\n len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;\n\n if (cur->symbol == '\\n') {\n break_type = 2;\n break_at = i;\n ass_msg(render_priv->library, MSGL_DBG2,\n \"forced line break at %d\", break_at);\n } else if (cur->symbol == ' ') {\n last_space = i;\n } else if (len >= max_text_width\n && (render_priv->state.wrap_style != 2)) {\n break_type = 1;\n break_at = last_space;\n if (break_at >= 0)\n ass_msg(render_priv->library, MSGL_DBG2, \"line break at %d\",\n break_at);\n }\n\n if (break_at != -1) {\n // need to use one more line\n // marking break_at+1 as start of a new line\n int lead = break_at + 1; // the first symbol of the new line\n if (text_info->n_lines >= text_info->max_lines) {\n // Raise maximum number of lines\n text_info->max_lines *= 2;\n text_info->lines = realloc(text_info->lines,\n sizeof(LineInfo) *\n text_info->max_lines);\n }\n if (lead < text_info->length) {\n text_info->glyphs[lead].linebreak = break_type;\n last_space = -1;\n s1 = text_info->glyphs + lead;\n text_info->n_lines++;\n }\n }\n }\n#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))\n exit = 0;\n while (!exit && render_priv->state.wrap_style != 1) {\n exit = 1;\n s3 = text_info->glyphs;\n s1 = s2 = 0;\n for (i = 0; i <= text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if ((i == text_info->length) || cur->linebreak) {\n s1 = s2;\n s2 = s3;\n s3 = cur;\n if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'\n double l1, l2, l1_new, l2_new;\n GlyphInfo *w = s2;\n\n do {\n --w;\n } while ((w > s1) && (w->symbol == ' '));\n while ((w > s1) && (w->symbol != ' ')) {\n --w;\n }\n e1 = w;\n while ((e1 > s1) && (e1->symbol == ' ')) {\n --e1;\n }\n if (w->symbol == ' ')\n ++w;\n\n l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (s2->bbox.xMin + s2->pos.x));\n l1_new = d6_to_double(\n (e1->bbox.xMax + e1->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2_new = d6_to_double(\n ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (w->bbox.xMin + w->pos.x));\n\n if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {\n w->linebreak = 1;\n s2->linebreak = 0;\n exit = 0;\n }\n }\n }\n if (i == text_info->length)\n break;\n }\n\n }\n assert(text_info->n_lines >= 1);\n#undef DIFF\n\n measure_text(render_priv);\n trim_whitespace(render_priv);\n\n cur_line = 1;\n run_offset = 0;\n\n i = 0;\n cur = text_info->glyphs + i;\n while (i < text_info->length && cur->skip)\n cur = text_info->glyphs + ++i;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y = 0.;\n\n for (i = 0; i < text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if (cur->linebreak) {\n while (i < text_info->length && cur->skip && cur->symbol != '\\n')\n cur = text_info->glyphs + ++i;\n double height =\n text_info->lines[cur_line - 1].desc +\n text_info->lines[cur_line].asc;\n text_info->lines[cur_line - 1].len = i -\n text_info->lines[cur_line - 1].offset;\n text_info->lines[cur_line].offset = i;\n cur_line++;\n run_offset++;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y += height + render_priv->settings.line_spacing;\n }\n cur->pos.x += double_to_d6(pen_shift_x);\n cur->pos.y += double_to_d6(pen_shift_y);\n }\n text_info->lines[cur_line - 1].len =\n text_info->length - text_info->lines[cur_line - 1].offset;\n\n#if 0\n // print line info\n for (i = 0; i < text_info->n_lines; i++) {\n printf(\"line %d offset %d length %d\\n\", i, text_info->lines[i].offset,\n text_info->lines[i].len);\n }\n#endif\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[3756, 3819]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3756, 3819]]}, "_func_name": "wrap_lines_smart", "_file_name": "libass/ass_render.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int dd_delete_item(struct dump_dir *dd, const char *name)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n char *path = concat_path_file(dd->dd_dirname, name);\n int res = unlink(path);\n\n if (res < 0)\n {\n if (errno == ENOENT)\n errno = res = 0;\n else\n perror_msg(\"Can't delete file '%s'\", path);\n }\n\n free(path);\n return res;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[145, 202]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[145, 202]]}, "_func_name": "dd_delete_item", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def repack(host, targets, channel='stable'):\n print(\"Repacking rust for %s...\" % host)\n url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'\n req = requests.get(url)\n req.raise_for_status()\n manifest = toml.loads(req.content)\n if manifest['manifest-version'] != '2':\n print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])\n return\n print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))\n rustc_version, rustc = package(manifest, 'rustc', host)\n if rustc['available']:\n print('rustc %s\\n %s\\n %s' % (rustc_version, rustc['url'], rustc['hash']))\n fetch(rustc['url'])\n cargo_version, cargo = package(manifest, 'cargo', host)\n if cargo['available']:\n print('cargo %s\\n %s\\n %s' % (cargo_version, cargo['url'], cargo['hash']))\n fetch(cargo['url'])\n stds = []\n for target in targets:\n version, info = package(manifest, 'rust-std', target)\n if info['available']:\n print('rust-std %s\\n %s\\n %s' % (version, info['url'], info['hash']))\n fetch(info['url'])\n stds.append(info)\n print('Installing packages...')\n tar_basename = 'rustc-%s-repack' % host\n install_dir = 'rustc'\n subprocess.check_call(['rm', '-rf', install_dir])\n install(os.path.basename(rustc['url']), install_dir)\n install(os.path.basename(cargo['url']), install_dir)\n for std in stds:\n install(os.path.basename(std['url']), install_dir)\n print('Tarring %s...' % tar_basename)\n subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])\n subprocess.check_call(['rm', '-rf', install_dir])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "repack", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void ttm_put_pages(struct page **pages, unsigned npages, int flags,\n\t\t\t enum ttm_caching_state cstate)\n{\n\tstruct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tstruct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);\n#endif\n\tunsigned long irq_flags;\n\tunsigned i;\n\n\tif (pool == NULL) {\n\t\t/* No pool for this memory type so free the pages */\n\t\ti = 0;\n\t\twhile (i < npages) {\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tstruct page *p = pages[i];\n#endif\n\t\t\tunsigned order = 0, j;\n\n\t\t\tif (!pages[i]) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tif (!(flags & TTM_PAGE_FLAG_DMA32) &&\n\t\t\t (npages - i) >= HPAGE_PMD_NR) {\n\t\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\t\tif (++p != pages[i + j])\n\t\t\t\t\t break;\n\n\t\t\t\tif (j == HPAGE_PMD_NR)\n\t\t\t\t\torder = HPAGE_PMD_ORDER;\n\t\t\t}\n#endif\n\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\t__free_pages(pages[i], order);\n\n\t\t\tj = 1 << order;\n\t\t\twhile (j) {\n\t\t\t\tpages[i++] = NULL;\n\t\t\t\t--j;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\ti = 0;\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tif (huge) {\n\t\tunsigned max_size, n2free;\n\n\t\tspin_lock_irqsave(&huge->lock, irq_flags);\n\t\twhile ((npages - i) >= HPAGE_PMD_NR) {\n\t\t\tstruct page *p = pages[i];\n\t\t\tunsigned j;\n\n\t\t\tif (!p)\n\t\t\t\tbreak;\n\n\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tif (++p != pages[i + j])\n\t\t\t\t break;\n\n\t\t\tif (j != HPAGE_PMD_NR)\n\t\t\t\tbreak;\n\n\t\t\tlist_add_tail(&pages[i]->lru, &huge->list);\n\n\t\t\tfor (j = 0; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tpages[i++] = NULL;\n\t\t\thuge->npages++;\n\t\t}\n\n\t\t/* Check that we don't go over the pool limit */\n\t\tmax_size = _manager->options.max_size;\n\t\tmax_size /= HPAGE_PMD_NR;\n\t\tif (huge->npages > max_size)\n\t\t\tn2free = huge->npages - max_size;\n\t\telse\n\t\t\tn2free = 0;\n\t\tspin_unlock_irqrestore(&huge->lock, irq_flags);\n\t\tif (n2free)\n\t\t\tttm_page_pool_free(huge, n2free, false);\n\t}\n#endif\n\n\tspin_lock_irqsave(&pool->lock, irq_flags);\n\twhile (i < npages) {\n\t\tif (pages[i]) {\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\tlist_add_tail(&pages[i]->lru, &pool->list);\n\t\t\tpages[i] = NULL;\n\t\t\tpool->npages++;\n\t\t}\n\t\t++i;\n\t}\n\t/* Check that we don't go over the pool limit */\n\tnpages = 0;\n\tif (pool->npages > _manager->options.max_size) {\n\t\tnpages = pool->npages - _manager->options.max_size;\n\t\t/* free at least NUM_PAGES_TO_ALLOC number of pages\n\t\t * to reduce calls to set_memory_wb */\n\t\tif (npages < NUM_PAGES_TO_ALLOC)\n\t\t\tnpages = NUM_PAGES_TO_ALLOC;\n\t}\n\tspin_unlock_irqrestore(&pool->lock, irq_flags);\n\tif (npages)\n\t\tttm_page_pool_free(pool, npages, false);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ttm_put_pages", "_file_name": "drivers/gpu/drm/ttm/ttm_page_alloc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "PlayerGeneric::~PlayerGeneric()\n{\n\n\tif (player)\n\t{\n\t\tif (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player))\n\t\t\tmixer->removeDevice(player);\n\t\tdelete player;\n\t}\n\t\n\tif (mixer)\n\t\tdelete mixer;\n\n\tdelete[] audioDriverName;\n\t\n\tdelete listener;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PlayerGeneric::~PlayerGeneric", "_file_name": "src/milkyplay/PlayerGeneric.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n{\n\tint i;\n\trdpBitmapCache* bitmapCache;\n\tbitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));\n\n\tif (!bitmapCache)\n\t\treturn NULL;\n\n\tbitmapCache->settings = settings;\n\tbitmapCache->update = ((freerdp*)settings->instance)->update;\n\tbitmapCache->context = bitmapCache->update->context;\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n\n\tif (!bitmapCache->cells)\n\t\tgoto fail;\n\n\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t{\n\t\tbitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;\n\t\t/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */\n\t\tbitmapCache->cells[i].entries =\n\t\t (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));\n\n\t\tif (!bitmapCache->cells[i].entries)\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapCache;\nfail:\n\n\tif (bitmapCache->cells)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t}\n\n\tfree(bitmapCache);\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[351, 503]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[351, 503]]}, "_func_name": "bitmap_cache_new", "_file_name": "libfreerdp/cache/bitmap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static PyObject* patch(PyObject* self, PyObject* args)\n{\n char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;\n Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;\n PyObject *controlTuples, *tuple, *results;\n off_t oldpos, newpos, x, y, z;\n int i, j, numTuples;\n\n if (!PyArg_ParseTuple(args, \"s#nO!s#s#\",\n &origData, &origDataLength, &newDataLength,\n &PyList_Type, &controlTuples,\n &diffBlock, &diffBlockLength,\n &extraBlock, &extraBlockLength))\n return NULL;\n\n /* allocate the memory for the new data */\n newData = PyMem_Malloc(newDataLength + 1);\n if (!newData)\n return PyErr_NoMemory();\n\n oldpos = 0;\n newpos = 0;\n diffPtr = diffBlock;\n extraPtr = extraBlock;\n numTuples = PyList_GET_SIZE(controlTuples);\n for (i = 0; i < numTuples; i++) {\n tuple = PyList_GET_ITEM(controlTuples, i);\n if (!PyTuple_Check(tuple)) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple\");\n return NULL;\n }\n if (PyTuple_GET_SIZE(tuple) != 3) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple of size 3\");\n return NULL;\n }\n x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));\n y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));\n z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));\n if (newpos + x > newDataLength ||\n diffPtr + x > diffBlock + diffBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, diffPtr, x);\n diffPtr += x;\n for (j = 0; j < x; j++)\n if ((oldpos + j >= 0) && (oldpos + j < origDataLength))\n newData[newpos + j] += origData[oldpos + j];\n newpos += x;\n oldpos += x;\n if (newpos + y > newDataLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, extraPtr, y);\n extraPtr += y;\n newpos += y;\n oldpos += z;\n }\n\n /* confirm that a valid patch was applied */\n if (newpos != newDataLength ||\n diffPtr != diffBlock + diffBlockLength ||\n extraPtr != extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (underflow)\");\n return NULL;\n }\n\n results = PyBytes_FromStringAndSize(newData, newDataLength);\n PyMem_Free(newData);\n return results;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "patch", "_file_name": "bsdiff4/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _keyify(key):\n return _key_pattern.sub(' ', key.lower())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[18, 63]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[18, 63]]}, "_func_name": "_keyify", "_file_name": "mistune.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def karma_rank(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n SELECT (SELECT COUNT(*) FROM people AS t2 WHERE t2.karma > t1.karma)\n AS row_Num FROM people AS t1 WHERE name='{}'\n '''.format(name))\n rank = cursor.fetchone()[0] + 1\n logger.debug('Rank of {} found for name {}'.format(rank, name))\n db.close()\n return rank\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[186, 269]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[186, 269]]}, "_func_name": "karma_rank", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/get_markets')\ndef get_markets():\n asset_id = request.args.get('asset_id')\n\n if not isObject(asset_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_asset_symbols\",[[\"' + asset_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n asset_id = j_l[\"result\"][0][\"id\"]\n\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT * FROM markets WHERE aid='\"+asset_id+\"'\"\n cur.execute(query)\n results = cur.fetchall()\n con.close()\n return jsonify(results)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[408, 469]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[408, 469]]}, "_func_name": "get_markets", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n{\n#define MaxDirectoryStack 16\n#define EXIF_DELIMITER \"\\n\"\n#define EXIF_NUM_FORMATS 12\n#define TAG_EXIF_OFFSET 0x8769\n#define TAG_INTEROP_OFFSET 0xa005\n\n typedef struct _DirectoryInfo\n {\n unsigned char\n *directory;\n\n size_t\n entry;\n } DirectoryInfo;\n\n DirectoryInfo\n directory_stack[MaxDirectoryStack];\n\n EndianType\n endian;\n\n size_t\n entry,\n length,\n number_entries;\n\n ssize_t\n id,\n level,\n offset;\n\n static int\n format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};\n\n unsigned char\n *directory,\n *exif;\n\n /*\n Set EXIF resolution tag.\n */\n length=GetStringInfoLength(profile);\n exif=GetStringInfoDatum(profile);\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadProfileShort(LSBEndian,exif);\n if ((id != 0x4949) && (id != 0x4D4D))\n {\n while (length != 0)\n {\n if (ReadProfileByte(&exif,&length) != 0x45)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x78)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x69)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x66)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x00)\n continue;\n if (ReadProfileByte(&exif,&length) != 0x00)\n continue;\n break;\n }\n if (length < 16)\n return(MagickFalse);\n id=(ssize_t) ReadProfileShort(LSBEndian,exif);\n }\n endian=LSBEndian;\n if (id == 0x4949)\n endian=LSBEndian;\n else\n if (id == 0x4D4D)\n endian=MSBEndian;\n else\n return(MagickFalse);\n if (ReadProfileShort(endian,exif+2) != 0x002a)\n return(MagickFalse);\n /*\n This the offset to the first IFD.\n */\n offset=(ssize_t) ReadProfileLong(endian,exif+4);\n if ((offset < 0) || (size_t) offset >= length)\n return(MagickFalse);\n directory=exif+offset;\n level=0;\n entry=0;\n do\n {\n if (level > 0)\n {\n level--;\n directory=directory_stack[level].directory;\n entry=directory_stack[level].entry;\n }\n if ((directory < exif) || (directory > (exif+length-2)))\n break;\n /*\n Determine how many entries there are in the current IFD.\n */\n number_entries=ReadProfileShort(endian,directory);\n for ( ; entry < number_entries; entry++)\n {\n int\n components;\n\n register unsigned char\n *p,\n *q;\n\n size_t\n number_bytes;\n\n ssize_t\n format,\n tag_value;\n\n q=(unsigned char *) (directory+2+(12*entry));\n if (q > (exif+length-12))\n break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n if (components < 0)\n break; /* corrupt EXIF */\n number_bytes=(size_t) components*format_bytes[format];\n if ((ssize_t) number_bytes < components)\n break; /* prevent overflow */\n if (number_bytes <= 4)\n p=q+8;\n else\n {\n /*\n The directory entry contains an offset.\n */\n offset=(ssize_t) ReadProfileLong(endian,q+8);\n if ((size_t) (offset+number_bytes) > length)\n continue;\n if (~length < number_bytes)\n continue; /* prevent overflow */\n p=(unsigned char *) (exif+offset);\n }\n switch (tag_value)\n {\n case 0x011a:\n {\n (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);\n (void) WriteProfileLong(endian,1UL,p+4);\n break;\n }\n case 0x011b:\n {\n (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);\n (void) WriteProfileLong(endian,1UL,p+4);\n break;\n }\n case 0x0112:\n {\n if (number_bytes == 4)\n {\n (void) WriteProfileLong(endian,(size_t) image->orientation,p);\n break;\n }\n (void) WriteProfileShort(endian,(unsigned short) image->orientation,\n p);\n break;\n }\n case 0x0128:\n {\n if (number_bytes == 4)\n {\n (void) WriteProfileLong(endian,(size_t) (image->units+1),p);\n break;\n }\n (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);\n break;\n }\n default:\n break;\n }\n if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))\n {\n offset=(ssize_t) ReadProfileLong(endian,p);\n if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=directory;\n entry++;\n directory_stack[level].entry=entry;\n level++;\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n level++;\n if ((directory+2+(12*number_entries)) > (exif+length))\n break;\n offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*\n number_entries));\n if ((offset != 0) && ((size_t) offset < length) &&\n (level < (MaxDirectoryStack-2)))\n {\n directory_stack[level].directory=exif+offset;\n directory_stack[level].entry=0;\n level++;\n }\n }\n break;\n }\n }\n } while (level > 0);\n return(MagickTrue);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "SyncExifProfile", "_file_name": "MagickCore/profile.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _set_connections(self):\n \"\"\"Set the number of concurrent connections.\n\n The 3PAR WS API server has a limit of concurrent connections.\n This is setting the number to the highest allowed, 15 connections.\n \"\"\"\n self._cli_run(\"setwsapi -sru high\", None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[243, 292]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[243, 292]]}, "_func_name": "_set_connections", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tag_num_to_tag(self, tag_num):\n ''' Returns tag given tag_num. '''\n\n q = \"SELECT tag FROM tags WHERE rowid = '\" + str(tag_num) + \"'\"\n self.query(q)\n return self.c.fetchone()[0]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[83, 155]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[83, 155]]}, "_func_name": "tag_num_to_tag", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,\n\t int* vs_israw, int v_israw,\n\t enum CCVALTYPE intype, enum CCVALTYPE* type,\n\t enum CCSTATE* state, ScanEnv* env)\n{\n int r;\n\n switch (*state) {\n case CCS_VALUE:\n if (*type == CCV_SB) {\n BITSET_SET_BIT(cc->bs, (int )(*vs));\n }\n else if (*type == CCV_CODE_POINT) {\n r = add_code_range(&(cc->mbuf), env, *vs, *vs);\n if (r < 0) return r;\n }\n break;\n\n case CCS_RANGE:\n if (intype == *type) {\n if (intype == CCV_SB) {\n if (*vs > 0xff || v > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )v);\n }\n else {\n r = add_code_range(&(cc->mbuf), env, *vs, v);\n if (r < 0) return r;\n }\n }\n else {\n#if 0\n if (intype == CCV_CODE_POINT && *type == CCV_SB) {\n#endif\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));\n r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);\n if (r < 0) return r;\n#if 0\n }\n else\n return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;\n#endif\n }\n ccs_range_end:\n *state = CCS_COMPLETE;\n break;\n\n case CCS_COMPLETE:\n case CCS_START:\n *state = CCS_VALUE;\n break;\n\n default:\n break;\n }\n\n *vs_israw = v_israw;\n *vs = v;\n *type = intype;\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[276, 319]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[276, 319]]}, "_func_name": "next_state_val", "_file_name": "src/regparse.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def create_playlist(name, db):\n db.execute(\n \"INSERT INTO playlist (name, video_position) VALUES('{name}', 0);\".format(name=name))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[47, 140]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[47, 140]]}, "_func_name": "create_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,\n uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)\n{\n\tconst cdf_section_header_t *shp;\n\tcdf_section_header_t sh;\n\tconst uint8_t *p, *q, *e;\n\tsize_t i, o4, nelements, j, slen, left;\n\tcdf_property_info_t *inp;\n\n\tif (offs > UINT32_MAX / 4) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tshp = CAST(const cdf_section_header_t *,\n\t cdf_offset(sst->sst_tab, offs));\n\tif (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)\n\t\tgoto out;\n\tsh.sh_len = CDF_TOLE4(shp->sh_len);\n\tif (sh.sh_len > CDF_SHLEN_LIMIT) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\n\tif (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)\n\t\tgoto out;\n\n\tsh.sh_properties = CDF_TOLE4(shp->sh_properties);\n\tDPRINTF((\"section len: %u properties %u\\n\", sh.sh_len,\n\t sh.sh_properties));\n\tif (sh.sh_properties > CDF_PROP_LIMIT)\n\t\tgoto out;\n\tinp = cdf_grow_info(info, maxcount, sh.sh_properties);\n\tif (inp == NULL)\n\t\tgoto out;\n\tinp += *count;\n\t*count += sh.sh_properties;\n\tp = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));\n\te = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));\n\tif (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)\n\t\tgoto out;\n\n\tfor (i = 0; i < sh.sh_properties; i++) {\n\t\tif ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)\n\t\t\tgoto out;\n\t\tinp[i].pi_id = CDF_GETUINT32(p, i << 1);\n\t\tleft = CAST(size_t, e - q);\n\t\tif (left < sizeof(uint32_t)) {\n\t\t\tDPRINTF((\"short info (no type)_\\n\"));\n\t\t\tgoto out;\n\t\t}\n\t\tinp[i].pi_type = CDF_GETUINT32(q, 0);\n\t\tDPRINTF((\"%\" SIZE_T_FORMAT \"u) id=%#x type=%#x offs=%#tx,%#x\\n\",\n\t\t i, inp[i].pi_id, inp[i].pi_type, q - p, offs));\n\t\tif (inp[i].pi_type & CDF_VECTOR) {\n\t\t\tif (left < sizeof(uint32_t) * 2) {\n\t\t\t\tDPRINTF((\"missing CDF_VECTOR length\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tnelements = CDF_GETUINT32(q, 1);\n\t\t\tif (nelements > CDF_ELEMENT_LIMIT || nelements == 0) {\n\t\t\t\tDPRINTF((\"CDF_VECTOR with nelements == %\"\n\t\t\t\t SIZE_T_FORMAT \"u\\n\", nelements));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tslen = 2;\n\t\t} else {\n\t\t\tnelements = 1;\n\t\t\tslen = 1;\n\t\t}\n\t\to4 = slen * sizeof(uint32_t);\n\t\tif (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))\n\t\t\tgoto unknown;\n\t\tswitch (inp[i].pi_type & CDF_TYPEMASK) {\n\t\tcase CDF_NULL:\n\t\tcase CDF_EMPTY:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\tcase CDF_BOOL:\n\t\tcase CDF_UNSIGNED32:\n\t\tcase CDF_FLOAT:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED64:\n\t\tcase CDF_UNSIGNED64:\n\t\tcase CDF_DOUBLE:\n\t\tcase CDF_FILETIME:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\tif (nelements > 1) {\n\t\t\t\tsize_t nelem = inp - *info;\n\t\t\t\tinp = cdf_grow_info(info, maxcount, nelements);\n\t\t\t\tif (inp == NULL)\n\t\t\t\t\tgoto out;\n\t\t\t\tinp += nelem;\n\t\t\t}\n\t\t\tfor (j = 0; j < nelements && i < sh.sh_properties;\n\t\t\t j++, i++)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\n\t\t\t\tif (o4 + sizeof(uint32_t) > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tl = CDF_GETUINT32(q, slen);\n\t\t\t\to4 += sizeof(uint32_t);\n\t\t\t\tif (o4 + l > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tinp[i].pi_str.s_len = l;\n\t\t\t\tinp[i].pi_str.s_buf = CAST(const char *,\n\t\t\t\t CAST(const void *, &q[o4]));\n\n\t\t\t\tDPRINTF((\"o=%\" SIZE_T_FORMAT \"u l=%d(%\"\n\t\t\t\t SIZE_T_FORMAT \"u), t=%\" SIZE_T_FORMAT\n\t\t\t\t \"u s=%s\\n\", o4, l, CDF_ROUND(l, sizeof(l)),\n\t\t\t\t left, inp[i].pi_str.s_buf));\n\n\t\t\t\tif (l & 1)\n\t\t\t\t\tl++;\n\n\t\t\t\tslen += l >> 1;\n\t\t\t\to4 = slen * sizeof(uint32_t);\n\t\t\t}\n\t\t\ti--;\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tdefault:\n\t\tunknown:\n\t\t\tmemset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));\n\t\t\tDPRINTF((\"Don't know how to deal with %#x\\n\",\n\t\t\t inp[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\nout:\n\tfree(*info);\n\t*info = NULL;\n\t*count = 0;\n\t*maxcount = 0;\n\terrno = EFTYPE;\n\treturn -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cdf_read_property_info", "_file_name": "src/cdf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def set_state(chat_id, value):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"update users set state = ? where chat_id = ?\", (str(value), str(chat_id)))\n settings.commit()\n settings.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set_state", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def login(self, username, password):\n select_query = \"\"\"\n SELECT client_id, username, balance, message\n FROM Clients\n WHERE username = ? AND password = ?\n LIMIT 1\n \"\"\"\n\n cursor = self.__conn.cursor()\n\n cursor.execute(select_query, (username, password))\n user = cursor.fetchone()\n\n if(user):\n return Client(user[0], user[1], user[2], user[3])\n else:\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "login", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void pb_controller::play_file(const std::string& file) {\n\tstd::string cmdline;\n\tstd::string player = cfg->get_configvalue(\"player\");\n\tif (player == \"\")\n\t\treturn;\n\tcmdline.append(player);\n\tcmdline.append(\" \\\"\");\n\tcmdline.append(utils::replace_all(file,\"\\\"\", \"\\\\\\\"\"));\n\tcmdline.append(\"\\\"\");\n\tstfl::reset();\n\tutils::run_interactively(cmdline, \"pb_controller::play_file\");\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[187, 290]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[187, 290]]}, "_func_name": "podbeuter::pb_controller::play_file", "_file_name": "src/pb_controller.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def _delete_vdisk(self, name, force):\n \"\"\"Deletes existing vdisks.\n\n It is very important to properly take care of mappings before deleting\n the disk:\n 1. If no mappings, then it was a vdisk, and can be deleted\n 2. If it is the source of a flashcopy mapping and copy_rate is 0, then\n it is a vdisk that has a snapshot. If the force flag is set,\n delete the mapping and the vdisk, otherwise set the mapping to\n copy and wait (this will allow users to delete vdisks that have\n snapshots if/when the upper layers allow it).\n 3. If it is the target of a mapping and copy_rate is 0, it is a\n snapshot, and we should properly stop the mapping and delete.\n 4. If it is the source/target of a mapping and copy_rate is not 0, it\n is a clone or vdisk created from a snapshot. We wait for the copy\n to complete (the mapping will be autodeleted) and then delete the\n vdisk.\n\n \"\"\"\n\n LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name)\n\n # Try to delete volume only if found on the storage\n vdisk_defined = self._is_vdisk_defined(name)\n if not vdisk_defined:\n LOG.info(_('warning: Tried to delete vdisk %s but it does not '\n 'exist.') % name)\n return\n\n self._ensure_vdisk_no_fc_mappings(name)\n\n forceflag = '-force' if force else ''\n cmd_params = {'frc': forceflag, 'name': name}\n ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmvdisk\n self._assert_ssh_return(len(out.strip()) == 0,\n ('_delete_vdisk %(name)s')\n % {'name': name},\n ssh_cmd, out, err)\n LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1403, 1569]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1403, 1569]]}, "_func_name": "_delete_vdisk", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):\n out = self._cli_run('showhost -d', None)\n # wwns_iqn may be a list of strings or a single\n # string. So, if necessary, create a list to loop.\n if not isinstance(wwns_iqn, list):\n wwn_iqn_list = [wwns_iqn]\n else:\n wwn_iqn_list = wwns_iqn\n\n for wwn_iqn in wwn_iqn_list:\n for showhost in out:\n if (wwn_iqn.upper() in showhost.upper()):\n return showhost.split(',')[1]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[57, 106]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[57, 106]]}, "_func_name": "_get_3par_hostname_from_wwn_iqn", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void Logger::addMessage(const QString &message, const Log::MsgType &type)\n{\n QWriteLocker locker(&lock);\n\n Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };\n m_messages.push_back(temp);\n\n if (m_messages.size() >= MAX_LOG_MESSAGES)\n m_messages.pop_front();\n\n emit newLogMessage(temp);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Logger::addMessage", "_file_name": "src/base/logger.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)\n{\n\tioapic->rtc_status.pending_eoi = 0;\n\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rtc_irq_eoi_tracking_reset", "_file_name": "arch/x86/kvm/ioapic.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int pure_strcmp(const char * const s1, const char * const s2)\n{\n return pure_memcmp(s1, s2, strlen(s1) + 1U);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[64, 113]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[64, 113]]}, "_func_name": "pure_strcmp", "_file_name": "src/utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_current_state(chat_id):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+\"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = ?\", (str(chat_id),))\n name = conn.fetchone()\n if name != None:\n return name[4]\n else:\n return False\n settings.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_current_state", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/h2h\")\ndef h2h():\n if db == None:\n init()\n\n player1 = request.args.get('tag1', default=\"christmasmike\")\n player2 = request.args.get('tag2', default=\"christmasmike\")\n sql = \"SELECT * FROM matches WHERE (player1 = '\"+str(player1)+\"' OR \"\\\n +\"player2 = '\"+str(player1)+\"') AND (player1 = '\"+str(player2)+\"' OR \"\\\n +\"player2 = '\"+str(player2)+\"') ORDER BY date DESC;\"\n result = db.exec(sql)\n return json.dumps(result)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[199, 423]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[199, 423]]}, "_func_name": "h2h", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/delete/', methods=['GET', 'POST'])\ndef delete(msg_id):\n if request.method == 'GET':\n cursor.execute(\"DELETE FROM message where msg_id = %s;\", (msg_id,))\n conn.commit()\n flash('Delete Success!')\n return redirect(url_for('show_entries'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_translationname(self, trname):\n \"\"\"Add new translation by item name for an item.\"\"\"\n if self.connection:\n for item in self.find_item_name([trname[0], '0']):\n self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (\"%s\", \"%s\", \"%s\")' % (item[0], trname[1], trname[2]))\n self.connection.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[194, 359]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[194, 359]]}, "_func_name": "add_translationname", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_lines(command: str) -> List[str]:\n \"\"\"\n Run a command and return lines of output\n\n :param str command: the command to run\n :returns: list of whitespace-stripped lines output by command\n \"\"\"\n stdout = get_output(command)\n return [line.strip().decode() for line in stdout.splitlines()]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[246, 312]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[246, 312]]}, "_func_name": "get_lines", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "IRC_PROTOCOL_CALLBACK(352)\n{\n char *pos_attr, *pos_hopcount, *pos_realname, *str_host;\n int arg_start, length;\n struct t_irc_channel *ptr_channel;\n struct t_irc_nick *ptr_nick;\n\n IRC_PROTOCOL_MIN_ARGS(5);\n\n /* silently ignore malformed 352 message (missing infos) */\n if (argc < 8)\n return WEECHAT_RC_OK;\n\n pos_attr = NULL;\n pos_hopcount = NULL;\n pos_realname = NULL;\n\n if (argc > 8)\n {\n arg_start = ((argc > 9) && (strcmp (argv[8], \"*\") == 0)) ? 9 : 8;\n if (argv[arg_start][0] == ':')\n {\n pos_attr = NULL;\n pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;\n pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;\n }\n else\n {\n pos_attr = argv[arg_start];\n pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;\n pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;\n }\n }\n\n ptr_channel = irc_channel_search (server, argv[3]);\n ptr_nick = (ptr_channel) ?\n irc_nick_search (server, ptr_channel, argv[7]) : NULL;\n\n /* update host in nick */\n if (ptr_nick)\n {\n length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;\n str_host = malloc (length);\n if (str_host)\n {\n snprintf (str_host, length, \"%s@%s\", argv[4], argv[5]);\n irc_nick_set_host (ptr_nick, str_host);\n free (str_host);\n }\n }\n\n /* update away flag in nick */\n if (ptr_channel && ptr_nick && pos_attr)\n {\n irc_nick_set_away (server, ptr_channel, ptr_nick,\n (pos_attr[0] == 'G') ? 1 : 0);\n }\n\n /* update realname in nick */\n if (ptr_channel && ptr_nick && pos_realname)\n {\n if (ptr_nick->realname)\n free (ptr_nick->realname);\n if (pos_realname &&\n weechat_hashtable_has_key (server->cap_list, \"extended-join\"))\n {\n ptr_nick->realname = strdup (pos_realname);\n }\n else\n {\n ptr_nick->realname = NULL;\n }\n }\n\n /* display output of who (manual who from user) */\n if (!ptr_channel || (ptr_channel->checking_whox <= 0))\n {\n weechat_printf_date_tags (\n irc_msgbuffer_get_target_buffer (\n server, NULL, command, \"who\", NULL),\n date,\n irc_protocol_tags (command, \"irc_numeric\", NULL, NULL),\n \"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)\",\n weechat_prefix (\"network\"),\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_CHAT_CHANNEL,\n argv[3],\n IRC_COLOR_CHAT_DELIMITERS,\n irc_nick_color_for_msg (server, 1, NULL, argv[7]),\n argv[7],\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_CHAT_HOST,\n argv[4],\n argv[5],\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_RESET,\n (pos_attr) ? pos_attr : \"\",\n (pos_attr) ? \" \" : \"\",\n (pos_hopcount) ? pos_hopcount : \"\",\n (pos_hopcount) ? \" \" : \"\",\n (pos_realname) ? pos_realname : \"\");\n }\n\n return WEECHAT_RC_OK;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "IRC_PROTOCOL_CALLBACK", "_file_name": "src/plugins/irc/irc-protocol.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connects()\n try:\n # The following introduces a deliberate security flaw. See section on SQL injecton below\n query = \"INSERT INTO crimes (description) VALUES ('{}');\".format(\n data)\n with connection.cursor() as cursor:\n cursor.execute(query)\n connection.commit()\n finally:\n connection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[182, 282]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[182, 282]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_mod_taken_together_with(code):\n '''\n Retrieves the list of modules taken together with the specified\n module code in the same semester.\n\n Returns a table of lists (up to 10 top results). Each list contains\n (specified code, module code of mod taken together, aySem, number of students)\n\n e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students\n taking CS1010 and CS1231 together in AY 16/17 Sem 1.\n '''\n NUM_TOP_RESULTS_TO_RETURN = 10\n\n sql_command = \"SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) \" + \\\n \"FROM studentPlans sp1, studentPlans sp2 \" + \\\n \"WHERE sp1.moduleCode = %s AND \" + \\\n \"sp2.moduleCode <> sp1.moduleCode AND \" + \\\n \"sp1.studentId = sp2.studentId AND \" + \\\n \"sp1.acadYearAndSem = sp2.acadYearAndSem \" + \\\n \"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem \" + \\\n \"ORDER BY COUNT(*) DESC\"\n\n DB_CURSOR.execute(sql_command, (code,))\n\n return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_mod_taken_together_with", "_file_name": "components/model.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {\n#if defined(OS_WIN)\n const auto converted = base::WideToUTF8(arg);\n const char* a = converted.c_str();\n#else\n const char* a = arg;\n#endif\n\n static const char* prefixes[] = {\"--\", \"-\", \"/\"};\n\n int prefix_length = 0;\n for (auto& prefix : prefixes) {\n if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) {\n prefix_length = strlen(prefix);\n break;\n }\n }\n\n if (prefix_length > 0) {\n a += prefix_length;\n std::string switch_name =\n base::ToLowerASCII(base::StringPiece(a, strcspn(a, \"=\")));\n auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist),\n switch_name);\n if (iter != std::end(kBlacklist) && switch_name == *iter) {\n return true;\n }\n }\n\n return false;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "IsBlacklistedArg", "_file_name": "atom/app/command_line_args.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def update_theory_base(tag, link):\n theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\theory.db\")\n conn = theory.cursor()\n conn.execute(\"insert into \" + str(tag) + \" values (?)\", (str(link), ))\n theory.commit()\n theory.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[151, 226]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[151, 226]]}, "_func_name": "update_theory_base", "_file_name": "bases/update.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n{\n MpegEncContext *s = &ctx->m;\n\n if (get_bits_left(gb) <= 32)\n return 0;\n\n s->partitioned_frame = 0;\n s->decode_mb = mpeg4_decode_studio_mb;\n\n decode_smpte_tc(ctx, gb);\n\n skip_bits(gb, 10); /* temporal_reference */\n skip_bits(gb, 2); /* vop_structure */\n s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */\n if (get_bits1(gb)) { /* vop_coded */\n skip_bits1(gb); /* top_field_first */\n skip_bits1(gb); /* repeat_first_field */\n s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */\n }\n\n if (s->pict_type == AV_PICTURE_TYPE_I) {\n if (get_bits1(gb))\n reset_studio_dc_predictors(s);\n }\n\n if (ctx->shape != BIN_ONLY_SHAPE) {\n s->alternate_scan = get_bits1(gb);\n s->frame_pred_frame_dct = get_bits1(gb);\n s->dct_precision = get_bits(gb, 2);\n s->intra_dc_precision = get_bits(gb, 2);\n s->q_scale_type = get_bits1(gb);\n }\n\n if (s->alternate_scan) {\n ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n } else {\n ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n }\n\n mpeg4_load_default_matrices(s);\n\n next_start_code_studio(gb);\n extension_and_user_data(s, gb, 4);\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[195, 238]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[195, 238]]}, "_func_name": "decode_studio_vop_header", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_first_ranked_month(db, scene, player):\n sql = \"select date from ranks where scene='{scene}' and player='{player}' order by date limit 1;\"\n args = {'scene': scene, 'player': player}\n res = db.exec(sql, args)\n date = res[0][0]\n return date", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_first_ranked_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tif (Stream_GetRemainingLength(licenseStream) < 8)\n\t\tgoto out_free_stream;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tif (Stream_GetRemainingLength(licenseStream) < 4)\n\t\tgoto out_free_stream;\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "license_read_new_or_upgrade_license_packet", "_file_name": "libfreerdp/core/license.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def delete(self, user_id):\n \"\"\" Deletes user with the corresponding user_id \"\"\"\n return database_utilities.execute_query(f\"\"\"delete from users where user_id = '{user_id}'\"\"\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[109, 210]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[109, 210]]}, "_func_name": "delete", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int string_scan_range(RList *list, RBinFile *bf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (from >= to) {\n\t\teprintf (\"Invalid range to find strings 0x%llx .. 0x%llx\\n\", from, to);\n\t\treturn -1;\n\t}\n\tut8 *buf = calloc (to - from, 1);\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\tr_buf_read_at (bf->buf, from, buf, to - from);\n\t// may oobread\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle - from, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc - from;\n\t\t\tif ((to - needle) > 5) {\n\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r) && r != '\\\\') {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\033\\\\\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 93) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \\\\\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t// reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tRBinString *bs = R_NEW0 (RBinString);\n\t\t\tif (!bs) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->type = str_type;\n\t\t\tbs->length = runes;\n\t\t\tbs->size = needle - str_start;\n\t\t\tbs->ordinal = count++;\n\t\t\t// TODO: move into adjust_offset\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\tif (str_start -from> 1) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 2 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tif (str_start -from> 3) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 4 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->paddr = bs->vaddr = str_start;\n\t\t\tbs->string = r_str_ndup ((const char *)tmp, i);\n\t\t\tif (list) {\n\t\t\t\tr_list_append (list, bs);\n\t\t\t} else {\n\t\t\t\tprint_string (bs, bf);\n\t\t\t\tr_bin_string_free (bs);\n\t\t\t}\n\t\t}\n\t}\n\tfree (buf);\n\treturn count;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[418, 453], [490, 538]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[418, 453], [490, 538]]}, "_func_name": "string_scan_range", "_file_name": "libr/bin/file.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n '(\\'OpenStack\\',) '\n 'fakehost iqn.1993-08.org.debian:01:222')\n in_use_ret = pack('\\r\\nalready used by host fakehost.foo ')\n _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])\n\n show_3par_cmd = 'showhost -verbose fakehost.foo'\n _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[639, 822]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[639, 822]]}, "_func_name": "test_create_invalid_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def estimate_size(task_id, taken_dirs, taken_files):\n report = AnalysisController.get_report(task_id)\n report = report[\"analysis\"]\n path = report[\"info\"][\"analysis_path\"]\n\n size_total = 0\n\n for directory in taken_dirs:\n destination = \"%s/%s\" % (path, directory)\n if os.path.isdir(destination):\n size_total += get_directory_size(destination)\n\n for filename in taken_files:\n destination = \"%s/%s\" % (path, filename)\n if os.path.isfile(destination):\n size_total += os.path.getsize(destination)\n\n # estimate file size after zipping; 60% compression rate typically\n size_estimated = size_total / 6.5\n\n return {\n \"size\": int(size_estimated),\n \"size_human\": filesizeformat(size_estimated)\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[276, 330], [473, 526]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[276, 330], [473, 526]]}, "_func_name": "estimate_size", "_file_name": "cuckoo/web/controllers/analysis/export/export.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_inverters(self):\n interfaces = self.config.get_connection_interfaces()\n for source in interfaces:\n if source[\"type\"] == \"inverter\":\n\n query = '''\n INSERT OR IGNORE INTO Inverters (\n Serial,\n EToday,\n ETotal\n ) VALUES (\n ?,\n ?,\n ?\n );\n '''\n self.c.execute(query, (source[\"serial_id\"], 0, source[\"prev_etotal\"]))\n\n query = '''\n UPDATE Inverters\n SET \n Name=?, \n Type=?, \n SW_Version=?, \n Status=?,\n TimeStamp=?\n WHERE Serial=?;\n '''\n self.c.execute(query, (source[\"name\"], source[\"inverter_type\"], \"s0-bridge v0\", \"OK\", int(datetime.now().timestamp()), source[\"serial_id\"] ))\n\n self.db.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_inverters", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _find_host_exhaustive(self, connector, hosts):\n for host in hosts:\n ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()),\n '_find_host_exhaustive',\n ssh_cmd, out, err)\n for attr_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attr_name, foo, attr_val = attr_line.partition('!')\n if (attr_name == 'iscsi_name' and\n 'initiator' in connector and\n attr_val == connector['initiator']):\n return host\n elif (attr_name == 'WWPN' and\n 'wwpns' in connector and\n attr_val.lower() in\n map(str.lower, map(str, connector['wwpns']))):\n return host\n return None", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_find_host_exhaustive", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_article_action(request: HttpRequest, default_foreward_url: str):\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n else:\n forward_url = \"/admin\"\n if \"rid\" not in request.GET:\n return HttpResponseRedirect(\"/admin?error=Missing%20reservation%20id%20in%20request\")\n u: Profile = get_current_user(request)\n current_reservation = GroupReservation.objects.get(id=str(request.GET[\"rid\"]))\n if current_reservation.createdByUser != u and u.rights < 2:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n if current_reservation.submitted == True:\n return HttpResponseRedirect(\"/admin?error=Already%20submitted\")\n # Test for multiple or single article\n if \"article_id\" in request.POST:\n # Actual adding of article\n aid: int = int(request.GET.get(\"article_id\"))\n quantity: int = int(request.POST[\"quantity\"])\n notes: str = escape(request.POST[\"notes\"])\n ar = ArticleRequested()\n ar.AID = Article.objects.get(id=aid)\n ar.RID = current_reservation\n if \"srid\" in request.GET:\n ar.SRID = SubReservation.objects.get(id=int(request.GET[\"srid\"]))\n ar.amount = quantity\n ar.notes = notes\n ar.save()\n # Actual adding of multiple articles\n else:\n if \"group_id\" not in request.GET:\n return HttpResponseRedirect(\"/admin?error=missing%20group%20id\")\n g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET[\"group_id\"]))\n for art in Article.objects.all().filter(group=g):\n if str(\"quantity_\" + str(art.id)) not in request.POST or str(\"notes_\" + str(art.id)) not in request.POST:\n return HttpResponseRedirect(\"/admin?error=Missing%20article%20data%20in%20request\")\n amount = int(request.POST[\"quantity_\" + str(art.id)])\n if amount > 0:\n ar = ArticleRequested()\n ar.AID = art\n ar.RID = current_reservation\n ar.amount = amount\n if \"srid\" in request.GET:\n ar.SRID = SubReservation.objects.get(id=int(request.GET[\"srid\"]))\n ar.notes = escape(str(request.POST[str(\"notes_\" + str(art.id))]))\n ar.save()\n if \"srid\" in request.GET:\n response = HttpResponseRedirect(forward_url + \"?rid=\" + str(current_reservation.id) + \"&srid=\" + request.GET[\"srid\"])\n else:\n response = HttpResponseRedirect(forward_url + \"?rid=\" + str(current_reservation.id))\n return response", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_article_action", "_file_name": "c3shop/frontpage/management/reservation_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n\tstruct user_namespace *user_ns)\n{\n\tmm->mmap = NULL;\n\tmm->mm_rb = RB_ROOT;\n\tmm->vmacache_seqnum = 0;\n\tatomic_set(&mm->mm_users, 1);\n\tatomic_set(&mm->mm_count, 1);\n\tinit_rwsem(&mm->mmap_sem);\n\tINIT_LIST_HEAD(&mm->mmlist);\n\tmm->core_state = NULL;\n\tatomic_long_set(&mm->nr_ptes, 0);\n\tmm_nr_pmds_init(mm);\n\tmm->map_count = 0;\n\tmm->locked_vm = 0;\n\tmm->pinned_vm = 0;\n\tmemset(&mm->rss_stat, 0, sizeof(mm->rss_stat));\n\tspin_lock_init(&mm->page_table_lock);\n\tmm_init_cpumask(mm);\n\tmm_init_aio(mm);\n\tmm_init_owner(mm, p);\n\tmmu_notifier_mm_init(mm);\n\tinit_tlb_flush_pending(mm);\n#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS\n\tmm->pmd_huge_pte = NULL;\n#endif\n\n\tif (current->mm) {\n\t\tmm->flags = current->mm->flags & MMF_INIT_MASK;\n\t\tmm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;\n\t} else {\n\t\tmm->flags = default_dump_filter;\n\t\tmm->def_flags = 0;\n\t}\n\n\tif (mm_alloc_pgd(mm))\n\t\tgoto fail_nopgd;\n\n\tif (init_new_context(p, mm))\n\t\tgoto fail_nocontext;\n\n\tmm->user_ns = get_user_ns(user_ns);\n\treturn mm;\n\nfail_nocontext:\n\tmm_free_pgd(mm);\nfail_nopgd:\n\tfree_mm(mm);\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[591, 618]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[591, 618]]}, "_func_name": "mm_init", "_file_name": "kernel/fork.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def isValidAdmToken(adm_token):\n conn, c = connectDB()\n req = \"SELECT * from {} where adm_token='{}'\".format(CFG(\"admintoken_table_name\"), adm_token)\n answer = bool(queryOne(c, req))\n closeDB(conn)\n return answer", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[58, 157]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[58, 157]]}, "_func_name": "isValidAdmToken", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen >= sizeof(*union_desc)) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bLength > buflen) {\n\t\t\tdev_err(&intf->dev, \"Too large descriptor\\n\");\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\n\t\t\tif (union_desc->bLength >= sizeof(*union_desc))\n\t\t\t\treturn union_desc;\n\n\t\t\tdev_err(&intf->dev,\n\t\t\t\t\"Union descriptor to short (%d vs %zd\\n)\",\n\t\t\t\tunion_desc->bLength, sizeof(*union_desc));\n\t\t\treturn NULL;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ims_pcu_get_cdc_union_desc", "_file_name": "drivers/input/misc/ims-pcu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _set_connections(self):\n \"\"\"Set the number of concurrent connections.\n\n The 3PAR WS API server has a limit of concurrent connections.\n This is setting the number to the highest allowed, 15 connections.\n \"\"\"\n self._cli_run(['setwsapi', '-sru', 'high'])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_set_connections", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/get_all_referrers')\ndef get_all_referrers():\n account_id = request.args.get('account_id')\n\n if not isObject(account_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_account_names\",[[\"' + account_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n\n account_id = j_l[\"result\"][0][\"id\"]\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"select * from referrers where referrer=%s\"\n cur.execute(query, (account_id,))\n results = cur.fetchall()\n\n return jsonify(results)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_all_referrers", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PHP_FUNCTION(unserialize)\n{\n\tchar *buf = NULL;\n\tsize_t buf_len;\n\tconst unsigned char *p;\n\tphp_unserialize_data_t var_hash;\n\tzval *options = NULL, *classes = NULL;\n\tzval *retval;\n\tHashTable *class_hash = NULL;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|a\", &buf, &buf_len, &options) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (buf_len == 0) {\n\t\tRETURN_FALSE;\n\t}\n\n\tp = (const unsigned char*) buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\tif(options != NULL) {\n\t\tclasses = zend_hash_str_find(Z_ARRVAL_P(options), \"allowed_classes\", sizeof(\"allowed_classes\")-1);\n\t\tif(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {\n\t\t\tALLOC_HASHTABLE(class_hash);\n\t\t\tzend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);\n\t\t}\n\t\tif(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {\n\t\t\tzval *entry;\n\t\t\tzend_string *lcname;\n\n\t\t\tZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {\n\t\t\t\tconvert_to_string_ex(entry);\n\t\t\t\tlcname = zend_string_tolower(Z_STR_P(entry));\n\t\t\t\tzend_hash_add_empty_element(class_hash, lcname);\n\t\t zend_string_release(lcname);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t}\n\t}\n\n\tretval = var_tmp_var(&var_hash);\n\tif (!php_var_unserialize_ex(retval, &p, p + buf_len, &var_hash, class_hash)) {\n\t\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\t\tif (class_hash) {\n\t\t\tzend_hash_destroy(class_hash);\n\t\t\tFREE_HASHTABLE(class_hash);\n\t\t}\n\t\tif (!EG(exception)) {\n\t\t\tphp_error_docref(NULL, E_NOTICE, \"Error at offset \" ZEND_LONG_FMT \" of %zd bytes\",\n\t\t\t\t(zend_long)((char*)p - buf), buf_len);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n\n\tZVAL_COPY(return_value, retval);\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (class_hash) {\n\t\tzend_hash_destroy(class_hash);\n\t\tFREE_HASHTABLE(class_hash);\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/standard/var.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,\n void *dummy,\n const char *arg)\n{\n const char *endp = ap_strrchr_c(arg, '>');\n const char *limited_methods;\n void *tog = cmd->cmd->cmd_data;\n apr_int64_t limited = 0;\n apr_int64_t old_limited = cmd->limited;\n const char *errmsg;\n\n if (endp == NULL) {\n return unclosed_directive(cmd);\n }\n\n limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg);\n\n if (!limited_methods[0]) {\n return missing_container_arg(cmd);\n }\n\n while (limited_methods[0]) {\n char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);\n int methnum;\n\n /* check for builtin or module registered method number */\n methnum = ap_method_number_of(method);\n\n if (methnum == M_TRACE && !tog) {\n return \"TRACE cannot be controlled by , see TraceEnable\";\n }\n else if (methnum == M_INVALID) {\n /* method has not been registered yet, but resource restriction\n * is always checked before method handling, so register it.\n */\n if (cmd->pool == cmd->temp_pool) {\n /* In .htaccess, we can't globally register new methods. */\n return apr_psprintf(cmd->pool, \"Could not register method '%s' \"\n \"for %s from .htaccess configuration\",\n method, cmd->cmd->name);\n }\n methnum = ap_method_register(cmd->pool,\n apr_pstrdup(cmd->pool, method));\n }\n\n limited |= (AP_METHOD_BIT << methnum);\n }\n\n /* Killing two features with one function,\n * if (tog == NULL) , else \n */\n limited = tog ? ~limited : limited;\n\n if (!(old_limited & limited)) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive excludes all methods\", NULL);\n }\n else if ((old_limited & limited) == old_limited) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive specifies methods already excluded\",\n NULL);\n }\n\n cmd->limited &= limited;\n\n errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);\n\n cmd->limited = old_limited;\n\n return errmsg;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ap_limit_section", "_file_name": "server/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int __init fm10k_init_module(void)\n{\n\tpr_info(\"%s - version %s\\n\", fm10k_driver_string, fm10k_driver_version);\n\tpr_info(\"%s\\n\", fm10k_copyright);\n\n\t/* create driver workqueue */\n\tfm10k_workqueue = alloc_workqueue(\"%s\", WQ_MEM_RECLAIM, 0,\n\t\t\t\t\t fm10k_driver_name);\n\tif (!fm10k_workqueue)\n\t\treturn -ENOMEM;\n\n\tfm10k_dbg_init();\n\n\treturn fm10k_register_pci_driver();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fm10k_init_module", "_file_name": "drivers/net/ethernet/intel/fm10k/fm10k_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def start():\n print(\"[*] Starting backdoor process\")\n print(\"[*] Decompressing target to tmp directory...\")\n #subprocess.call(\"jar -x %s\" % target, shell=True)\n with zipfile.ZipFile(target, 'r') as zip:\n zip.extractall(\"tmp\")\n print(\"[*] Target dumped to tmp directory\")\n\n print(\"[*] Modifying manifest file...\")\n oldmain=\"\"\n man = open(\"tmp/META-INF/MANIFEST.MF\",\"r\").read()\n with open(\"tmp/META-INF/MANIFEST.MF\",\"w\") as f:\n for l in man.split(\"\\n\"):\n if \"Main-Class\" in l:\n oldmain=l[12:]\n f.write(\"Main-Class: %s\\n\" % \"Backdoor\")\n else:\n f.write(\"%s\\n\" % l)\n print(\"[*] Manifest file modified\")\n \n print(\"[*] Modifying provided backdoor...\")\n inmain=False\n level=0\n bd=open(backdoor, \"r\").read()\n with open(\"tmp/%s\" % backdoor,'w') as f:\n for l in bd.split(\"\\n\"):\n if \"main(\" in l:\n inmain=True\n f.write(l)\n elif \"}\" in l and level<2 and inmain:\n f.write(\"%s.main(args);}\" % oldmain)\n inmain=False\n elif \"}\" in l and level>1 and inmain:\n level-=1\n f.write(l)\n elif \"{\" in l and inmain:\n level+=1\n f.write(l)\n else:\n f.write(l)\n print(\"[*] Provided backdoor successfully modified\")\n\n print(\"[*] Compiling modified backdoor...\")\n #if subprocess.call(\"javac -cp tmp/ tmp/%s\" % backdoor, shell=True) != 0:\n if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0:\n print(\"[!] Error compiling %s\" % backdoor)\n print(\"[*] Compiled modified backdoor\")\n \n if(len(oldmain)<1):\n print(\"[!] Main-Class manifest attribute not found\")\n else:\n print(\"[*] Repackaging target jar file...\")\n createZip(\"tmp\",outfile)\n print(\"[*] Target jar successfully repackaged\")\n shutil.rmtree('tmp/')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "start", "_file_name": "ajar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_active_nsp(self, hostname):\n \"\"\"Return the active nsp, if one exists, for the given host.\"\"\"\n result = self.common._cli_run('showvlun -a -host %s' % hostname, None)\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 4:\n return info[4]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[113, 192]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[113, 192]]}, "_func_name": "_get_active_nsp", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, path):\n return static_file(path, self.get_base_path())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[25, 79]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[25, 79]]}, "_func_name": "get", "_file_name": "seagull/routes/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)\n{\n int i, j, len;\n UChar *p;\n\n for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {\n len = enclen(enc, p);\n if (i + len > OPT_EXACT_MAXLEN) break;\n for (j = 0; j < len && p < end; j++)\n to->s[i++] = *p++;\n }\n\n to->len = i;\n\n if (p >= end)\n to->reach_end = 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[195, 238]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[195, 238]]}, "_func_name": "concat_opt_exact_str", "_file_name": "src/regcomp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tstruct ahash_request *req = &ctx->req;\n\tchar state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];\n\tstruct sock *sk2;\n\tstruct alg_sock *ask2;\n\tstruct hash_ctx *ctx2;\n\tbool more;\n\tint err;\n\n\tlock_sock(sk);\n\tmore = ctx->more;\n\terr = more ? crypto_ahash_export(req, state) : 0;\n\trelease_sock(sk);\n\n\tif (err)\n\t\treturn err;\n\n\terr = af_alg_accept(ask->parent, newsock);\n\tif (err)\n\t\treturn err;\n\n\tsk2 = newsock->sk;\n\task2 = alg_sk(sk2);\n\tctx2 = ask2->private;\n\tctx2->more = more;\n\n\tif (!more)\n\t\treturn err;\n\n\terr = crypto_ahash_import(&ctx2->req, state);\n\tif (err) {\n\t\tsock_orphan(sk2);\n\t\tsock_put(sk2);\n\t}\n\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "hash_accept", "_file_name": "crypto/algif_hash.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)\n{\n\tint r;\n\t/* Assume we're using HV mode when the HV module is loaded */\n\tint hv_enabled = kvmppc_hv_ops ? 1 : 0;\n\n\tif (kvm) {\n\t\t/*\n\t\t * Hooray - we know which VM type we're running on. Depend on\n\t\t * that rather than the guess above.\n\t\t */\n\t\thv_enabled = is_kvmppc_hv_enabled(kvm);\n\t}\n\n\tswitch (ext) {\n#ifdef CONFIG_BOOKE\n\tcase KVM_CAP_PPC_BOOKE_SREGS:\n\tcase KVM_CAP_PPC_BOOKE_WATCHDOG:\n\tcase KVM_CAP_PPC_EPR:\n#else\n\tcase KVM_CAP_PPC_SEGSTATE:\n\tcase KVM_CAP_PPC_HIOR:\n\tcase KVM_CAP_PPC_PAPR:\n#endif\n\tcase KVM_CAP_PPC_UNSET_IRQ:\n\tcase KVM_CAP_PPC_IRQ_LEVEL:\n\tcase KVM_CAP_ENABLE_CAP:\n\tcase KVM_CAP_ENABLE_CAP_VM:\n\tcase KVM_CAP_ONE_REG:\n\tcase KVM_CAP_IOEVENTFD:\n\tcase KVM_CAP_DEVICE_CTRL:\n\tcase KVM_CAP_IMMEDIATE_EXIT:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_PPC_PAIRED_SINGLES:\n\tcase KVM_CAP_PPC_OSI:\n\tcase KVM_CAP_PPC_GET_PVINFO:\n#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)\n\tcase KVM_CAP_SW_TLB:\n#endif\n\t\t/* We support this only for PR */\n\t\tr = !hv_enabled;\n\t\tbreak;\n#ifdef CONFIG_KVM_MPIC\n\tcase KVM_CAP_IRQ_MPIC:\n\t\tr = 1;\n\t\tbreak;\n#endif\n\n#ifdef CONFIG_PPC_BOOK3S_64\n\tcase KVM_CAP_SPAPR_TCE:\n\tcase KVM_CAP_SPAPR_TCE_64:\n\t\t/* fallthrough */\n\tcase KVM_CAP_SPAPR_TCE_VFIO:\n\tcase KVM_CAP_PPC_RTAS:\n\tcase KVM_CAP_PPC_FIXUP_HCALL:\n\tcase KVM_CAP_PPC_ENABLE_HCALL:\n#ifdef CONFIG_KVM_XICS\n\tcase KVM_CAP_IRQ_XICS:\n#endif\n\t\tr = 1;\n\t\tbreak;\n\n\tcase KVM_CAP_PPC_ALLOC_HTAB:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif /* CONFIG_PPC_BOOK3S_64 */\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_SMT:\n\t\tr = 0;\n\t\tif (kvm) {\n\t\t\tif (kvm->arch.emul_smt_mode > 1)\n\t\t\t\tr = kvm->arch.emul_smt_mode;\n\t\t\telse\n\t\t\t\tr = kvm->arch.smt_mode;\n\t\t} else if (hv_enabled) {\n\t\t\tif (cpu_has_feature(CPU_FTR_ARCH_300))\n\t\t\t\tr = 1;\n\t\t\telse\n\t\t\t\tr = threads_per_subcore;\n\t\t}\n\t\tbreak;\n\tcase KVM_CAP_PPC_SMT_POSSIBLE:\n\t\tr = 1;\n\t\tif (hv_enabled) {\n\t\t\tif (!cpu_has_feature(CPU_FTR_ARCH_300))\n\t\t\t\tr = ((threads_per_subcore << 1) - 1);\n\t\t\telse\n\t\t\t\t/* P9 can emulate dbells, so allow any mode */\n\t\t\t\tr = 8 | 4 | 2 | 1;\n\t\t}\n\t\tbreak;\n\tcase KVM_CAP_PPC_RMA:\n\t\tr = 0;\n\t\tbreak;\n\tcase KVM_CAP_PPC_HWRNG:\n\t\tr = kvmppc_hwrng_present();\n\t\tbreak;\n\tcase KVM_CAP_PPC_MMU_RADIX:\n\t\tr = !!(hv_enabled && radix_enabled());\n\t\tbreak;\n\tcase KVM_CAP_PPC_MMU_HASH_V3:\n\t\tr = !!(hv_enabled && !radix_enabled() &&\n\t\t cpu_has_feature(CPU_FTR_ARCH_300));\n\t\tbreak;\n#endif\n\tcase KVM_CAP_SYNC_MMU:\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\t\tr = hv_enabled;\n#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)\n\t\tr = 1;\n#else\n\t\tr = 0;\n#endif\n\t\tbreak;\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_HTAB_FD:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif\n\tcase KVM_CAP_NR_VCPUS:\n\t\t/*\n\t\t * Recommending a number of CPUs is somewhat arbitrary; we\n\t\t * return the number of present CPUs for -HV (since a host\n\t\t * will have secondary threads \"offline\"), and for other KVM\n\t\t * implementations just count online CPUs.\n\t\t */\n\t\tif (hv_enabled)\n\t\t\tr = num_present_cpus();\n\t\telse\n\t\t\tr = num_online_cpus();\n\t\tbreak;\n\tcase KVM_CAP_NR_MEMSLOTS:\n\t\tr = KVM_USER_MEM_SLOTS;\n\t\tbreak;\n\tcase KVM_CAP_MAX_VCPUS:\n\t\tr = KVM_MAX_VCPUS;\n\t\tbreak;\n#ifdef CONFIG_PPC_BOOK3S_64\n\tcase KVM_CAP_PPC_GET_SMMU_INFO:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_SPAPR_MULTITCE:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_SPAPR_RESIZE_HPT:\n\t\t/* Disable this on POWER9 until code handles new HPTE format */\n\t\tr = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);\n\t\tbreak;\n#endif\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_FWNMI:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif\n\tcase KVM_CAP_PPC_HTM:\n\t\tr = cpu_has_feature(CPU_FTR_TM_COMP) &&\n\t\t is_kvmppc_hv_enabled(kvm);\n\t\tbreak;\n\tdefault:\n\t\tr = 0;\n\t\tbreak;\n\t}\n\treturn r;\n\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[3515, 3590]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3515, 3590]]}, "_func_name": "kvm_vm_ioctl_check_extension", "_file_name": "arch/powerpc/kvm/powerpc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_extra_args(self, args=None):\n \"\"\"Add more args depending on how known args are set.\"\"\"\n parsed = vars(self.parse_known_args(nohelp=True)[0])\n\n # find which image mode specified if any, and add additional arguments\n image_mode = parsed.get('image_mode', None)\n if image_mode is not None and image_mode != 'none':\n self.add_image_args(image_mode)\n\n # find which task specified if any, and add its specific arguments\n task = parsed.get('task', None)\n if task is not None:\n self.add_task_args(task)\n evaltask = parsed.get('evaltask', None)\n if evaltask is not None:\n self.add_task_args(evaltask)\n\n # find which model specified if any, and add its specific arguments\n model = parsed.get('model', None)\n if model is not None:\n self.add_model_subargs(model)\n\n # reset parser-level defaults over any model-level defaults\n try:\n self.set_defaults(**self._defaults)\n except AttributeError:\n raise RuntimeError('Please file an issue on github that argparse '\n 'got an attribute error when parsing.')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[106, 167]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[106, 167]]}, "_func_name": "add_extra_args", "_file_name": "parlai/core/params.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):\n \"\"\"\n This function is used to alter the reservation beeing build inside\n a cookie. This function automatically crafts the required response.\n \"\"\"\n js_string: str = \"\"\n r: GroupReservation = None\n u: Profile = get_current_user(request)\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if \"srid\" in request.GET:\n if not request.GET.get(\"rid\"):\n return HttpResponseRedirect(\"/admin?error=missing%20primary%20reservation%20id\")\n srid: int = int(request.GET[\"srid\"])\n sr: SubReservation = None\n if srid == 0:\n sr = SubReservation()\n else:\n sr = SubReservation.objects.get(id=srid)\n if request.POST.get(\"notes\"):\n sr.notes = request.POST[\"notes\"]\n else:\n sr.notes = \" \"\n sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n sr.save()\n print(request.POST)\n print(sr.notes)\n return HttpResponseRedirect(\"/admin/reservations/edit?rid=\" + str(int(request.GET[\"rid\"])) + \"&srid=\" + str(sr.id))\n if \"rid\" in request.GET:\n # update reservation\n r = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():\n r = GroupReservation()\n r.createdByUser = u\n r.ready = False\n r.open = True\n r.pickupDate = datetime.datetime.now()\n else:\n return HttpResponseRedirect(\"/admin?error=Too%20Many%20reservations\")\n if request.POST.get(\"notes\"):\n r.notes = request.POST[\"notes\"]\n if request.POST.get(\"contact\"):\n r.responsiblePerson = str(request.POST[\"contact\"])\n if (r.createdByUser == u or o.rights > 1) and not r.submitted:\n r.save()\n else:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n response: HttpResponseRedirect = HttpResponseRedirect(forward_url + \"?rid=\" + str(r.id))\n return response", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[869, 914], [1748, 1788], [1824, 1883]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[869, 914], [1748, 1788], [1824, 1883]]}, "_func_name": "manipulate_reservation_action", "_file_name": "c3shop/frontpage/management/reservation_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def test_skip_paths_issue_938(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'line_length = 88\\n'\n 'multi_line_output = 4\\n'\n 'lines_after_imports = 2\\n'\n 'skip_glob =\\n'\n ' migrations/**.py\\n')\n base_dir.join('dont_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n migrations_dir = base_dir.mkdir('migrations')\n migrations_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped' not in results.lower()\n\n os.chdir(str(base_dir))\n results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped 1' in results.lower()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1187, 1273], [1386, 1525]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1187, 1273], [1386, 1525]]}, "_func_name": "test_skip_paths_issue_938", "_file_name": "test_isort.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tid_to_tid_num(self, tid):\n ''' Returns tid_num, given tid. '''\n\n q = \"SELECT rowid FROM tids WHERE tid = '\" + tid + \"'\"\n self.query(q)\n return self.c.fetchone()[0]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[80, 143]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[80, 143]]}, "_func_name": "tid_to_tid_num", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_current_state(chat_id):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+\"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = '\" + str(chat_id) + \"'\")\n name = conn.fetchone()\n if name != None:\n return name[4]\n else:\n return False\n settings.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[159, 238]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[159, 238]]}, "_func_name": "get_current_state", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def handle(self, keepalive=True, initial_timeout=None):\n # we are requested to skip processing and keep the previous values\n if self.skip:\n return self.response.handle()\n\n # default to no keepalive in case something happens while even trying ensure we have a request\n self.keepalive = False\n\n self.headers = HTTPHeaders()\n\n # if initial_timeout is set, only wait that long for the initial request line\n if initial_timeout:\n self.connection.settimeout(initial_timeout)\n else:\n self.connection.settimeout(self.timeout)\n\n # get request line\n try:\n # ignore empty lines waiting on request\n request = '\\r\\n'\n while request == '\\r\\n':\n request = self.rfile.readline(max_line_size + 1).decode(http_encoding)\n # if read hits timeout or has some other error, ignore the request\n except Exception:\n return True\n\n # ignore empty requests\n if not request:\n return True\n\n # we have a request, go back to normal timeout\n if initial_timeout:\n self.connection.settimeout(self.timeout)\n\n # remove \\r\\n from the end\n self.request_line = request[:-2]\n\n # set some reasonable defaults in case the worst happens and we need to tell the client\n self.method = ''\n self.resource = '/'\n\n try:\n # HTTP Status 414\n if len(request) > max_line_size:\n raise HTTPError(414)\n\n # HTTP Status 400\n if request[-2:] != '\\r\\n':\n raise HTTPError(400)\n\n # try the request line and error out if can't parse it\n try:\n self.method, self.resource, self.request_http = self.request_line.split()\n # HTTP Status 400\n except ValueError:\n raise HTTPError(400)\n\n # HTTP Status 505\n if self.request_http != http_version:\n raise HTTPError(505)\n\n # read and parse request headers\n while True:\n line = self.rfile.readline(max_line_size + 1).decode(http_encoding)\n\n # hit end of headers\n if line == '\\r\\n':\n break\n\n self.headers.add(line)\n\n # if we are requested to close the connection after we finish, do so\n if self.headers.get('Connection') == 'close':\n self.keepalive = False\n # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed)\n else:\n self.keepalive = keepalive\n\n # find a matching regex to handle the request with\n for regex, handler in self.server.routes.items():\n match = regex.match(self.resource)\n if match:\n # create a dictionary of groups\n groups = match.groupdict()\n values = groups.values()\n\n for idx, group in enumerate(match.groups()):\n if group not in values:\n groups[idx] = group\n\n # create handler\n self.handler = handler(self, self.response, groups)\n break\n # HTTP Status 404\n # if loop is not broken (handler is not found), raise a 404\n else:\n raise HTTPError(404)\n # use DummyHandler so the error is raised again when ready for response\n except Exception as error:\n self.handler = DummyHandler(self, self.response, (), error)\n finally:\n # we finished listening and handling early errors and so let a response class now finish up the job of talking\n return self.response.handle()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1744, 1834]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1744, 1834]]}, "_func_name": "handle", "_file_name": "fooster/web/web.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @handler.unsupported_on_local_server\n @handler.get(handler.HTML)\n def get(self):\n \"\"\"Handle a get request.\"\"\"\n dest = self.request.get('dest')\n base_handler.check_redirect_url(dest)\n\n self.render(\n 'login.html', {\n 'apiKey': local_config.ProjectConfig().get('firebase.api_key'),\n 'authDomain': auth.auth_domain(),\n 'dest': dest,\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "src/appengine/handlers/login.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def download_check_files(self, filelist):\n # only admins and allowed users may download\n if not cherrypy.session['admin']:\n uo = self.useroptions.forUser(self.getUserId())\n if not uo.getOptionValue('media.may_download'):\n return 'not_permitted'\n # make sure nobody tries to escape from basedir\n for f in filelist:\n if '/../' in f:\n return 'invalid_file'\n # make sure all files are smaller than maximum download size\n size_limit = cherry.config['media.maximum_download_size']\n try:\n if self.model.file_size_within_limit(filelist, size_limit):\n return 'ok'\n else:\n return 'too_big'\n except OSError as e: # use OSError for python2 compatibility\n return str(e)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[383, 411]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[383, 411]]}, "_func_name": "download_check_files", "_file_name": "cherrymusicserver/httphandler.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_month_data_row(self, inverter_serial, ts, etoday, etotal):\n\n y = datetime.fromtimestamp(ts) - timedelta(days=1)\n y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp())\n\n query = '''\n INSERT INTO MonthData (\n TimeStamp,\n Serial,\n DayYield,\n TotalYield \n ) VALUES (\n %s,\n %s,\n %s,\n %s\n );\n ''' % (y_ts, inverter_serial, etoday, etotal)\n self.c.execute(query)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[434, 513], [528, 611]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[434, 513], [528, 611]]}, "_func_name": "add_month_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[438, 493]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[438, 493]]}, "_func_name": "FromkLinuxSockAddr", "_file_name": "asylo/platform/system_call/type_conversions/manual_types_functions.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n int row = m_listModel->rowCount();\n // Adding Peer to peer list\n m_listModel->insertRow(row);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n }\n else {\n m_missingFlags.insert(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n\n return m_listModel->item(row, PeerListDelegate::IP);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PeerListWidget::addPeer", "_file_name": "src/gui/properties/peerlistwidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def change_message(self, new_message, logged_user):\n update_sql = \"\"\"\n UPDATE Clients\n SET message = ?\n WHERE client_id = ?\n \"\"\"\n\n cursor = self.__conn.cursor()\n\n cursor.execute(update_sql, (new_message, logged_user.get_client_id()))\n self.__conn.commit()\n logged_user.set_message(new_message)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "change_message", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _modify_3par_iscsi_host(self, hostname, iscsi_iqn):\n # when using -add, you can not send the persona or domain options\n command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn]\n self.common._cli_run(command)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_modify_3par_iscsi_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def download_check_files(self, filelist):\n # only admins and allowed users may download\n if not cherrypy.session['admin']:\n uo = self.useroptions.forUser(self.getUserId())\n if not uo.getOptionValue('media.may_download'):\n return 'not_permitted'\n # make sure nobody tries to escape from basedir\n for f in filelist:\n # don't allow to traverse up in the file system\n if '/../' in f or f.startswith('../'):\n return 'invalid_file'\n # CVE-2015-8309: do not allow absolute file paths\n if os.path.isabs(f):\n return 'invalid_file'\n # make sure all files are smaller than maximum download size\n size_limit = cherry.config['media.maximum_download_size']\n try:\n if self.model.file_size_within_limit(filelist, size_limit):\n return 'ok'\n else:\n return 'too_big'\n except OSError as e: # use OSError for python2 compatibility\n return str(e)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "download_check_files", "_file_name": "cherrymusicserver/httphandler.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "openscript(\n char_u\t*name,\n int\t\tdirectly)\t/* when TRUE execute directly */\n{\n if (curscript + 1 == NSCRIPT)\n {\n\temsg(_(e_nesting));\n\treturn;\n }\n\n // Disallow sourcing a file in the sandbox, the commands would be executed\n // later, possibly outside of the sandbox.\n if (check_secure())\n\treturn;\n\n#ifdef FEAT_EVAL\n if (ignore_script)\n\t/* Not reading from script, also don't open one. Warning message? */\n\treturn;\n#endif\n\n if (scriptin[curscript] != NULL)\t/* already reading script */\n\t++curscript;\n\t\t\t\t/* use NameBuff for expanded name */\n expand_env(name, NameBuff, MAXPATHL);\n if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)\n {\n\tsemsg(_(e_notopen), name);\n\tif (curscript)\n\t --curscript;\n\treturn;\n }\n if (save_typebuf() == FAIL)\n\treturn;\n\n /*\n * Execute the commands from the file right now when using \":source!\"\n * after \":global\" or \":argdo\" or in a loop. Also when another command\n * follows. This means the display won't be updated. Don't do this\n * always, \"make test\" would fail.\n */\n if (directly)\n {\n\toparg_T\toa;\n\tint\toldcurscript;\n\tint\tsave_State = State;\n\tint\tsave_restart_edit = restart_edit;\n\tint\tsave_insertmode = p_im;\n\tint\tsave_finish_op = finish_op;\n\tint\tsave_msg_scroll = msg_scroll;\n\n\tState = NORMAL;\n\tmsg_scroll = FALSE;\t/* no msg scrolling in Normal mode */\n\trestart_edit = 0;\t/* don't go to Insert mode */\n\tp_im = FALSE;\t\t/* don't use 'insertmode' */\n\tclear_oparg(&oa);\n\tfinish_op = FALSE;\n\n\toldcurscript = curscript;\n\tdo\n\t{\n\t update_topline_cursor();\t// update cursor position and topline\n\t normal_cmd(&oa, FALSE);\t// execute one command\n\t vpeekc();\t\t\t// check for end of file\n\t}\n\twhile (scriptin[oldcurscript] != NULL);\n\n\tState = save_State;\n\tmsg_scroll = save_msg_scroll;\n\trestart_edit = save_restart_edit;\n\tp_im = save_insertmode;\n\tfinish_op = save_finish_op;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "openscript", "_file_name": "src/getchar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int run(const CommandLineOptions& options)\n{\n\tIR::Module irModule;\n\n\t// Load the module.\n\tif(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }\n\tif(options.onlyCheck) { return EXIT_SUCCESS; }\n\n\t// Compile the module.\n\tRuntime::Module* module = nullptr;\n\tif(!options.precompiled) { module = Runtime::compileModule(irModule); }\n\telse\n\t{\n\t\tconst UserSection* precompiledObjectSection = nullptr;\n\t\tfor(const UserSection& userSection : irModule.userSections)\n\t\t{\n\t\t\tif(userSection.name == \"wavm.precompiled_object\")\n\t\t\t{\n\t\t\t\tprecompiledObjectSection = &userSection;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(!precompiledObjectSection)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Input file did not contain 'wavm.precompiled_object' section\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmodule = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);\n\t\t}\n\t}\n\n\t// Link the module with the intrinsic modules.\n\tCompartment* compartment = Runtime::createCompartment();\n\tContext* context = Runtime::createContext(compartment);\n\tRootResolver rootResolver(compartment);\n\n\tEmscripten::Instance* emscriptenInstance = nullptr;\n\tif(options.enableEmscripten)\n\t{\n\t\temscriptenInstance = Emscripten::instantiate(compartment, irModule);\n\t\tif(emscriptenInstance)\n\t\t{\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"env\", emscriptenInstance->env);\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"asm2wasm\", emscriptenInstance->asm2wasm);\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"global\", emscriptenInstance->global);\n\t\t}\n\t}\n\n\tif(options.enableThreadTest)\n\t{\n\t\tModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);\n\t\trootResolver.moduleNameToInstanceMap.set(\"threadTest\", threadTestInstance);\n\t}\n\n\tLinkResult linkResult = linkModule(irModule, rootResolver);\n\tif(!linkResult.success)\n\t{\n\t\tLog::printf(Log::error, \"Failed to link module:\\n\");\n\t\tfor(auto& missingImport : linkResult.missingImports)\n\t\t{\n\t\t\tLog::printf(Log::error,\n\t\t\t\t\t\t\"Missing import: module=\\\"%s\\\" export=\\\"%s\\\" type=\\\"%s\\\"\\n\",\n\t\t\t\t\t\tmissingImport.moduleName.c_str(),\n\t\t\t\t\t\tmissingImport.exportName.c_str(),\n\t\t\t\t\t\tasString(missingImport.type).c_str());\n\t\t}\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t// Instantiate the module.\n\tModuleInstance* moduleInstance = instantiateModule(\n\t\tcompartment, module, std::move(linkResult.resolvedImports), options.filename);\n\tif(!moduleInstance) { return EXIT_FAILURE; }\n\n\t// Call the module start function, if it has one.\n\tFunctionInstance* startFunction = getStartFunction(moduleInstance);\n\tif(startFunction) { invokeFunctionChecked(context, startFunction, {}); }\n\n\tif(options.enableEmscripten)\n\t{\n\t\t// Call the Emscripten global initalizers.\n\t\tEmscripten::initializeGlobals(context, irModule, moduleInstance);\n\t}\n\n\t// Look up the function export to call.\n\tFunctionInstance* functionInstance;\n\tif(!options.functionName)\n\t{\n\t\tfunctionInstance = asFunctionNullable(getInstanceExport(moduleInstance, \"main\"));\n\t\tif(!functionInstance)\n\t\t{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, \"_main\")); }\n\t\tif(!functionInstance)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Module does not export main function\\n\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfunctionInstance\n\t\t\t= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));\n\t\tif(!functionInstance)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Module does not export '%s'\\n\", options.functionName);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tFunctionType functionType = getFunctionType(functionInstance);\n\n\t// Set up the arguments for the invoke.\n\tstd::vector invokeArgs;\n\tif(!options.functionName)\n\t{\n\t\tif(functionType.params().size() == 2)\n\t\t{\n\t\t\tMemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance);\n\t\t\tif(!defaultMemory)\n\t\t\t{\n\t\t\t\tLog::printf(\n\t\t\t\t\tLog::error,\n\t\t\t\t\t\"Module does not declare a default memory object to put arguments in.\\n\");\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\n\t\t\tstd::vector argStrings;\n\t\t\targStrings.push_back(options.filename);\n\t\t\tchar** args = options.args;\n\t\t\twhile(*args) { argStrings.push_back(*args++); };\n\n\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n\t\t}\n\t\telse if(functionType.params().size() > 0)\n\t\t{\n\t\t\tLog::printf(Log::error,\n\t\t\t\t\t\t\"WebAssembly function requires %\" PRIu64\n\t\t\t\t\t\t\" argument(s), but only 0 or 2 can be passed!\",\n\t\t\t\t\t\tfunctionType.params().size());\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(U32 i = 0; options.args[i]; ++i)\n\t\t{\n\t\t\tValue value;\n\t\t\tswitch(functionType.params()[i])\n\t\t\t{\n\t\t\tcase ValueType::i32: value = (U32)atoi(options.args[i]); break;\n\t\t\tcase ValueType::i64: value = (U64)atol(options.args[i]); break;\n\t\t\tcase ValueType::f32: value = (F32)atof(options.args[i]); break;\n\t\t\tcase ValueType::f64: value = atof(options.args[i]); break;\n\t\t\tcase ValueType::v128:\n\t\t\tcase ValueType::anyref:\n\t\t\tcase ValueType::anyfunc:\n\t\t\t\tErrors::fatalf(\"Cannot parse command-line argument for %s function parameter\",\n\t\t\t\t\t\t\t asString(functionType.params()[i]));\n\t\t\tdefault: Errors::unreachable();\n\t\t\t}\n\t\t\tinvokeArgs.push_back(value);\n\t\t}\n\t}\n\n\t// Invoke the function.\n\tTiming::Timer executionTimer;\n\tIR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);\n\tTiming::logTimer(\"Invoked function\", executionTimer);\n\n\tif(options.functionName)\n\t{\n\t\tLog::printf(Log::debug,\n\t\t\t\t\t\"%s returned: %s\\n\",\n\t\t\t\t\toptions.functionName,\n\t\t\t\t\tasString(functionResults).c_str());\n\t\treturn EXIT_SUCCESS;\n\t}\n\telse if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)\n\t{\n\t\treturn functionResults[0].i32;\n\t}\n\telse\n\t{\n\t\treturn EXIT_SUCCESS;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[3608, 3708]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3608, 3708]]}, "_func_name": "run", "_file_name": "Programs/wavm/wavm.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def get(self, space_id):\n \"\"\" Fetch data for space with the corresponding space_id \"\"\"\n return database_utilities.execute_query(\n f\"\"\"select * from spaces where space_id = %s\"\"\", (space_id, ))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "apis/spaces.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,\n unsigned char **p,\n unsigned char *end )\n{\n int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;\n size_t len;\n ((void) ssl);\n\n /*\n * PSK parameters:\n *\n * opaque psk_identity_hint<0..2^16-1>;\n */\n if( (*p) > end - 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n len = (*p)[0] << 8 | (*p)[1];\n *p += 2;\n\n if( (*p) > end - len )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad server key exchange message \"\n \"(psk_identity_hint length)\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );\n }\n\n /*\n * Note: we currently ignore the PKS identity hint, as we only allow one\n * PSK to be provisionned on the client. This could be changed later if\n * someone needs that feature.\n */\n *p += len;\n ret = 0;\n\n return( ret );\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ssl_parse_server_psk_hint", "_file_name": "library/ssl_cli.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_ports(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI),\n ''])\n self.mox.ReplayAll()\n\n ports = self.driver.common.get_ports()\n self.assertEqual(ports['FC'][0], '20210002AC00383D')\n self.assertEqual(ports['iSCSI']['10.10.120.252']['nsp'], '0:8:2')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_get_ports", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_least_used_nsp(self, nspss):\n \"\"\"\"Return the nsp that has the fewest active vluns.\"\"\"\n # return only the nsp (node:server:port)\n result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])\n\n # count the number of nsps (there is 1 for each active vlun)\n nsp_counts = {}\n for nsp in nspss:\n # initialize counts to zero\n nsp_counts[nsp] = 0\n\n current_least_used_nsp = None\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n nsp = line.strip()\n if nsp in nsp_counts:\n nsp_counts[nsp] = nsp_counts[nsp] + 1\n\n # identify key (nsp) of least used nsp\n current_smallest_count = sys.maxint\n for (nsp, count) in nsp_counts.iteritems():\n if count < current_smallest_count:\n current_least_used_nsp = nsp\n current_smallest_count = count\n\n return current_least_used_nsp", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_least_used_nsp", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,\n ExceptionInfo *exception)\n{\n char\n *attribute,\n format[MagickPathExtent],\n name[MagickPathExtent],\n *resource;\n\n const StringInfo\n *profile;\n\n const unsigned char\n *info;\n\n long\n start,\n stop;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n size_t\n length;\n\n ssize_t\n count,\n id,\n sub_number;\n\n /*\n There are no newlines in path names, so it's safe as terminator.\n */\n profile=GetImageProfile(image,\"8bim\");\n if (profile == (StringInfo *) NULL)\n return(MagickFalse);\n count=(ssize_t) sscanf(key,\"8BIM:%ld,%ld:%1024[^\\n]\\n%1024[^\\n]\",&start,&stop,\n name,format);\n if ((count != 2) && (count != 3) && (count != 4))\n return(MagickFalse);\n if (count < 4)\n (void) CopyMagickString(format,\"SVG\",MagickPathExtent);\n if (count < 3)\n *name='\\0';\n sub_number=1;\n if (*name == '#')\n sub_number=(ssize_t) StringToLong(&name[1]);\n sub_number=MagickMax(sub_number,1L);\n resource=(char *) NULL;\n status=MagickFalse;\n length=GetStringInfoLength(profile);\n info=GetStringInfoDatum(profile);\n while ((length > 0) && (status == MagickFalse))\n {\n if (ReadPropertyByte(&info,&length) != (unsigned char) '8')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')\n continue;\n id=(ssize_t) ReadPropertyMSBShort(&info,&length);\n if (id < (ssize_t) start)\n continue;\n if (id > (ssize_t) stop)\n continue;\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n count=(ssize_t) ReadPropertyByte(&info,&length);\n if ((count != 0) && ((size_t) count <= length))\n {\n resource=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n resource=(char *) AcquireQuantumMemory((size_t) count+\n MagickPathExtent,sizeof(*resource));\n if (resource != (char *) NULL)\n {\n for (i=0; i < (ssize_t) count; i++)\n resource[i]=(char) ReadPropertyByte(&info,&length);\n resource[count]='\\0';\n }\n }\n if ((count & 0x01) == 0)\n (void) ReadPropertyByte(&info,&length);\n count=(ssize_t) ReadPropertyMSBLong(&info,&length);\n if ((*name != '\\0') && (*name != '#'))\n if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))\n {\n /*\n No name match, scroll forward and try next.\n */\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n if ((*name == '#') && (sub_number != 1))\n {\n /*\n No numbered match, scroll forward and try next.\n */\n sub_number--;\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n /*\n We have the resource of interest.\n */\n attribute=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,\n sizeof(*attribute));\n if (attribute != (char *) NULL)\n {\n (void) CopyMagickMemory(attribute,(char *) info,(size_t) count);\n attribute[count]='\\0';\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n if ((id <= 1999) || (id >= 2999))\n (void) SetImageProperty((Image *) image,key,(const char *)\n attribute,exception);\n else\n {\n char\n *path;\n\n if (LocaleCompare(format,\"svg\") == 0)\n path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,\n image->columns,image->rows);\n else\n path=TracePSClippath((unsigned char *) attribute,(size_t) count);\n (void) SetImageProperty((Image *) image,key,(const char *) path,\n exception);\n path=DestroyString(path);\n }\n attribute=DestroyString(attribute);\n status=MagickTrue;\n }\n }\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n return(status);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2403, 2446]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2403, 2446]]}, "_func_name": "Get8BIMProperty", "_file_name": "MagickCore/property.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int enc_untrusted_inet_pton(int af, const char *src, void *dst) {\n if (!src || !dst) {\n return 0;\n }\n\n MessageWriter input;\n input.Push(TokLinuxAfFamily(af));\n input.PushByReference(Extent{\n src, std::min(strlen(src) + 1, static_cast(INET6_ADDRSTRLEN))});\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetPtonHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_pton\", 3);\n\n int result = output.next();\n int klinux_errno = output.next();\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return -1;\n }\n\n auto klinux_addr_buffer = output.next();\n size_t max_size = 0;\n if (af == AF_INET) {\n max_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n max_size = sizeof(struct in6_addr);\n }\n memcpy(dst, klinux_addr_buffer.data(),\n std::min(klinux_addr_buffer.size(), max_size));\n return result;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[747, 786]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[747, 786]]}, "_func_name": "enc_untrusted_inet_pton", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n{\n\tstruct mmu_gather tlb;\n\tstruct vm_area_struct *vma;\n\tbool ret = true;\n\n\t/*\n\t * We have to make sure to not race with the victim exit path\n\t * and cause premature new oom victim selection:\n\t * __oom_reap_task_mm\t\texit_mm\n\t * mmget_not_zero\n\t *\t\t\t\t mmput\n\t *\t\t\t\t atomic_dec_and_test\n\t *\t\t\t\t exit_oom_victim\n\t *\t\t\t\t[...]\n\t *\t\t\t\tout_of_memory\n\t *\t\t\t\t select_bad_process\n\t *\t\t\t\t # no TIF_MEMDIE task selects new victim\n\t * unmap_page_range # frees some memory\n\t */\n\tmutex_lock(&oom_lock);\n\n\tif (!down_read_trylock(&mm->mmap_sem)) {\n\t\tret = false;\n\t\ttrace_skip_task_reaping(tsk->pid);\n\t\tgoto unlock_oom;\n\t}\n\n\t/*\n\t * If the mm has notifiers then we would need to invalidate them around\n\t * unmap_page_range and that is risky because notifiers can sleep and\n\t * what they do is basically undeterministic. So let's have a short\n\t * sleep to give the oom victim some more time.\n\t * TODO: we really want to get rid of this ugly hack and make sure that\n\t * notifiers cannot block for unbounded amount of time and add\n\t * mmu_notifier_invalidate_range_{start,end} around unmap_page_range\n\t */\n\tif (mm_has_notifiers(mm)) {\n\t\tup_read(&mm->mmap_sem);\n\t\tschedule_timeout_idle(HZ);\n\t\tgoto unlock_oom;\n\t}\n\n\t/*\n\t * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't\n\t * work on the mm anymore. The check for MMF_OOM_SKIP must run\n\t * under mmap_sem for reading because it serializes against the\n\t * down_write();up_write() cycle in exit_mmap().\n\t */\n\tif (test_bit(MMF_OOM_SKIP, &mm->flags)) {\n\t\tup_read(&mm->mmap_sem);\n\t\ttrace_skip_task_reaping(tsk->pid);\n\t\tgoto unlock_oom;\n\t}\n\n\ttrace_start_task_reaping(tsk->pid);\n\n\t/*\n\t * Tell all users of get_user/copy_from_user etc... that the content\n\t * is no longer stable. No barriers really needed because unmapping\n\t * should imply barriers already and the reader would hit a page fault\n\t * if it stumbled over a reaped memory.\n\t */\n\tset_bit(MMF_UNSTABLE, &mm->flags);\n\n\ttlb_gather_mmu(&tlb, mm, 0, -1);\n\tfor (vma = mm->mmap ; vma; vma = vma->vm_next) {\n\t\tif (!can_madv_dontneed_vma(vma))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * Only anonymous pages have a good chance to be dropped\n\t\t * without additional steps which we cannot afford as we\n\t\t * are OOM already.\n\t\t *\n\t\t * We do not even care about fs backed pages because all\n\t\t * which are reclaimable have already been reclaimed and\n\t\t * we do not want to block exit_mmap by keeping mm ref\n\t\t * count elevated without a good reason.\n\t\t */\n\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))\n\t\t\tunmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,\n\t\t\t\t\t NULL);\n\t}\n\ttlb_finish_mmu(&tlb, 0, -1);\n\tpr_info(\"oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\\n\",\n\t\t\ttask_pid_nr(tsk), tsk->comm,\n\t\t\tK(get_mm_counter(mm, MM_ANONPAGES)),\n\t\t\tK(get_mm_counter(mm, MM_FILEPAGES)),\n\t\t\tK(get_mm_counter(mm, MM_SHMEMPAGES)));\n\tup_read(&mm->mmap_sem);\n\n\ttrace_finish_task_reaping(tsk->pid);\nunlock_oom:\n\tmutex_unlock(&oom_lock);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1997, 2081], [2637, 2670]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1997, 2081], [2637, 2670]]}, "_func_name": "__oom_reap_task_mm", "_file_name": "mm/oom_kill.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)\n{\n\tstruct uvesafb_pal_entry *entries;\n\tint shift = 16 - dac_width;\n\tint i, err = 0;\n\n\tif (info->var.bits_per_pixel == 8) {\n\t\tif (cmap->start + cmap->len > info->cmap.start +\n\t\t info->cmap.len || cmap->start < info->cmap.start)\n\t\t\treturn -EINVAL;\n\n\t\tentries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);\n\t\tif (!entries)\n\t\t\treturn -ENOMEM;\n\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\tentries[i].red = cmap->red[i] >> shift;\n\t\t\tentries[i].green = cmap->green[i] >> shift;\n\t\t\tentries[i].blue = cmap->blue[i] >> shift;\n\t\t\tentries[i].pad = 0;\n\t\t}\n\t\terr = uvesafb_setpalette(entries, cmap->len, cmap->start, info);\n\t\tkfree(entries);\n\t} else {\n\t\t/*\n\t\t * For modes with bpp > 8, we only set the pseudo palette in\n\t\t * the fb_info struct. We rely on uvesafb_setcolreg to do all\n\t\t * sanity checking.\n\t\t */\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\terr |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],\n\t\t\t\t\t\tcmap->green[i], cmap->blue[i],\n\t\t\t\t\t\t0, info);\n\t\t}\n\t}\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[321, 384]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[321, 384]]}, "_func_name": "uvesafb_setcmap", "_file_name": "drivers/video/fbdev/uvesafb.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@login_manager.user_loader\ndef load_user(s_id):\n email = str(s_id)\n query = '''select * from usr where email like\\'''' + email + '\\''\n cursor = g.conn.execute(query)\n user = User()\n for row in cursor:\n user.name = str(row.name)\n user.email = str(row.email)\n break\n return user", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[70, 140]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[70, 140]]}, "_func_name": "load_user", "_file_name": "Web-app/Server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def system_search(self, search):\r\n search = search.lower()\r\n conn = sqlite3.connect('data/ed.db').cursor()\r\n table = conn.execute('select * from populated where lower(name) = ?', (search,))\r\n results = table.fetchone()\r\n if not results:\r\n table = conn.execute('select * from systems where lower(name) = ?', (search,))\r\n results = table.fetchone()\r\n if results:\r\n keys = tuple(i[0] for i in table.description) \r\n return '\\n'.join(f'{key.replace(\"_\", \" \").title()}: {field}'\r\n for key, field in zip(keys[1:], results[1:]) if field)\r\n else:\r\n return 'No systems found.'", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "system_search", "_file_name": "eddb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)\n{\n\tstatic bool intel_regs_sorted = false;\n\tunsigned int first = 0;\n\tunsigned int last = ARR_SIZE(insn_regs_intel) - 1;\n\tunsigned int mid;\n\n\tif (!intel_regs_sorted) {\n\t\tmemcpy(insn_regs_intel_sorted, insn_regs_intel,\n\t\t\t\tsizeof(insn_regs_intel_sorted));\n\t\tqsort(insn_regs_intel_sorted,\n\t\t\t\tARR_SIZE(insn_regs_intel_sorted),\n\t\t\t\tsizeof(struct insn_reg), regs_cmp);\n\t\tintel_regs_sorted = true;\n\t}\n\n\tif (insn_regs_intel_sorted[0].insn > id ||\n\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n\t\treturn 0;\n\t}\n\n\twhile (first <= last) {\n\t\tmid = (first + last) / 2;\n\t\tif (insn_regs_intel_sorted[mid].insn < id) {\n\t\t\tfirst = mid + 1;\n\t\t} else if (insn_regs_intel_sorted[mid].insn == id) {\n\t\t\tif (access) {\n\t\t\t\t*access = insn_regs_intel_sorted[mid].access;\n\t\t\t}\n\t\t\treturn insn_regs_intel_sorted[mid].reg;\n\t\t} else {\n\t\t\tif (mid == 0)\n\t\t\t\tbreak;\n\t\t\tlast = mid - 1;\n\t\t}\n\t}\n\n\t// not found\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "X86_insn_reg_intel", "_file_name": "arch/X86/X86Mapping.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def usage(args=None):\n '''\n Return usage information for volumes mounted on this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' disk.usage\n '''\n flags = ''\n allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n for flag in args:\n if flag in allowed:\n flags += flag\n else:\n break\n if __grains__['kernel'] == 'Linux':\n cmd = 'df -P'\n elif __grains__['kernel'] == 'OpenBSD':\n cmd = 'df -kP'\n else:\n cmd = 'df'\n if args:\n cmd += ' -{0}'.format(flags)\n ret = {}\n out = __salt__['cmd.run'](cmd).splitlines()\n for line in out:\n if not line:\n continue\n if line.startswith('Filesystem'):\n continue\n comps = line.split()\n while not comps[1].isdigit():\n comps[0] = '{0} {1}'.format(comps[0], comps[1])\n comps.pop(1)\n try:\n if __grains__['kernel'] == 'Darwin':\n ret[comps[8]] = {\n 'filesystem': comps[0],\n '512-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n 'iused': comps[5],\n 'ifree': comps[6],\n '%iused': comps[7],\n }\n else:\n ret[comps[5]] = {\n 'filesystem': comps[0],\n '1K-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n }\n except IndexError:\n log.warn(\"Problem parsing disk usage information\")\n ret = {}\n return ret", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usage", "_file_name": "salt/modules/disk.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/ranks\")\ndef ranks():\n if db == None:\n init()\n\n scene = request.args.get('scene', default='austin')\n date = request.args.get('date')\n \n # If no date was provided, pick the date of the latest tournament\n if date == None:\n sql = \"SELECT distinct date FROM ranks WHERE scene='{scene}' ORDER BY date DESC LIMIT 1;\"\n args = {'scene': scene}\n res = db.exec(sql, args)\n date = res[0][0]\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n args = {'scene': scene, 'date': date}\n res = db.exec(sql, args)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n cur_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n cur_ranks[tag] = rank\n\n # Now get the ranks from last month, so we know if these players went up or down\n y, m, d = date.split('-')\n prev_date = bracket_utils.get_previous_month(date)\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM ranks WHERE scene = '{scene}' and date='{date}'\"\n args = {'scene': scene, 'date': prev_date}\n res = db.exec(sql, args)\n\n # Make a dict out of this data\n # eg {'christmasmike': 50}\n prev_ranks = {}\n for r in res:\n tag = r[1]\n rank = r[2]\n\n prev_ranks[tag] = rank\n\n return render_template('libraries/html/ranks.html', cur_ranks=cur_ranks, prev_ranks=prev_ranks, scene=scene, date=date)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ranks", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def patch(self, user_id):\n \"\"\" Replaces information of corresponding user_id with request body \"\"\"\n query = f\"\"\"update users set user_id = %s \"\"\"\n query += f\"\"\"where user_id = '{user_id}'\"\"\"\n json_data = request.get_json()\n parameters = (json_data['user_id'], )\n database_utilities.execute_query(query, parameters)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[182, 234]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[182, 234]]}, "_func_name": "patch", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/delete_video/')\ndef delete_video(filename):\n\tif 'username' in session:\n\t\t#os.remove(\"static/videos/{}\".format(filename))\n\t\tprint(session['username'], file=sys.stdout)\n\t\tdata=users.query.filter_by(Username=session['username']).first()\n\t\tvideo=Video.query.filter_by(UserID=data.UserID,Name=filename).first()\n\t\tif video != None:\n\t\t\t#os.remove(\"static/videos/{}\".format(filename))\n\t\t\tos.system(\"rm static/videos/{}\".format(filename))\n\t\t\tdb.session.delete(video)\n\t\t\tdb.session.commit()\n\t\telse:\n\t\t\treturn \"Don't delete other people's videos!\"\n\t\treturn redirect(url_for('upload'))\n\treturn \"test\"", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_video", "_file_name": "Trialwebsite/app/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def compare_and_update(user, message):\n \"\"\"\n This method compare a user object from the bot and his info from\n the Telegram message to check whether a user has changed his bio\n or not. If yes, the user object that represents him in the bot will\n be updated accordingly. Now this function is called only when a user\n asks the bot for showing the most popular cams\n\n :param user: user object that represents a Telegram user in this bot\n :param message: object from Telegram that contains info about user's\n message and about himself\n :return: None\n \"\"\"\n\n log.info('Checking whether user have changed his info or not...')\n msg = message.from_user\n usr_from_message = User(message.chat.id, msg.first_name, msg.username,\n msg.last_name)\n\n if user.chat_id != usr_from_message.chat_id:\n log.error(\"Wrong user to compare!\")\n return\n\n if user.first_name != usr_from_message.first_name:\n user.first_name = usr_from_message.first_name\n\n elif user.nickname != usr_from_message.nickname:\n user.nickname = usr_from_message.nickname\n\n elif user.last_name != usr_from_message.last_name:\n user.last_name = usr_from_message.last_name\n\n else:\n log.debug(\"User's info hasn't changed\")\n return\n\n log.info(\"User has changed his info\")\n log.debug(\"Updating user's info in the database...\")\n query = (f\"UPDATE users \"\n f\"SET first_name='{user.first_name}', \"\n f\"nickname='{user.nickname}', \"\n f\"last_name='{user.last_name}' \"\n f\"WHERE chat_id={user.chat_id}\")\n\n try:\n db.add(query)\n except DatabaseError:\n log.error(\"Could not update info about %s in the database\",\n user)\n else:\n log.debug(\"User's info has been updated\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1578, 1784]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1578, 1784]]}, "_func_name": "compare_and_update", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)\n{\n\tstruct tun_struct *tun;\n\tstruct tun_file *tfile = file->private_data;\n\tstruct net_device *dev;\n\tint err;\n\n\tif (tfile->detached)\n\t\treturn -EINVAL;\n\n\tdev = __dev_get_by_name(net, ifr->ifr_name);\n\tif (dev) {\n\t\tif (ifr->ifr_flags & IFF_TUN_EXCL)\n\t\t\treturn -EBUSY;\n\t\tif ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse\n\t\t\treturn -EINVAL;\n\n\t\tif (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=\n\t\t !!(tun->flags & IFF_MULTI_QUEUE))\n\t\t\treturn -EINVAL;\n\n\t\tif (tun_not_capable(tun))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_open(tun->security);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\terr = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\tif (tun->flags & IFF_MULTI_QUEUE &&\n\t\t (tun->numqueues + tun->numdisabled > 1)) {\n\t\t\t/* One or more queue has already been attached, no need\n\t\t\t * to initialize the device again.\n\t\t\t */\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tchar *name;\n\t\tunsigned long flags = 0;\n\t\tint queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?\n\t\t\t MAX_TAP_QUEUES : 1;\n\n\t\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_create();\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\t/* Set dev type */\n\t\tif (ifr->ifr_flags & IFF_TUN) {\n\t\t\t/* TUN device */\n\t\t\tflags |= IFF_TUN;\n\t\t\tname = \"tun%d\";\n\t\t} else if (ifr->ifr_flags & IFF_TAP) {\n\t\t\t/* TAP device */\n\t\t\tflags |= IFF_TAP;\n\t\t\tname = \"tap%d\";\n\t\t} else\n\t\t\treturn -EINVAL;\n\n\t\tif (*ifr->ifr_name)\n\t\t\tname = ifr->ifr_name;\n\n\t\tdev = alloc_netdev_mqs(sizeof(struct tun_struct), name,\n\t\t\t\t NET_NAME_UNKNOWN, tun_setup, queues,\n\t\t\t\t queues);\n\n\t\tif (!dev)\n\t\t\treturn -ENOMEM;\n\t\terr = dev_get_valid_name(net, dev, name);\n\t\tif (err < 0)\n\t\t\tgoto err_free_dev;\n\n\t\tdev_net_set(dev, net);\n\t\tdev->rtnl_link_ops = &tun_link_ops;\n\t\tdev->ifindex = tfile->ifindex;\n\t\tdev->sysfs_groups[0] = &tun_attr_group;\n\n\t\ttun = netdev_priv(dev);\n\t\ttun->dev = dev;\n\t\ttun->flags = flags;\n\t\ttun->txflt.count = 0;\n\t\ttun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);\n\n\t\ttun->align = NET_SKB_PAD;\n\t\ttun->filter_attached = false;\n\t\ttun->sndbuf = tfile->socket.sk->sk_sndbuf;\n\t\ttun->rx_batched = 0;\n\n\t\ttun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);\n\t\tif (!tun->pcpu_stats) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto err_free_dev;\n\t\t}\n\n\t\tspin_lock_init(&tun->lock);\n\n\t\terr = security_tun_dev_alloc_security(&tun->security);\n\t\tif (err < 0)\n\t\t\tgoto err_free_stat;\n\n\t\ttun_net_init(dev);\n\t\ttun_flow_init(tun);\n\n\t\tdev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |\n\t\t\t\t TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX;\n\t\tdev->features = dev->hw_features | NETIF_F_LLTX;\n\t\tdev->vlan_features = dev->features &\n\t\t\t\t ~(NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX);\n\n\t\tINIT_LIST_HEAD(&tun->disabled);\n\t\terr = tun_attach(tun, file, false);\n\t\tif (err < 0)\n\t\t\tgoto err_free_flow;\n\n\t\terr = register_netdevice(tun->dev);\n\t\tif (err < 0)\n\t\t\tgoto err_detach;\n\t}\n\n\tnetif_carrier_on(tun->dev);\n\n\ttun_debug(KERN_INFO, tun, \"tun_set_iff\\n\");\n\n\ttun->flags = (tun->flags & ~TUN_FEATURES) |\n\t\t(ifr->ifr_flags & TUN_FEATURES);\n\n\t/* Make sure persistent devices do not get stuck in\n\t * xoff state.\n\t */\n\tif (netif_running(tun->dev))\n\t\tnetif_tx_wake_all_queues(tun->dev);\n\n\tstrcpy(ifr->ifr_name, tun->dev->name);\n\treturn 0;\n\nerr_detach:\n\ttun_detach_all(dev);\n\t/* register_netdevice() already called tun_free_netdev() */\n\tgoto err_free_dev;\n\nerr_free_flow:\n\ttun_flow_uninit(tun);\n\tsecurity_tun_dev_free_security(tun->security);\nerr_free_stat:\n\tfree_percpu(tun->pcpu_stats);\nerr_free_dev:\n\tfree_netdev(dev);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tun_set_iff", "_file_name": "drivers/net/tun.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_last_month(db, scene):\n sql = \"select date from matches where scene='{}' order by date desc limit 1;\".format(scene)\n res = db.exec(sql)\n date = res[0][0]\n\n # If it has been more than 1 month since this last tournament,\n # go ahead and round this date up by a 1 month\n # eg, if the last tournament was 2015-01-15 (a long time ago)\n # we can assume the scene won't have more tournaments\n # So just round to 2015-02-01\n today = datetime.datetime.today().strftime('%Y-%m-%d')\n y, m, d = today.split('-')\n cy, cm, cd = date.split('-')\n if y > cy or m > cm:\n # Add 1 to the month before we return\n # eg 2018-03-01 -> 2018-04-01\n date = get_next_month(date)\n\n return date", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[31, 127]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[31, 127]]}, "_func_name": "get_last_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def update_inverter(self, inverter_serial, ts, status, etoday, etotal):\n query = '''\n UPDATE Inverters\n SET \n TimeStamp=?, \n Status=?, \n eToday=?,\n eTotal=?\n WHERE Serial=?;\n '''\n self.c.execute(query, (ts, status, etoday, etotal, inverter_serial))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_inverter", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def incrementOption(cursor, poll_name, option):\n key = poll_name+\"-\"+option\n req = \"UPDATE {} SET count=count+1 WHERE name_option = '{}';\".format(CFG(\"options_table_name\"), key)\n cursor.execute(req)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[79, 184]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[79, 184]]}, "_func_name": "incrementOption", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def verify(self, data):\n credentials = self._formatCredentials(data, name='current')\n command = [\n 'rclone',\n 'lsjson',\n 'current:',\n ]\n\n try:\n result = self._execute(command, credentials)\n return {\n 'result': True,\n 'message': 'Success',\n }\n except subprocess.CalledProcessError as e:\n returncode = e.returncode\n return {\n 'result': False,\n 'message': 'Exit status {}'.format(returncode),\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "verify", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _cliq_run(self, verb, cliq_args, check_exit_code=True):\n \"\"\"Runs a CLIQ command over SSH, without doing any result parsing\"\"\"\n cliq_arg_strings = []\n for k, v in cliq_args.items():\n cliq_arg_strings.append(\" %s=%s\" % (k, v))\n cmd = verb + ''.join(cliq_arg_strings)\n\n return self._run_ssh(cmd, check_exit_code)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[141, 171], [210, 312]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[141, 171], [210, 312]]}, "_func_name": "_cliq_run", "_file_name": "cinder/volume/drivers/san/hp_lefthand.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int blk_init_allocated_queue(struct request_queue *q)\n{\n\tWARN_ON_ONCE(q->mq_ops);\n\n\tq->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);\n\tif (!q->fq)\n\t\treturn -ENOMEM;\n\n\tif (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))\n\t\tgoto out_free_flush_queue;\n\n\tif (blk_init_rl(&q->root_rl, q, GFP_KERNEL))\n\t\tgoto out_exit_flush_rq;\n\n\tINIT_WORK(&q->timeout_work, blk_timeout_work);\n\tq->queue_flags\t\t|= QUEUE_FLAG_DEFAULT;\n\n\t/*\n\t * This also sets hw/phys segments, boundary and size\n\t */\n\tblk_queue_make_request(q, blk_queue_bio);\n\n\tq->sg_reserved_size = INT_MAX;\n\n\tif (elevator_init(q))\n\t\tgoto out_exit_flush_rq;\n\treturn 0;\n\nout_exit_flush_rq:\n\tif (q->exit_rq_fn)\n\t\tq->exit_rq_fn(q, q->fq->flush_rq);\nout_free_flush_queue:\n\tblk_free_flush_queue(q->fq);\n\tq->fq = NULL;\n\treturn -ENOMEM;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "blk_init_allocated_queue", "_file_name": "block/blk-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _set_qos_rule(self, qos, vvs_name):\n max_io = self._get_qos_value(qos, 'maxIOPS')\n max_bw = self._get_qos_value(qos, 'maxBWS')\n cli_qos_string = \"\"\n if max_io is not None:\n cli_qos_string += ('-io %s ' % max_io)\n if max_bw is not None:\n cli_qos_string += ('-bw %sM ' % max_bw)\n self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_set_qos_rule", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "\tdef render(self, request):\n\t\taction = \"download\"\n\t\tif \"action\" in request.args:\n\t\t\taction = request.args[\"action\"][0]\n\n\t\tif \"file\" in request.args:\n\t\t\tfilename = request.args[\"file\"][0].decode('utf-8', 'ignore').encode('utf-8')\n\t\t\tfilename = re.sub(\"^/+\", \"/\", os.path.realpath(filename))\n\n\t\t\tif not os.path.exists(filename):\n\t\t\t\treturn \"File '%s' not found\" % (filename)\n\n\t\t\tif action == \"stream\":\n\t\t\t\tname = \"stream\"\n\t\t\t\tif \"name\" in request.args:\n\t\t\t\t\tname = request.args[\"name\"][0]\n\n\t\t\t\tport = config.OpenWebif.port.value\n\t\t\t\tproto = 'http'\n\t\t\t\tif request.isSecure():\n\t\t\t\t\tport = config.OpenWebif.https_port.value\n\t\t\t\t\tproto = 'https'\n\t\t\t\tourhost = request.getHeader('host')\n\t\t\t\tm = re.match('.+\\:(\\d+)$', ourhost)\n\t\t\t\tif m is not None:\n\t\t\t\t\tport = m.group(1)\n\n\t\t\t\tresponse = \"#EXTM3U\\n#EXTVLCOPT--http-reconnect=true\\n#EXTINF:-1,%s\\n%s://%s:%s/file?action=download&file=%s\" % (name, proto, request.getRequestHostname(), port, quote(filename))\n\t\t\t\trequest.setHeader(\"Content-Disposition\", 'attachment;filename=\"%s.m3u\"' % name)\n\t\t\t\trequest.setHeader(\"Content-Type\", \"application/x-mpegurl\")\n\t\t\t\treturn response\n\t\t\telif action == \"delete\":\n\t\t\t\trequest.setResponseCode(http.OK)\n\t\t\t\treturn \"TODO: DELETE FILE: %s\" % (filename)\n\t\t\telif action == \"download\":\n\t\t\t\trequest.setHeader(\"Content-Disposition\", \"attachment;filename=\\\"%s\\\"\" % (filename.split('/')[-1]))\n\t\t\t\trfile = static.File(filename, defaultType = \"application/octet-stream\")\n\t\t\t\treturn rfile.render(request)\n\t\t\telse: \n\t\t\t\treturn \"wrong action parameter\"\n\n\t\tif \"dir\" in request.args:\n\t\t\tpath = request.args[\"dir\"][0]\n\t\t\tpattern = '*'\n\t\t\tdata = []\n\t\t\tif \"pattern\" in request.args:\n\t\t\t\tpattern = request.args[\"pattern\"][0]\n\t\t\tdirectories = []\n\t\t\tfiles = []\n\t\t\tif fileExists(path):\n\t\t\t\ttry:\n\t\t\t\t\tfiles = glob.glob(path+'/'+pattern)\n\t\t\t\texcept:\n\t\t\t\t\tfiles = []\n\t\t\t\tfiles.sort()\n\t\t\t\ttmpfiles = files[:]\n\t\t\t\tfor x in tmpfiles:\n\t\t\t\t\tif os.path.isdir(x):\n\t\t\t\t\t\tdirectories.append(x + '/')\n\t\t\t\t\t\tfiles.remove(x)\n\t\t\t\tdata.append({\"result\": True,\"dirs\": directories,\"files\": files})\n\t\t\telse:\n\t\t\t\tdata.append({\"result\": False,\"message\": \"path %s not exits\" % (path)})\n\t\t\trequest.setHeader(\"content-type\", \"application/json; charset=utf-8\")\n\t\t\treturn json.dumps(data, indent=2)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[149, 290]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[149, 290]]}, "_func_name": "render", "_file_name": "plugin/controllers/file.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "Mat_VarReadNextInfo4(mat_t *mat)\n{\n int M,O,data_type,class_type;\n mat_int32_t tmp;\n long nBytes;\n size_t readresult;\n matvar_t *matvar = NULL;\n union {\n mat_uint32_t u;\n mat_uint8_t c[4];\n } endian;\n\n if ( mat == NULL || mat->fp == NULL )\n return NULL;\n else if ( NULL == (matvar = Mat_VarCalloc()) )\n return NULL;\n\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n endian.u = 0x01020304;\n\n /* See if MOPT may need byteswapping */\n if ( tmp < 0 || tmp > 4052 ) {\n if ( Mat_int32Swap(&tmp) > 4052 ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n }\n\n M = (int)floor(tmp / 1000.0);\n switch ( M ) {\n case 0:\n /* IEEE little endian */\n mat->byteswap = endian.c[0] != 4;\n break;\n case 1:\n /* IEEE big endian */\n mat->byteswap = endian.c[0] != 1;\n break;\n default:\n /* VAX, Cray, or bogus */\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= M*1000;\n O = (int)floor(tmp / 100.0);\n /* O must be zero */\n if ( 0 != O ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= O*100;\n data_type = (int)floor(tmp / 10.0);\n /* Convert the V4 data type */\n switch ( data_type ) {\n case 0:\n matvar->data_type = MAT_T_DOUBLE;\n break;\n case 1:\n matvar->data_type = MAT_T_SINGLE;\n break;\n case 2:\n matvar->data_type = MAT_T_INT32;\n break;\n case 3:\n matvar->data_type = MAT_T_INT16;\n break;\n case 4:\n matvar->data_type = MAT_T_UINT16;\n break;\n case 5:\n matvar->data_type = MAT_T_UINT8;\n break;\n default:\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= data_type*10;\n class_type = (int)floor(tmp / 1.0);\n switch ( class_type ) {\n case 0:\n matvar->class_type = MAT_C_DOUBLE;\n break;\n case 1:\n matvar->class_type = MAT_C_CHAR;\n break;\n case 2:\n matvar->class_type = MAT_C_SPARSE;\n break;\n default:\n Mat_VarFree(matvar);\n return NULL;\n }\n\n matvar->rank = 2;\n matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));\n if ( NULL == matvar->dims ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n matvar->dims[0] = tmp;\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n matvar->dims[1] = tmp;\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n /* Check that the length of the variable name is at least 1 */\n if ( tmp < 1 ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n matvar->name = (char*)malloc(tmp);\n if ( NULL == matvar->name ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);\n if ( tmp != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n } else {\n matvar->name[tmp - 1] = '\\0';\n }\n\n matvar->internal->datapos = ftell((FILE*)mat->fp);\n if ( matvar->internal->datapos == -1L ) {\n Mat_VarFree(matvar);\n Mat_Critical(\"Couldn't determine file position\");\n return NULL;\n }\n {\n int err;\n size_t tmp2 = Mat_SizeOf(matvar->data_type);\n if ( matvar->isComplex )\n tmp2 *= 2;\n err = SafeMulDims(matvar, &tmp2);\n if ( err ) {\n Mat_VarFree(matvar);\n Mat_Critical(\"Integer multiplication overflow\");\n return NULL;\n }\n\n nBytes = (long)tmp2;\n }\n (void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);\n\n return matvar;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Mat_VarReadNextInfo4", "_file_name": "src/mat4.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,\n OnigCompileInfo* ci, OnigErrorInfo* einfo)\n{\n int r;\n UChar *cpat, *cpat_end;\n\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n if (ci->pattern_enc != ci->target_enc) {\n r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end,\n &cpat, &cpat_end);\n if (r != 0) return r;\n }\n else {\n cpat = (UChar* )pattern;\n cpat_end = (UChar* )pattern_end;\n }\n\n *reg = (regex_t* )xmalloc(sizeof(regex_t));\n if (IS_NULL(*reg)) {\n r = ONIGERR_MEMORY;\n goto err2;\n }\n\n r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,\n ci->syntax);\n if (r != 0) goto err;\n\n r = onig_compile(*reg, cpat, cpat_end, einfo);\n if (r != 0) {\n err:\n onig_free(*reg);\n *reg = NULL;\n }\n\n err2:\n if (cpat != pattern) xfree(cpat);\n\n return r;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[274, 418]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[274, 418]]}, "_func_name": "onig_new_deluxe", "_file_name": "src/regext.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@api.route('/items/', methods=['GET'])\ndef get_item(item_id):\n sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)\n cursor = mysql.connection.cursor()\n cursor.execute(sql)\n data = cursor.fetchone()\n\n if data:\n item = {}\n for tup in zip([column[0] for column in cursor.description], data):\n item[tup[0]] = tup[1]\n else:\n return jsonify({\"error\": \"item not found\"}), 404\n\n return jsonify(item)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[75, 182]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[75, 182]]}, "_func_name": "get_item", "_file_name": "timf/api/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)\n{\n\tstruct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);\n\tbool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||\n\t\t ipv6_sk_rxinfo(sk);\n\n\tif (prepare && skb_rtable(skb)) {\n\t\t/* skb->cb is overloaded: prior to this point it is IP{6}CB\n\t\t * which has interface index (iif) as the first member of the\n\t\t * underlying inet{6}_skb_parm struct. This code then overlays\n\t\t * PKTINFO_SKB_CB and in_pktinfo also has iif as the first\n\t\t * element so the iif is picked up from the prior IPCB. If iif\n\t\t * is the loopback interface, then return the sending interface\n\t\t * (e.g., process binds socket to eth0 for Tx which is\n\t\t * redirected to loopback in the rtable/dst).\n\t\t */\n\t\tif (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)\n\t\t\tpktinfo->ipi_ifindex = inet_iif(skb);\n\n\t\tpktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);\n\t} else {\n\t\tpktinfo->ipi_ifindex = 0;\n\t\tpktinfo->ipi_spec_dst.s_addr = 0;\n\t}\n\tskb_dst_drop(skb);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[972, 992]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[972, 992]]}, "_func_name": "ipv4_pktinfo_prepare", "_file_name": "net/ipv4/ip_sockglue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)\n{\n mrb_value orig;\n mrb_value buf;\n struct mrb_io *fptr_copy;\n struct mrb_io *fptr_orig;\n mrb_bool failed = TRUE;\n\n mrb_get_args(mrb, \"o\", &orig);\n fptr_orig = io_get_open_fptr(mrb, orig);\n fptr_copy = (struct mrb_io *)DATA_PTR(copy);\n if (fptr_copy != NULL) {\n fptr_finalize(mrb, fptr_copy, FALSE);\n mrb_free(mrb, fptr_copy);\n }\n fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);\n\n DATA_TYPE(copy) = &mrb_io_type;\n DATA_PTR(copy) = fptr_copy;\n\n buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, \"@buf\"));\n mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, \"@buf\"), buf);\n\n fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);\n if (failed) {\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd);\n\n if (fptr_orig->fd2 != -1) {\n fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);\n if (failed) {\n close(fptr_copy->fd);\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd2);\n }\n\n fptr_copy->pid = fptr_orig->pid;\n fptr_copy->readable = fptr_orig->readable;\n fptr_copy->writable = fptr_orig->writable;\n fptr_copy->sync = fptr_orig->sync;\n fptr_copy->is_socket = fptr_orig->is_socket;\n\n return copy;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mrb_io_initialize_copy", "_file_name": "mrbgems/mruby-io/src/io.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s,\n AUTODETECT_RSP_PDU* autodetectRspPdu)\n{\n\tBOOL success = TRUE;\n\n\tif (autodetectRspPdu->headerLength != 0x0E)\n\t\treturn FALSE;\n\n\tWLog_VRB(AUTODETECT_TAG, \"received Bandwidth Measure Results PDU\");\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */\n\tStream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */\n\n\tif (rdp->autodetect->bandwidthMeasureTimeDelta > 0)\n\t\trdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 /\n\t\t rdp->autodetect->bandwidthMeasureTimeDelta;\n\telse\n\t\trdp->autodetect->netCharBandwidth = 0;\n\n\tIFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context,\n\t autodetectRspPdu->sequenceNumber);\n\treturn success;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[327, 421]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[327, 421]]}, "_func_name": "autodetect_recv_bandwidth_measure_results", "_file_name": "libfreerdp/core/autodetect.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n if (output_index >= src->num_outputs()) {\n return errors::InvalidArgument(\n \"Output \", output_index, \" of node \", src->name(),\n \" does not exist. Node only has \", src->num_outputs(), \" outputs.\");\n }\n if (input_index >= dst->num_inputs()) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(),\n \" does not exist. Node only has \", dst->num_inputs(), \" inputs.\");\n }\n\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tensorflow::GraphConstructor::MakeEdge", "_file_name": "tensorflow/core/common_runtime/graph_constructor.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def add_user(username, password):\n encPass = crypt.crypt(password,\"22\")\n os.system(\"useradd -G docker,wheel -p \"+encPass+\" \"+username)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[75, 140]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[75, 140]]}, "_func_name": "add_user", "_file_name": "vuedj/configtitania/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mode_input(self, request):\n \"\"\"\n This is called by render_POST when the client\n is sending data to the server.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n self.last_alive[csessid] = (time.time(), False)\n sess = self.sessionhandler.sessions_from_csessid(csessid)\n if sess:\n sess = sess[0]\n cmdarray = json.loads(cgi.escape(request.args.get('data')[0]))\n sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]})\n return '\"\"'", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mode_input", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid)\n{\n\tint frameSize = afGetVirtualFrameSize(infile, trackid, 1);\n\n\tconst int kBufferFrameCount = 65536;\n\tvoid *buffer = malloc(kBufferFrameCount * frameSize);\n\n\tAFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);\n\tAFframecount totalFramesWritten = 0;\n\n\tbool success = true;\n\n\twhile (totalFramesWritten < totalFrames)\n\t{\n\t\tAFframecount framesToRead = totalFrames - totalFramesWritten;\n\t\tif (framesToRead > kBufferFrameCount)\n\t\t\tframesToRead = kBufferFrameCount;\n\n\t\tAFframecount framesRead = afReadFrames(infile, trackid, buffer,\n\t\t\tframesToRead);\n\n\t\tif (framesRead < framesToRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad read of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tAFframecount framesWritten = afWriteFrames(outfile, trackid, buffer,\n\t\t\tframesRead);\n\n\t\tif (framesWritten < framesRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad write of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\ttotalFramesWritten += framesWritten;\n\t}\n\n\tfree(buffer);\n\n\treturn success;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[139, 232]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[139, 232]]}, "_func_name": "copyaudiodata", "_file_name": "sfcommands/sfconvert.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_requested_month_for_inverter(self, inverter_serial, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, DayYield AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN ? AND ? AND Serial=?;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query, (month_start, month_end, inverter_serial)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM MonthData \n WHERE Serial=?;\n '''\n\n self.c.execute(query, (inverter_serial,))\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_requested_month_for_inverter", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @property\n async def html_content(self):\n content = markupsafe.escape(await self.content)\n if not content:\n return ''\n return markdown(content)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "html_content", "_file_name": "models/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "TfLiteStatus Subgraph::Invoke() {\n if (!consistent_) {\n ReportError(\"Invoke called on model that is not consistent.\");\n return kTfLiteError;\n }\n\n TfLiteStatus status = kTfLiteOk;\n if (state_ == kStateUninvokable) {\n ReportError(\"Invoke called on model that is not ready.\");\n return kTfLiteError;\n } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {\n ReportError(\"Non-persistent memory is not available.\");\n return kTfLiteError;\n }\n\n // This is only needed for UseNNAPI(true);\n if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) {\n TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate()));\n // only need to modify the graph once upon the first invocation.\n applied_nnapi_delegate_ = true;\n }\n\n // Invocations are always done in node order.\n // Note that calling Invoke repeatedly will cause the original memory plan to\n // be reused, unless either ResizeInputTensor() or AllocateTensors() has been\n // called.\n for (int execution_plan_index = 0;\n execution_plan_index < execution_plan_.size(); execution_plan_index++) {\n if (execution_plan_index == next_execution_plan_index_to_prepare_) {\n TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());\n TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >=\n execution_plan_index);\n }\n int node_index = execution_plan_[execution_plan_index];\n TfLiteNode& node = nodes_and_registration_[node_index].first;\n const TfLiteRegistration& registration =\n nodes_and_registration_[node_index].second;\n\n const char* op_name = nullptr;\n if (profiler_) op_name = GetTFLiteOpName(registration);\n TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index);\n\n // TODO(ycling): This is an extra loop through inputs to check if the data\n // need to be copied from Delegate buffer to raw memory, which is often not\n // needed. We may want to cache this in prepare to know if this needs to be\n // done for a node or not.\n for (int i = 0; i < node.inputs->size; ++i) {\n int tensor_index = node.inputs->data[i];\n if (tensor_index == kTfLiteOptionalTensor) {\n continue;\n }\n TfLiteTensor* tensor = &tensors_[tensor_index];\n if (tensor->delegate && tensor->delegate != node.delegate &&\n tensor->data_is_stale) {\n TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index));\n }\n }\n\n if (check_cancelled_func_ != nullptr &&\n check_cancelled_func_(cancellation_data_)) {\n ReportError(\"Client requested cancel during Invoke()\");\n return kTfLiteError;\n }\n\n EnsureTensorsVectorCapacity();\n tensor_resized_since_op_invoke_ = false;\n if (OpInvoke(registration, &node) != kTfLiteOk) {\n return ReportOpError(&context_, node, registration, node_index,\n \"failed to invoke\");\n }\n\n // Force execution prep for downstream ops if the latest op triggered the\n // resize of a dynamic tensor.\n if (tensor_resized_since_op_invoke_ &&\n HasDynamicTensor(context_, node.outputs)) {\n next_execution_plan_index_to_prepare_ = execution_plan_index + 1;\n\n // This happens when an intermediate dynamic tensor is resized.\n // We don't have to prepare all the ops, but we need to recompute\n // the allocation plan.\n if (next_execution_plan_index_to_plan_allocation_ >\n next_execution_plan_index_to_prepare_) {\n next_execution_plan_index_to_plan_allocation_ =\n next_execution_plan_index_to_prepare_;\n if (memory_planner_) {\n TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter(\n next_execution_plan_index_to_plan_allocation_ - 1));\n }\n }\n }\n }\n\n return status;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[2461, 2467]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2461, 2467]]}, "_func_name": "tflite::Subgraph::Invoke", "_file_name": "tensorflow/lite/core/subgraph.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef commentcounts(context, filediff, interfilediff=None):\n \"\"\"\n Returns a JSON array of current comments for a filediff, sorted by\n line number.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n comment_id The ID of the comment\n text The text of the comment\n line The first line number\n num_lines The number of lines this comment spans\n user A dictionary containing \"username\" and \"name\" keys\n for the user\n url The URL to the comment\n localdraft True if this is the current user's draft comment\n =========== ==================================================\n \"\"\"\n comment_dict = {}\n user = context.get('user', None)\n\n if interfilediff:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff=interfilediff)\n else:\n query = Comment.objects.filter(filediff=filediff,\n interfilediff__isnull=True)\n\n for comment in query:\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n key = (comment.first_line, comment.num_lines)\n\n comment_dict.setdefault(key, []).append({\n 'comment_id': comment.id,\n 'text': comment.text,\n 'line': comment.first_line,\n 'num_lines': comment.num_lines,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n #'timestamp': comment.timestamp,\n 'url': comment.get_review_url(),\n 'localdraft': review.user == user and \\\n not review.public,\n })\n\n comments_array = []\n\n for key, value in comment_dict.iteritems():\n comments_array.append({\n 'linenum': key[0],\n 'num_lines': key[1],\n 'comments': value,\n })\n\n comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or\n cmp(x['num_lines'], y['num_lines'])))\n\n return simplejson.dumps(comments_array)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1548, 1586]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1548, 1586]]}, "_func_name": "commentcounts", "_file_name": "reviewboard/reviews/templatetags/reviewtags.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char *enl_ipc_get(const char *msg_data)\n{\n\n\tstatic char *message = NULL;\n\tstatic unsigned short len = 0;\n\tchar buff[13], *ret_msg = NULL;\n\tregister unsigned char i;\n\tunsigned char blen;\n\n\tif (msg_data == IPC_TIMEOUT) {\n\t\treturn(IPC_TIMEOUT);\n\t}\n\tfor (i = 0; i < 12; i++) {\n\t\tbuff[i] = msg_data[i];\n\t}\n\tbuff[12] = 0;\n\tblen = strlen(buff);\n\tif (message != NULL) {\n\t\tlen += blen;\n\t\tmessage = (char *) erealloc(message, len + 1);\n\t\tstrcat(message, buff);\n\t} else {\n\t\tlen = blen;\n\t\tmessage = (char *) emalloc(len + 1);\n\t\tstrcpy(message, buff);\n\t}\n\tif (blen < 12) {\n\t\tret_msg = message;\n\t\tmessage = NULL;\n\t\tD((\"Received complete reply: \\\"%s\\\"\\n\", ret_msg));\n\t}\n\treturn(ret_msg);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[73, 105]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[73, 105]]}, "_func_name": "enl_ipc_get", "_file_name": "src/wallpaper.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):\n # XXX see if we want to keep an external call here\n if verbose:\n zipoptions = \"-r\"\n else:\n zipoptions = \"-rq\"\n from distutils.errors import DistutilsExecError\n from distutils.spawn import spawn\n try:\n spawn([\"zip\", zipoptions, zip_filename, base_dir], dry_run=dry_run)\n except DistutilsExecError:\n # XXX really should distinguish between \"couldn't find\n # external 'zip' command\" and \"zip failed\".\n raise ExecError, \\\n (\"unable to create zip file '%s': \"\n \"could neither import the 'zipfile' module nor \"\n \"find a standalone zip utility\") % zip_filename", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 78], [212, 302], [311, 418]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 78], [212, 302], [311, 418]]}, "_func_name": "_call_external_zip", "_file_name": "Lib/shutil.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def getCommentsLike(self,commentid):\n sqlText=\"select userid from comment_like where commentid=%d\"%(commentid)\n result=sql.queryDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[41, 122]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[41, 122]]}, "_func_name": "getCommentsLike", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int mif_process_cmpt(mif_hdr_t *hdr, char *buf)\n{\n\tjas_tvparser_t *tvp;\n\tmif_cmpt_t *cmpt;\n\tint id;\n\n\tcmpt = 0;\n\ttvp = 0;\n\n\tif (!(cmpt = mif_cmpt_create())) {\n\t\tgoto error;\n\t}\n\tcmpt->tlx = 0;\n\tcmpt->tly = 0;\n\tcmpt->sampperx = 0;\n\tcmpt->samppery = 0;\n\tcmpt->width = 0;\n\tcmpt->height = 0;\n\tcmpt->prec = 0;\n\tcmpt->sgnd = -1;\n\tcmpt->data = 0;\n\n\tif (!(tvp = jas_tvparser_create(buf))) {\n\t\tgoto error;\n\t}\n\twhile (!(id = jas_tvparser_next(tvp))) {\n\t\tswitch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags,\n\t\t jas_tvparser_gettag(tvp)))->id) {\n\t\tcase MIF_TLX:\n\t\t\tcmpt->tlx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_TLY:\n\t\t\tcmpt->tly = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_WIDTH:\n\t\t\tcmpt->width = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_HEIGHT:\n\t\t\tcmpt->height = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_HSAMP:\n\t\t\tcmpt->sampperx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_VSAMP:\n\t\t\tcmpt->samppery = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_PREC:\n\t\t\tcmpt->prec = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_SGND:\n\t\t\tcmpt->sgnd = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_DATA:\n\t\t\tif (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!cmpt->sampperx || !cmpt->samppery) {\n\t\tgoto error;\n\t}\n\tif (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) {\n\t\tgoto error;\n\t}\n\tjas_tvparser_destroy(tvp);\n\treturn 0;\n\nerror:\n\tif (cmpt) {\n\t\tmif_cmpt_destroy(cmpt);\n\t}\n\tif (tvp) {\n\t\tjas_tvparser_destroy(tvp);\n\t}\n\treturn -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mif_process_cmpt", "_file_name": "src/libjasper/mif/mif_cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def fetch_issue(cursor, id):\n \"\"\"\n Fetch an issue by id along with its tags. Returns None if no issue\n with the specified id exists in the database.\n \"\"\"\n cursor.execute(\"\"\"\n SELECT\n issue.id,\n issue.title,\n issue.description,\n tag.namespace,\n tag.predicate,\n tag.value\n FROM\n issue LEFT JOIN tag\n ON issue.id = tag.issue_id\n WHERE\n issue.id = ?\n \"\"\", (id,))\n\n issue = None\n for row in cursor:\n if issue is None:\n issue = {\n \"id\": row[\"id\"],\n \"title\": row[\"title\"],\n \"description\": row[\"description\"],\n \"tags\": [],\n }\n # If tag exists in row, add to issue.\n if row[\"value\"]:\n issue[\"tags\"].append({\n \"namespace\": row[\"namespace\"],\n \"predicate\": row[\"predicate\"],\n \"value\": row[\"value\"],\n })\n\n return issue", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fetch_issue", "_file_name": "server/server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,\n\t\t\t struct netlink_ext_ack *extack)\n{\n\tstruct net *net = sock_net(in_skb->sk);\n\tstruct rtmsg *rtm;\n\tstruct nlattr *tb[RTA_MAX+1];\n\tstruct fib_result res = {};\n\tstruct rtable *rt = NULL;\n\tstruct flowi4 fl4;\n\t__be32 dst = 0;\n\t__be32 src = 0;\n\tu32 iif;\n\tint err;\n\tint mark;\n\tstruct sk_buff *skb;\n\tu32 table_id = RT_TABLE_MAIN;\n\tkuid_t uid;\n\n\terr = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,\n\t\t\t extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\trtm = nlmsg_data(nlh);\n\n\tskb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);\n\tif (!skb) {\n\t\terr = -ENOBUFS;\n\t\tgoto errout;\n\t}\n\n\t/* Reserve room for dummy headers, this skb can pass\n\t through good chunk of routing engine.\n\t */\n\tskb_reset_mac_header(skb);\n\tskb_reset_network_header(skb);\n\n\tsrc = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;\n\tdst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;\n\tiif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;\n\tmark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;\n\tif (tb[RTA_UID])\n\t\tuid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));\n\telse\n\t\tuid = (iif ? INVALID_UID : current_uid());\n\n\t/* Bugfix: need to give ip_route_input enough of an IP header to\n\t * not gag.\n\t */\n\tip_hdr(skb)->protocol = IPPROTO_UDP;\n\tip_hdr(skb)->saddr = src;\n\tip_hdr(skb)->daddr = dst;\n\n\tskb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));\n\n\tmemset(&fl4, 0, sizeof(fl4));\n\tfl4.daddr = dst;\n\tfl4.saddr = src;\n\tfl4.flowi4_tos = rtm->rtm_tos;\n\tfl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;\n\tfl4.flowi4_mark = mark;\n\tfl4.flowi4_uid = uid;\n\n\trcu_read_lock();\n\n\tif (iif) {\n\t\tstruct net_device *dev;\n\n\t\tdev = dev_get_by_index_rcu(net, iif);\n\t\tif (!dev) {\n\t\t\terr = -ENODEV;\n\t\t\tgoto errout_free;\n\t\t}\n\n\t\tskb->protocol\t= htons(ETH_P_IP);\n\t\tskb->dev\t= dev;\n\t\tskb->mark\t= mark;\n\t\terr = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,\n\t\t\t\t\t dev, &res);\n\n\t\trt = skb_rtable(skb);\n\t\tif (err == 0 && rt->dst.error)\n\t\t\terr = -rt->dst.error;\n\t} else {\n\t\trt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);\n\t\terr = 0;\n\t\tif (IS_ERR(rt))\n\t\t\terr = PTR_ERR(rt);\n\t\telse\n\t\t\tskb_dst_set(skb, &rt->dst);\n\t}\n\n\tif (err)\n\t\tgoto errout_free;\n\n\tif (rtm->rtm_flags & RTM_F_NOTIFY)\n\t\trt->rt_flags |= RTCF_NOTIFY;\n\n\tif (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)\n\t\ttable_id = rt->rt_table_id;\n\n\tif (rtm->rtm_flags & RTM_F_FIB_MATCH)\n\t\terr = fib_dump_info(skb, NETLINK_CB(in_skb).portid,\n\t\t\t\t nlh->nlmsg_seq, RTM_NEWROUTE, table_id,\n\t\t\t\t rt->rt_type, res.prefix, res.prefixlen,\n\t\t\t\t fl4.flowi4_tos, res.fi, 0);\n\telse\n\t\terr = rt_fill_info(net, dst, src, table_id, &fl4, skb,\n\t\t\t\t NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);\n\tif (err < 0)\n\t\tgoto errout_free;\n\n\trcu_read_unlock();\n\n\terr = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);\nerrout:\n\treturn err;\n\nerrout_free:\n\trcu_read_unlock();\n\tkfree_skb(skb);\n\tgoto errout;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[2323, 2362], [2548, 2554]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2323, 2362], [2548, 2554]]}, "_func_name": "inet_rtm_getroute", "_file_name": "net/ipv4/route.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)\n{\n clear();\n m_torrent = torrent;\n downloaded_pieces->setTorrent(m_torrent);\n pieces_availability->setTorrent(m_torrent);\n if (!m_torrent) return;\n\n // Save path\n updateSavePath(m_torrent);\n // Hash\n hash_lbl->setText(m_torrent->hash());\n PropListModel->model()->clear();\n if (m_torrent->hasMetadata()) {\n // Creation date\n lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));\n\n label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));\n\n // Comment\n comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment())));\n\n // URL seeds\n loadUrlSeeds();\n\n label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator()));\n\n // List files in torrent\n PropListModel->model()->setupModelData(m_torrent->info());\n filesList->setExpanded(PropListModel->index(0, 0), true);\n\n // Load file priorities\n PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());\n }\n // Load dynamic data\n loadDynamicData();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PropertiesWidget::loadTorrentInfos", "_file_name": "src/gui/properties/propertieswidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static ExprList *exprListAppendList(\n Parse *pParse, /* Parsing context */\n ExprList *pList, /* List to which to append. Might be NULL */\n ExprList *pAppend, /* List of values to append. Might be NULL */\n int bIntToNull\n){\n if( pAppend ){\n int i;\n int nInit = pList ? pList->nExpr : 0;\n for(i=0; inExpr; i++){\n Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);\n assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n if( bIntToNull && pDup && pDup->op==TK_INTEGER ){\n pDup->op = TK_NULL;\n pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);\n pDup->u.zToken = 0;\n }\n pList = sqlite3ExprListAppend(pParse, pList, pDup);\n if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;\n }\n }\n return pList;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "exprListAppendList", "_file_name": "src/window.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def all_deposits(self,coin):\n sql = \"SELECT * FROM deposits WHERE coin='%s'\"\n self.cursor.execute(sql, (coin,))\n return self.cursor.fetchall()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "all_deposits", "_file_name": "deposit.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n const CString sSkin = sSkinName.Replace_n(\"/\", \"_\").Replace_n(\".\", \"_\");\n\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkin;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkin;\n }\n }\n\n return sRet + \"/\";\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "CWebSock::GetSkinPath", "_file_name": "src/WebModules.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "choose_volume(struct archive_read *a, struct iso9660 *iso9660)\n{\n\tstruct file_info *file;\n\tint64_t skipsize;\n\tstruct vd *vd;\n\tconst void *block;\n\tchar seenJoliet;\n\n\tvd = &(iso9660->primary);\n\tif (!iso9660->opt_support_joliet)\n\t\tiso9660->seenJoliet = 0;\n\tif (iso9660->seenJoliet &&\n\t\tvd->location > iso9660->joliet.location)\n\t\t/* This condition is unlikely; by way of caution. */\n\t\tvd = &(iso9660->joliet);\n\n\tskipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;\n\tskipsize = __archive_read_consume(a, skipsize);\n\tif (skipsize < 0)\n\t\treturn ((int)skipsize);\n\tiso9660->current_position = skipsize;\n\n\tblock = __archive_read_ahead(a, vd->size, NULL);\n\tif (block == NULL) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Failed to read full block when scanning \"\n\t\t \"ISO9660 directory list\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\n\t/*\n\t * While reading Root Directory, flag seenJoliet must be zero to\n\t * avoid converting special name 0x00(Current Directory) and\n\t * next byte to UCS2.\n\t */\n\tseenJoliet = iso9660->seenJoliet;/* Save flag. */\n\tiso9660->seenJoliet = 0;\n\tfile = parse_file_info(a, NULL, block);\n\tif (file == NULL)\n\t\treturn (ARCHIVE_FATAL);\n\tiso9660->seenJoliet = seenJoliet;\n\n\t/*\n\t * If the iso image has both RockRidge and Joliet, we preferentially\n\t * use RockRidge Extensions rather than Joliet ones.\n\t */\n\tif (vd == &(iso9660->primary) && iso9660->seenRockridge\n\t && iso9660->seenJoliet)\n\t\tiso9660->seenJoliet = 0;\n\n\tif (vd == &(iso9660->primary) && !iso9660->seenRockridge\n\t && iso9660->seenJoliet) {\n\t\t/* Switch reading data from primary to joliet. */\n\t\tvd = &(iso9660->joliet);\n\t\tskipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;\n\t\tskipsize -= iso9660->current_position;\n\t\tskipsize = __archive_read_consume(a, skipsize);\n\t\tif (skipsize < 0)\n\t\t\treturn ((int)skipsize);\n\t\tiso9660->current_position += skipsize;\n\n\t\tblock = __archive_read_ahead(a, vd->size, NULL);\n\t\tif (block == NULL) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Failed to read full block when scanning \"\n\t\t\t \"ISO9660 directory list\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tiso9660->seenJoliet = 0;\n\t\tfile = parse_file_info(a, NULL, block);\n\t\tif (file == NULL)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tiso9660->seenJoliet = seenJoliet;\n\t}\n\n\t/* Store the root directory in the pending list. */\n\tif (add_entry(a, iso9660, file) != ARCHIVE_OK)\n\t\treturn (ARCHIVE_FATAL);\n\tif (iso9660->seenRockridge) {\n\t\ta->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;\n\t\ta->archive.archive_format_name =\n\t\t \"ISO9660 with Rockridge extensions\";\n\t}\n\n\treturn (ARCHIVE_OK);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "choose_volume", "_file_name": "libarchive/archive_read_support_format_iso9660.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8* ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4)\n\treturn 0;\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer (on the other hand, the Python part of the driver\n makes sure this is always the case) */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr))\n\treturn 0;\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (I16(ptr+4) != 0xF1FA) {\n\tstate->errcode = IMAGING_CODEC_UNKNOWN;\n\treturn -1;\n }\n\n chunks = I16(ptr+6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n\tUINT8* data;\n\tif (bytes < 10) {\n\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t return -1;\n\t}\n\tdata = ptr + 6;\n\tswitch (I16(ptr+4)) {\n\tcase 4: case 11:\n\t /* FLI COLOR chunk */\n\t break; /* ignored; handled by Python code */\n\tcase 7:\n\t /* FLI SS2 chunk (word delta) */\n\t lines = I16(data); data += 2;\n\t for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tint p, packets;\n\t\tpackets = I16(data); data += 2;\n\t\twhile (packets & 0x8000) {\n\t\t /* flag word */\n\t\t if (packets & 0x4000) {\n\t\t\ty += 65536 - packets; /* skip lines */\n\t\t\tif (y >= state->ysize) {\n\t\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t\t return -1;\n\t\t\t}\n\t\t\tbuf = (UINT8*) im->image[y];\n\t\t } else {\n\t\t\t/* store last byte (used if line width is odd) */\n\t\t\tbuf[state->xsize-1] = (UINT8) packets;\n\t\t }\n\t\t packets = I16(data); data += 2;\n\t\t}\n\t\tfor (p = x = 0; p < packets; p++) {\n\t\t x += data[0]; /* pixel skip */\n\t\t if (data[1] >= 128) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i + i > state->xsize)\n\t\t\t break;\n\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t buf[x++] = data[2];\n\t\t\t buf[x++] = data[3];\n\t\t\t}\n\t\t\tdata += 2 + 2;\n\t\t } else {\n\t\t\ti = 2 * (int) data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(buf + x, data + 2, i);\n\t\t\tdata += 2 + i;\n\t\t\tx += i;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (l < lines) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 12:\n\t /* FLI LC chunk (byte delta) */\n\t y = I16(data); ymax = y + I16(data+2); data += 4;\n\t for (; y < ymax && y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tint p, packets = *data++;\n\t\tfor (p = x = 0; p < packets; p++, x += i) {\n\t\t x += data[0]; /* skip pixels */\n\t\t if (data[1] & 0x80) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemset(out + x, data[2], i);\n\t\t\tdata += 3;\n\t\t } else {\n\t\t\ti = data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(out + x, data + 2, i);\n\t\t\tdata += i + 2;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (y < ymax) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 13:\n\t /* FLI BLACK chunk */\n\t for (y = 0; y < state->ysize; y++)\n\t\tmemset(im->image[y], 0, state->xsize);\n\t break;\n\tcase 15:\n\t /* FLI BRUN chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tdata += 1; /* ignore packetcount byte */\n\t\tfor (x = 0; x < state->xsize; x += i) {\n\t\t if (data[0] & 0x80) {\n\t\t\ti = 256 - data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemcpy(out + x, data + 1, i);\n\t\t\tdata += i + 1;\n\t\t } else {\n\t\t\ti = data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemset(out + x, data[1], i);\n\t\t\tdata += 2;\n\t\t }\n\t\t}\n\t\tif (x != state->xsize) {\n\t\t /* didn't unpack whole line */\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t return -1;\n\t\t}\n\t }\n\t break;\n\tcase 16:\n\t /* COPY chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tmemcpy(buf, data, state->xsize);\n\t\tdata += state->xsize;\n\t }\n\t break;\n\tcase 18:\n\t /* PSTAMP chunk */\n\t break; /* ignored */\n\tdefault:\n\t /* unknown chunk */\n\t /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n\t state->errcode = IMAGING_CODEC_UNKNOWN;\n\t return -1;\n\t}\n\tadvance = I32(ptr);\n\tptr += advance;\n\tbytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[364, 480]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[364, 480]]}, "_func_name": "ImagingFliDecode", "_file_name": "src/libImaging/FliDecode.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_queryset(self, **kwargs):\n queryset = Article.objects.order_by('-time')\n for i in queryset:\n i.md = safe_md(i.content)\n\n return queryset", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_queryset", "_file_name": "app/Index/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:\n \"\"\" Get all projects a user has mapped on \"\"\"\n\n # This query looks scary, but we're really just creating an outer join between the query that gets the\n # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to\n # handle cases where users have only validated tasks on a project, or only mapped on a project.\n sql = '''SELECT p.id,\n p.status,\n p.default_locale,\n c.mapped,\n c.validated,\n st_asgeojson(p.centroid)\n FROM projects p,\n (SELECT coalesce(v.project_id, m.project_id) project_id,\n coalesce(v.validated, 0) validated,\n coalesce(m.mapped, 0) mapped\n FROM (SELECT t.project_id,\n count (t.validated_by) validated\n FROM tasks t\n WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n AND t.validated_by = :user_id\n GROUP BY t.project_id, t.validated_by) v\n FULL OUTER JOIN\n (SELECT t.project_id,\n count(t.mapped_by) mapped\n FROM tasks t\n WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n AND t.mapped_by = :user_id\n GROUP BY t.project_id, t.mapped_by) m\n ON v.project_id = m.project_id) c\n WHERE p.id = c.project_id ORDER BY p.id DESC'''\n\n results = db.engine.execute(text(sql), user_id=user_id)\n\n if results.rowcount == 0:\n raise NotFound()\n\n mapped_projects_dto = UserMappedProjectsDTO()\n for row in results:\n mapped_project = MappedProject()\n mapped_project.project_id = row[0]\n mapped_project.status = ProjectStatus(row[1]).name\n mapped_project.tasks_mapped = row[3]\n mapped_project.tasks_validated = row[4]\n mapped_project.centroid = geojson.loads(row[5])\n\n project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])\n mapped_project.name = project_info.name\n\n mapped_projects_dto.mapped_projects.append(mapped_project)\n\n return mapped_projects_dto", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_mapped_projects", "_file_name": "server/models/postgis/user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def findNPC(race, classe, sex,level):\n\tc, conn = getConnection()\n\tdate = now()\n\t#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;\n\tc.execute(\"select image, avg(legit) as l FROM npc WHERE race=(?) AND class=(?) AND sex=(?) GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC\",(race,classe,sex))\n\tconn.commit()\n\tout = c.fetchmany(5)\n\tconn.close()\n\treturn out", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "findNPC", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _map_vol_to_host(self, volume_name, host_name):\n \"\"\"Create a mapping between a volume to a host.\"\"\"\n\n LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to '\n 'host %(host_name)s')\n % {'volume_name': volume_name, 'host_name': host_name})\n\n # Check if this volume is already mapped to this host\n mapping_data = self._get_hostvdisk_mappings(host_name)\n\n mapped_flag = False\n result_lun = '-1'\n if volume_name in mapping_data:\n mapped_flag = True\n result_lun = mapping_data[volume_name]['SCSI_id']\n else:\n lun_used = [int(v['SCSI_id']) for v in mapping_data.values()]\n lun_used.sort()\n # Assume all luns are taken to this point, and then try to find\n # an unused one\n result_lun = str(len(lun_used))\n for index, n in enumerate(lun_used):\n if n > index:\n result_lun = str(index)\n break\n\n # Volume is not mapped to host, create a new LUN\n if not mapped_flag:\n ssh_cmd = ['svctask', 'mkvdiskhostmap', '-host', host_name,\n '-scsi', result_lun, volume_name]\n out, err = self._run_ssh(ssh_cmd, check_exit_code=False)\n if err and err.startswith('CMMVC6071E'):\n if not self.configuration.storwize_svc_multihostmap_enabled:\n LOG.error(_('storwize_svc_multihostmap_enabled is set '\n 'to False, Not allow multi host mapping'))\n exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\\\n 'was not created because the VDisk is '\\\n 'already mapped to a host.\\n\"'\n raise exception.CinderException(data=exception_msg)\n\n for i in range(len(ssh_cmd)):\n if ssh_cmd[i] == 'mkvdiskhostmap':\n ssh_cmd.insert(i + 1, '-force')\n\n # try to map one volume to multiple hosts\n out, err = self._run_ssh(ssh_cmd)\n LOG.warn(_('volume %s mapping to multi host') % volume_name)\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n else:\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume '\n '%(volume_name)s, host %(host_name)s') %\n {'result_lun': result_lun,\n 'volume_name': volume_name,\n 'host_name': host_name})\n return result_lun", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_map_vol_to_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void * CAPSTONE_API cs_winkernel_malloc(size_t size)\n{\n\t// Disallow zero length allocation because they waste pool header space and,\n\t// in many cases, indicate a potential validation issue in the calling code.\n\tNT_ASSERT(size);\n\n\t// FP; a use of NonPagedPool is required for Windows 7 support\n#pragma prefast(suppress : 30030)\t\t// Allocating executable POOL_TYPE memory\n\tsize_t number_of_bytes = 0;\n\tCS_WINKERNEL_MEMBLOCK *block = NULL;\n\t// A specially crafted size value can trigger the overflow.\n\t// If the sum in a value that overflows or underflows the capacity of the type,\n\t// the function returns NULL.\n\tif (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) {\n\t\treturn NULL;\n\t}\n\tblock = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(\n\t\t\tNonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG);\n\tif (!block) {\n\t\treturn NULL;\n\t}\n\tblock->size = size;\n\n\treturn block->data;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cs_winkernel_malloc", "_file_name": "windows/winkernel_mm.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_files(self, submit_id, password=None, astree=False):\n \"\"\"\n Returns files from a submitted analysis.\n @param password: The password to unlock container archives with\n @param astree: sflock option; determines the format in which the files are returned\n @return: A tree of files\n \"\"\"\n submit = Database().view_submit(submit_id)\n files, duplicates = [], []\n\n for data in submit.data[\"data\"]:\n if data[\"type\"] == \"file\":\n filename = Storage.get_filename_from_path(data[\"data\"])\n filepath = os.path.join(submit.tmp_path, data[\"data\"])\n filedata = open(filepath, \"rb\").read()\n\n unpacked = sflock.unpack(\n filepath=filename, contents=filedata,\n password=password, duplicates=duplicates\n )\n\n if astree:\n unpacked = unpacked.astree()\n\n files.append(unpacked)\n elif data[\"type\"] == \"url\":\n files.append({\n \"filename\": data[\"data\"],\n \"filepath\": \"\",\n \"relapath\": \"\",\n \"selected\": True,\n \"size\": 0,\n \"type\": \"url\",\n \"package\": \"ie\",\n \"extrpath\": [],\n \"duplicate\": False,\n \"children\": [],\n \"mime\": \"text/html\",\n \"finger\": {\n \"magic_human\": \"url\",\n \"magic\": \"url\"\n }\n })\n else:\n raise RuntimeError(\n \"Unknown data entry type: %s\" % data[\"type\"]\n )\n\n return {\n \"files\": files,\n \"path\": submit.tmp_path,\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[574, 700], [743, 862], [1776, 1867]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[574, 700], [743, 862], [1776, 1867]]}, "_func_name": "get_files", "_file_name": "cuckoo/core/submit.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _run_ssh(self, cmd_list, check_exit=True, attempts=1):\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n\n if not self.sshpool:\n self.sshpool = utils.SSHPool(self.config.san_ip,\n self.config.san_ssh_port,\n self.config.ssh_conn_timeout,\n self.config.san_login,\n password=self.config.san_password,\n privatekey=\n self.config.san_private_key,\n min_size=\n self.config.ssh_min_pool_conn,\n max_size=\n self.config.ssh_max_pool_conn)\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return self._ssh_execute(ssh, command,\n check_exit_code=check_exit)\n except Exception as e:\n LOG.error(e)\n greenthread.sleep(randint(20, 500) / 100.0)\n msg = (_(\"SSH Command failed after '%(total_attempts)r' \"\n \"attempts : '%(command)s'\") %\n {'total_attempts': total_attempts, 'command': command})\n raise paramiko.SSHException(msg)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running ssh command: %s\") % command)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_run_ssh", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_title_from_youtube_url(url):\n try:\n output = str(subprocess.check_output('youtube-dl --get-title %s --no-warnings' % url, stderr=subprocess.STDOUT,\n shell=True)).strip()\n except subprocess.CalledProcessError as ex:\n output = str(ex.output).strip()\n except OSError as ex:\n output = 'youtube-dl not found: %s' % ex\n except Exception as ex:\n output = 'Something bad happened: %s' % ex\n return remove_commas_from_string(output)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[46, 232]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[46, 232]]}, "_func_name": "get_title_from_youtube_url", "_file_name": "src/util.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void ImportEPUB::ExtractContainer()\n{\n int res = 0;\n if (!cp437) {\n cp437 = new QCodePage437Codec();\n }\n#ifdef Q_OS_WIN32\n zlib_filefunc64_def ffunc;\n fill_win32_filefunc64W(&ffunc);\n unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);\n#else\n unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());\n#endif\n\n if (zfile == NULL) {\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot unzip EPUB: %1\")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));\n }\n\n res = unzGoToFirstFile(zfile);\n\n if (res == UNZ_OK) {\n do {\n // Get the name of the file in the archive.\n char file_name[MAX_PATH] = {0};\n unz_file_info64 file_info;\n unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);\n QString qfile_name;\n QString cp437_file_name;\n qfile_name = QString::fromUtf8(file_name);\n if (!(file_info.flag & (1<<11))) {\n // General purpose bit 11 says the filename is utf-8 encoded. If not set then\n // IBM 437 encoding might be used.\n cp437_file_name = cp437->toUnicode(file_name);\n }\n\n // If there is no file name then we can't do anything with it.\n if (!qfile_name.isEmpty()) {\n\n\t // for security reasons we need the file path to always be inside the \n // target folder and not outside, so we will remove all relative upward \n // paths segments \"..\" from the file path before prepending the target \n // folder to create the final target path\n\t qfile_name = qfile_name.replace(\"../\",\"\");\n cp437_file_name = cp437_file_name.replace(\"../\",\"\");\n\n // We use the dir object to create the path in the temporary directory.\n // Unfortunately, we need a dir ojbect to do this as it's not a static function.\n QDir dir(m_ExtractedFolderPath);\n // Full file path in the temporary directory.\n QString file_path = m_ExtractedFolderPath + \"/\" + qfile_name;\n QFileInfo qfile_info(file_path);\n\n // Is this entry a directory?\n if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {\n dir.mkpath(qfile_name);\n continue;\n } else {\n dir.mkpath(qfile_info.path());\n\t\t // add it to the list of files found inside the zip\n\t\t if (cp437_file_name.isEmpty()) {\n\t\t m_ZipFilePaths << qfile_name;\n\t\t } else {\n m_ZipFilePaths << cp437_file_name;\n\t\t }\n }\n\n // Open the file entry in the archive for reading.\n if (unzOpenCurrentFile(zfile) != UNZ_OK) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // Open the file on disk to write the entry in the archive to.\n QFile entry(file_path);\n\n if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // Buffered reading and writing.\n char buff[BUFF_SIZE] = {0};\n int read = 0;\n\n while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {\n entry.write(buff, read);\n }\n\n entry.close();\n\n // Read errors are marked by a negative read amount.\n if (read < 0) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // The file was read but the CRC did not match.\n // We don't check the read file size vs the uncompressed file size\n // because if they're different there should be a CRC error.\n if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {\n QString cp437_file_path = m_ExtractedFolderPath + \"/\" + cp437_file_name;\n QFile::copy(file_path, cp437_file_path);\n }\n }\n } while ((res = unzGoToNextFile(zfile)) == UNZ_OK);\n }\n\n if (res != UNZ_END_OF_LIST_OF_FILE) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot open EPUB: %1\")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));\n }\n\n unzClose(zfile);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ImportEPUB::ExtractContainer", "_file_name": "src/Importers/ImportEPUB.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int jpc_pi_nextcprl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->compno = pchg->compnostart, pi->picomp =\n\t &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,\n\t ++pi->picomp) {\n\t\tpirlvl = pi->picomp->pirlvls;\n\t\tpi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));\n\t\tpi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));\n\t\tfor (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];\n\t\t rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\tpi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *\n\t\t\t (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +\n\t\t\t pi->picomp->numrlvls - rlvlno - 1)));\n\t\t\tpi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *\n\t\t\t (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +\n\t\t\t pi->picomp->numrlvls - rlvlno - 1)));\n\t\t}\n\t\tfor (pi->y = pi->ystart; pi->y < pi->yend;\n\t\t pi->y += pi->ystep - (pi->y % pi->ystep)) {\n\t\t\tfor (pi->x = pi->xstart; pi->x < pi->xend;\n\t\t\t pi->x += pi->xstep - (pi->x % pi->xstep)) {\n\t\t\t\tfor (pi->rlvlno = pchg->rlvlnostart,\n\t\t\t\t pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <\n\t\t\t\t pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\tif (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||\n\t\t\t\t\t !(pi->x % (pi->picomp->hsamp << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||\n\t\t\t\t\t !(pi->y % (pi->picomp->vsamp << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,\n\t\t\t\t\t\t pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,\n\t\t\t\t\t\t pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind *\n\t\t\t\t\t\t pi->pirlvl->numhprcs +\n\t\t\t\t\t\t prchind;\n\t\t\t\t\t\tassert(pi->prcno <\n\t\t\t\t\t\t pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno <\n\t\t\t\t\t\t pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jpc_pi_nextcprl", "_file_name": "src/libjasper/jpc/jpc_t2cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "next_line(struct archive_read *a,\n const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)\n{\n\tssize_t len;\n\tint quit;\n\t\n\tquit = 0;\n\tif (*avail == 0) {\n\t\t*nl = 0;\n\t\tlen = 0;\n\t} else\n\t\tlen = get_line_size(*b, *avail, nl);\n\t/*\n\t * Read bytes more while it does not reach the end of line.\n\t */\n\twhile (*nl == 0 && len == *avail && !quit) {\n\t\tssize_t diff = *ravail - *avail;\n\t\tsize_t nbytes_req = (*ravail+1023) & ~1023U;\n\t\tssize_t tested;\n\n\t\t/* Increase reading bytes if it is not enough to at least\n\t\t * new two lines. */\n\t\tif (nbytes_req < (size_t)*ravail + 160)\n\t\t\tnbytes_req <<= 1;\n\n\t\t*b = __archive_read_ahead(a, nbytes_req, avail);\n\t\tif (*b == NULL) {\n\t\t\tif (*ravail >= *avail)\n\t\t\t\treturn (0);\n\t\t\t/* Reading bytes reaches the end of file. */\n\t\t\t*b = __archive_read_ahead(a, *avail, avail);\n\t\t\tquit = 1;\n\t\t}\n\t\t*ravail = *avail;\n\t\t*b += diff;\n\t\t*avail -= diff;\n\t\ttested = len;/* Skip some bytes we already determinated. */\n\t\tlen = get_line_size(*b, *avail, nl);\n\t\tif (len >= 0)\n\t\t\tlen += tested;\n\t}\n\treturn (len);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[933, 972]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[933, 972]]}, "_func_name": "next_line", "_file_name": "libarchive/archive_read_support_format_mtree.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static ssize_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate)\n{\n Image\n *mask;\n\n MagickOffsetType\n rows_offset;\n\n size_t\n channels,\n count,\n length,\n offset_length;\n\n unsigned char\n *compact_pixels;\n\n count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(next_image);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if (next_image->storage_class != PseudoClass)\n {\n if (IsGrayImage(next_image,&next_image->exception) == MagickFalse)\n channels=next_image->colorspace == CMYKColorspace ? 4 : 3;\n if (next_image->matte != MagickFalse)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if (next_image->storage_class == PseudoClass)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsGrayImage(next_image,&next_image->exception) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateImage(next_image,MagickFalse);\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->matte != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateImage(next_image,MagickFalse);\n if (separate != MagickFalse)\n {\n const char\n *property;\n\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n &image->exception);\n if (mask != (Image *) NULL)\n {\n if (mask->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WritePSDChannels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_MPEGAudioSampleEntryBox *ptr;\n\tchar *data;\n\tu8 a, b, c, d;\n\tu32 i, size, v, nb_alnum;\n\tGF_Err e;\n\tu64 pos, start;\n\n\tptr = (GF_MPEGAudioSampleEntryBox *)s;\n\n\tstart = gf_bs_get_position(bs);\n\tgf_bs_seek(bs, start + 8);\n\tv = gf_bs_read_u16(bs);\n\tif (v)\n\t\tptr->is_qtff = 1;\n\n\t//try to disambiguate QTFF v1 and MP4 v1 audio sample entries ...\n\tif (v==1) {\n\t\t//go to end of ISOM audio sample entry, skip 4 byte (box size field), read 4 bytes (box type) and check if this looks like a box\n\t\tgf_bs_seek(bs, start + 8 + 20 + 4);\n\t\ta = gf_bs_read_u8(bs);\n\t\tb = gf_bs_read_u8(bs);\n\t\tc = gf_bs_read_u8(bs);\n\t\td = gf_bs_read_u8(bs);\n\t\tnb_alnum = 0;\n\t\tif (isalnum(a)) nb_alnum++;\n\t\tif (isalnum(b)) nb_alnum++;\n\t\tif (isalnum(c)) nb_alnum++;\n\t\tif (isalnum(d)) nb_alnum++;\n\t\tif (nb_alnum>2) ptr->is_qtff = 0;\n\t}\n\n\tgf_bs_seek(bs, start);\n\te = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs);\n\tif (e) return e;\n\tpos = gf_bs_get_position(bs);\n\tsize = (u32) s->size;\n\n\t//when cookie is set on bs, always convert qtff-style mp4a to isobmff-style\n\t//since the conversion is done in addBox and we don't have the bitstream there (arg...), flag the box\n \tif (gf_bs_get_cookie(bs)) {\n \t\tptr->is_qtff |= 1<<16;\n \t}\n\n\te = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox);\n\tif (!e) return GF_OK;\n\tif (size<8) return GF_ISOM_INVALID_FILE;\n\n\t/*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/\n\tgf_bs_seek(bs, pos);\n\tdata = (char*)gf_malloc(sizeof(char) * size);\n\tgf_bs_read_data(bs, data, size);\n\tfor (i=0; iesd) {\n\t\t\t\tif (!use_dump_mode) gf_isom_box_del((GF_Box *)ptr->esd);\n\t\t\t\tptr->esd=NULL;\n\t\t\t}\n\n\t\t\te = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs);\n\n\t\t\tif (e==GF_OK) {\n\t\t\t\tgf_isom_box_add_for_dump_mode((GF_Box*)ptr, (GF_Box*)ptr->esd);\n\t\t\t} else if (ptr->esd) {\n\t\t\t\tgf_isom_box_del((GF_Box *)ptr->esd);\n\t\t\t\tptr->esd=NULL;\n\t\t\t}\n\n\t\t\tgf_bs_del(mybs);\n\t\t\tbreak;\n\t\t}\n\t}\n\tgf_free(data);\n\treturn e;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "audio_sample_entry_Read", "_file_name": "src/isomedia/box_code_base.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _create_3par_vlun(self, volume, hostname):\n out = self._cli_run(['createvlun', volume, 'auto', hostname])\n if out and len(out) > 1:\n if \"must be in the same domain\" in out[0]:\n err = out[0].strip()\n err = err + \" \" + out[1].strip()\n raise exception.Invalid3PARDomain(err=err)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_create_3par_vlun", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tUINT32 PathLength;\n\tStream_Seek(irp->input, 28);\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tStream_Read_UINT32(irp->input, PathLength);\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n\t &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[330, 475]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[330, 475]]}, "_func_name": "parallel_process_irp_create", "_file_name": "channels/parallel/client/parallel_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):\n out = self._cli_run(['showhost', '-d'])\n # wwns_iqn may be a list of strings or a single\n # string. So, if necessary, create a list to loop.\n if not isinstance(wwns_iqn, list):\n wwn_iqn_list = [wwns_iqn]\n else:\n wwn_iqn_list = wwns_iqn\n\n for wwn_iqn in wwn_iqn_list:\n for showhost in out:\n if (wwn_iqn.upper() in showhost.upper()):\n return showhost.split(',')[1]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_3par_hostname_from_wwn_iqn", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PyImaging_MapBuffer(PyObject* self, PyObject* args)\n{\n Py_ssize_t y, size;\n Imaging im;\n\n PyObject* target;\n Py_buffer view;\n char* mode;\n char* codec;\n PyObject* bbox;\n Py_ssize_t offset;\n int xsize, ysize;\n int stride;\n int ystep;\n\n if (!PyArg_ParseTuple(args, \"O(ii)sOn(sii)\", &target, &xsize, &ysize,\n &codec, &bbox, &offset, &mode, &stride, &ystep))\n return NULL;\n\n if (!PyImaging_CheckBuffer(target)) {\n PyErr_SetString(PyExc_TypeError, \"expected string or buffer\");\n return NULL;\n }\n\n if (stride <= 0) {\n if (!strcmp(mode, \"L\") || !strcmp(mode, \"P\"))\n stride = xsize;\n else if (!strncmp(mode, \"I;16\", 4))\n stride = xsize * 2;\n else\n stride = xsize * 4;\n }\n\n if (ysize > INT_MAX / stride) {\n PyErr_SetString(PyExc_MemoryError, \"Integer overflow in ysize\");\n return NULL;\n }\n\n size = (Py_ssize_t) ysize * stride;\n\n if (offset > SIZE_MAX - size) {\n PyErr_SetString(PyExc_MemoryError, \"Integer overflow in offset\");\n return NULL;\n } \n\n /* check buffer size */\n if (PyImaging_GetBuffer(target, &view) < 0)\n return NULL;\n\n if (view.len < 0) {\n PyErr_SetString(PyExc_ValueError, \"buffer has negative size\");\n return NULL;\n }\n if (offset + size > view.len) {\n PyErr_SetString(PyExc_ValueError, \"buffer is not large enough\");\n return NULL;\n }\n\n im = ImagingNewPrologueSubtype(\n mode, xsize, ysize, sizeof(ImagingBufferInstance)\n );\n if (!im)\n return NULL;\n\n /* setup file pointers */\n if (ystep > 0)\n for (y = 0; y < ysize; y++)\n im->image[y] = (char*)view.buf + offset + y * stride;\n else\n for (y = 0; y < ysize; y++)\n im->image[ysize-y-1] = (char*)view.buf + offset + y * stride;\n\n im->destroy = mapping_destroy_buffer;\n\n Py_INCREF(target);\n ((ImagingBufferInstance*) im)->target = target;\n ((ImagingBufferInstance*) im)->view = view;\n\n if (!ImagingNewEpilogue(im))\n return NULL;\n\n return PyImagingNew(im);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PyImaging_MapBuffer", "_file_name": "map.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n{\n\tstruct mmu_gather tlb;\n\tstruct vm_area_struct *vma;\n\tbool ret = true;\n\n\t/*\n\t * We have to make sure to not race with the victim exit path\n\t * and cause premature new oom victim selection:\n\t * __oom_reap_task_mm\t\texit_mm\n\t * mmget_not_zero\n\t *\t\t\t\t mmput\n\t *\t\t\t\t atomic_dec_and_test\n\t *\t\t\t\t exit_oom_victim\n\t *\t\t\t\t[...]\n\t *\t\t\t\tout_of_memory\n\t *\t\t\t\t select_bad_process\n\t *\t\t\t\t # no TIF_MEMDIE task selects new victim\n\t * unmap_page_range # frees some memory\n\t */\n\tmutex_lock(&oom_lock);\n\n\tif (!down_read_trylock(&mm->mmap_sem)) {\n\t\tret = false;\n\t\ttrace_skip_task_reaping(tsk->pid);\n\t\tgoto unlock_oom;\n\t}\n\n\t/*\n\t * If the mm has notifiers then we would need to invalidate them around\n\t * unmap_page_range and that is risky because notifiers can sleep and\n\t * what they do is basically undeterministic. So let's have a short\n\t * sleep to give the oom victim some more time.\n\t * TODO: we really want to get rid of this ugly hack and make sure that\n\t * notifiers cannot block for unbounded amount of time and add\n\t * mmu_notifier_invalidate_range_{start,end} around unmap_page_range\n\t */\n\tif (mm_has_notifiers(mm)) {\n\t\tup_read(&mm->mmap_sem);\n\t\tschedule_timeout_idle(HZ);\n\t\tgoto unlock_oom;\n\t}\n\n\t/*\n\t * MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't\n\t * work on the mm anymore. The check for MMF_OOM_SKIP must run\n\t * under mmap_sem for reading because it serializes against the\n\t * down_write();up_write() cycle in exit_mmap().\n\t */\n\tif (test_bit(MMF_OOM_SKIP, &mm->flags)) {\n\t\tup_read(&mm->mmap_sem);\n\t\ttrace_skip_task_reaping(tsk->pid);\n\t\tgoto unlock_oom;\n\t}\n\n\ttrace_start_task_reaping(tsk->pid);\n\n\t/*\n\t * Tell all users of get_user/copy_from_user etc... that the content\n\t * is no longer stable. No barriers really needed because unmapping\n\t * should imply barriers already and the reader would hit a page fault\n\t * if it stumbled over a reaped memory.\n\t */\n\tset_bit(MMF_UNSTABLE, &mm->flags);\n\n\tfor (vma = mm->mmap ; vma; vma = vma->vm_next) {\n\t\tif (!can_madv_dontneed_vma(vma))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * Only anonymous pages have a good chance to be dropped\n\t\t * without additional steps which we cannot afford as we\n\t\t * are OOM already.\n\t\t *\n\t\t * We do not even care about fs backed pages because all\n\t\t * which are reclaimable have already been reclaimed and\n\t\t * we do not want to block exit_mmap by keeping mm ref\n\t\t * count elevated without a good reason.\n\t\t */\n\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {\n\t\t\ttlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);\n\t\t\tunmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,\n\t\t\t\t\t NULL);\n\t\t\ttlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end);\n\t\t}\n\t}\n\tpr_info(\"oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\\n\",\n\t\t\ttask_pid_nr(tsk), tsk->comm,\n\t\t\tK(get_mm_counter(mm, MM_ANONPAGES)),\n\t\t\tK(get_mm_counter(mm, MM_FILEPAGES)),\n\t\t\tK(get_mm_counter(mm, MM_SHMEMPAGES)));\n\tup_read(&mm->mmap_sem);\n\n\ttrace_finish_task_reaping(tsk->pid);\nunlock_oom:\n\tmutex_unlock(&oom_lock);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__oom_reap_task_mm", "_file_name": "mm/oom_kill.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def tid_to_tid_num(self, tid):\n ''' Returns tid_num, given tid. '''\n\n q = \"SELECT rowid FROM tids WHERE tid = ?\"\n self.query(q, tid)\n return self.c.fetchone()[0]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tid_to_tid_num", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int hci_uart_set_proto(struct hci_uart *hu, int id)\n{\n\tconst struct hci_uart_proto *p;\n\tint err;\n\n\tp = hci_uart_get_proto(id);\n\tif (!p)\n\t\treturn -EPROTONOSUPPORT;\n\n\thu->proto = p;\n\tset_bit(HCI_UART_PROTO_READY, &hu->flags);\n\n\terr = hci_uart_register_dev(hu);\n\tif (err) {\n\t\tclear_bit(HCI_UART_PROTO_READY, &hu->flags);\n\t\treturn err;\n\t}\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[187, 231], [278, 342]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[187, 231], [278, 342]]}, "_func_name": "hci_uart_set_proto", "_file_name": "drivers/bluetooth/hci_ldisc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,\n\t\t\t\t int tlen, int offset)\n{\n\t__wsum csum = skb->csum;\n\n\tif (skb->ip_summed != CHECKSUM_COMPLETE)\n\t\treturn;\n\n\tif (offset != 0)\n\t\tcsum = csum_sub(csum,\n\t\t\t\tcsum_partial(skb_transport_header(skb) + tlen,\n\t\t\t\t\t offset, 0));\n\n\tput_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[203, 301]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[203, 301]]}, "_func_name": "ip_cmsg_recv_checksum", "_file_name": "net/ipv4/ip_sockglue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "lha_read_file_header_1(struct archive_read *a, struct lha *lha)\n{\n\tconst unsigned char *p;\n\tsize_t extdsize;\n\tint i, err, err2;\n\tint namelen, padding;\n\tunsigned char headersum, sum_calculated;\n\n\terr = ARCHIVE_OK;\n\n\tif ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)\n\t\treturn (truncated_error(a));\n\n\tlha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;\n\theadersum = p[H1_HEADER_SUM_OFFSET];\n\t/* Note: An extended header size is included in a compsize. */\n\tlha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);\n\tlha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);\n\tlha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);\n\tnamelen = p[H1_NAME_LEN_OFFSET];\n\t/* Calculate a padding size. The result will be normally 0 only(?) */\n\tpadding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;\n\n\tif (namelen > 230 || padding < 0)\n\t\tgoto invalid;\n\n\tif ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)\n\t\treturn (truncated_error(a));\n\n\tfor (i = 0; i < namelen; i++) {\n\t\tif (p[i + H1_FILE_NAME_OFFSET] == 0xff)\n\t\t\tgoto invalid;/* Invalid filename. */\n\t}\n\tarchive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);\n\tlha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);\n\tlha->setflag |= CRC_IS_SET;\n\n\tsum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);\n\t/* Consume used bytes but not include `next header size' data\n\t * since it will be consumed in lha_read_file_extended_header(). */\n\t__archive_read_consume(a, lha->header_size - 2);\n\n\t/* Read extended headers */\n\terr2 = lha_read_file_extended_header(a, lha, NULL, 2,\n\t (size_t)(lha->compsize + 2), &extdsize);\n\tif (err2 < ARCHIVE_WARN)\n\t\treturn (err2);\n\tif (err2 < err)\n\t\terr = err2;\n\t/* Get a real compressed file size. */\n\tlha->compsize -= extdsize - 2;\n\n\tif (lha->compsize < 0)\n\t\tgoto invalid;\t/* Invalid compressed file size */\n\n\tif (sum_calculated != headersum) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"LHa header sum error\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\treturn (err);\ninvalid:\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t \"Invalid LHa header\");\n\treturn (ARCHIVE_FATAL);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "lha_read_file_header_1", "_file_name": "libarchive/archive_read_support_format_lha.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit/', methods=['GET', 'POST'])\ndef edit(cmt_id):\n m = None\n if request.method == 'GET':\n cursor.execute(\"SELECT * FROM comment where cmt_id = %s;\", (cmt_id,))\n m = cursor.fetchone()\n return render_template('comment/edit.html', m=m, cmt_id=cmt_id)\n\n if request.method == 'POST':\n content = request.form['content']\n cursor.execute(\"UPDATE comment SET content = %s where cmt_id = %s;\", (content, cmt_id))\n conn.commit()\n cursor.execute(\"SELECT msg_id FROM comment where cmt_id = %s;\", (cmt_id,))\n m = cursor.fetchone()\n flash('Edit Success!')\n return redirect(url_for('comment.show', msg_id=m[0]))\n\n return render_template('comment/edit.html', m=m, cmt_id=cmt_id)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[838, 923], [1038, 1125]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[838, 923], [1038, 1125]]}, "_func_name": "repodata_schema2id", "_file_name": "src/repodata.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def ls(self, data, path):\n credentials = self._formatCredentials(data, name='current')\n\n command = (\n '{credentials} '\n 'rclone lsjson current:{path}'\n ).format(\n credentials=credentials,\n path=path,\n )\n\n try:\n result = self._execute(command)\n result = json.loads(result)\n return result\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[98, 279]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[98, 279]]}, "_func_name": "ls", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def markTokenUsedExternal(token, optStr=\"\"):\n conn, c = connectDB()\n req = \"UPDATE {} SET \\\"options_selected\\\"=? WHERE token=?\".format(CFG(\"tokens_table_name\"))\n c.execute(req, (optStr, token,))\n closeDB(conn)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "markTokenUsedExternal", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_read(int fd, void *buf, size_t count) {\n ssize_t ret = static_cast(EnsureInitializedAndDispatchSyscall(\n asylo::system_call::kSYS_read, fd, buf, count));\n if (ret != -1 && ret > count) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_read: read result exceeds requested\");\n }\n return ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_read", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def getSeriesDateFromDatabase(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = '\" + str(getTitle(submission)) + \"'\").fetchone()[0]\n database.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[120, 256]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[120, 256]]}, "_func_name": "getSeriesDateFromDatabase", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def fetch_page_name(self, page_id):\n '''\n Returns the page name corresponding to the provided page ID.\n\n Args:\n page_id: The page ID whose ID to fetch.\n\n Returns:\n str: The page name corresponding to the provided page ID.\n\n Raises:\n ValueError: If the provided page ID is invalid or does not exist.\n '''\n helpers.validate_page_id(page_id)\n\n query = 'SELECT name FROM pages WHERE id = ?;'\n query_bindings = (page_id,)\n self.cursor.execute(query, query_bindings)\n\n page_name = self.cursor.fetchone()\n\n if not page_name:\n raise ValueError('Invalid page ID \"{0}\" provided. Page ID does not exist.'.format(page_id))\n\n return page_name[0].encode('utf-8').replace('_', ' ')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fetch_page_name", "_file_name": "sdow/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def delete(self, email):\n \"\"\" Deletes admin with the corresponding email \"\"\"\n return database_utilities.execute_query(f\"\"\"delete from admins where email = '{email}'\"\"\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[106, 204]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[106, 204]]}, "_func_name": "delete", "_file_name": "apis/admins.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def adb_call(*args):\n clean_name = name.replace('_', '-')\n arg_str = ' '.join(str(elem) for elem in args)\n return self._exec_adb_cmd(clean_name, arg_str)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 194]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 194]]}, "_func_name": "__getattr__.adb_call", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int nsv_read_chunk(AVFormatContext *s, int fill_header)\n{\n NSVContext *nsv = s->priv_data;\n AVIOContext *pb = s->pb;\n AVStream *st[2] = {NULL, NULL};\n NSVStream *nst;\n AVPacket *pkt;\n int i, err = 0;\n uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */\n uint32_t vsize;\n uint16_t asize;\n uint16_t auxsize;\n int ret;\n\n if (nsv->ahead[0].data || nsv->ahead[1].data)\n return 0; //-1; /* hey! eat what you've in your plate first! */\n\nnull_chunk_retry:\n if (pb->eof_reached)\n return -1;\n\n for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)\n err = nsv_resync(s);\n if (err < 0)\n return err;\n if (nsv->state == NSV_FOUND_NSVS)\n err = nsv_parse_NSVs_header(s);\n if (err < 0)\n return err;\n if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)\n return -1;\n\n auxcount = avio_r8(pb);\n vsize = avio_rl16(pb);\n asize = avio_rl16(pb);\n vsize = (vsize << 4) | (auxcount >> 4);\n auxcount &= 0x0f;\n av_log(s, AV_LOG_TRACE, \"NSV CHUNK %\"PRIu8\" aux, %\"PRIu32\" bytes video, %\"PRIu16\" bytes audio\\n\",\n auxcount, vsize, asize);\n /* skip aux stuff */\n for (i = 0; i < auxcount; i++) {\n uint32_t av_unused auxtag;\n auxsize = avio_rl16(pb);\n auxtag = avio_rl32(pb);\n avio_skip(pb, auxsize);\n vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */\n }\n\n if (pb->eof_reached)\n return -1;\n if (!vsize && !asize) {\n nsv->state = NSV_UNSYNC;\n goto null_chunk_retry;\n }\n\n /* map back streams to v,a */\n if (s->nb_streams > 0)\n st[s->streams[0]->id] = s->streams[0];\n if (s->nb_streams > 1)\n st[s->streams[1]->id] = s->streams[1];\n\n if (vsize && st[NSV_ST_VIDEO]) {\n nst = st[NSV_ST_VIDEO]->priv_data;\n pkt = &nsv->ahead[NSV_ST_VIDEO];\n if ((ret = av_get_packet(pb, pkt, vsize)) < 0)\n return ret;\n pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;\n pkt->dts = nst->frame_offset;\n pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */\n for (i = 0; i < FFMIN(8, vsize); i++)\n av_log(s, AV_LOG_TRACE, \"NSV video: [%d] = %02\"PRIx8\"\\n\",\n i, pkt->data[i]);\n }\n if(st[NSV_ST_VIDEO])\n ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;\n\n if (asize && st[NSV_ST_AUDIO]) {\n nst = st[NSV_ST_AUDIO]->priv_data;\n pkt = &nsv->ahead[NSV_ST_AUDIO];\n /* read raw audio specific header on the first audio chunk... */\n /* on ALL audio chunks ?? seems so! */\n if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {\n uint8_t bps;\n uint8_t channels;\n uint16_t samplerate;\n bps = avio_r8(pb);\n channels = avio_r8(pb);\n samplerate = avio_rl16(pb);\n if (!channels || !samplerate)\n return AVERROR_INVALIDDATA;\n asize-=4;\n av_log(s, AV_LOG_TRACE, \"NSV RAWAUDIO: bps %\"PRIu8\", nchan %\"PRIu8\", srate %\"PRIu16\"\\n\",\n bps, channels, samplerate);\n if (fill_header) {\n st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */\n if (bps != 16) {\n av_log(s, AV_LOG_TRACE, \"NSV AUDIO bit/sample != 16 (%\"PRIu8\")!!!\\n\", bps);\n }\n bps /= channels; // ???\n if (bps == 8)\n st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;\n samplerate /= 4;/* UGH ??? XXX */\n channels = 1;\n st[NSV_ST_AUDIO]->codecpar->channels = channels;\n st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;\n av_log(s, AV_LOG_TRACE, \"NSV RAWAUDIO: bps %\"PRIu8\", nchan %\"PRIu8\", srate %\"PRIu16\"\\n\",\n bps, channels, samplerate);\n }\n }\n if ((ret = av_get_packet(pb, pkt, asize)) < 0)\n return ret;\n pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;\n pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */\n if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {\n /* on a nsvs frame we have new information on a/v sync */\n pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);\n pkt->dts *= (int64_t)1000 * nsv->framerate.den;\n pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;\n av_log(s, AV_LOG_TRACE, \"NSV AUDIO: sync:%\"PRId16\", dts:%\"PRId64,\n nsv->avsync, pkt->dts);\n }\n nst->frame_offset++;\n }\n\n nsv->state = NSV_UNSYNC;\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "nsv_read_chunk", "_file_name": "libavformat/nsvdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def add_post(content):\n \"\"\"Add a post to the 'database' with the current timestamp.\"\"\"\n conn = psycopg2.connect(\"dbname=forum\")\n cursor = conn.cursor()\n one_post = content\n cursor.execute(\"insert into posts values (%s)\", (one_post,))\n conn.commit()\n conn.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_post", "_file_name": "forumdb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_invalid_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']\n config.iscsi_ip_address = '10.10.10.10'\n self.mox.ReplayAll()\n\n # no valid ip addr should be configured.\n self.assertRaises(exception.InvalidInput,\n self.setup_driver,\n config,\n set_up_fakes=False)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[294, 329], [401, 445], [583, 631]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[294, 329], [401, 445], [583, 631]]}, "_func_name": "test_invalid_iscsi_ip", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def is_safe_url(url, host=None):\n \"\"\"\n Return ``True`` if the url is a safe redirection (i.e. it doesn't point to\n a different host and uses a safe scheme).\n\n Always returns ``False`` on an empty url.\n \"\"\"\n if url is not None:\n url = url.strip()\n if not url:\n return False\n # Chrome treats \\ completely as / in paths but it could be part of some\n # basic auth credentials so we need to check both URLs.\n return _is_safe_url(url, host) and _is_safe_url(url.replace('\\\\', '/'), host)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "is_safe_url", "_file_name": "django/utils/http.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tut8 *end, *need = NULL;\n\tconst char *section_name = \"\";\n\tElf_(Shdr) *link_shdr = NULL;\n\tconst char *link_section_name = \"\";\n\tSdb *sdb_vernaux = NULL;\n\tSdb *sdb_version = NULL;\n\tSdb *sdb = NULL;\n\tint i, cnt;\n\n\tif (!bin || !bin->dynstr) {\n\t\treturn NULL;\n\t}\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn NULL;\n\t}\n\tif (shdr->sh_size < 1) {\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tif (!sdb) {\n\t\treturn NULL;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {\n\t\tbprintf (\"Warning: Cannot allocate memory for Elf_(Verneed)\\n\");\n\t\tgoto beach;\n\t}\n\tend = need + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"num_entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tif (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {\n\t\tgoto beach;\n\t}\n\tif (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {\n\t\tgoto beach;\n\t}\n\ti = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);\n\tif (i < 0)\n\t\tgoto beach;\n\t//XXX we should use DT_VERNEEDNUM instead of sh_info\n\t//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html\n\tfor (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {\n\t\tint j, isum;\n\t\tut8 *vstart = need + i;\n\t\tElf_(Verneed) vvn = {0};\n\t\tif (vstart + sizeof (Elf_(Verneed)) > end) {\n\t\t\tgoto beach;\n\t\t}\n\t\tElf_(Verneed) *entry = &vvn;\n\t\tchar key[32] = {0};\n\t\tsdb_version = sdb_new0 ();\n\t\tif (!sdb_version) {\n\t\t\tgoto beach;\n\t\t}\n\t\tj = 0;\n\t\tvvn.vn_version = READ16 (vstart, j)\n\t\tvvn.vn_cnt = READ16 (vstart, j)\n\t\tvvn.vn_file = READ32 (vstart, j)\n\t\tvvn.vn_aux = READ32 (vstart, j)\n\t\tvvn.vn_next = READ32 (vstart, j)\n\n\t\tsdb_num_set (sdb_version, \"vn_version\", entry->vn_version, 0);\n\t\tsdb_num_set (sdb_version, \"idx\", i, 0);\n\t\tif (entry->vn_file > bin->dynstr_size) {\n\t\t\tgoto beach;\n\t\t}\n\t\t{\n\t\t\tchar *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);\n\t\t\tsdb_set (sdb_version, \"file_name\", s, 0);\n\t\t\tfree (s);\n\t\t}\n\t\tsdb_num_set (sdb_version, \"cnt\", entry->vn_cnt, 0);\n\t\tst32 vnaux = entry->vn_aux;\n\t\tif (vnaux < 1) {\n\t\t\tgoto beach;\n\t\t}\n\t\tvstart += vnaux;\n\t\tfor (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {\n\t\t\tint k;\n\t\t\tElf_(Vernaux) * aux = NULL;\n\t\t\tElf_(Vernaux) vaux = {0};\n\t\t\tsdb_vernaux = sdb_new0 ();\n\t\t\tif (!sdb_vernaux) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\taux = (Elf_(Vernaux)*)&vaux;\n\t\t\tk = 0;\n\t\t\tvaux.vna_hash = READ32 (vstart, k)\n\t\t\tvaux.vna_flags = READ16 (vstart, k)\n\t\t\tvaux.vna_other = READ16 (vstart, k)\n\t\t\tvaux.vna_name = READ32 (vstart, k)\n\t\t\tvaux.vna_next = READ32 (vstart, k)\n\t\t\tif (aux->vna_name > bin->dynstr_size) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_vernaux, \"idx\", isum, 0);\n\t\t\tif (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {\n\t\t\t\tchar name [16];\n\t\t\t\tstrncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);\n\t\t\t\tname[sizeof(name)-1] = 0;\n\t\t\t\tsdb_set (sdb_vernaux, \"name\", name, 0);\n\t\t\t}\n\t\t\tsdb_set (sdb_vernaux, \"flags\", get_ver_flags (aux->vna_flags), 0);\n\t\t\tsdb_num_set (sdb_vernaux, \"version\", aux->vna_other, 0);\n\t\t\tisum += aux->vna_next;\n\t\t\tvstart += aux->vna_next;\n\t\t\tsnprintf (key, sizeof (key), \"vernaux%d\", j);\n\t\t\tsdb_ns_set (sdb_version, key, sdb_vernaux);\n\t\t}\n\t\tif ((int)entry->vn_next < 0) {\n\t\t\tbprintf (\"Invalid vn_next\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += entry->vn_next;\n\t\tsnprintf (key, sizeof (key), \"version%d\", cnt );\n\t\tsdb_ns_set (sdb, key, sdb_version);\n\t\t//if entry->vn_next is 0 it iterate infinitely\n\t\tif (!entry->vn_next) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfree (need);\n\treturn sdb;\nbeach:\n\tfree (need);\n\tsdb_free (sdb_vernaux);\n\tsdb_free (sdb_version);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "store_versioninfo_gnu_verneed", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def analyze_smashgg(self, urls, name):\n LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls)))\n for url in urls:\n # Before we process this URL, check to see if we already have\n sql = \"SELECT * FROM analyzed where base_url='{}'\".format(url)\n res = self.db.exec(sql)\n if len(res) == 0:\n\n display_name = bracket_utils.get_display_base(url)\n\n # We don't care about doubles tournaments\n if 'doubles' in display_name.lower() or 'dubs' in display_name.lower():\n LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name))\n continue\n\n LOG.info('About to process pro bracket {}'.format(url))\n self.data_processor.process(url, name, display_name)\n else:\n LOG.info(\"Skpping pro bracket because it has already been analyzed: {}\".format(url))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[236, 311]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[236, 311]]}, "_func_name": "analyze_smashgg", "_file_name": "validURLs.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def whitelist(users: str):\n for user in users.split():\n call(WHITELIST_COMMAND_TEMPLATE.format(user))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 27], [58, 111]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 27], [58, 111]]}, "_func_name": "whitelist", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_language(lang):\n try:\n cur.execute(\"INSERT INTO language (name) VALUES (%s)\", (lang, ))\n except Exception as e:\n pass\n cur.execute(\"SELECT language_id FROM language where name=%s\", (lang, ))\n lang_id = cur.fetchone()[0]\n if conn.commit():\n return lang_id\n return lang_id", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_language", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickExport Image *AdaptiveThresholdImage(const Image *image,\n const size_t width,const size_t height,const double bias,\n ExceptionInfo *exception)\n{\n#define AdaptiveThresholdImageTag \"AdaptiveThreshold/Image\"\n\n CacheView\n *image_view,\n *threshold_view;\n\n Image\n *threshold_image;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MagickSizeType\n number_pixels;\n\n ssize_t\n y;\n\n /*\n Initialize threshold image attributes.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n if (width == 0)\n return(threshold_image);\n status=SetImageStorageClass(threshold_image,DirectClass,exception);\n if (status == MagickFalse)\n {\n threshold_image=DestroyImage(threshold_image);\n return((Image *) NULL);\n }\n /*\n Threshold image.\n */\n status=MagickTrue;\n progress=0;\n number_pixels=(MagickSizeType) width*height;\n image_view=AcquireVirtualCacheView(image,exception);\n threshold_view=AcquireAuthenticCacheView(threshold_image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n magick_number_threads(image,threshold_image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n double\n channel_bias[MaxPixelChannels],\n channel_sum[MaxPixelChannels];\n\n register const Quantum\n *magick_restrict p,\n *magick_restrict pixels;\n\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n center,\n u,\n v;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)\n (height/2L),image->columns+width,height,exception);\n q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,\n 1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+\n GetPixelChannels(image)*(width/2);\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n pixels=p;\n channel_bias[channel]=0.0;\n channel_sum[channel]=0.0;\n for (v=0; v < (ssize_t) height; v++)\n {\n for (u=0; u < (ssize_t) width; u++)\n {\n if (u == (ssize_t) (width-1))\n channel_bias[channel]+=pixels[i];\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image);\n }\n pixels+=GetPixelChannels(image)*image->columns;\n }\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n double\n mean;\n\n PixelChannel channel = GetPixelChannelChannel(image,i);\n PixelTrait traits = GetPixelChannelTraits(image,channel);\n PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,\n channel);\n if ((traits == UndefinedPixelTrait) ||\n (threshold_traits == UndefinedPixelTrait))\n continue;\n if ((threshold_traits & CopyPixelTrait) != 0)\n {\n SetPixelChannel(threshold_image,channel,p[center+i],q);\n continue;\n }\n channel_sum[channel]-=channel_bias[channel];\n channel_bias[channel]=0.0;\n pixels=p;\n for (v=0; v < (ssize_t) height; v++)\n {\n channel_bias[channel]+=pixels[i];\n pixels+=(width-1)*GetPixelChannels(image);\n channel_sum[channel]+=pixels[i];\n pixels+=GetPixelChannels(image)*(image->columns+1);\n }\n mean=(double) (channel_sum[channel]/number_pixels+bias);\n SetPixelChannel(threshold_image,channel,(Quantum) ((double)\n p[center+i] <= mean ? 0 : QuantumRange),q);\n }\n p+=GetPixelChannels(image);\n q+=GetPixelChannels(threshold_image);\n }\n if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n threshold_image->type=image->type;\n threshold_view=DestroyCacheView(threshold_view);\n image_view=DestroyCacheView(image_view);\n if (status == MagickFalse)\n threshold_image=DestroyImage(threshold_image);\n return(threshold_image);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "AdaptiveThresholdImage", "_file_name": "MagickCore/threshold.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int usb_console_setup(struct console *co, char *options)\n{\n\tstruct usbcons_info *info = &usbcons_info;\n\tint baud = 9600;\n\tint bits = 8;\n\tint parity = 'n';\n\tint doflow = 0;\n\tint cflag = CREAD | HUPCL | CLOCAL;\n\tchar *s;\n\tstruct usb_serial *serial;\n\tstruct usb_serial_port *port;\n\tint retval;\n\tstruct tty_struct *tty = NULL;\n\tstruct ktermios dummy;\n\n\tif (options) {\n\t\tbaud = simple_strtoul(options, NULL, 10);\n\t\ts = options;\n\t\twhile (*s >= '0' && *s <= '9')\n\t\t\ts++;\n\t\tif (*s)\n\t\t\tparity = *s++;\n\t\tif (*s)\n\t\t\tbits = *s++ - '0';\n\t\tif (*s)\n\t\t\tdoflow = (*s++ == 'r');\n\t}\n\t\n\t/* Sane default */\n\tif (baud == 0)\n\t\tbaud = 9600;\n\n\tswitch (bits) {\n\tcase 7:\n\t\tcflag |= CS7;\n\t\tbreak;\n\tdefault:\n\tcase 8:\n\t\tcflag |= CS8;\n\t\tbreak;\n\t}\n\tswitch (parity) {\n\tcase 'o': case 'O':\n\t\tcflag |= PARODD;\n\t\tbreak;\n\tcase 'e': case 'E':\n\t\tcflag |= PARENB;\n\t\tbreak;\n\t}\n\tco->cflag = cflag;\n\n\t/*\n\t * no need to check the index here: if the index is wrong, console\n\t * code won't call us\n\t */\n\tport = usb_serial_port_get_by_minor(co->index);\n\tif (port == NULL) {\n\t\t/* no device is connected yet, sorry :( */\n\t\tpr_err(\"No USB device connected to ttyUSB%i\\n\", co->index);\n\t\treturn -ENODEV;\n\t}\n\tserial = port->serial;\n\n\tretval = usb_autopm_get_interface(serial->interface);\n\tif (retval)\n\t\tgoto error_get_interface;\n\n\ttty_port_tty_set(&port->port, NULL);\n\n\tinfo->port = port;\n\n\t++port->port.count;\n\tif (!tty_port_initialized(&port->port)) {\n\t\tif (serial->type->set_termios) {\n\t\t\t/*\n\t\t\t * allocate a fake tty so the driver can initialize\n\t\t\t * the termios structure, then later call set_termios to\n\t\t\t * configure according to command line arguments\n\t\t\t */\n\t\t\ttty = kzalloc(sizeof(*tty), GFP_KERNEL);\n\t\t\tif (!tty) {\n\t\t\t\tretval = -ENOMEM;\n\t\t\t\tgoto reset_open_count;\n\t\t\t}\n\t\t\tkref_init(&tty->kref);\n\t\t\ttty->driver = usb_serial_tty_driver;\n\t\t\ttty->index = co->index;\n\t\t\tinit_ldsem(&tty->ldisc_sem);\n\t\t\tspin_lock_init(&tty->files_lock);\n\t\t\tINIT_LIST_HEAD(&tty->tty_files);\n\t\t\tkref_get(&tty->driver->kref);\n\t\t\t__module_get(tty->driver->owner);\n\t\t\ttty->ops = &usb_console_fake_tty_ops;\n\t\t\ttty_init_termios(tty);\n\t\t\ttty_port_tty_set(&port->port, tty);\n\t\t}\n\n\t\t/* only call the device specific open if this\n\t\t * is the first time the port is opened */\n\t\tretval = serial->type->open(NULL, port);\n\t\tif (retval) {\n\t\t\tdev_err(&port->dev, \"could not open USB console port\\n\");\n\t\t\tgoto fail;\n\t\t}\n\n\t\tif (serial->type->set_termios) {\n\t\t\ttty->termios.c_cflag = cflag;\n\t\t\ttty_termios_encode_baud_rate(&tty->termios, baud, baud);\n\t\t\tmemset(&dummy, 0, sizeof(struct ktermios));\n\t\t\tserial->type->set_termios(tty, port, &dummy);\n\n\t\t\ttty_port_tty_set(&port->port, NULL);\n\t\t\ttty_kref_put(tty);\n\t\t}\n\t\ttty_port_set_initialized(&port->port, 1);\n\t}\n\t/* Now that any required fake tty operations are completed restore\n\t * the tty port count */\n\t--port->port.count;\n\t/* The console is special in terms of closing the device so\n\t * indicate this port is now acting as a system console. */\n\tport->port.console = 1;\n\n\tmutex_unlock(&serial->disc_mutex);\n\treturn retval;\n\n fail:\n\ttty_port_tty_set(&port->port, NULL);\n\ttty_kref_put(tty);\n reset_open_count:\n\tport->port.count = 0;\n\tusb_autopm_put_interface(serial->interface);\n error_get_interface:\n\tusb_serial_put(serial);\n\tmutex_unlock(&serial->disc_mutex);\n\treturn retval;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[3110, 3156]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3110, 3156]]}, "_func_name": "usb_console_setup", "_file_name": "drivers/usb/serial/console.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_value(self):\n if self.column.render_function:\n # We don't want to escape our html\n return self.column.render_function(self.object)\n\n field = getattr(self.object, self.column.field_name) if self.column.field_name else None\n if type(self.object) == dict:\n value = self.object.get(self.column.field_name)\n elif callable(field):\n value = field() if getattr(field, 'do_not_call_in_templates', False) else field\n else:\n display_function = getattr(self.object, 'get_%s_display' % self.column.field_name, False)\n value = display_function() if display_function else field\n\n return escape(value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[25, 270], [677, 705]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[25, 270], [677, 705]]}, "_func_name": "get_value", "_file_name": "smart_lists/helpers.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool handle_client_startup(PgSocket *client, PktHdr *pkt)\n{\n\tconst char *passwd;\n\tconst uint8_t *key;\n\tbool ok;\n\n\tSBuf *sbuf = &client->sbuf;\n\n\t/* don't tolerate partial packets */\n\tif (incomplete_pkt(pkt)) {\n\t\tdisconnect_client(client, true, \"client sent partial pkt in startup phase\");\n\t\treturn false;\n\t}\n\n\tif (client->wait_for_welcome) {\n\t\tif (finish_client_login(client)) {\n\t\t\t/* the packet was already parsed */\n\t\t\tsbuf_prepare_skip(sbuf, pkt->len);\n\t\t\treturn true;\n\t\t} else\n\t\t\treturn false;\n\t}\n\n\tswitch (pkt->type) {\n\tcase PKT_SSLREQ:\n\t\tslog_noise(client, \"C: req SSL\");\n\t\tslog_noise(client, \"P: nak\");\n\n\t\t/* reject SSL attempt */\n\t\tif (!sbuf_answer(&client->sbuf, \"N\", 1)) {\n\t\t\tdisconnect_client(client, false, \"failed to nak SSL\");\n\t\t\treturn false;\n\t\t}\n\t\tbreak;\n\tcase PKT_STARTUP_V2:\n\t\tdisconnect_client(client, true, \"Old V2 protocol not supported\");\n\t\treturn false;\n\tcase PKT_STARTUP:\n\t\tif (client->pool) {\n\t\t\tdisconnect_client(client, true, \"client re-sent startup pkt\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!decide_startup_pool(client, pkt))\n\t\t\treturn false;\n\n\t\tif (client->pool->db->admin) {\n\t\t\tif (!admin_pre_login(client))\n\t\t\t\treturn false;\n\t\t}\n\n\t\tif (cf_auth_type <= AUTH_TRUST || client->own_user) {\n\t\t\tif (!finish_client_login(client))\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tif (!send_client_authreq(client)) {\n\t\t\t\tdisconnect_client(client, false, \"failed to send auth req\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 'p':\t\t/* PasswordMessage */\n\t\t/* haven't requested it */\n\t\tif (cf_auth_type <= AUTH_TRUST) {\n\t\t\tdisconnect_client(client, true, \"unrequested passwd pkt\");\n\t\t\treturn false;\n\t\t}\n\n\t\tok = mbuf_get_string(&pkt->data, &passwd);\n\t\tif (ok && check_client_passwd(client, passwd)) {\n\t\t\tif (!finish_client_login(client))\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tdisconnect_client(client, true, \"Auth failed\");\n\t\t\treturn false;\n\t\t}\n\t\tbreak;\n\tcase PKT_CANCEL:\n\t\tif (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN\n\t\t && mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))\n\t\t{\n\t\t\tmemcpy(client->cancel_key, key, BACKENDKEY_LEN);\n\t\t\taccept_cancel_request(client);\n\t\t} else\n\t\t\tdisconnect_client(client, false, \"bad cancel request\");\n\t\treturn false;\n\tdefault:\n\t\tdisconnect_client(client, false, \"bad packet\");\n\t\treturn false;\n\t}\n\tsbuf_prepare_skip(sbuf, pkt->len);\n\tclient->request_time = get_cached_time();\n\treturn true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1457, 1486]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1457, 1486]]}, "_func_name": "handle_client_startup", "_file_name": "src/client.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int __mdiobus_register(struct mii_bus *bus, struct module *owner)\n{\n\tstruct mdio_device *mdiodev;\n\tint i, err;\n\tstruct gpio_desc *gpiod;\n\n\tif (NULL == bus || NULL == bus->name ||\n\t NULL == bus->read || NULL == bus->write)\n\t\treturn -EINVAL;\n\n\tBUG_ON(bus->state != MDIOBUS_ALLOCATED &&\n\t bus->state != MDIOBUS_UNREGISTERED);\n\n\tbus->owner = owner;\n\tbus->dev.parent = bus->parent;\n\tbus->dev.class = &mdio_bus_class;\n\tbus->dev.groups = NULL;\n\tdev_set_name(&bus->dev, \"%s\", bus->id);\n\n\terr = device_register(&bus->dev);\n\tif (err) {\n\t\tpr_err(\"mii_bus %s failed to register\\n\", bus->id);\n\t\tput_device(&bus->dev);\n\t\treturn -EINVAL;\n\t}\n\n\tmutex_init(&bus->mdio_lock);\n\n\t/* de-assert bus level PHY GPIO reset */\n\tgpiod = devm_gpiod_get_optional(&bus->dev, \"reset\", GPIOD_OUT_LOW);\n\tif (IS_ERR(gpiod)) {\n\t\tdev_err(&bus->dev, \"mii_bus %s couldn't get reset GPIO\\n\",\n\t\t\tbus->id);\n\t\tdevice_del(&bus->dev);\n\t\treturn PTR_ERR(gpiod);\n\t} else\tif (gpiod) {\n\t\tbus->reset_gpiod = gpiod;\n\n\t\tgpiod_set_value_cansleep(gpiod, 1);\n\t\tudelay(bus->reset_delay_us);\n\t\tgpiod_set_value_cansleep(gpiod, 0);\n\t}\n\n\tif (bus->reset)\n\t\tbus->reset(bus);\n\n\tfor (i = 0; i < PHY_MAX_ADDR; i++) {\n\t\tif ((bus->phy_mask & (1 << i)) == 0) {\n\t\t\tstruct phy_device *phydev;\n\n\t\t\tphydev = mdiobus_scan(bus, i);\n\t\t\tif (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) {\n\t\t\t\terr = PTR_ERR(phydev);\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\tmdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device);\n\n\tbus->state = MDIOBUS_REGISTERED;\n\tpr_info(\"%s: probed\\n\", bus->name);\n\treturn 0;\n\nerror:\n\twhile (--i >= 0) {\n\t\tmdiodev = bus->mdio_map[i];\n\t\tif (!mdiodev)\n\t\t\tcontinue;\n\n\t\tmdiodev->device_remove(mdiodev);\n\t\tmdiodev->device_free(mdiodev);\n\t}\n\n\t/* Put PHYs in RESET to save power */\n\tif (bus->reset_gpiod)\n\t\tgpiod_set_value_cansleep(bus->reset_gpiod, 1);\n\n\tdevice_del(&bus->dev);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[589, 632]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[589, 632]]}, "_func_name": "__mdiobus_register", "_file_name": "drivers/net/phy/mdio_bus.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('//save', methods=['POST'])\ndef save_page_edit(page_name):\n # grab the new content from the user\n content = request.form.get('content')\n # check if 'page_name' exists in the database\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n result = query.namedresult()\n # if it doesn't exist, create a new page in the database\n if len(result) < 1:\n db.insert(\n 'page', {\n 'page_name': page_name\n }\n )\n else:\n pass\n # now that we're certain that the page exists in the database, we again grab the query\n # and insert new content in the database\n query = db.query(\"select id from page where page_name = '%s'\" % page_name)\n page_id = query.namedresult()[0].id\n db.insert(\n 'page_content', {\n 'page_id': page_id,\n 'content': content,\n 'timestamp': time.strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n }\n )\n return redirect(\"/%s\" % page_name)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[214, 454]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[214, 454]]}, "_func_name": "save_page_edit", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_bracket_graph_data(db, tag):\n # First, we have to find out which scenes this player has brackets in\n sql = \"SELECT DISTINCT scene FROM ranks WHERE player='{tag}'\"\n args = {'tag': tag}\n scenes = db.exec(sql, args)\n scenes = [s[0] for s in scenes]\n\n bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes}\n\n return bracket_placings_by_scene", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_bracket_graph_data", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int shadow_server_start(rdpShadowServer* server)\n{\n\tBOOL ipc;\n\tBOOL status;\n\tWSADATA wsaData;\n\n\tif (!server)\n\t\treturn -1;\n\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)\n\t\treturn -1;\n\n#ifndef _WIN32\n\tsignal(SIGPIPE, SIG_IGN);\n#endif\n\tserver->screen = shadow_screen_new(server);\n\n\tif (!server->screen)\n\t{\n\t\tWLog_ERR(TAG, \"screen_new failed\");\n\t\treturn -1;\n\t}\n\n\tserver->capture = shadow_capture_new(server);\n\n\tif (!server->capture)\n\t{\n\t\tWLog_ERR(TAG, \"capture_new failed\");\n\t\treturn -1;\n\t}\n\n\t/* Bind magic:\n\t *\n\t * emtpy ... bind TCP all\n\t * ... bind local (IPC)\n\t * bind-socket,
... bind TCP to specified interface\n\t */\n\tipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket,\n\t strnlen(bind_address, sizeof(bind_address))) != 0);\n\tif (!ipc)\n\t{\n\t\tsize_t x, count;\n\t\tchar** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count);\n\t\tif (!list || (count <= 1))\n\t\t{\n\t\t\tfree(list);\n\t\t\tif (server->ipcSocket == NULL)\n\t\t\t{\n\t\t\t\tif (!open_port(server, NULL))\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn -1;\n\t\t}\n\n\t\tfor (x = 1; x < count; x++)\n\t\t{\n\t\t\tBOOL success = open_port(server, list[x]);\n\t\t\tif (!success)\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tfree(list);\n\t}\n\telse\n\t{\n\t\tstatus = server->listener->OpenLocal(server->listener, server->ipcSocket);\n\t\tif (!status)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Problem creating local socket listener. (Port already used or \"\n\t\t\t \"insufficient permissions?)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL)))\n\t{\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[981, 1030]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[981, 1030]]}, "_func_name": "shadow_server_start", "_file_name": "server/shadow/shadow_server.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def create_playlist(name):\n db = connect_to_database()\n cursor = db.cursor()\n cursor.execute(\n \"INSERT INTO playlist (name, video_position) VALUES('{name}', 0);\".format(name=name))\n db.commit()\n db.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[103, 197]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[103, 197]]}, "_func_name": "create_playlist", "_file_name": "main_test.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def delete_event(self, event_id):\n sql = \"\"\"DELETE FROM events\n WHERE event_id = {0}\n \"\"\".format(event_id)\n affected_count = self.cur.execute(sql)\n self.conn.commit()\n return affected_count", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[74, 150]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[74, 150]]}, "_func_name": "delete_event", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only, although later\n\t\t * we use first_node(nodes) to grab a single node, so here\n\t\t * nodelist (or nodes) cannot be empty.\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t\tif (nodes_empty(nodes))\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mpol_parse_str", "_file_name": "mm/mempolicy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def ls(self, data, path):\n credentials = self._formatCredentials(data, name='current')\n command = [\n 'rclone',\n 'lsjson',\n 'current:{}'.format(path),\n ]\n\n try:\n result = self._execute(command, credentials)\n result = json.loads(result)\n return result\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ls", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength;\n if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {\n setToBogus();\n return *this;\n }\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "UnicodeString::doAppend", "_file_name": "icu4c/source/common/unistr.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def adb_call(args=None, shell=False):\n \"\"\"Wrapper for an ADB command.\n\n Args:\n args: string or list of strings, arguments to the adb command.\n See subprocess.Proc() documentation.\n shell: bool, True to run this command through the system shell,\n False to invoke it directly. See subprocess.Proc() docs.\n\n Returns:\n The output of the adb command run if exit code is 0.\n \"\"\"\n args = args or ''\n clean_name = name.replace('_', '-')\n return self._exec_adb_cmd(clean_name, args, shell=shell)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__getattr__.adb_call", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@contextmanager\ndef run_interactive_shell_command(command, **kwargs):\n \"\"\"\n Runs a single command in shell and provides stdout, stderr and stdin\n streams.\n\n This function creates a context manager that sets up the process (using\n `subprocess.Popen()`), returns to caller, closes streams and waits for\n process to exit on leaving.\n\n Shell execution is disabled by default (so no shell expansion takes place).\n If you want to turn shell execution on, you can pass `shell=True` like you\n would do for `subprocess.Popen()`.\n\n The process is opened in `universal_newlines` mode by default.\n\n :param command: The command to run on shell. This parameter can either\n be a sequence of arguments that are directly passed to\n the process or a string. A string gets splitted beforehand\n using `shlex.split()`.\n :param kwargs: Additional keyword arguments to pass to `subprocess.Popen`\n that is used to spawn the process (except `stdout`,\n `stderr`, `stdin` and `universal_newlines`, a `TypeError`\n is raised then).\n :return: A context manager yielding the process started from the\n command.\n \"\"\"\n if isinstance(command, str):\n command = shlex.split(command)\n\n process = Popen(command,\n stdout=PIPE,\n stderr=PIPE,\n stdin=PIPE,\n universal_newlines=True,\n **kwargs)\n try:\n yield process\n finally:\n process.stdout.close()\n process.stderr.close()\n process.stdin.close()\n process.wait()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "run_interactive_shell_command", "_file_name": "coalib/misc/Shell.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_inverters(self):\n interfaces = self.config.get_connection_interfaces()\n for source in interfaces:\n if source[\"type\"] == \"inverter\":\n\n query = '''\n INSERT OR IGNORE INTO Inverters (\n Serial,\n EToday,\n ETotal\n ) VALUES (\n %s,\n %s,\n %s\n );\n ''' % (source[\"serial_id\"], 0, source[\"prev_etotal\"])\n self.c.execute(query)\n\n query = '''\n UPDATE Inverters\n SET \n Name='%s', \n Type='%s', \n SW_Version='%s', \n Status='%s',\n TimeStamp='%s'\n WHERE Serial='%s';\n ''' % (source[\"name\"], source[\"inverter_type\"], \"s0-bridge v0\", \"OK\", int(datetime.now().timestamp()), source[\"serial_id\"] )\n self.c.execute(query)\n\n self.db.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[378, 461], [484, 592], [687, 1095]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[378, 461], [484, 592], [687, 1095]]}, "_func_name": "add_inverters", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/movies/search', methods=['GET', 'POST'])\ndef search_films():\n form = SearchForm()\n if not form.validate_on_submit():\n return render_template('search.html', title='Search for films', form=form)\n search_terms = form.data['term'].split(' ')\n search_string = ' & '.join(search_terms)\n cur.execute(\"SELECT * FROM film where fulltext @@ to_tsquery(%s)\", (search_string, ))\n res = cur.fetchall()\n return render_template('search_results.html', title='Home', res=len(res))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "search_films", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_theory_base(tag, link):\n theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\theory.db\")\n conn = theory.cursor()\n conn.execute(\"insert into ? values (?)\", (tag, str(link)))\n theory.commit()\n theory.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_theory_base", "_file_name": "bases/update.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, char **buf, int *buf_type)\n{\n\tstruct smb_rqst rqst;\n\tint resp_buftype, rc = -EACCES;\n\tstruct smb2_read_plain_req *req = NULL;\n\tstruct smb2_read_rsp *rsp = NULL;\n\tstruct kvec iov[1];\n\tstruct kvec rsp_iov;\n\tunsigned int total_len;\n\tint flags = CIFS_LOG_ERROR;\n\tstruct cifs_ses *ses = io_parms->tcon->ses;\n\n\t*nbytes = 0;\n\trc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);\n\tif (rc)\n\t\treturn rc;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\tiov[0].iov_base = (char *)req;\n\tiov[0].iov_len = total_len;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = 1;\n\n\trc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);\n\trsp = (struct smb2_read_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\tif (rc != -ENODATA) {\n\t\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);\n\t\t\tcifs_dbg(VFS, \"Send error in read = %d\\n\", rc);\n\t\t\ttrace_smb3_read_err(xid, req->PersistentFileId,\n\t\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t\t io_parms->offset, io_parms->length,\n\t\t\t\t\t rc);\n\t\t} else\n\t\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, 0);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t\treturn rc == -ENODATA ? 0 : rc;\n\t} else\n\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length);\n\n\tcifs_small_buf_release(req);\n\n\t*nbytes = le32_to_cpu(rsp->DataLength);\n\tif ((*nbytes > CIFS_MAX_MSGSIZE) ||\n\t (*nbytes > io_parms->length)) {\n\t\tcifs_dbg(FYI, \"bad length %d for count %d\\n\",\n\t\t\t *nbytes, io_parms->length);\n\t\trc = -EIO;\n\t\t*nbytes = 0;\n\t}\n\n\tif (*buf) {\n\t\tmemcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t} else if (resp_buftype != CIFS_NO_BUFFER) {\n\t\t*buf = rsp_iov.iov_base;\n\t\tif (resp_buftype == CIFS_SMALL_BUFFER)\n\t\t\t*buf_type = CIFS_SMALL_BUFFER;\n\t\telse if (resp_buftype == CIFS_LARGE_BUFFER)\n\t\t\t*buf_type = CIFS_LARGE_BUFFER;\n\t}\n\treturn rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "SMB2_read", "_file_name": "fs/cifs/smb2pdu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)\n{\n\tstruct grid_cell\t*gc = &ictx->cell.cell;\n\tchar\t\t\t*s = ictx->param_list[i].str, *copy, *ptr, *out;\n\tint\t\t\t p[8];\n\tu_int\t\t\t n;\n\tconst char\t\t*errstr;\n\n\tfor (n = 0; n < nitems(p); n++)\n\t\tp[n] = -1;\n\tn = 0;\n\n\tptr = copy = xstrdup(s);\n\twhile ((out = strsep(&ptr, \":\")) != NULL) {\n\t\tif (*out != '\\0') {\n\t\t\tp[n++] = strtonum(out, 0, INT_MAX, &errstr);\n\t\t\tif (errstr != NULL || n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else\n\t\t\tn++;\n\t\tlog_debug(\"%s: %u = %d\", __func__, n - 1, p[n - 1]);\n\t}\n\tfree(copy);\n\n\tif (n == 0)\n\t\treturn;\n\tif (p[0] == 4) {\n\t\tif (n != 2)\n\t\t\treturn;\n\t\tswitch (p[1]) {\n\t\tcase 0:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_2;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_3;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_4;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_5;\n\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t}\n\tif (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))\n\t\treturn;\n\tswitch (p[1]) {\n\tcase 2:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tif (n == 5)\n\t\t\ti = 2;\n\t\telse\n\t\t\ti = 3;\n\t\tif (n < i + 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],\n\t\t p[i + 2]);\n\t\tbreak;\n\tcase 5:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);\n\t\tbreak;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[485, 494]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[485, 494]]}, "_func_name": "input_csi_dispatch_sgr_colon", "_file_name": "input.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,\n socklen_t input_len, struct sockaddr *output,\n socklen_t *output_len,\n void (*abort_handler)(const char *)) {\n if (!input || !output || !output_len || input_len == 0) {\n output = nullptr;\n return false;\n }\n\n int16_t klinux_family = input->klinux_sa_family;\n if (klinux_family == kLinux_AF_UNIX) {\n if (input_len < sizeof(struct klinux_sockaddr_un)) {\n return false;\n }\n\n struct klinux_sockaddr_un *klinux_sockaddr_un_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_un sockaddr_un_out;\n sockaddr_un_out.sun_family = AF_UNIX;\n InitializeToZeroArray(sockaddr_un_out.sun_path);\n ReinterpretCopyArray(\n sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,\n std::min(sizeof(sockaddr_un_out.sun_path),\n sizeof(klinux_sockaddr_un_in->klinux_sun_path)));\n CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET) {\n if (input_len < sizeof(struct klinux_sockaddr_in)) {\n return false;\n }\n struct klinux_sockaddr_in *klinux_sockaddr_in_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in sockaddr_in_out;\n sockaddr_in_out.sin_family = AF_INET;\n sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;\n InitializeToZeroSingle(&sockaddr_in_out.sin_addr);\n ReinterpretCopySingle(&sockaddr_in_out.sin_addr,\n &klinux_sockaddr_in_in->klinux_sin_addr);\n InitializeToZeroArray(sockaddr_in_out.sin_zero);\n ReinterpretCopyArray(sockaddr_in_out.sin_zero,\n klinux_sockaddr_in_in->klinux_sin_zero);\n CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);\n } else if (klinux_family == kLinux_AF_INET6) {\n if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n return false;\n }\n\n struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =\n const_cast(\n reinterpret_cast(input));\n\n struct sockaddr_in6 sockaddr_in6_out;\n sockaddr_in6_out.sin6_family = AF_INET6;\n sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;\n sockaddr_in6_out.sin6_flowinfo =\n klinux_sockaddr_in6_in->klinux_sin6_flowinfo;\n sockaddr_in6_out.sin6_scope_id =\n klinux_sockaddr_in6_in->klinux_sin6_scope_id;\n InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);\n ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,\n &klinux_sockaddr_in6_in->klinux_sin6_addr);\n CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,\n output_len);\n } else if (klinux_family == kLinux_AF_UNSPEC) {\n output = nullptr;\n *output_len = 0;\n } else {\n if (abort_handler != nullptr) {\n std::string message = absl::StrCat(\n \"Type conversion error - Unsupported AF family: \", klinux_family);\n abort_handler(message.c_str());\n } else {\n abort();\n }\n }\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "FromkLinuxSockAddr", "_file_name": "asylo/platform/system_call/type_conversions/manual_types_functions.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@hook.command(autohelp=False)\ndef showPoll(pollID, db=None):\n \"\"\"Shows the answers for a given poll.\"\"\"\n if not db_ready: db_init(db)\n if pollID == None:\n poll = db.execute(\"SELECT pollID, question FROM polls WHERE active = 1\")\n if len(poll) == 0:\n reply(\"There's no poll open.\")\n return\n else:\n poll = db.execute(\"SELECT pollID, question FROM polls WHERE pollID = '{}'\".format(pollID))\n if len(poll) == 0:\n reply(\"No such poll found.\")\n return\n pollID = poll[0][0]\n question = poll[0][1]\n reply(question)\n for (index, answer, votes) in db.execute(\"SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = {} GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC\".format(pollID, )):\n reply(\"%s. %s (%s)\" % (index, answer, votes))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[343, 442], [599, 851]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[343, 442], [599, 851]]}, "_func_name": "showPoll", "_file_name": "plugins/poll.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen > 0) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\t\t\treturn union_desc;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[398, 420]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[398, 420]]}, "_func_name": "ims_pcu_get_cdc_union_desc", "_file_name": "drivers/input/misc/ims-pcu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void disk_seqf_stop(struct seq_file *seqf, void *v)\n{\n\tstruct class_dev_iter *iter = seqf->private;\n\n\t/* stop is called even after start failed :-( */\n\tif (iter) {\n\t\tclass_dev_iter_exit(iter);\n\t\tkfree(iter);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[215, 218]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[215, 218]]}, "_func_name": "disk_seqf_stop", "_file_name": "block/genhd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int dd_delete_item(struct dump_dir *dd, const char *name)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot delete item. '%s' is not a valid file name\", name);\n\n char *path = concat_path_file(dd->dd_dirname, name);\n int res = unlink(path);\n\n if (res < 0)\n {\n if (errno == ENOENT)\n errno = res = 0;\n else\n perror_msg(\"Can't delete file '%s'\", path);\n }\n\n free(path);\n return res;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_delete_item", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)\n{\n char obj_txt[128];\n\n OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n BIO_printf(bio, \"%s\\n\", obj_txt);\n\n return 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TS_OBJ_print_bio", "_file_name": "crypto/ts/ts_lib.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get(self, key):\n try:\n result = self.etcd.get(os.path.join(self.namespace, key))\n except etcd.EtcdException as err:\n log_error(\"Error fetching key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to get key')\n return result.value", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[37, 107]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[37, 107]]}, "_func_name": "get", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "struct net *get_net_ns_by_id(struct net *net, int id)\n{\n\tstruct net *peer;\n\n\tif (id < 0)\n\t\treturn NULL;\n\n\trcu_read_lock();\n\tspin_lock_bh(&net->nsid_lock);\n\tpeer = idr_find(&net->netns_ids, id);\n\tif (peer)\n\t\tpeer = maybe_get_net(peer);\n\tspin_unlock_bh(&net->nsid_lock);\n\trcu_read_unlock();\n\n\treturn peer;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_net_ns_by_id", "_file_name": "net/core/net_namespace.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const MagickBooleanType separate,ExceptionInfo *exception)\n{\n size_t\n channels,\n packet_size;\n\n unsigned char\n *compact_pixels;\n\n /*\n Write uncompressed pixels as separate planes.\n */\n channels=1;\n packet_size=next_image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*\n next_image->columns)+1,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (IsImageGray(next_image) != MagickFalse)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GrayQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GrayQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n if (next_image->storage_class == PseudoClass)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,IndexQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n IndexQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,RedQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GreenQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlueQuantum,exception);\n if (next_image->colorspace == CMYKColorspace)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlackQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n (void) SetImageProgress(image,SaveImagesTag,0,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n RedQuantum,MagickTrue,exception);\n (void) SetImageProgress(image,SaveImagesTag,1,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GreenQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,2,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlueQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,3,6);\n if (next_image->colorspace == CMYKColorspace)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlackQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,4,6);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,5,6);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n }\n if (next_image->compression == RLECompression)\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n return(MagickTrue);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WriteImageChannels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,\n const TfLiteNode* node, int index) {\n const bool use_tensor = index < node->inputs->size &&\n node->inputs->data[index] != kTfLiteOptionalTensor;\n if (use_tensor) {\n return GetMutableInput(context, node, index);\n }\n return nullptr;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[153, 379]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[153, 379]]}, "_func_name": "tflite::GetOptionalInputTensor", "_file_name": "tensorflow/lite/kernels/kernel_util.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def get_top_author(top_num):\r\n \"\"\" query the top(top_num) popular author\r\n top_num => list of [author, count]\r\n \"\"\"\r\n cmd = \"\"\"SELECT authors.name,author_result.num\r\n FROM authors JOIN\r\n (SELECT SUM(article_result.num) as num,\r\n article_result.author\r\n from (SELECT articles.title, articles.author,\r\n SUM(log.views) AS num\r\n FROM articles\r\n INNER JOIN (\r\n SELECT path, count(path) AS views\r\n FROM log GROUP BY log.path\r\n ) AS log ON log.path = '/article/'\r\n || articles.slug\r\n GROUP BY articles.title, articles.author)\r\n AS article_result\r\n GROUP BY article_result.author) as author_result\r\n ON authors.id = author_result.author\r\n ORDER BY num DESC LIMIT {}\"\"\".format(top_num)\r\n return execute_query(cmd)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[931, 998]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[931, 998]]}, "_func_name": "get_top_author", "_file_name": "logAnalyzerDb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tid_num_to_tag_nums(self, tid_num):\n ''' Returns list of the associated tag_nums to the given tid_num. '''\n\n q = \"SELECT tag FROM tid_tag WHERE tid = ?\"\n self.query(q, tid_num)\n return [i[0] for i in self.c.fetchall()]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tid_num_to_tag_nums", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData)\n{\n\tWINPR_UNUSED(update);\n\tif (Stream_GetRemainingLength(s) < 18)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, bitmapData->destLeft);\n\tStream_Read_UINT16(s, bitmapData->destTop);\n\tStream_Read_UINT16(s, bitmapData->destRight);\n\tStream_Read_UINT16(s, bitmapData->destBottom);\n\tStream_Read_UINT16(s, bitmapData->width);\n\tStream_Read_UINT16(s, bitmapData->height);\n\tStream_Read_UINT16(s, bitmapData->bitsPerPixel);\n\tStream_Read_UINT16(s, bitmapData->flags);\n\tStream_Read_UINT16(s, bitmapData->bitmapLength);\n\n\tif (bitmapData->flags & BITMAP_COMPRESSION)\n\t{\n\t\tif (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR))\n\t\t{\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */\n\t\t\tStream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */\n\t\t\tStream_Read_UINT16(s,\n\t\t\t bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */\n\t\t\tbitmapData->bitmapLength = bitmapData->cbCompMainBodySize;\n\t\t}\n\n\t\tbitmapData->compressed = TRUE;\n\t}\n\telse\n\t\tbitmapData->compressed = FALSE;\n\n\tif (Stream_GetRemainingLength(s) < bitmapData->bitmapLength)\n\t\treturn FALSE;\n\n\tif (bitmapData->bitmapLength > 0)\n\t{\n\t\tbitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength);\n\n\t\tif (!bitmapData->bitmapDataStream)\n\t\t\treturn FALSE;\n\n\t\tmemcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength);\n\t\tStream_Seek(s, bitmapData->bitmapLength);\n\t}\n\n\treturn TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[699, 724]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[699, 724]]}, "_func_name": "update_read_bitmap_data", "_file_name": "libfreerdp/core/update.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int mif_process_cmpt(mif_hdr_t *hdr, char *buf)\n{\n\tjas_tvparser_t *tvp;\n\tmif_cmpt_t *cmpt;\n\tint id;\n\n\tcmpt = 0;\n\ttvp = 0;\n\n\tif (!(cmpt = mif_cmpt_create())) {\n\t\tgoto error;\n\t}\n\tcmpt->tlx = 0;\n\tcmpt->tly = 0;\n\tcmpt->sampperx = 0;\n\tcmpt->samppery = 0;\n\tcmpt->width = 0;\n\tcmpt->height = 0;\n\tcmpt->prec = 0;\n\tcmpt->sgnd = -1;\n\tcmpt->data = 0;\n\n\tif (!(tvp = jas_tvparser_create(buf))) {\n\t\tgoto error;\n\t}\n\twhile (!(id = jas_tvparser_next(tvp))) {\n\t\tswitch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags,\n\t\t jas_tvparser_gettag(tvp)))->id) {\n\t\tcase MIF_TLX:\n\t\t\tcmpt->tlx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_TLY:\n\t\t\tcmpt->tly = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_WIDTH:\n\t\t\tcmpt->width = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_HEIGHT:\n\t\t\tcmpt->height = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_HSAMP:\n\t\t\tcmpt->sampperx = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_VSAMP:\n\t\t\tcmpt->samppery = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_PREC:\n\t\t\tcmpt->prec = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_SGND:\n\t\t\tcmpt->sgnd = atoi(jas_tvparser_getval(tvp));\n\t\t\tbreak;\n\t\tcase MIF_DATA:\n\t\t\tif (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tjas_tvparser_destroy(tvp);\n\tif (!cmpt->sampperx || !cmpt->samppery) {\n\t\tgoto error;\n\t}\n\tif (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) {\n\t\tgoto error;\n\t}\n\treturn 0;\n\nerror:\n\tif (cmpt) {\n\t\tmif_cmpt_destroy(cmpt);\n\t}\n\tif (tvp) {\n\t\tjas_tvparser_destroy(tvp);\n\t}\n\treturn -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1274, 1345]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1274, 1345]]}, "_func_name": "mif_process_cmpt", "_file_name": "src/libjasper/mif/mif_cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)\n{\n\tstruct usb_device *dev = chip->dev;\n\tstruct usb_host_interface *host_iface;\n\tstruct usb_interface_descriptor *altsd;\n\tvoid *control_header;\n\tint i, protocol;\n\tint rest_bytes;\n\n\t/* find audiocontrol interface */\n\thost_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];\n\tcontrol_header = snd_usb_find_csint_desc(host_iface->extra,\n\t\t\t\t\t\t host_iface->extralen,\n\t\t\t\t\t\t NULL, UAC_HEADER);\n\taltsd = get_iface_desc(host_iface);\n\tprotocol = altsd->bInterfaceProtocol;\n\n\tif (!control_header) {\n\t\tdev_err(&dev->dev, \"cannot find UAC_HEADER\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\trest_bytes = (void *)(host_iface->extra + host_iface->extralen) -\n\t\tcontrol_header;\n\n\t/* just to be sure -- this shouldn't hit at all */\n\tif (rest_bytes <= 0) {\n\t\tdev_err(&dev->dev, \"invalid control header\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tswitch (protocol) {\n\tdefault:\n\t\tdev_warn(&dev->dev,\n\t\t\t \"unknown interface protocol %#02x, assuming v1\\n\",\n\t\t\t protocol);\n\t\t/* fall through */\n\n\tcase UAC_VERSION_1: {\n\t\tstruct uac1_ac_header_descriptor *h1 = control_header;\n\n\t\tif (rest_bytes < sizeof(*h1)) {\n\t\t\tdev_err(&dev->dev, \"too short v1 buffer descriptor\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (!h1->bInCollection) {\n\t\t\tdev_info(&dev->dev, \"skipping empty audio interface (v1)\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (rest_bytes < h1->bLength) {\n\t\t\tdev_err(&dev->dev, \"invalid buffer length (v1)\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (h1->bLength < sizeof(*h1) + h1->bInCollection) {\n\t\t\tdev_err(&dev->dev, \"invalid UAC_HEADER (v1)\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tfor (i = 0; i < h1->bInCollection; i++)\n\t\t\tsnd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);\n\n\t\tbreak;\n\t}\n\n\tcase UAC_VERSION_2: {\n\t\tstruct usb_interface_assoc_descriptor *assoc =\n\t\t\tusb_ifnum_to_if(dev, ctrlif)->intf_assoc;\n\n\t\tif (!assoc) {\n\t\t\t/*\n\t\t\t * Firmware writers cannot count to three. So to find\n\t\t\t * the IAD on the NuForce UDH-100, also check the next\n\t\t\t * interface.\n\t\t\t */\n\t\t\tstruct usb_interface *iface =\n\t\t\t\tusb_ifnum_to_if(dev, ctrlif + 1);\n\t\t\tif (iface &&\n\t\t\t iface->intf_assoc &&\n\t\t\t iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&\n\t\t\t iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)\n\t\t\t\tassoc = iface->intf_assoc;\n\t\t}\n\n\t\tif (!assoc) {\n\t\t\tdev_err(&dev->dev, \"Audio class v2 interfaces need an interface association\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tfor (i = 0; i < assoc->bInterfaceCount; i++) {\n\t\t\tint intf = assoc->bFirstInterface + i;\n\n\t\t\tif (intf != ctrlif)\n\t\t\t\tsnd_usb_create_stream(chip, ctrlif, intf);\n\t\t}\n\n\t\tbreak;\n\t}\n\t}\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "snd_usb_create_streams", "_file_name": "sound/usb/card.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def test_settings_path_skip_issue_909(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'skip =\\n'\n ' file_to_be_skipped.py\\n'\n 'skip_glob =\\n'\n ' *glob_skip*\\n')\n\n base_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n base_dir.join('file_to_be_skipped.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors\n subprocess.run(['isort', '--check-only'], check=True)\n result = subprocess.run(\n ['isort', '--check-only', '--settings-path=conf/.isort.cfg'],\n stdout=subprocess.PIPE,\n check=True\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped 2' in result.stdout.lower()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_settings_path_skip_issue_909", "_file_name": "test_isort.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--\n\n#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count\n\n int\n pixel;\n\n register ssize_t\n i,\n j;\n\n size_t\n length;\n\n ssize_t\n packets;\n\n packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n CheckNumberCompactPixels;\n compact_pixels++;\n }\n }\n return(i);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[3548, 3588]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3548, 3588]]}, "_func_name": "DecodePSDPixels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return(((image->columns+7)/8)*GetPSDPacketSize(image));\n else\n return(image->columns*GetPSDPacketSize(image));\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "GetPSDRowSize", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int jpeg_size(unsigned char* data, unsigned int data_size,\n int *width, int *height)\n{\n int i = 0;\n if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&\n data[i+2] == 0xFF && data[i+3] == 0xE0) {\n i += 4;\n if(i + 6 < data_size &&\n data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&\n data[i+5] == 'F' && data[i+6] == 0x00) {\n unsigned short block_length = data[i] * 256 + data[i+1];\n while(i= data_size)\n return -1;\n if(data[i] != 0xFF)\n return -1;\n if(data[i+1] == 0xC0) {\n *height = data[i+5]*256 + data[i+6];\n *width = data[i+7]*256 + data[i+8];\n return 0;\n }\n i+=2;\n block_length = data[i] * 256 + data[i+1];\n }\n }\n }\n\n return -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[930, 988]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[930, 988]]}, "_func_name": "jpeg_size", "_file_name": "pdfgen.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def patch(self, user_id):\n \"\"\" Replaces information of corresponding user_id with request body \"\"\"\n query = f\"\"\"update users set user_id = %s \"\"\"\n query += f\"\"\"where user_id = %s\"\"\"\n json_data = request.get_json()\n parameters = (json_data['user_id'], user_id)\n database_utilities.execute_query(query, parameters)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "patch", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def init_settings(self, ipython_app, kernel_manager, contents_manager,\n cluster_manager, session_manager, kernel_spec_manager,\n config_manager,\n log, base_url, default_url, settings_overrides,\n jinja_env_options=None):\n\n _template_path = settings_overrides.get(\n \"template_path\",\n ipython_app.template_file_path,\n )\n if isinstance(_template_path, py3compat.string_types):\n _template_path = (_template_path,)\n template_path = [os.path.expanduser(path) for path in _template_path]\n\n jenv_opt = jinja_env_options if jinja_env_options else {}\n env = Environment(loader=FileSystemLoader(template_path), **jenv_opt)\n \n sys_info = get_sys_info()\n if sys_info['commit_source'] == 'repository':\n # don't cache (rely on 304) when working from master\n version_hash = ''\n else:\n # reset the cache on server restart\n version_hash = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n settings = dict(\n # basics\n log_function=log_request,\n base_url=base_url,\n default_url=default_url,\n template_path=template_path,\n static_path=ipython_app.static_file_path,\n static_handler_class = FileFindHandler,\n static_url_prefix = url_path_join(base_url,'/static/'),\n static_handler_args = {\n # don't cache custom.js\n 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],\n },\n version_hash=version_hash,\n \n # authentication\n cookie_secret=ipython_app.cookie_secret,\n login_url=url_path_join(base_url,'/login'),\n login_handler_class=ipython_app.login_handler_class,\n logout_handler_class=ipython_app.logout_handler_class,\n password=ipython_app.password,\n\n # managers\n kernel_manager=kernel_manager,\n contents_manager=contents_manager,\n cluster_manager=cluster_manager,\n session_manager=session_manager,\n kernel_spec_manager=kernel_spec_manager,\n config_manager=config_manager,\n\n # IPython stuff\n jinja_template_vars=ipython_app.jinja_template_vars,\n nbextensions_path=ipython_app.nbextensions_path,\n websocket_url=ipython_app.websocket_url,\n mathjax_url=ipython_app.mathjax_url,\n config=ipython_app.config,\n jinja2_env=env,\n terminals_available=False, # Set later if terminals are available\n )\n\n # allow custom overrides for the tornado web app.\n settings.update(settings_overrides)\n return settings", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[629, 695]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[629, 695]]}, "_func_name": "init_settings", "_file_name": "IPython/html/notebookapp.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def set_state(chat_id, value):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"update users set state ='\" + str(value) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n settings.commit()\n settings.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[160, 264]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[160, 264]]}, "_func_name": "set_state", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)\n{\n// if (!dd->locked)\n// error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n if (!str_is_correct_filename(name))\n {\n error_msg(\"Cannot load text. '%s' is not a valid file name\", name);\n if (!(flags & DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE))\n xfunc_die();\n }\n\n /* Compat with old abrt dumps. Remove in abrt-2.1 */\n if (strcmp(name, \"release\") == 0)\n name = FILENAME_OS_RELEASE;\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n char *ret = load_text_file(full_path, flags);\n free(full_path);\n\n return ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_load_text_ext", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value)\ndef get_login2(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n if bases.createuserbase.check_username(message.text):\n bot.send_message(message.chat.id, \"Invalid handle.\")\n set_state(message.chat.id, config.States.S_START.value)\n return 0\n conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n name = conn.fetchone()\n settings.close()\n bases.update.cf_update()\n bases.createuserbase.clean_base(name[1])\n bases.createuserbase.clean_base(message.text)\n bot.send_message(message.chat.id, \"Creating base...\")\n bases.createuserbase.init_user(message.text, message.chat.id)\n bot.send_message(message.chat.id, \"Done!\")\n set_state(message.chat.id, config.States.S_START.value)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_login2", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void regulator_ena_gpio_free(struct regulator_dev *rdev)\n{\n\tstruct regulator_enable_gpio *pin, *n;\n\n\tif (!rdev->ena_pin)\n\t\treturn;\n\n\t/* Free the GPIO only in case of no use */\n\tlist_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {\n\t\tif (pin->gpiod == rdev->ena_pin->gpiod) {\n\t\t\tif (pin->request_count <= 1) {\n\t\t\t\tpin->request_count = 0;\n\t\t\t\tgpiod_put(pin->gpiod);\n\t\t\t\tlist_del(&pin->list);\n\t\t\t\tkfree(pin);\n\t\t\t} else {\n\t\t\t\tpin->request_count--;\n\t\t\t}\n\t\t}\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[426, 438]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[426, 438]]}, "_func_name": "regulator_ena_gpio_free", "_file_name": "drivers/regulator/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;\n\n size_t\n length;\n\n unsigned char\n *datum;\n\n unsigned int\n count,\n long_sans;\n\n unsigned short\n id,\n short_sans;\n\n length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;\n\n q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n if ((q+PSDQuantum(count)+12) < (datum+length-16))\n {\n (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-\n (PSDQuantum(count)+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));\n }\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "RemoveICCProfileFromResourceBlock", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n conn = connect()\n cursor = conn.cursor()\n query = \"INSERT INTO playsRecord (winner, loser) VALUES (%s, %s);\"\n cursor.execute(query, (winner, loser));\n conn.commit()\n conn.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "reportMatch", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit', methods=['GET', 'POST'])\ndef edit():\n cursor.execute(\"SELECT * FROM users where email = %s;\", (session['logged_email'],))\n u = cursor.fetchone()\n if request.method == 'POST':\n cursor.execute(\"UPDATE users SET nickname = %s where email = %s\", (request.form['nickname'], session['logged_email']))\n cursor.execute(\"SELECT * FROM users where email = %s;\", (session['logged_email'],))\n u = cursor.fetchone()\n conn.commit()\n flash('Edit Nickname Success!')\n return render_template('users/edit.html', u=u)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def save_failure_transaction(self, user_id, project_id, money):\n self.cursor.execute(\"insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, \"\n \"%s, now(), 'failed' )\", (project_id, user_id, money))\n self.db.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "save_failure_transaction", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tid_num_to_tag_nums(self, tid_num):\n ''' Returns list of the associated tag_nums to the given tid_num. '''\n\n q = \"SELECT tag FROM tid_tag WHERE tid = '\" + str(tid_num) + \"'\"\n self.query(q)\n return [i[0] for i in self.c.fetchall()]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[123, 196]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[123, 196]]}, "_func_name": "tid_num_to_tag_nums", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def save_failure_transaction(self, user_id, project_id, money):\n self.cursor.execute(\"insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, %s, now(), 'failed' )\" % (project_id, user_id, money))\n self.db.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[68, 239]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[68, 239]]}, "_func_name": "save_failure_transaction", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def create_basename_core(basename):\n try:\n basename = basename.casefold()\n except Exception:\n basename = basename.lower()\n\n basename = basename.replace(' ', '-')\n basename = re.sub(r'<[^>]*>', r'', basename)\n basename = re.sub(r'[^a-z0-9\\-]', r'', basename)\n basename = re.sub(r'\\-\\-', r'-', basename)\n basename = urllib.parse.quote_plus(basename)\n\n return basename", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[143, 185]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[143, 185]]}, "_func_name": "create_basename_core", "_file_name": "MeTal/core/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n QStandardItem *item = m_peerItems.value(ip);\n int row = item->row();\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n m_missingFlags.remove(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PeerListWidget::updatePeer", "_file_name": "src/gui/properties/peerlistwidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)\n{\n\tstruct super_block *sb;\n\tint err;\n\tint rc;\n\n\tif (!ext4_handle_valid(handle)) {\n\t\text4_put_nojournal(handle);\n\t\treturn 0;\n\t}\n\n\tif (!handle->h_transaction) {\n\t\terr = jbd2_journal_stop(handle);\n\t\treturn handle->h_err ? handle->h_err : err;\n\t}\n\n\tsb = handle->h_transaction->t_journal->j_private;\n\terr = handle->h_err;\n\trc = jbd2_journal_stop(handle);\n\n\tif (!err)\n\t\terr = rc;\n\tif (err)\n\t\t__ext4_std_error(sb, where, line, err);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[239, 320], [324, 397]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[239, 320], [324, 397]]}, "_func_name": "__ext4_journal_stop", "_file_name": "fs/ext4/ext4_jbd2.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def tag_num_to_tag(self, tag_num):\n ''' Returns tag given tag_num. '''\n\n q = \"SELECT tag FROM tags WHERE rowid = ?\"\n self.query(q, tag_num)\n return self.c.fetchone()[0]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tag_num_to_tag", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def callback(recipeName):\n menu.pack_forget()\n viewRecipeFrame.pack(expand=True, fill='both')\n groceryButton.pack_forget()\n database_file = \"meal_planner.db\"\n print(recipeName)\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n selection = cursor.execute(\"\"\"SELECT * FROM recipe WHERE name = \"\"\" + \"\\\"\" + recipeName + \"\\\"\")\n for result in [selection]:\n for row in result.fetchall():\n name = row[0]\n time = row[1]\n servings = row[2]\n ingredients = row[4]\n directions = row[5]\n\n string = (\"Name: {} \\n Cook time: {} \\n Number of Servings: {} \\n \".format(name, time, servings))\n secondString = (\"Ingredients: {}\".format(ingredients))\n thirdString = (\"Directions: {}\".format(directions))\n Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=\"#f8f8f8\", fg=\"#000000\").pack(side=TOP)\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [viewRecipeFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[336, 448]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[336, 448]]}, "_func_name": "__init__.callback", "_file_name": "mealPlan.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mode_keepalive(self, request):\n \"\"\"\n This is called by render_POST when the\n client is replying to the keepalive.\n \"\"\"\n csessid = request.args.get('csessid')[0]\n self.last_alive[csessid] = (time.time(), False)\n return '\"\"'", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[155, 204]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[155, 204]]}, "_func_name": "mode_keepalive", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_read(int fd, void *buf, size_t count) {\n return static_cast(EnsureInitializedAndDispatchSyscall(\n asylo::system_call::kSYS_read, fd, buf, count));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[62, 129]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[62, 129]]}, "_func_name": "enc_untrusted_read", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def git_hook(strict=False, modify=False):\n \"\"\"\n Git pre-commit hook to check staged files for isort errors\n\n :param bool strict - if True, return number of errors on exit,\n causing the hook to fail. If False, return zero so it will\n just act as a warning.\n :param bool modify - if True, fix the sources if they are not\n sorted properly. If False, only report result without\n modifying anything.\n\n :return number of errors if in strict mode, 0 otherwise.\n \"\"\"\n\n # Get list of files modified and staged\n diff_cmd = \"git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD\"\n files_modified = get_lines(diff_cmd)\n\n errors = 0\n for filename in files_modified:\n if filename.endswith('.py'):\n # Get the staged contents of the file\n staged_cmd = \"git show :%s\" % filename\n staged_contents = get_output(staged_cmd)\n\n sort = SortImports(\n file_path=filename,\n file_contents=staged_contents.decode(),\n check=True\n )\n\n if sort.incorrectly_sorted:\n errors += 1\n if modify:\n SortImports(\n file_path=filename,\n file_contents=staged_contents.decode(),\n check=False,\n )\n\n return errors if strict else 0", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[984, 1040], [1254, 1318]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[984, 1040], [1254, 1318]]}, "_func_name": "git_hook", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int expand_downwards(struct vm_area_struct *vma,\n\t\t\t\t unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *prev;\n\tint error = 0;\n\n\taddress &= PAGE_MASK;\n\tif (address < mmap_min_addr)\n\t\treturn -EPERM;\n\n\t/* Enforce stack_guard_gap */\n\tprev = vma->vm_prev;\n\t/* Check that both stack segments have the same anon_vma? */\n\tif (prev && !(prev->vm_flags & VM_GROWSDOWN) &&\n\t\t\t(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (address - prev->vm_end < stack_guard_gap)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;\n\n\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);\n\n\t/* Somebody else might have raced and expanded it already */\n\tif (address < vma->vm_start) {\n\t\tunsigned long size, grow;\n\n\t\tsize = vma->vm_end - address;\n\t\tgrow = (vma->vm_start - address) >> PAGE_SHIFT;\n\n\t\terror = -ENOMEM;\n\t\tif (grow <= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_start = address;\n\t\t\t\tvma->vm_pgoff -= grow;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tvma_gap_update(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);\n\n\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "expand_downwards", "_file_name": "mm/mmap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {\n#if defined(OS_WIN)\n const auto converted = base::WideToUTF8(arg);\n const char* a = converted.c_str();\n#else\n const char* a = arg;\n#endif\n\n static const char* prefixes[] = {\"--\", \"-\", \"/\"};\n\n int prefix_length = 0;\n for (auto& prefix : prefixes) {\n if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) {\n prefix_length = strlen(prefix);\n break;\n }\n }\n\n if (prefix_length > 0) {\n a += prefix_length;\n std::string switch_name(a, strcspn(a, \"=\"));\n auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist),\n switch_name);\n if (iter != std::end(kBlacklist) && switch_name == *iter) {\n return true;\n }\n }\n\n return false;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[500, 549]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[500, 549]]}, "_func_name": "IsBlacklistedArg", "_file_name": "atom/app/command_line_args.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def shame_add(name):\n shame = shame_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if shame is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES(%(name)s,0,1)\n ''', (name, ))\n db.commit()\n logger.debug('Inserted into karmadb 1 shame for {}'.format(name))\n db.close()\n return 1\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n\n else:\n shame = shame + 1\n try:\n cursor.execute('''\n UPDATE people SET shame = %(karma)s WHERE name = %(name)s\n ''' (\n shame,\n name,\n ))\n db.commit()\n logger.debug('Inserted into karmadb {} shame for {}'.format(\n shame, name))\n db.close()\n return shame\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "shame_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int usb_audio_probe(struct usb_interface *intf,\n\t\t\t const struct usb_device_id *usb_id)\n{\n\tstruct usb_device *dev = interface_to_usbdev(intf);\n\tconst struct snd_usb_audio_quirk *quirk =\n\t\t(const struct snd_usb_audio_quirk *)usb_id->driver_info;\n\tstruct snd_usb_audio *chip;\n\tint i, err;\n\tstruct usb_host_interface *alts;\n\tint ifnum;\n\tu32 id;\n\n\talts = &intf->altsetting[0];\n\tifnum = get_iface_desc(alts)->bInterfaceNumber;\n\tid = USB_ID(le16_to_cpu(dev->descriptor.idVendor),\n\t\t le16_to_cpu(dev->descriptor.idProduct));\n\tif (get_alias_id(dev, &id))\n\t\tquirk = get_alias_quirk(dev, id);\n\tif (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)\n\t\treturn -ENXIO;\n\n\terr = snd_usb_apply_boot_quirk(dev, intf, quirk, id);\n\tif (err < 0)\n\t\treturn err;\n\n\t/*\n\t * found a config. now register to ALSA\n\t */\n\n\t/* check whether it's already registered */\n\tchip = NULL;\n\tmutex_lock(®ister_mutex);\n\tfor (i = 0; i < SNDRV_CARDS; i++) {\n\t\tif (usb_chip[i] && usb_chip[i]->dev == dev) {\n\t\t\tif (atomic_read(&usb_chip[i]->shutdown)) {\n\t\t\t\tdev_err(&dev->dev, \"USB device is in the shutdown state, cannot create a card instance\\n\");\n\t\t\t\terr = -EIO;\n\t\t\t\tgoto __error;\n\t\t\t}\n\t\t\tchip = usb_chip[i];\n\t\t\tatomic_inc(&chip->active); /* avoid autopm */\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (! chip) {\n\t\t/* it's a fresh one.\n\t\t * now look for an empty slot and create a new card instance\n\t\t */\n\t\tfor (i = 0; i < SNDRV_CARDS; i++)\n\t\t\tif (!usb_chip[i] &&\n\t\t\t (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&\n\t\t\t (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {\n\t\t\t\tif (enable[i]) {\n\t\t\t\t\terr = snd_usb_audio_create(intf, dev, i, quirk,\n\t\t\t\t\t\t\t\t id, &chip);\n\t\t\t\t\tif (err < 0)\n\t\t\t\t\t\tgoto __error;\n\t\t\t\t\tchip->pm_intf = intf;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (vid[i] != -1 || pid[i] != -1) {\n\t\t\t\t\tdev_info(&dev->dev,\n\t\t\t\t\t\t \"device (%04x:%04x) is disabled\\n\",\n\t\t\t\t\t\t USB_ID_VENDOR(id),\n\t\t\t\t\t\t USB_ID_PRODUCT(id));\n\t\t\t\t\terr = -ENOENT;\n\t\t\t\t\tgoto __error;\n\t\t\t\t}\n\t\t\t}\n\t\tif (!chip) {\n\t\t\tdev_err(&dev->dev, \"no available usb audio device\\n\");\n\t\t\terr = -ENODEV;\n\t\t\tgoto __error;\n\t\t}\n\t}\n\tdev_set_drvdata(&dev->dev, chip);\n\n\t/*\n\t * For devices with more than one control interface, we assume the\n\t * first contains the audio controls. We might need a more specific\n\t * check here in the future.\n\t */\n\tif (!chip->ctrl_intf)\n\t\tchip->ctrl_intf = alts;\n\n\tchip->txfr_quirk = 0;\n\terr = 1; /* continue */\n\tif (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {\n\t\t/* need some special handlings */\n\t\terr = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\tif (err > 0) {\n\t\t/* create normal USB audio interfaces */\n\t\terr = snd_usb_create_streams(chip, ifnum);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t\terr = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\t/* we are allowed to call snd_card_register() many times */\n\terr = snd_card_register(chip->card);\n\tif (err < 0)\n\t\tgoto __error;\n\n\tusb_chip[chip->index] = chip;\n\tchip->num_interfaces++;\n\tusb_set_intfdata(intf, chip);\n\tatomic_dec(&chip->active);\n\tmutex_unlock(®ister_mutex);\n\treturn 0;\n\n __error:\n\tif (chip) {\n\t\t/* chip->active is inside the chip->card object,\n\t\t * decrement before memory is possibly returned.\n\t\t */\n\t\tatomic_dec(&chip->active);\n\t\tif (!chip->num_interfaces)\n\t\t\tsnd_card_free(chip->card);\n\t}\n\tmutex_unlock(®ister_mutex);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "usb_audio_probe", "_file_name": "sound/usb/card.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_invalid_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']\n config.iscsi_ip_address = '10.10.10.10'\n self.mox.ReplayAll()\n\n # no valid ip addr should be configured.\n self.assertRaises(exception.InvalidInput,\n self.setup_driver,\n config,\n set_up_fakes=False)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_invalid_iscsi_ip", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp)\n{\n\tsize_t olen;\n\n\tif (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[84, 157]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[84, 157]]}, "_func_name": "security_fips_decrypt", "_file_name": "libfreerdp/core/security.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst,\n int input_index) {\n DataType src_out = src->output_type(output_index);\n DataType dst_in = dst->input_type(input_index);\n if (!TypesCompatible(dst_in, src_out)) {\n return errors::InvalidArgument(\n \"Input \", input_index, \" of node \", dst->name(), \" was passed \",\n DataTypeString(src_out), \" from \", src->name(), \":\", output_index,\n \" incompatible with expected \", DataTypeString(dst_in), \".\");\n }\n g_->AddEdge(src, output_index, dst, input_index);\n return Status::OK();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[127, 180]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[127, 180]]}, "_func_name": "tensorflow::GraphConstructor::MakeEdge", "_file_name": "tensorflow/core/common_runtime/graph_constructor.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)\ndef get_task(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n name = conn.fetchone()\n settings.close()\n if name == None:\n bot.send_message(message.chat.id, \"You should login before get tasks.\")\n else:\n bases.update.update_user(name[1], name[0], name[2])\n bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))\n set_state(message.chat.id, config.States.S_START.value)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_task", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_requested_month(self, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN ? AND ?\n GROUP BY TimeStamp;\n '''\n\n data['data'] = list()\n for row in self.c.execute(query, (month_start, month_end)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM MonthData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_requested_month", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _run_ssh(self, command, check_exit_code=True, attempts=1):\n if not self.sshpool:\n password = self.configuration.san_password\n privatekey = self.configuration.san_private_key\n min_size = self.configuration.ssh_min_pool_conn\n max_size = self.configuration.ssh_max_pool_conn\n self.sshpool = utils.SSHPool(self.configuration.san_ip,\n self.configuration.san_ssh_port,\n self.configuration.ssh_conn_timeout,\n self.configuration.san_login,\n password=password,\n privatekey=privatekey,\n min_size=min_size,\n max_size=max_size)\n last_exception = None\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return utils.ssh_execute(\n ssh,\n command,\n check_exit_code=check_exit_code)\n except Exception as e:\n LOG.error(e)\n last_exception = e\n greenthread.sleep(random.randint(20, 500) / 100.0)\n try:\n raise exception.ProcessExecutionError(\n exit_code=last_exception.exit_code,\n stdout=last_exception.stdout,\n stderr=last_exception.stderr,\n cmd=last_exception.cmd)\n except AttributeError:\n raise exception.ProcessExecutionError(\n exit_code=-1,\n stdout=\"\",\n stderr=\"Error running SSH command\",\n cmd=command)\n\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running SSH command: %s\") % command)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 67]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 67]]}, "_func_name": "_run_ssh", "_file_name": "cinder/volume/drivers/san/san.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'POST':\n msg_id = int(request.form['msg_id'])\n user_id = session['logged_id']\n content = request.form['content']\n c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n cursor.execute(\"INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);\", (msg_id, user_id, content, c_time))\n conn.commit()\n return redirect(url_for('comment.show', msg_id=msg_id))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int track_header(VividasDemuxContext *viv, AVFormatContext *s, uint8_t *buf, int size)\n{\n int i, j, ret;\n int64_t off;\n int val_1;\n int num_video;\n AVIOContext pb0, *pb = &pb0;\n\n ffio_init_context(pb, buf, size, 0, NULL, NULL, NULL, NULL);\n\n ffio_read_varlen(pb); // track_header_len\n avio_r8(pb); // '1'\n\n val_1 = ffio_read_varlen(pb);\n\n for (i=0;iid = i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;\n st->codecpar->codec_id = AV_CODEC_ID_VP6;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb);\n avio_r8(pb); // '3'\n avio_r8(pb); // val_7\n num = avio_rl32(pb); // frame_time\n den = avio_rl32(pb); // time_base\n avpriv_set_pts_info(st, 64, num, den);\n st->nb_frames = avio_rl32(pb); // n frames\n st->codecpar->width = avio_rl16(pb); // width\n st->codecpar->height = avio_rl16(pb); // height\n avio_r8(pb); // val_8\n avio_rl32(pb); // val_9\n\n avio_seek(pb, off, SEEK_SET);\n }\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // val_10\n avio_r8(pb); // '4'\n viv->num_audio = avio_r8(pb);\n avio_seek(pb, off, SEEK_SET);\n\n if (viv->num_audio != 1)\n av_log(s, AV_LOG_WARNING, \"number of audio tracks %d is not 1\\n\", viv->num_audio);\n\n for(i=0;inum_audio;i++) {\n int q;\n AVStream *st = avformat_new_stream(s, NULL);\n if (!st)\n return AVERROR(ENOMEM);\n\n st->id = num_video + i;\n\n st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;\n st->codecpar->codec_id = AV_CODEC_ID_VORBIS;\n\n off = avio_tell(pb);\n off += ffio_read_varlen(pb); // length\n avio_r8(pb); // '5'\n avio_r8(pb); //codec_id\n avio_rl16(pb); //codec_subid\n st->codecpar->channels = avio_rl16(pb); // channels\n st->codecpar->sample_rate = avio_rl32(pb); // sample_rate\n avio_seek(pb, 10, SEEK_CUR); // data_1\n q = avio_r8(pb);\n avio_seek(pb, q, SEEK_CUR); // data_2\n avio_r8(pb); // zeropad\n\n if (avio_tell(pb) < off) {\n int num_data;\n int xd_size = 0;\n int data_len[256];\n int offset = 1;\n uint8_t *p;\n ffio_read_varlen(pb); // val_13\n avio_r8(pb); // '19'\n ffio_read_varlen(pb); // len_3\n num_data = avio_r8(pb);\n for (j = 0; j < num_data; j++) {\n uint64_t len = ffio_read_varlen(pb);\n if (len > INT_MAX/2 - xd_size) {\n return AVERROR_INVALIDDATA;\n }\n data_len[j] = len;\n xd_size += len;\n }\n\n ret = ff_alloc_extradata(st->codecpar, 64 + xd_size + xd_size / 255);\n if (ret < 0)\n return ret;\n\n p = st->codecpar->extradata;\n p[0] = 2;\n\n for (j = 0; j < num_data - 1; j++) {\n unsigned delta = av_xiphlacing(&p[offset], data_len[j]);\n if (delta > data_len[j]) {\n return AVERROR_INVALIDDATA;\n }\n offset += delta;\n }\n\n for (j = 0; j < num_data; j++) {\n int ret = avio_read(pb, &p[offset], data_len[j]);\n if (ret < data_len[j]) {\n st->codecpar->extradata_size = 0;\n av_freep(&st->codecpar->extradata);\n break;\n }\n offset += data_len[j];\n }\n\n if (offset < st->codecpar->extradata_size)\n st->codecpar->extradata_size = offset;\n }\n }\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[2925, 2954], [3488, 3570], [3810, 3919]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2925, 2954], [3488, 3570], [3810, 3919]]}, "_func_name": "track_header", "_file_name": "libavformat/vividas.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _get_settings(view):\n return {\n 'linters': get_settings(view, 'anaconda_go_linters', []),\n 'lint_test': get_settings(\n view, 'anaconda_go_lint_test', False),\n 'exclude_regexps': get_settings(\n view, 'anaconda_go_exclude_regexps', []),\n 'max_line_length': get_settings(\n view, 'anaconda_go_max_line_length', 120),\n 'gocyclo_threshold': get_settings(\n view, 'anaconda_go_gocyclo_threshold', 10),\n 'golint_min_confidence': get_settings(\n view, 'anaconda_go_golint_min_confidence', 0.80),\n 'goconst_min_occurrences': get_settings(\n view, 'anaconda_go_goconst_min_occurrences', 3),\n 'min_const_length': get_settings(\n view, 'anaconda_go_min_const_length', 3),\n 'dupl_threshold': get_settings(\n view, 'anaconda_go_dupl_threshold', 50),\n 'path': get_working_directory(view)\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[888, 932]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[888, 932]]}, "_func_name": "_get_settings", "_file_name": "lib/_sublime.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def cancelFollow(self,userid,friendid):\n sqlText=\"delete from friends where userid=%d and friendid=%d;\"%(userid,friendid)\n result=sql.deleteDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[44, 133]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[44, 133]]}, "_func_name": "cancelFollow", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,\n const int whence,void *user_data)\n{\n PhotoshopProfile\n *profile;\n\n profile=(PhotoshopProfile *) user_data;\n switch (whence)\n {\n case SEEK_SET:\n default:\n {\n if (offset < 0)\n return(-1);\n profile->offset=offset;\n break;\n }\n case SEEK_CUR:\n {\n if ((profile->offset+offset) < 0)\n return(-1);\n profile->offset+=offset;\n break;\n }\n case SEEK_END:\n {\n if (((MagickOffsetType) profile->length+offset) < 0)\n return(-1);\n profile->offset=profile->length+offset;\n break;\n }\n }\n\n return(profile->offset);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[366, 406]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[366, 406]]}, "_func_name": "TIFFSeekCustomStream", "_file_name": "coders/tiff.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)\n{\n\tsc_context_t *ctx;\n\tsc_apdu_t apdu;\n\tu8 rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tu8 sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\ttcos_data *data;\n\tint tcos3, r;\n\n\tassert(card != NULL && crgram != NULL && out != NULL);\n\tctx = card->ctx;\n\ttcos3=(card->type==SC_CARD_TYPE_TCOS_V3);\n\tdata=(tcos_data *)card->drv_data;\n\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t\t\"TCOS3:%d PKCS1:%d\\n\",tcos3,\n\t\t!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));\n\n\tsc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = crgram_len;\n\n\tapdu.data = sbuf;\n\tapdu.lc = apdu.datalen = crgram_len+1;\n\tsbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);\n\tif (sizeof sbuf - 1 < crgram_len)\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\tmemcpy(sbuf+1, crgram, crgram_len);\n\n\tr = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, r, \"APDU transmit failed\");\n\n\tif (apdu.sw1==0x90 && apdu.sw2==0x00) {\n\t\tsize_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;\n\t\tunsigned int offset=0;\n\t\tif(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) {\n\t\t\toffset=2; while(offsetctx, SC_LOG_DEBUG_VERBOSE, len-offset);\n\t}\n\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tcos_decipher", "_file_name": "src/libopensc/card-tcos.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _check_camera_tags(tags):\n \"\"\"\n Function that convert stupid code name of a smartphone or camera\n from EXIF to meaningful one by looking a collation in a special MySQL\n table For example instead of just Nikon there can be\n NIKON CORPORATION in EXIF\n\n :param tags: name of a camera and lens from EXIF\n :return: list with one or two strings which are name of\n camera and/or lens. If there is not better name for the gadget\n in database, function just returns name how it is\n \"\"\"\n checked_tags = []\n\n for tag in tags:\n if tag: # If there was this information inside EXIF of the photo\n tag = str(tag).strip()\n log.info('Looking up collation for %s', tag)\n query = ('SELECT right_tag '\n 'FROM tag_table '\n 'WHERE wrong_tag=\"{}\"'.format(tag))\n cursor = db.execute_query(query)\n if not cursor:\n log.error(\"Can't check the tag because of the db error\")\n log.warning(\"Tag will stay as is.\")\n continue\n if cursor.rowcount:\n # Get appropriate tag from the table\n tag = cursor.fetchone()[0]\n log.info('Tag after looking up in tag_tables - %s.', tag)\n\n checked_tags.append(tag)\n return checked_tags", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[891, 952]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[891, 952]]}, "_func_name": "_check_camera_tags", "_file_name": "photogpsbot/process_image.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)\n{\n\tGC_REFCOUNT(ht) = 1;\n\tGC_TYPE_INFO(ht) = IS_ARRAY;\n\tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n\tht->nTableMask = HT_MIN_MASK;\n\tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n\tht->nNumUsed = 0;\n\tht->nNumOfElements = 0;\n\tht->nInternalPointer = HT_INVALID_IDX;\n\tht->nNextFreeElement = 0;\n\tht->pDestructor = pDestructor;\n\tht->nTableSize = zend_hash_check_size(nSize);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_zend_hash_init", "_file_name": "Zend/zend_hash.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def initialize_connection(self, volume, connector):\n \"\"\"Restrict access to a volume.\"\"\"\n try:\n cmd = ['volume', 'select', volume['name'], 'access', 'create',\n 'initiator', connector['initiator']]\n if self.configuration.eqlx_use_chap:\n cmd.extend(['authmethod', 'chap', 'username',\n self.configuration.eqlx_chap_login])\n self._eql_execute(*cmd)\n iscsi_properties = self._get_iscsi_properties(volume)\n return {\n 'driver_volume_type': 'iscsi',\n 'data': iscsi_properties\n }\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_('Failed to initialize connection to volume %s'),\n volume['name'])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "initialize_connection", "_file_name": "cinder/volume/drivers/eqlx.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def create_event(self, title, start_time, time_zone, server_id, description):\n sql = \"\"\"\n INSERT INTO events (title, start_time, time_zone, server_id, description)\n VALUES (%s, %s, %s, %s, %s)\n \"\"\"\n self.cur.execute(sql, (title, start_time, time_zone, server_id, description))\n self.conn.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_event", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)\n{\n\tstruct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);\n\tstruct skcipher_alg *alg = crypto_skcipher_alg(skcipher);\n\n\tif (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)\n\t\treturn crypto_init_skcipher_ops_blkcipher(tfm);\n\n\tif (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||\n\t tfm->__crt_alg->cra_type == &crypto_givcipher_type)\n\t\treturn crypto_init_skcipher_ops_ablkcipher(tfm);\n\n\tskcipher->setkey = alg->setkey;\n\tskcipher->encrypt = alg->encrypt;\n\tskcipher->decrypt = alg->decrypt;\n\tskcipher->ivsize = alg->ivsize;\n\tskcipher->keysize = alg->max_keysize;\n\n\tif (alg->exit)\n\t\tskcipher->base.exit = crypto_skcipher_exit_tfm;\n\n\tif (alg->init)\n\t\treturn alg->init(skcipher);\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[464, 497]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[464, 497]]}, "_func_name": "crypto_skcipher_init_tfm", "_file_name": "crypto/skcipher.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_3par_host(self, hostname):\n out = self._cli_run('showhost -verbose %s' % (hostname), None)\n LOG.debug(\"OUTPUT = \\n%s\" % (pprint.pformat(out)))\n host = {'id': None, 'name': None,\n 'domain': None,\n 'descriptors': {},\n 'iSCSIPaths': [],\n 'FCPaths': []}\n\n if out:\n err = out[0]\n if err == 'no hosts listed':\n msg = {'code': 'NON_EXISTENT_HOST',\n 'desc': \"HOST '%s' was not found\" % hostname}\n raise hpexceptions.HTTPNotFound(msg)\n\n # start parsing the lines after the header line\n for line in out[1:]:\n if line == '':\n break\n tmp = line.split(',')\n paths = {}\n\n LOG.debug(\"line = %s\" % (pprint.pformat(tmp)))\n host['id'] = tmp[0]\n host['name'] = tmp[1]\n\n portPos = tmp[4]\n LOG.debug(\"portPos = %s\" % (pprint.pformat(portPos)))\n if portPos == '---':\n portPos = None\n else:\n port = portPos.split(':')\n portPos = {'node': int(port[0]), 'slot': int(port[1]),\n 'cardPort': int(port[2])}\n\n paths['portPos'] = portPos\n\n # If FC entry\n if tmp[5] == 'n/a':\n paths['wwn'] = tmp[3]\n host['FCPaths'].append(paths)\n # else iSCSI entry\n else:\n paths['name'] = tmp[3]\n paths['ipAddr'] = tmp[5]\n host['iSCSIPaths'].append(paths)\n\n # find the offset to the description stuff\n offset = 0\n for line in out:\n if line[:15] == '---------- Host':\n break\n else:\n offset += 1\n\n info = out[offset + 2]\n tmp = info.split(':')\n host['domain'] = tmp[1]\n\n info = out[offset + 4]\n tmp = info.split(':')\n host['descriptors']['location'] = tmp[1]\n\n info = out[offset + 5]\n tmp = info.split(':')\n host['descriptors']['ipAddr'] = tmp[1]\n\n info = out[offset + 6]\n tmp = info.split(':')\n host['descriptors']['os'] = tmp[1]\n\n info = out[offset + 7]\n tmp = info.split(':')\n host['descriptors']['model'] = tmp[1]\n\n info = out[offset + 8]\n tmp = info.split(':')\n host['descriptors']['contact'] = tmp[1]\n\n info = out[offset + 9]\n tmp = info.split(':')\n host['descriptors']['comment'] = tmp[1]\n\n return host", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[40, 111]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[40, 111]]}, "_func_name": "_get_3par_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n error = None\n email = request.form['email'].strip()\n nickname = request.form['nickname'].strip()\n password = request.form['password'].strip()\n password2 = request.form['password2'].strip()\n\n email = email.lower()\n\n if email == \"\" or nickname == \"\" or password == \"\" or password2 == \"\":\n error = 'Please input all the information'\n elif password2 != password:\n error = 'The password is not repeated correctly'\n elif len(password) < 6:\n error = 'The password has at least 6 characters'\n elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +\n '[0-9a-zA-Z]{1,15}\\.[com,cn,net]', email):\n error = 'Please input the right email'\n\n sql = \"SELECT * FROM users where email = '%s';\" % (email)\n cursor.execute(sql)\n u = cursor.fetchone()\n\n if u is not None:\n error = 'The email has already exsit'\n\n if error is not None:\n return render_template('register.html', error=error)\n else:\n password = bcrypt.generate_password_hash(password)\n cursor.execute(\"INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);\", (email, nickname, password))\n conn.commit()\n flash('Register Success!')\n return redirect(url_for('users.login'))\n\n return render_template('register.html')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[852, 946]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[852, 946]]}, "_func_name": "register", "_file_name": "flaskr/flaskr/views/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n register const unsigned char\n *p;\n\n size_t\n length;\n\n unsigned char\n *datum;\n\n unsigned int\n count,\n long_sans;\n\n unsigned short\n id,\n short_sans;\n\n length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n register unsigned char\n *q;\n\n q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-\n (PSDQuantum(count)+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[766, 948]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[766, 948]]}, "_func_name": "RemoveICCProfileFromResourceBlock", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)\n{\n\tswitch (mem->type) {\n\tcase RXE_MEM_TYPE_DMA:\n\t\treturn 0;\n\n\tcase RXE_MEM_TYPE_MR:\n\tcase RXE_MEM_TYPE_FMR:\n\t\tif (iova < mem->iova ||\n\t\t length > mem->length ||\n\t\t iova > mem->iova + mem->length - length)\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tdefault:\n\t\treturn -EFAULT;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mem_check_range", "_file_name": "drivers/infiniband/sw/rxe/rxe_mr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/referrer_count')\ndef referrer_count():\n account_id = request.args.get('account_id')\n\n if not isObject(account_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_account_names\",[[\"' + account_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n\n account_id = j_l[\"result\"][0][\"id\"]\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"select count(*) from referrers where referrer='\"+account_id+\"'\"\n cur.execute(query)\n results = cur.fetchone()\n\n return jsonify(results)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[424, 501]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[424, 501]]}, "_func_name": "referrer_count", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "SWFInput_readSBits(SWFInput input, int number)\n{\n\tint num = SWFInput_readBits(input, number);\n\n\tif(number && num & (1<<(number-1)))\n\t\treturn num - (1< 0) {\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Company\",\n TAG_NONE, TAG_FMT_STRING, l1, buffer+2);\n if (length > 2+l1+1) {\n l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1);\n exif_iif_add_tag(ImageInfo, SECTION_APP12, \"Info\",\n TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);\n }\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[339, 393]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[339, 393]]}, "_func_name": "HPHP::exif_process_APP12", "_file_name": "hphp/runtime/ext/gd/ext_gd.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,\n\t\tunsigned char **out, size_t *out_len,\n\t\tint verify_pin)\n{\n\tstruct sc_context *ctx = p15card->card->ctx;\n\tstruct sc_card *card = p15card->card;\n\tstruct sc_file *file = NULL;\n\tstruct sc_path path;\n\tsize_t sz;\n\tint rv;\n\n\tLOG_FUNC_CALLED(ctx);\n\tif (!in_path || !out || !out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Cannot read oberthur file\");\n\n\tsc_log(ctx, \"read file '%s'; verify_pin:%i\", in_path, verify_pin);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tsc_format_path(in_path, &path);\n\trv = sc_select_file(card, &path, &file);\n\tif (rv != SC_SUCCESS) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot select oberthur file to read\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT)\n\t\tsz = file->size;\n\telse\n\t\tsz = (file->record_length + 2) * file->record_count;\n\n\t*out = calloc(sz, 1);\n\tif (*out == NULL) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot read oberthur file\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT) {\n\t\trv = sc_read_binary(card, 0, *out, sz, 0);\n\t}\n\telse\t{\n\t\tsize_t rec;\n\t\tsize_t offs = 0;\n\t\tsize_t rec_len = file->record_length;\n\n\t\tfor (rec = 1; ; rec++) {\n\t\t\tif (rec > file->record_count) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);\n\t\t\tif (rv == SC_ERROR_RECORD_NOT_FOUND) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rv < 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\trec_len = rv;\n\n\t\t\t*(*out + offs) = 'R';\n\t\t\t*(*out + offs + 1) = rv;\n\n\t\t\toffs += rv + 2;\n\t\t}\n\n\t\tsz = offs;\n\t}\n\n\tsc_log(ctx, \"read oberthur file result %i\", rv);\n\tif (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tstruct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;\n\t\tconst struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\t\tint ii;\n\n\t\trv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);\n\t\tif (rv != SC_SUCCESS) {\n\t\t\tsc_file_free(file);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Cannot read oberthur file: get AUTH objects error\");\n\t\t}\n\n\t\tfor (ii=0; iidata;\n\t\t\tsc_log(ctx, \"compare PIN/ACL refs:%i/%i, method:%i/%i\",\n\t\t\t\t\tauth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);\n\t\t\tif (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {\n\t\t\t\tpin_obj = objs[ii];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!pin_obj || !pin_obj->content.value) {\n\t\t\trv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;\n\t\t}\n\t\telse {\n\t\t\trv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);\n\t\t\tif (!rv)\n\t\t\t\trv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);\n\t\t}\n\t};\n\n\tsc_file_free(file);\n\n\tif (rv < 0) {\n\t\tfree(*out);\n\t\t*out = NULL;\n\t\t*out_len = 0;\n\t}\n\n\t*out_len = sz;\n\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "sc_oberthur_read_file", "_file_name": "src/libopensc/pkcs15-oberthur.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def likeComments(self,commentid,userid):\n sqlText=\"insert into comment_like values(%s,%s);\"\n params=[userid,commentid]\n result=sql.insertDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "likeComments", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_list_context(context=None):\n\tlist_context = frappe._dict(\n\t\ttemplate = \"templates/includes/blog/blog.html\",\n\t\tget_list = get_blog_list,\n\t\thide_filters = True,\n\t\tchildren = get_children(),\n\t\t# show_search = True,\n\t\ttitle = _('Blog')\n\t)\n\n\tcategory = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category)\n\tif category:\n\t\tcategory_title = get_blog_category(category)\n\t\tlist_context.sub_title = _(\"Posts filed under {0}\").format(category_title)\n\t\tlist_context.title = category_title\n\n\telif frappe.local.form_dict.blogger:\n\t\tblogger = frappe.db.get_value(\"Blogger\", {\"name\": frappe.local.form_dict.blogger}, \"full_name\")\n\t\tlist_context.sub_title = _(\"Posts by {0}\").format(blogger)\n\t\tlist_context.title = blogger\n\n\telif frappe.local.form_dict.txt:\n\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(sanitize_html(frappe.local.form_dict.txt))\n\n\tif list_context.sub_title:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"},\n\t\t\t\t\t\t\t\t{\"name\": \"Blog\", \"route\": \"/blog\"}]\n\telse:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"}]\n\n\tlist_context.update(frappe.get_doc(\"Blog Settings\", \"Blog Settings\").as_dict(no_default_fields=True))\n\treturn list_context", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_list_context", "_file_name": "frappe/website/doctype/blog_post/blog_post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @unpack\n def test_process_as_form(self, job_number, dcn_key, was_prev_matched,\n was_prev_closed, was_prev_tracked):\n email_obj = {\n 'sender' : \"Alex Roy \",\n 'subject' : \"DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`\",\n 'date' : \"Tue, 7 May 2019 17:34:17 +0000\",\n 'content' : (\n f\"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&\"\n f\"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&\"\n f\"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&\"\n f\"quality=2&cc_email=&link_to_cert={dcn_key}\\r\\n\"\n )\n }\n # set-up new entries in db, if necessary\n fake_dilfo_insert = \"\"\"\n INSERT INTO df_dilfo (job_number, receiver_email, closed)\n VALUES ({}, 'alex.roy616@gmail.com', {})\n \"\"\"\n fake_match_insert = \"\"\"\n INSERT INTO df_matched (job_number, verifier, ground_truth)\n VALUES ({}, 'alex.roy616@gmail.com', {})\n \"\"\"\n with create_connection() as conn:\n if was_prev_closed or was_prev_tracked:\n conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed))\n if was_prev_matched:\n if was_prev_closed:\n conn.cursor().execute(fake_match_insert.format(job_number, 1))\n else:\n conn.cursor().execute(fake_match_insert.format(job_number, 0))\n with create_connection() as conn:\n df_dilfo_pre = pd.read_sql(f\"SELECT * FROM df_dilfo WHERE job_number={job_number}\", conn)\n df_matched_pre = pd.read_sql(f\"SELECT * FROM df_matched WHERE job_number={job_number}\", conn)\n process_as_form(email_obj)\n # make assertions about db now that reply has been processed\n with create_connection() as conn:\n df_dilfo_post = pd.read_sql(f\"SELECT * FROM df_dilfo WHERE job_number={job_number}\", conn)\n df_matched_post = pd.read_sql(f\"SELECT * FROM df_matched WHERE job_number={job_number}\", conn)\n self.assertEqual(len(df_dilfo_post), 1)\n self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))\n self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))\n self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))\n self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))\n self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[823, 876], [992, 1045], [1151, 1244], [1313, 1396], [1418, 1501], [1543, 1751], [1897, 2107]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[823, 876], [992, 1045], [1151, 1244], [1313, 1396], [1418, 1501], [1543, 1751], [1897, 2107]]}, "_func_name": "test_process_as_form", "_file_name": "tests.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n try:\n int(winner)\n int(loser)\n except ValueError:\n raise ValueError(\n \"\\\"winner\\\" and/or \\\"loser\\\" input are not integers.\\n\"\n \"Please use the id number of each player to report match results.\"\n )\n w = str(winner)\n l = str(loser)\n db = connect()\n c = db.cursor()\n c.execute(\"INSERT INTO matches values (%s, %s)\", (w,l))\n db.commit()\n db.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "reportMatch", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def populate_custom_grains_and_pillar():\n '''\n Populate local salt-minion grains and pillar fields values as specified in\n config file.\n\n For example:\n\n custom_grains_pillar:\n grains:\n - selinux: selinux:enabled\n - release: osrelease\n pillar:\n - ntpserver: network_services:ntpserver\n\n Note that the core grains are already included in hubble grains -- this\n is only necessary for custom grains and pillar data.\n '''\n log.debug('Fetching custom grains and pillar details')\n grains = {}\n salt.modules.config.__opts__ = __opts__\n custom_grains = __salt__['config.get']('custom_grains_pillar:grains', [])\n for grain in custom_grains:\n for key in grain:\n if _valid_command(grain[key]):\n value = __salt__['cmd.run']('salt-call grains.get {0}'.format(grain[key])).split('\\n')[1].strip()\n grains[key] = value\n custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', [])\n for pillar in custom_pillar:\n for key in pillar:\n if _valid_command(pillar[key]):\n value = __salt__['cmd.run']('salt-call pillar.get {0}'.format(pillar[key])).split('\\n')[1].strip()\n grains[key] = value\n log.debug('Done with fetching custom grains and pillar details')\n return grains", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[751, 944], [1082, 1277]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[751, 944], [1082, 1277]]}, "_func_name": "populate_custom_grains_and_pillar", "_file_name": "hubblestack/extmods/grains/custom_grains_pillar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_hostvdisk_mappings(self, host_name):\n \"\"\"Return the defined storage mappings for a host.\"\"\"\n\n return_data = {}\n ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name\n out, err = self._run_ssh(ssh_cmd)\n\n mappings = out.strip().split('\\n')\n if len(mappings):\n header = mappings.pop(0)\n for mapping_line in mappings:\n mapping_data = self._get_hdr_dic(header, mapping_line, '!')\n return_data[mapping_data['vdisk_name']] = mapping_data\n\n return return_data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[138, 205]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[138, 205]]}, "_func_name": "_get_hostvdisk_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('//edit')\ndef render_page_edit(page_name):\n query = db.query(\"select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n wiki_page = query.namedresult()\n if len(wiki_page) > 0:\n content = wiki_page[0].content\n else:\n content = \"\"\n return render_template(\n 'edit_page.html',\n page_name = page_name,\n content = content\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "render_page_edit", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def retrieve_last_video_position(playlist_id, db):\n db.execute(\n \"SELECT max(position) as position from video WHERE playlist_id=%s;\", (playlist_id,))\n row = db.fetchone()\n return row['position']", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "retrieve_last_video_position", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)\n{\n\tstruct usb_device *dev = chip->dev;\n\tstruct usb_host_interface *host_iface;\n\tstruct usb_interface_descriptor *altsd;\n\tvoid *control_header;\n\tint i, protocol;\n\n\t/* find audiocontrol interface */\n\thost_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];\n\tcontrol_header = snd_usb_find_csint_desc(host_iface->extra,\n\t\t\t\t\t\t host_iface->extralen,\n\t\t\t\t\t\t NULL, UAC_HEADER);\n\taltsd = get_iface_desc(host_iface);\n\tprotocol = altsd->bInterfaceProtocol;\n\n\tif (!control_header) {\n\t\tdev_err(&dev->dev, \"cannot find UAC_HEADER\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tswitch (protocol) {\n\tdefault:\n\t\tdev_warn(&dev->dev,\n\t\t\t \"unknown interface protocol %#02x, assuming v1\\n\",\n\t\t\t protocol);\n\t\t/* fall through */\n\n\tcase UAC_VERSION_1: {\n\t\tstruct uac1_ac_header_descriptor *h1 = control_header;\n\n\t\tif (!h1->bInCollection) {\n\t\t\tdev_info(&dev->dev, \"skipping empty audio interface (v1)\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (h1->bLength < sizeof(*h1) + h1->bInCollection) {\n\t\t\tdev_err(&dev->dev, \"invalid UAC_HEADER (v1)\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tfor (i = 0; i < h1->bInCollection; i++)\n\t\t\tsnd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);\n\n\t\tbreak;\n\t}\n\n\tcase UAC_VERSION_2: {\n\t\tstruct usb_interface_assoc_descriptor *assoc =\n\t\t\tusb_ifnum_to_if(dev, ctrlif)->intf_assoc;\n\n\t\tif (!assoc) {\n\t\t\t/*\n\t\t\t * Firmware writers cannot count to three. So to find\n\t\t\t * the IAD on the NuForce UDH-100, also check the next\n\t\t\t * interface.\n\t\t\t */\n\t\t\tstruct usb_interface *iface =\n\t\t\t\tusb_ifnum_to_if(dev, ctrlif + 1);\n\t\t\tif (iface &&\n\t\t\t iface->intf_assoc &&\n\t\t\t iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&\n\t\t\t iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)\n\t\t\t\tassoc = iface->intf_assoc;\n\t\t}\n\n\t\tif (!assoc) {\n\t\t\tdev_err(&dev->dev, \"Audio class v2 interfaces need an interface association\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tfor (i = 0; i < assoc->bInterfaceCount; i++) {\n\t\t\tint intf = assoc->bFirstInterface + i;\n\n\t\t\tif (intf != ctrlif)\n\t\t\t\tsnd_usb_create_stream(chip, ctrlif, intf);\n\t\t}\n\n\t\tbreak;\n\t}\n\t}\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[235, 236]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[235, 236]]}, "_func_name": "snd_usb_create_streams", "_file_name": "sound/usb/card.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def respond_error(self, context, exception):\n context.respond_server_error()\n stack = traceback.format_exc()\n return \"\"\"\n \n \n\n \n\n \n
\n

\n Server error\n

\n
\n%s\n                
\n \n \n \"\"\" % cgi.escape(stack)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "respond_error", "_file_name": "ajenti/routing.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_initialize_connection(self):\n self.driver._eql_execute = self.mox.\\\n CreateMock(self.driver._eql_execute)\n volume = {'name': self.volume_name}\n self.stubs.Set(self.driver, \"_get_iscsi_properties\",\n self._fake_get_iscsi_properties)\n self.driver._eql_execute('volume', 'select', volume['name'], 'access',\n 'create', 'initiator',\n self.connector['initiator'],\n 'authmethod', 'chap',\n 'username',\n self.configuration.eqlx_chap_login)\n self.mox.ReplayAll()\n iscsi_properties = self.driver.initialize_connection(volume,\n self.connector)\n self.assertEqual(iscsi_properties['data'],\n self._fake_get_iscsi_properties(volume))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_initialize_connection", "_file_name": "cinder/tests/test_eqlx.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/referrer_count')\ndef referrer_count():\n account_id = request.args.get('account_id')\n\n if not isObject(account_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_account_names\",[[\"' + account_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n\n account_id = j_l[\"result\"][0][\"id\"]\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"select count(*) from referrers where referrer=%s\"\n cur.execute(query, (account_id,))\n results = cur.fetchone()\n\n return jsonify(results)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "referrer_count", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)\n{\n uint32_t *input_u32;\n uint8_t *input_u8, *output_u8;\n size_t length;\n int rc;\n\n if (!input)\n {\n if (output)\n\t*output = 0;\n return IDN2_OK;\n }\n\n input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));\n if (!input_u32)\n return IDN2_MALLOC;\n\n u32_cpy (input_u32, input, inlen);\n input_u32[inlen] = 0;\n\n input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);\n free (input_u32);\n if (!input_u8)\n {\n if (errno == ENOMEM)\n\treturn IDN2_MALLOC;\n return IDN2_ENCODING_ERROR;\n }\n\n rc = idn2_lookup_u8 (input_u8, &output_u8, flags);\n free (input_u8);\n\n if (rc == IDN2_OK)\n {\n /* wow, this is ugly, but libidn manpage states:\n * char * out output zero terminated string that must have room for at\n * least 63 characters plus the terminating zero.\n */\n if (output)\n\tstrcpy (output, (const char *) output_u8);\n\n free(output_u8);\n }\n\n return rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[933, 977]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[933, 977]]}, "_func_name": "idn2_to_ascii_4i", "_file_name": "lib/lookup.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def pascal_case(value: str) -> str:\n return stringcase.pascalcase(value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[36, 75]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[36, 75]]}, "_func_name": "pascal_case", "_file_name": "openapi_python_client/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def valid_id(opts, id_):\n '''\n Returns if the passed id is valid\n '''\n try:\n return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)\n except (AttributeError, KeyError, TypeError) as e:\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[88, 215]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[88, 215]]}, "_func_name": "valid_id", "_file_name": "salt/utils/verify.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])\n\n create_host_cmd = ('createhost -add fakehost '\n '123456789012345 123456789054321')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[635, 752]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[635, 752]]}, "_func_name": "test_create_modify_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def userLogin(self):\n\n sqlName=\"select count(*) from users where name='%s' and \\\n password='%s';\"%(self.name,self.password)\n checkName=sql.queryDB(self.conn,sqlName)\n\n result=checkName[0][0]\n if result == 0:\n self.clean()\n return False\n else:\n return True", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[26, 199]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[26, 199]]}, "_func_name": "userLogin", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy)\n{\n mrb_value orig;\n mrb_value buf;\n struct mrb_io *fptr_copy;\n struct mrb_io *fptr_orig;\n mrb_bool failed = TRUE;\n\n mrb_get_args(mrb, \"o\", &orig);\n fptr_copy = (struct mrb_io *)DATA_PTR(copy);\n if (fptr_copy != NULL) {\n fptr_finalize(mrb, fptr_copy, FALSE);\n mrb_free(mrb, fptr_copy);\n }\n fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb);\n fptr_orig = io_get_open_fptr(mrb, orig);\n\n DATA_TYPE(copy) = &mrb_io_type;\n DATA_PTR(copy) = fptr_copy;\n\n buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, \"@buf\"));\n mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, \"@buf\"), buf);\n\n fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed);\n if (failed) {\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd);\n\n if (fptr_orig->fd2 != -1) {\n fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed);\n if (failed) {\n close(fptr_copy->fd);\n mrb_sys_fail(mrb, 0);\n }\n mrb_fd_cloexec(mrb, fptr_copy->fd2);\n }\n\n fptr_copy->pid = fptr_orig->pid;\n fptr_copy->readable = fptr_orig->readable;\n fptr_copy->writable = fptr_orig->writable;\n fptr_copy->sync = fptr_orig->sync;\n fptr_copy->is_socket = fptr_orig->is_socket;\n\n return copy;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[358, 451]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[358, 451]]}, "_func_name": "mrb_io_initialize_copy", "_file_name": "mrbgems/mruby-io/src/io.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int exif_scan_JPEG_header(image_info_type *ImageInfo) {\n int section, sn;\n int marker = 0, last_marker = M_PSEUDO, comment_correction=1;\n int ll, lh;\n unsigned char *Data;\n size_t fpos, size, got, itemlen;\n jpeg_sof_info sof_info;\n\n for(section=0;;section++) {\n // get marker byte, swallowing possible padding\n // some software does not count the length bytes of COM section\n // one company doing so is very much envolved in JPEG...\n // so we accept too\n if (last_marker==M_COM && comment_correction) {\n comment_correction = 2;\n }\n do {\n if ((marker = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n if (last_marker==M_COM && comment_correction>0) {\n if (marker!=0xFF) {\n marker = 0xff;\n comment_correction--;\n } else {\n last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */\n }\n }\n } while (marker == 0xff);\n if (last_marker==M_COM && !comment_correction) {\n raise_notice(\"Image has corrupt COM section: some software set \"\n \"wrong length information\");\n }\n if (last_marker==M_COM && comment_correction)\n return M_EOI; /* ah illegal: char after COM section not 0xFF */\n\n fpos = ImageInfo->infile->tell();\n\n if (marker == 0xff) {\n // 0xff is legal padding, but if we get that many, something's wrong.\n raise_warning(\"To many padding bytes\");\n return 0;\n }\n\n /* Read the length of the section. */\n\n if ((lh = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n if ((ll = ImageInfo->infile->getc()) == EOF) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n itemlen = (lh << 8) | ll;\n\n if (itemlen < 2) {\n raise_warning(\"File structure corrupted\");\n return 0;\n }\n\n sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr);\n if (sn == -1) return 0;\n Data = ImageInfo->file.list[sn].data;\n\n /* Store first two pre-read bytes. */\n Data[0] = (unsigned char)lh;\n Data[1] = (unsigned char)ll;\n\n String str = ImageInfo->infile->read(itemlen-2);\n got = str.length();\n if (got != itemlen-2) {\n raise_warning(\"Error reading from file: \"\n \"got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)\",\n got, got, itemlen-2, itemlen-2);\n return 0;\n }\n memcpy(Data+2, str.c_str(), got);\n switch(marker) {\n case M_SOS: /* stop before hitting compressed data */\n // If reading entire image is requested, read the rest of the data.\n if (ImageInfo->read_all) {\n /* Determine how much file is left. */\n fpos = ImageInfo->infile->tell();\n size = ImageInfo->FileSize - fpos;\n sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr);\n if (sn == -1) return 0;\n Data = ImageInfo->file.list[sn].data;\n str = ImageInfo->infile->read(size);\n got = str.length();\n if (got != size) {\n raise_warning(\"Unexpected end of file reached\");\n return 0;\n }\n memcpy(Data, str.c_str(), got);\n }\n return 1;\n\n case M_EOI: /* in case it's a tables-only JPEG stream */\n raise_warning(\"No image in jpeg!\");\n return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0;\n\n case M_COM: /* Comment section */\n exif_process_COM(ImageInfo, (char *)Data, itemlen);\n break;\n\n case M_EXIF:\n if (!(ImageInfo->sections_found&FOUND_IFD0)) {\n /*ImageInfo->sections_found |= FOUND_EXIF;*/\n /* Seen files from some 'U-lead' software with Vivitar scanner\n that uses marker 31 later in the file (no clue what for!) */\n exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos);\n }\n break;\n\n case M_APP12:\n exif_process_APP12(ImageInfo, (char *)Data, itemlen);\n break;\n\n\n case M_SOF0:\n case M_SOF1:\n case M_SOF2:\n case M_SOF3:\n case M_SOF5:\n case M_SOF6:\n case M_SOF7:\n case M_SOF9:\n case M_SOF10:\n case M_SOF11:\n case M_SOF13:\n case M_SOF14:\n case M_SOF15:\n if ((itemlen - 2) < 6) {\n return 0;\n }\n\n exif_process_SOFn(Data, marker, &sof_info);\n ImageInfo->Width = sof_info.width;\n ImageInfo->Height = sof_info.height;\n if (sof_info.num_components == 3) {\n ImageInfo->IsColor = 1;\n } else {\n ImageInfo->IsColor = 0;\n }\n break;\n default:\n /* skip any other marker silently. */\n break;\n }\n\n /* keep track of last marker */\n last_marker = marker;\n }\n return 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::exif_scan_JPEG_header", "_file_name": "hphp/runtime/ext/gd/ext_gd.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)\n{\n struct lys_restr *result;\n int i;\n\n if (!size) {\n return NULL;\n }\n\n result = calloc(size, sizeof *result);\n LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);\n\n for (i = 0; i < size; i++) {\n /* copying unresolved extensions is not supported */\n if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n result[i].ext_size = old[i].ext_size;\n lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n }\n result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);\n result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);\n result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);\n result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);\n result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);\n }\n\n return result;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "lys_restr_dup", "_file_name": "src/tree_schema.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)\n{\n\tstruct uvesafb_pal_entry *entries;\n\tint shift = 16 - dac_width;\n\tint i, err = 0;\n\n\tif (info->var.bits_per_pixel == 8) {\n\t\tif (cmap->start + cmap->len > info->cmap.start +\n\t\t info->cmap.len || cmap->start < info->cmap.start)\n\t\t\treturn -EINVAL;\n\n\t\tentries = kmalloc_array(cmap->len, sizeof(*entries),\n\t\t\t\t\tGFP_KERNEL);\n\t\tif (!entries)\n\t\t\treturn -ENOMEM;\n\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\tentries[i].red = cmap->red[i] >> shift;\n\t\t\tentries[i].green = cmap->green[i] >> shift;\n\t\t\tentries[i].blue = cmap->blue[i] >> shift;\n\t\t\tentries[i].pad = 0;\n\t\t}\n\t\terr = uvesafb_setpalette(entries, cmap->len, cmap->start, info);\n\t\tkfree(entries);\n\t} else {\n\t\t/*\n\t\t * For modes with bpp > 8, we only set the pseudo palette in\n\t\t * the fb_info struct. We rely on uvesafb_setcolreg to do all\n\t\t * sanity checking.\n\t\t */\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\terr |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],\n\t\t\t\t\t\tcmap->green[i], cmap->blue[i],\n\t\t\t\t\t\t0, info);\n\t\t}\n\t}\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "uvesafb_setcmap", "_file_name": "drivers/video/fbdev/uvesafb.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "\tdef getFileCacheID(self, pth):\n\t\t\"\"\"\n\t\tReturns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID.\n\t\t:param pth:\n\t\t:return:\n\t\t\"\"\"\n\t\tcommand = \"SELECT file_id FROM {0} WHERE path='{1}'\".format(TABLE_NAME, pth)\n\t\tdata = self._run_command(command)\n\n\t\ttry:\n\t\t\tdata = data[0][0]\n\t\texcept IndexError:\n\t\t\tdata = None\n\n\t\treturn data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[168, 247]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[168, 247]]}, "_func_name": "getFileCacheID", "_file_name": "file_db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)\n{\n\tint i;\n\tint ch;\n\tchar id[5];\n\tt_chunk_info *cidx;\n\tint sidx;\n\tint nc;\n\n\tGD2_DBG(php_gd_error(\"Reading gd2 header info\"));\n\n\tfor (i = 0; i < 4; i++) {\n\t\tch = gdGetC(in);\n\t\tif (ch == EOF) {\n\t\t\tgoto fail1;\n\t\t}\n\t\tid[i] = ch;\n\t}\n\tid[4] = 0;\n\n\tGD2_DBG(php_gd_error(\"Got file code: %s\", id));\n\n\t/* Equiv. of 'magick'. */\n\tif (strcmp(id, GD2_ID) != 0) {\n\t\tGD2_DBG(php_gd_error(\"Not a valid gd2 file\"));\n\t\tgoto fail1;\n\t}\n\n\t/* Version */\n\tif (gdGetWord(vers, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Version: %d\", *vers));\n\n\tif ((*vers != 1) && (*vers != 2)) {\n\t\tGD2_DBG(php_gd_error(\"Bad version: %d\", *vers));\n\t\tgoto fail1;\n\t}\n\n\t/* Image Size */\n\tif (!gdGetWord(sx, in)) {\n\t\tGD2_DBG(php_gd_error(\"Could not get x-size\"));\n\t\tgoto fail1;\n\t}\n\tif (!gdGetWord(sy, in)) {\n\t\tGD2_DBG(php_gd_error(\"Could not get y-size\"));\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Image is %dx%d\", *sx, *sy));\n\n\t/* Chunk Size (pixels, not bytes!) */\n\tif (gdGetWord(cs, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"ChunkSize: %d\", *cs));\n\n\tif ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {\n\t\tGD2_DBG(php_gd_error(\"Bad chunk size: %d\", *cs));\n\t\tgoto fail1;\n\t}\n\n\t/* Data Format */\n\tif (gdGetWord(fmt, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"Format: %d\", *fmt));\n\n\tif ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {\n\t\tGD2_DBG(php_gd_error(\"Bad data format: %d\", *fmt));\n\t\tgoto fail1;\n\t}\n\n\t/* # of chunks wide */\n\tif (gdGetWord(ncx, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"%d Chunks Wide\", *ncx));\n\n\t/* # of chunks high */\n\tif (gdGetWord(ncy, in) != 1) {\n\t\tgoto fail1;\n\t}\n\tGD2_DBG(php_gd_error(\"%d Chunks vertically\", *ncy));\n\n\tif (gd2_compressed(*fmt)) {\n\t\tnc = (*ncx) * (*ncy);\n\t\tGD2_DBG(php_gd_error(\"Reading %d chunk index entries\", nc));\n\t\tsidx = sizeof(t_chunk_info) * nc;\n\t\tif (sidx <= 0) {\n\t\t\tgoto fail1;\n\t\t}\n\t\tcidx = gdCalloc(sidx, 1);\n\t\tfor (i = 0; i < nc; i++) {\n\t\t\tif (gdGetInt(&cidx[i].offset, in) != 1) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t\tif (gdGetInt(&cidx[i].size, in) != 1) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t\tif (cidx[i].offset < 0 || cidx[i].size < 0) {\n\t\t\t\tgdFree(cidx);\n\t\t\t\tgoto fail1;\n\t\t\t}\n\t\t}\n\t\t*chunkIdx = cidx;\n\t}\n\n\tGD2_DBG(php_gd_error(\"gd2 header complete\"));\n\n\treturn 1;\n\nfail1:\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[1983, 2019]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1983, 2019]]}, "_func_name": "_gd2GetHeader", "_file_name": "ext/gd/libgd/gd_gd2.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def insertUsage(user, command):\n\tc, conn = getConnection()\n\tdate = now()\n\tc.execute(\"INSERT INTO usage (date,user,command) VALUES ('\"+date+\"','\"+str(user)+\"','\"+command+\"')\")\n\tconn.commit()\n\tconn.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[73, 175]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[73, 175]]}, "_func_name": "insertUsage", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_user(self):\n if not hasattr(self, '_user'):\n qs = \"select * from account_access where access_token = %s\"\n result = self.db.get(qs, self.access_token)\n if result:\n self._user = result\n else:\n self._user = None\n \n return self._user", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_user", "_file_name": "src/auth.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len)\n{\n\t/* OpenSc Operation values for each command operation-type */\n\tconst int df_idx[8] = {\t /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/\n\t\tSC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\tSC_AC_OP_LOCK, SC_AC_OP_DELETE, -1};\n\tconst int ef_idx[8] = {\n\t\tSC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\tconst int efi_idx[8] = { /* internal EF used for RSA keys */\n\t\tSC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE,\n\t\tSC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE,\n\t\t-1, SC_AC_OP_ERASE, -1};\n\n\tu8\t\tbValue;\n\tint\t\ti;\n\tint\t\tiKeyRef = 0;\n\tint\t\tiMethod;\n\tint\t\tiPinCount;\n\tint\t\tiOffset = 0;\n\tint\t\tiOperation;\n\tconst int*\tp_idx;\n\n\t/* Check all sub-AC definitions within the total AC */\n\twhile (len > 1) {\t\t\t\t/* minimum length = 2 */\n\t\tsize_t iACLen = buf[iOffset] & 0x0F;\n\t\tif (iACLen > len)\n\t\t\tbreak;\n\n\t\tiMethod = SC_AC_NONE;\t\t/* default no authentication required */\n\n\t\tif (buf[iOffset] & 0X80) { /* AC in adaptive coding */\n\t\t\t/* Evaluates only the command-byte, not the optional P1/P2/Option bytes */\n\t\t\tsize_t\tiParmLen = 1;\t\t\t/* command-byte is always present */\n\t\t\tsize_t\tiKeyLen = 0;\t\t\t/* Encryption key is optional */\n\n\t\t\tif (buf[iOffset] & 0x20) iKeyLen++;\n\t\t\tif (buf[iOffset+1] & 0x40) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x20) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x10) iParmLen++;\n\t\t\tif (buf[iOffset+1] & 0x08) iParmLen++;\n\n\t\t\t/* Get KeyNumber if available */\n\t\t\tif(iKeyLen) {\n\t\t\t\tint iSC;\n\t\t\t\tif (len < 1+(size_t)iACLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiSC = buf[iOffset+iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ){\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\t\t\t}\n\n\t\t\t/* Get PinNumber if available */\n\t\t\tif (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */\n\t\t\t\tif (len < 1+1+1+(size_t)iParmLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Convert SETCOS command to OpenSC command group */\n\t\t\tif (len < 1+2)\n\t\t\t\tbreak;\n\t\t\tswitch(buf[iOffset+2]){\n\t\t\tcase 0x2A:\t\t\t/* crypto operation */\n\t\t\t\tiOperation = SC_AC_OP_CRYPTO;\n\t\t\t\tbreak;\n\t\t\tcase 0x46:\t\t\t/* key-generation operation */\n\t\t\t\tiOperation = SC_AC_OP_UPDATE;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tiOperation = SC_AC_OP_SELECT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef);\n\t\t}\n\t\telse { /* AC in simple coding */\n\t\t\t /* Initial AC is treated as an operational AC */\n\n\t\t\t/* Get specific Cmd groups for specified file-type */\n\t\t\tswitch (file->type) {\n\t\t\tcase SC_FILE_TYPE_DF: /* DF */\n\t\t\t\tp_idx = df_idx;\n\t\t\t\tbreak;\n\t\t\tcase SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */\n\t\t\t\tp_idx = efi_idx;\n\t\t\t\tbreak;\n\t\t\tdefault: /* EF */\n\t\t\t\tp_idx = ef_idx;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Encryption key present ? */\n\t\t\tiPinCount = iACLen > 0 ? iACLen - 1 : 0;\n\n\t\t\tif (buf[iOffset] & 0x20) {\n\t\t\t\tint iSC;\n\t\t\t\tif (len < 1 + (size_t)iACLen)\n\t\t\t\t\tbreak;\n\t\t\t\tiSC = buf[iOffset + iACLen];\n\n\t\t\t\tswitch( (iSC>>5) & 0x03 ) {\n\t\t\t\tcase 0:\n\t\t\t\t\tiMethod = SC_AC_TERM;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tiMethod = SC_AC_AUT;\t\t/* key authentication */\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\tcase 3:\n\t\t\t\t\tiMethod = SC_AC_PRO;\t\t/* secure messaging */\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tiKeyRef = iSC & 0x1F;\t\t\t/* get key number */\n\n\t\t\t\tiPinCount--;\t\t\t\t/* one byte used for keyReference */\n\t\t\t}\n\n\t\t\t/* Pin present ? */\n\t\t\tif ( iPinCount > 0 ) {\n\t\t\t\tif (len < 1 + 2)\n\t\t\t\t\tbreak;\n\t\t\t\tiKeyRef = buf[iOffset + 2];\t/* pin ref */\n\t\t\t\tiMethod = SC_AC_CHV;\n\t\t\t}\n\n\t\t\t/* Add AC for each command-operationType into OpenSc structure */\n\t\t\tbValue = buf[iOffset + 1];\n\t\t\tfor (i = 0; i < 8; i++) {\n\t\t\t\tif((bValue & 1) && (p_idx[i] >= 0))\n\t\t\t\t\tsc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef);\n\t\t\t\tbValue >>= 1;\n\t\t\t}\n\t\t}\n\t\t/* Current field treated, get next AC sub-field */\n\t\tiOffset += iACLen +1;\t\t/* AC + PTL-byte */\n\t\tlen -= iACLen +1;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "parse_sec_attr_44", "_file_name": "src/libopensc/card-setcos.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n const unsigned char *end )\n{\n int ret = 0;\n size_t n;\n\n if( ssl->conf->f_psk == NULL &&\n ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Receive client pre-shared key identity name\n */\n if( *p + 2 > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n n = ( (*p)[0] << 8 ) | (*p)[1];\n *p += 2;\n\n if( n < 1 || n > 65535 || *p + n > end )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->conf->f_psk != NULL )\n {\n if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n else\n {\n /* Identity is not a big secret since clients send it in the clear,\n * but treat it carefully anyway, just in case */\n if( n != ssl->conf->psk_identity_len ||\n mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n {\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n }\n\n if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n {\n MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n }\n\n *p += n;\n\n return( 0 );\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[571, 594], [794, 839]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[571, 594], [794, 839]]}, "_func_name": "ssl_parse_client_psk_identity", "_file_name": "library/ssl_srv.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _create_host(self, connector):\n \"\"\"Create a new host on the storage system.\n\n We create a host name and associate it with the given connection\n information.\n\n \"\"\"\n\n LOG.debug(_('enter: _create_host: host %s') % connector['host'])\n\n rand_id = str(random.randint(0, 99999999)).zfill(8)\n host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),\n rand_id)\n\n # Get all port information from the connector\n ports = []\n if 'initiator' in connector:\n ports.append('-iscsiname %s' % connector['initiator'])\n if 'wwpns' in connector:\n for wwpn in connector['wwpns']:\n ports.append('-hbawwpn %s' % wwpn)\n\n # When creating a host, we need one port\n self._driver_assert(len(ports), _('_create_host: No connector ports'))\n port1 = ports.pop(0)\n arg_name, arg_val = port1.split()\n ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',\n '\"%s\"' % host_name]\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return('successfully created' in out,\n '_create_host', ssh_cmd, out, err)\n\n # Add any additional ports to the host\n for port in ports:\n arg_name, arg_val = port.split()\n ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,\n host_name]\n out, err = self._run_ssh(ssh_cmd)\n\n LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %\n {'host': connector['host'], 'host_name': host_name})\n return host_name", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_create_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_exe_section *sects, uint16_t scount, uint32_t pe, int desc) {\n uint8_t *structs = wwsect + 0x2a1, *compd, *ccur, *unpd, *ucur, bc;\n uint32_t src, srcend, szd, bt, bits;\n int error=0, i;\n\n cli_dbgmsg(\"in wwunpack\\n\");\n while (1) {\n if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, structs, 17)) {\n cli_dbgmsg(\"WWPack: Array of structs out of section\\n\");\n break;\n }\n src = sects[scount].rva - cli_readint32(structs); /* src delta / dst delta - not used / dwords / end of src */\n structs+=8;\n szd = cli_readint32(structs) * 4;\n structs+=4;\n srcend = cli_readint32(structs);\n structs+=4;\n\n unpd = ucur = exe+src+srcend+4-szd;\n if (!szd || !CLI_ISCONTAINED(exe, exesz, unpd, szd)) {\n cli_dbgmsg(\"WWPack: Compressed data out of file\\n\");\n break;\n }\n cli_dbgmsg(\"WWP: src: %x, szd: %x, srcend: %x - %x\\n\", src, szd, srcend, srcend+4-szd);\n if (!(compd = cli_malloc(szd))) {\n cli_dbgmsg(\"WWPack: Unable to allocate memory for compd\\n\");\n break;\n }\n memcpy(compd, unpd, szd);\n memset(unpd, -1, szd); /*FIXME*/\n ccur=compd;\n \n RESEED;\n while(!error) {\n uint32_t backbytes, backsize;\n uint8_t saved;\n\n BIT;\n if (!bits) { /* BYTE copy */\n\tif(ccur-compd>=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1))\n\t error=1;\n\telse\n\t *ucur++=*ccur++;\n\tcontinue;\n }\n\n BITS(2);\n if(bits==3) { /* WORD backcopy */\n\tuint8_t shifted, subbed = 31;\n\tBITS(2);\n\tshifted = bits + 5;\n\tif(bits>=2) {\n\t shifted++;\n\t subbed += 0x80;\n\t}\n\tbackbytes = (1< exesz || pe+7 > exesz || pe+0x28 > exesz ||\n\t\tpe+0x50 > exesz || pe+0x14 > exesz) \n\treturn CL_EFORMAT;\n exe[pe+6]=(uint8_t)scount;\n exe[pe+7]=(uint8_t)(scount>>8);\n cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299);\n cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz);\n\n structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18];\n for(i=0 ; i> 8) & 0xFF;\n *pb++ = (crc >> 16) & 0xFF;\n *pb++ = (crc >> 24) & 0xFF;\n *pb++ = in_len & 0xFF;\n *pb++ = (in_len >> 8) & 0xFF;\n *pb++ = (in_len >> 16) & 0xFF;\n *pb++ = (in_len >> 24) & 0xFF;\n\n /* Set the real buffer size for the caller */\n *out_len += FLB_GZIP_HEADER_OFFSET + 8;\n *out_data = out_buf;\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "flb_gzip_compress", "_file_name": "src/flb_gzip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,\n\t\t\t const struct host_cmd_ds_command *resp)\n{\n\tu8 *curr = (u8 *) &resp->params.get_wmm_status;\n\tuint16_t resp_len = le16_to_cpu(resp->size), tlv_len;\n\tint mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;\n\tbool valid = true;\n\n\tstruct mwifiex_ie_types_data *tlv_hdr;\n\tstruct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;\n\tstruct ieee_types_wmm_parameter *wmm_param_ie = NULL;\n\tstruct mwifiex_wmm_ac_status *ac_status;\n\n\tmwifiex_dbg(priv->adapter, INFO,\n\t\t \"info: WMM: WMM_GET_STATUS cmdresp received: %d\\n\",\n\t\t resp_len);\n\n\twhile ((resp_len >= sizeof(tlv_hdr->header)) && valid) {\n\t\ttlv_hdr = (struct mwifiex_ie_types_data *) curr;\n\t\ttlv_len = le16_to_cpu(tlv_hdr->header.len);\n\n\t\tif (resp_len < tlv_len + sizeof(tlv_hdr->header))\n\t\t\tbreak;\n\n\t\tswitch (le16_to_cpu(tlv_hdr->header.type)) {\n\t\tcase TLV_TYPE_WMMQSTATUS:\n\t\t\ttlv_wmm_qstatus =\n\t\t\t\t(struct mwifiex_ie_types_wmm_queue_status *)\n\t\t\t\ttlv_hdr;\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"QSTATUS TLV: %d, %d, %d\\n\",\n\t\t\t\t tlv_wmm_qstatus->queue_index,\n\t\t\t\t tlv_wmm_qstatus->flow_required,\n\t\t\t\t tlv_wmm_qstatus->disabled);\n\n\t\t\tac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->\n\t\t\t\t\t\t\t queue_index];\n\t\t\tac_status->disabled = tlv_wmm_qstatus->disabled;\n\t\t\tac_status->flow_required =\n\t\t\t\t\t\ttlv_wmm_qstatus->flow_required;\n\t\t\tac_status->flow_created = tlv_wmm_qstatus->flow_created;\n\t\t\tbreak;\n\n\t\tcase WLAN_EID_VENDOR_SPECIFIC:\n\t\t\t/*\n\t\t\t * Point the regular IEEE IE 2 bytes into the Marvell IE\n\t\t\t * and setup the IEEE IE type and length byte fields\n\t\t\t */\n\n\t\t\twmm_param_ie =\n\t\t\t\t(struct ieee_types_wmm_parameter *) (curr +\n\t\t\t\t\t\t\t\t 2);\n\t\t\twmm_param_ie->vend_hdr.len = (u8) tlv_len;\n\t\t\twmm_param_ie->vend_hdr.element_id =\n\t\t\t\t\t\tWLAN_EID_VENDOR_SPECIFIC;\n\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"WMM Parameter Set Count: %d\\n\",\n\t\t\t\t wmm_param_ie->qos_info_bitmap & mask);\n\n\t\t\tif (wmm_param_ie->vend_hdr.len + 2 >\n\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n\t\t\t\tbreak;\n\n\t\t\tmemcpy((u8 *) &priv->curr_bss_params.bss_descriptor.\n\t\t\t wmm_ie, wmm_param_ie,\n\t\t\t wmm_param_ie->vend_hdr.len + 2);\n\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tvalid = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tcurr += (tlv_len + sizeof(tlv_hdr->header));\n\t\tresp_len -= (tlv_len + sizeof(tlv_hdr->header));\n\t}\n\n\tmwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);\n\tmwifiex_wmm_setup_ac_downgrade(priv);\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mwifiex_ret_wmm_get_status", "_file_name": "drivers/net/wireless/marvell/mwifiex/wmm.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _set_qos_rule(self, qos, vvs_name):\n max_io = self._get_qos_value(qos, 'maxIOPS')\n max_bw = self._get_qos_value(qos, 'maxBWS')\n cli_qos_string = \"\"\n if max_io is not None:\n cli_qos_string += ('-io %s ' % max_io)\n if max_bw is not None:\n cli_qos_string += ('-bw %sM ' % max_bw)\n self._cli_run('setqos %svvset:%s' %\n (cli_qos_string, vvs_name), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[342, 441]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[342, 441]]}, "_func_name": "_set_qos_rule", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {\n setupUi(this);\n if (size == 1)\n label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(Utils::String::toHtmlEscaped(name)));\n else\n label->setText(tr(\"Are you sure you want to delete these %1 torrents from the transfer list?\", \"Are you sure you want to delete these 5 torrents from the transfer list?\").arg(QString::number(size)));\n // Icons\n lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(\"dialog-warning\").pixmap(lbl_warn->height()));\n lbl_warn->setFixedWidth(lbl_warn->height());\n rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(\"object-locked\"));\n\n move(Utils::Misc::screenCenter(this));\n checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());\n connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));\n buttonBox->button(QDialogButtonBox::Cancel)->setFocus();\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "DeletionConfirmationDlg::DeletionConfirmationDlg", "_file_name": "src/gui/deletionconfirmationdlg.h", "lang": "c", "label_confidence": "diff-derived"} {"code": "void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot save binary. '%s' is not a valid file name\", name);\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);\n free(full_path);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_save_binary", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k,\n struct opj_stream_private *p_stream,\n struct opj_event_mgr * p_manager\n )\n{\n OPJ_BYTE * l_current_data = 00;\n OPJ_UINT32 l_mco_size;\n opj_tcp_t * l_tcp = 00;\n opj_simple_mcc_decorrelation_data_t * l_mcc_record;\n OPJ_UINT32 i;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);\n l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n\n l_mco_size = 5 + l_tcp->m_nb_mcc_records;\n if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {\n\n OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);\n if (! new_header_tile_data) {\n opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);\n p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;\n p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;\n opj_event_msg(p_manager, EVT_ERROR, \"Not enough memory to write MCO marker\\n\");\n return OPJ_FALSE;\n }\n p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;\n p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;\n }\n\n opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */\n l_current_data += 2;\n\n opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */\n l_current_data += 2;\n\n opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one tranform stage*/\n ++l_current_data;\n\n l_mcc_record = l_tcp->m_mcc_records;\n for (i=0;im_nb_mcc_records;++i) {\n opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/\n ++l_current_data;\n\n ++l_mcc_record;\n }\n\n if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) {\n return OPJ_FALSE;\n }\n\n return OPJ_TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[636, 715], [2061, 2115], [2227, 2261]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[636, 715], [2061, 2115], [2227, 2261]]}, "_func_name": "opj_j2k_write_mco", "_file_name": "src/lib/openjp2/j2k.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(commands=['stats'])\ndef stats(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n name = conn.fetchone()\n settings.close()\n if name != None:\n bases.update.update_user(name[1], name[0], name[2])\n bases.problem.create_text_stats(name[1])\n img = open(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\users\\\\\" + name[1] + \".png\", \"rb\")\n bot.send_photo(message.chat.id, img)\n img.close()\n if bases.problem.create_stats_picture(name[1]):\n bot.send_message(message.chat.id, \"Sorry, you haven't solved tasks.\")\n return 0\n img = open(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\users\\\\\" + name[1] + \".png\", \"rb\")\n bot.send_photo(message.chat.id, img)\n img.close()\n else:\n bot.send_message(message.chat.id, \"You should login before getting statistic.\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[190, 277]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[190, 277]]}, "_func_name": "stats", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpc_pi_nextrpcl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tint compno;\n\tjpc_picomp_t *picomp;\n\tint xstep;\n\tint ystep;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->xstep = 0;\n\t\tpi->ystep = 0;\n\t\tfor (compno = 0, picomp = pi->picomps; compno < pi->numcomps;\n\t\t ++compno, ++picomp) {\n\t\t\tfor (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <\n\t\t\t picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\t\t// Check for the potential for overflow problems.\n\t\t\t\tif (pirlvl->prcwidthexpn + pi->picomp->numrlvls >\n\t\t\t\t JAS_UINTFAST32_NUMBITS - 2 ||\n\t\t\t\t pirlvl->prcheightexpn + pi->picomp->numrlvls >\n\t\t\t\t JAS_UINTFAST32_NUMBITS - 2) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\txstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t\t\t (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1));\n\t\t\t\tystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<\n\t\t\t\t (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1));\n\t\t\t\tpi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);\n\t\t\t\tpi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);\n\t\t\t}\n\t\t}\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&\n\t pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {\n\t\tfor (pi->y = pi->ystart; pi->y < pi->yend; pi->y +=\n\t\t pi->ystep - (pi->y % pi->ystep)) {\n\t\t\tfor (pi->x = pi->xstart; pi->x < pi->xend; pi->x +=\n\t\t\t pi->xstep - (pi->x % pi->xstep)) {\n\t\t\t\tfor (pi->compno = pchg->compnostart,\n\t\t\t\t pi->picomp = &pi->picomps[pi->compno];\n\t\t\t\t pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <\n\t\t\t\t pi->numcomps; ++pi->compno, ++pi->picomp) {\n\t\t\t\t\tif (pi->rlvlno >= pi->picomp->numrlvls) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\tif (((pi->x == pi->xstart &&\n\t\t\t\t\t ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx)))\n\t\t\t\t\t || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart &&\n\t\t\t\t\t ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy)))\n\t\t\t\t\t || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,\n\t\t\t\t\t\t pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -\n\t\t\t\t\t\t JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,\n\t\t\t\t\t\t pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -\n\t\t\t\t\t\t JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;\n\n\t\t\t\t\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno <\n\t\t\t\t\t\t pi->numlyrs && pi->lyrno < JAS_CAST(int,\n\t\t\t\t\t\t pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[656, 710], [746, 799]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[656, 710], [746, 799]]}, "_func_name": "jpc_pi_nextrpcl", "_file_name": "src/libjasper/jpc/jpc_t2cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def retrieve_video(id, playlist_id, db):\n db.execute(\"SELECT id, position from video WHERE id={id} and playlist_id={playlist_id};\".format(\n id=id, playlist_id=playlist_id))\n row = db.fetchone()\n return row", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[41, 183]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[41, 183]]}, "_func_name": "retrieve_video", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_day_data_row(self, ts, data, prev_etotal):\n\n if data['power'] > 0:\n\n inv_serial = data['source']['serial_id']\n query = '''\n INSERT INTO DayData (\n TimeStamp,\n Serial,\n Power,\n TotalYield\n ) VALUES (\n ?,\n ?,\n ?,\n ?\n );\n '''\n self.c.execute(query, (ts, inv_serial, data['power'], prev_etotal + data['energy']))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_day_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "filter_session_io(struct io *io, int evt, void *arg)\n{\n\tstruct filter_session *fs = arg;\n\tchar *line = NULL;\n\tssize_t len;\n\n\tlog_trace(TRACE_IO, \"filter session: %p: %s %s\", fs, io_strevent(evt),\n\t io_strio(io));\n\n\tswitch (evt) {\n\tcase IO_DATAIN:\n\tnextline:\n\t\tline = io_getline(fs->io, &len);\n\t\t/* No complete line received */\n\t\tif (line == NULL)\n\t\t\treturn;\n\n\t\tfilter_data(fs->id, line);\n\n\t\tgoto nextline;\n\n\tcase IO_DISCONNECTED:\n\t\tio_free(fs->io);\n\t\tfs->io = NULL;\n\t\tbreak;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[409, 478]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[409, 478]]}, "_func_name": "filter_session_io", "_file_name": "usr.sbin/smtpd/lka_filter.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType ReadPSDChannelPixels(Image *image,\n const size_t channels,const size_t row,const ssize_t type,\n const unsigned char *pixels,ExceptionInfo *exception)\n{\n Quantum\n pixel;\n\n register const unsigned char\n *p;\n\n register Quantum\n *q;\n\n register ssize_t\n x;\n\n size_t\n packet_size;\n\n unsigned short\n nibble;\n\n p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n {\n p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n switch (type)\n {\n case -1:\n {\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case -2:\n case 0:\n {\n SetPixelRed(image,pixel,q);\n if (channels == 1 || type == -2)\n SetPixelGray(image,pixel,q);\n if (image->storage_class == PseudoClass)\n {\n if (packet_size == 1)\n SetPixelIndex(image,ScaleQuantumToChar(pixel),q);\n else\n SetPixelIndex(image,ScaleQuantumToShort(pixel),q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);\n if (image->depth == 1)\n {\n ssize_t\n bit,\n number_bits;\n \n number_bits=image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit=0; bit < number_bits; bit++)\n {\n SetPixelIndex(image,(((unsigned char) pixel) &\n (0x01 << (7-bit))) != 0 ? 0 : 255,q);\n SetPixelViaPixelInfo(image,image->colormap+(ssize_t)\n GetPixelIndex(image,q),q);\n q+=GetPixelChannels(image);\n x++;\n }\n x--;\n continue;\n }\n }\n break;\n }\n case 1:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelGreen(image,pixel,q);\n break;\n }\n case 2:\n {\n if (image->storage_class == PseudoClass)\n SetPixelAlpha(image,pixel,q);\n else\n SetPixelBlue(image,pixel,q);\n break;\n }\n case 3:\n {\n if (image->colorspace == CMYKColorspace)\n SetPixelBlack(image,pixel,q);\n else\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n case 4:\n {\n if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&\n (channels > 3))\n break;\n if (image->alpha_trait != UndefinedPixelTrait)\n SetPixelAlpha(image,pixel,q);\n break;\n }\n default:\n break;\n }\n q+=GetPixelChannels(image);\n }\n return(SyncAuthenticPixels(image,exception));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1913, 1960]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1913, 1960]]}, "_func_name": "ReadPSDChannelPixels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool Utility::UnZip(const QString &zippath, const QString &destpath)\n{\n int res = 0;\n QDir dir(destpath);\n if (!cp437) {\n cp437 = new QCodePage437Codec();\n }\n#ifdef Q_OS_WIN32\n zlib_filefunc64_def ffunc;\n fill_win32_filefunc64W(&ffunc);\n unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);\n#else\n unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());\n#endif\n\n if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) {\n return false;\n }\n\n res = unzGoToFirstFile(zfile);\n\n if (res == UNZ_OK) {\n do {\n // Get the name of the file in the archive.\n char file_name[MAX_PATH] = {0};\n unz_file_info64 file_info;\n unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);\n QString qfile_name;\n QString cp437_file_name;\n qfile_name = QString::fromUtf8(file_name);\n if (!(file_info.flag & (1<<11))) {\n // General purpose bit 11 says the filename is utf-8 encoded. If not set then\n // IBM 437 encoding might be used.\n cp437_file_name = cp437->toUnicode(file_name);\n }\n\n // If there is no file name then we can't do anything with it.\n if (!qfile_name.isEmpty()) {\n // We use the dir object to create the path in the temporary directory.\n // Unfortunately, we need a dir ojbect to do this as it's not a static function.\n // Full file path in the temporary directory.\n QString file_path = destpath + \"/\" + qfile_name;\n QFileInfo qfile_info(file_path);\n\n // Is this entry a directory?\n if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {\n dir.mkpath(qfile_name);\n continue;\n } else {\n dir.mkpath(qfile_info.path());\n }\n\n // Open the file entry in the archive for reading.\n if (unzOpenCurrentFile(zfile) != UNZ_OK) {\n unzClose(zfile);\n return false;\n }\n\n // Open the file on disk to write the entry in the archive to.\n QFile entry(file_path);\n\n if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n return false;\n }\n\n // Buffered reading and writing.\n char buff[BUFF_SIZE] = {0};\n int read = 0;\n\n while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {\n entry.write(buff, read);\n }\n\n entry.close();\n\n // Read errors are marked by a negative read amount.\n if (read < 0) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n return false;\n }\n\n // The file was read but the CRC did not match.\n // We don't check the read file size vs the uncompressed file size\n // because if they're different there should be a CRC error.\n if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {\n unzClose(zfile);\n return false;\n }\n\n if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {\n QString cp437_file_path = destpath + \"/\" + cp437_file_name;\n QFile::copy(file_path, cp437_file_path);\n }\n }\n } while ((res = unzGoToNextFile(zfile)) == UNZ_OK);\n }\n\n if (res != UNZ_END_OF_LIST_OF_FILE) {\n unzClose(zfile);\n return false;\n }\n\n unzClose(zfile);\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1400, 1488]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1400, 1488]]}, "_func_name": "Utility::UnZip", "_file_name": "src/Misc/Utility.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def getPostsByPostid(self,postid):\n sqlText=\"select users.name,post.comment from users,post where \\\n users.userid=post.userid and post.postid=%s\"\n params=[postid]\n result=sql.queryDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getPostsByPostid", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def talk(myText):\r\n if( myText.find( \"twitter\" ) >= 0 ):\r\n myText += \"0\"\r\n myText = myText[7:-1]\r\n try:\r\n\t myText = twitter.getTweet( myText )\r\n\texcept:\r\n\t print( \"!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.\")\r\n return\r\n \r\n os.system( \"espeak \\\",...\\\" 2>/dev/null\" ) # Sometimes the beginning of audio can get cut off. Insert silence.\r\n time.sleep( 0.5 )\r\n subprocess.call([\"espeak\", \"-w\", \"speech.wav\", myText, \"-s\", \"130\"])\r\n audio.play(\"speech.wav\")\r\n return myText", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "talk", "_file_name": "chippyRuxpin.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "lha_read_file_header_1(struct archive_read *a, struct lha *lha)\n{\n\tconst unsigned char *p;\n\tsize_t extdsize;\n\tint i, err, err2;\n\tint namelen, padding;\n\tunsigned char headersum, sum_calculated;\n\n\terr = ARCHIVE_OK;\n\n\tif ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)\n\t\treturn (truncated_error(a));\n\n\tlha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;\n\theadersum = p[H1_HEADER_SUM_OFFSET];\n\t/* Note: An extended header size is included in a compsize. */\n\tlha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);\n\tlha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);\n\tlha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);\n\tnamelen = p[H1_NAME_LEN_OFFSET];\n\t/* Calculate a padding size. The result will be normally 0 only(?) */\n\tpadding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;\n\n\tif (namelen > 230 || padding < 0)\n\t\tgoto invalid;\n\n\tif ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)\n\t\treturn (truncated_error(a));\n\n\tfor (i = 0; i < namelen; i++) {\n\t\tif (p[i + H1_FILE_NAME_OFFSET] == 0xff)\n\t\t\tgoto invalid;/* Invalid filename. */\n\t}\n\tarchive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);\n\tlha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);\n\tlha->setflag |= CRC_IS_SET;\n\n\tsum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);\n\t/* Consume used bytes but not include `next header size' data\n\t * since it will be consumed in lha_read_file_extended_header(). */\n\t__archive_read_consume(a, lha->header_size - 2);\n\n\t/* Read extended headers */\n\terr2 = lha_read_file_extended_header(a, lha, NULL, 2,\n\t (size_t)(lha->compsize + 2), &extdsize);\n\tif (err2 < ARCHIVE_WARN)\n\t\treturn (err2);\n\tif (err2 < err)\n\t\terr = err2;\n\t/* Get a real compressed file size. */\n\tlha->compsize -= extdsize - 2;\n\n\tif (sum_calculated != headersum) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"LHa header sum error\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\treturn (err);\ninvalid:\n\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n\t \"Invalid LHa header\");\n\treturn (ARCHIVE_FATAL);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1755, 1791]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1755, 1791]]}, "_func_name": "lha_read_file_header_1", "_file_name": "libarchive/archive_read_support_format_lha.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int unimac_mdio_probe(struct platform_device *pdev)\n{\n\tstruct unimac_mdio_pdata *pdata = pdev->dev.platform_data;\n\tstruct unimac_mdio_priv *priv;\n\tstruct device_node *np;\n\tstruct mii_bus *bus;\n\tstruct resource *r;\n\tint ret;\n\n\tnp = pdev->dev.of_node;\n\n\tpriv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\n\t/* Just ioremap, as this MDIO block is usually integrated into an\n\t * Ethernet MAC controller register range\n\t */\n\tpriv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));\n\tif (!priv->base) {\n\t\tdev_err(&pdev->dev, \"failed to remap register\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv->mii_bus = mdiobus_alloc();\n\tif (!priv->mii_bus)\n\t\treturn -ENOMEM;\n\n\tbus = priv->mii_bus;\n\tbus->priv = priv;\n\tif (pdata) {\n\t\tbus->name = pdata->bus_name;\n\t\tpriv->wait_func = pdata->wait_func;\n\t\tpriv->wait_func_data = pdata->wait_func_data;\n\t\tbus->phy_mask = ~pdata->phy_mask;\n\t} else {\n\t\tbus->name = \"unimac MII bus\";\n\t\tpriv->wait_func_data = priv;\n\t\tpriv->wait_func = unimac_mdio_poll;\n\t}\n\tbus->parent = &pdev->dev;\n\tbus->read = unimac_mdio_read;\n\tbus->write = unimac_mdio_write;\n\tbus->reset = unimac_mdio_reset;\n\tsnprintf(bus->id, MII_BUS_ID_SIZE, \"%s-%d\", pdev->name, pdev->id);\n\n\tret = of_mdiobus_register(bus, np);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"MDIO bus registration failed\\n\");\n\t\tgoto out_mdio_free;\n\t}\n\n\tplatform_set_drvdata(pdev, priv);\n\n\tdev_info(&pdev->dev, \"Broadcom UniMAC MDIO bus at 0x%p\\n\", priv->base);\n\n\treturn 0;\n\nout_mdio_free:\n\tmdiobus_free(bus);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[403, 404]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[403, 404]]}, "_func_name": "unimac_mdio_probe", "_file_name": "drivers/net/phy/mdio-bcm-unimac.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[32];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[285, 307]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[285, 307]]}, "_func_name": "yaffsfs_istat", "_file_name": "tsk/fs/yaffs.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "INST_HANDLER (lds) {\t// LDS Rd, k\n\tint d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);\n\tint k = (buf[3] << 8) | buf[2];\n\top->ptr = k;\n\n\t// load value from RAMPD:k\n\t__generic_ld_st (op, \"ram\", 0, 1, 0, k, 0);\n\tESIL_A (\"r%d,=,\", d);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[34, 90]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[34, 90]]}, "_func_name": "INST_HANDLER", "_file_name": "libr/anal/p/anal_avr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def delete_playlists_videos(playlist_id, db):\n db.execute(\"DELETE FROM video where playlist_id=%s;\", (playlist_id,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_playlists_videos", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef screenshotcommentcounts(context, screenshot):\n \"\"\"\n Returns a JSON array of current comments for a screenshot.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n text The text of the comment\n localdraft True if this is the current user's draft comment\n x The X location of the comment's region\n y The Y location of the comment's region\n w The width of the comment's region\n h The height of the comment's region\n =========== ==================================================\n \"\"\"\n comments = {}\n user = context.get('user', None)\n\n for comment in screenshot.comments.all():\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n position = '%dx%d+%d+%d' % (comment.w, comment.h, \\\n comment.x, comment.y)\n\n comments.setdefault(position, []).append({\n 'id': comment.id,\n 'text': comment.text,\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n 'url': comment.get_review_url(),\n 'localdraft' : review.user == user and \\\n not review.public,\n 'x' : comment.x,\n 'y' : comment.y,\n 'w' : comment.w,\n 'h' : comment.h,\n })\n\n return simplejson.dumps(comments)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1249, 1287]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1249, 1287]]}, "_func_name": "screenshotcommentcounts", "_file_name": "reviewboard/reviews/templatetags/reviewtags.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsnprintf(addr, sizeof(addr), \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle_PORT", "_file_name": "src/ftpcmd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs)\n{\n\tGF_MPEGAudioSampleEntryBox *ptr;\n\tchar *data;\n\tu8 a, b, c, d;\n\tu32 i, size, v, nb_alnum;\n\tGF_Err e;\n\tu64 pos, start;\n\n\tptr = (GF_MPEGAudioSampleEntryBox *)s;\n\n\tstart = gf_bs_get_position(bs);\n\tgf_bs_seek(bs, start + 8);\n\tv = gf_bs_read_u16(bs);\n\tif (v)\n\t\tptr->is_qtff = 1;\n\n\t//try to disambiguate QTFF v1 and MP4 v1 audio sample entries ...\n\tif (v==1) {\n\t\t//go to end of ISOM audio sample entry, skip 4 byte (box size field), read 4 bytes (box type) and check if this looks like a box\n\t\tgf_bs_seek(bs, start + 8 + 20 + 4);\n\t\ta = gf_bs_read_u8(bs);\n\t\tb = gf_bs_read_u8(bs);\n\t\tc = gf_bs_read_u8(bs);\n\t\td = gf_bs_read_u8(bs);\n\t\tnb_alnum = 0;\n\t\tif (isalnum(a)) nb_alnum++;\n\t\tif (isalnum(b)) nb_alnum++;\n\t\tif (isalnum(c)) nb_alnum++;\n\t\tif (isalnum(d)) nb_alnum++;\n\t\tif (nb_alnum>2) ptr->is_qtff = 0;\n\t}\n\n\tgf_bs_seek(bs, start);\n\te = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs);\n\tif (e) return e;\n\tpos = gf_bs_get_position(bs);\n\tsize = (u32) s->size;\n\n\t//when cookie is set on bs, always convert qtff-style mp4a to isobmff-style\n\t//since the conversion is done in addBox and we don't have the bitstream there (arg...), flag the box\n \tif (gf_bs_get_cookie(bs)) {\n \t\tptr->is_qtff |= 1<<16;\n \t}\n\n\te = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox);\n\tif (!e) return GF_OK;\n\tif (size<8) return GF_ISOM_INVALID_FILE;\n\n\t/*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/\n\tgf_bs_seek(bs, pos);\n\tdata = (char*)gf_malloc(sizeof(char) * size);\n\tgf_bs_read_data(bs, data, size);\n\tfor (i=0; iesd) {\n\t\t\t\tgf_isom_box_del((GF_Box *)ptr->esd);\n\t\t\t\tptr->esd=NULL;\n\t\t\t}\n\n\t\t\te = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs);\n\n\t\t\tif (e==GF_OK) {\n\t\t\t\tgf_isom_box_add_for_dump_mode((GF_Box*)ptr, (GF_Box*)ptr->esd);\n\t\t\t} else if (ptr->esd) {\n\t\t\t\tgf_isom_box_del((GF_Box *)ptr->esd);\n\t\t\t\tptr->esd=NULL;\n\t\t\t}\n\n\t\t\tgf_bs_del(mybs);\n\t\t\tbreak;\n\t\t}\n\t}\n\tgf_free(data);\n\treturn e;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1827, 1868]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1827, 1868]]}, "_func_name": "audio_sample_entry_Read", "_file_name": "src/isomedia/box_code_base.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut + 1;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "voutf", "_file_name": "src/tool_msgs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_iscsi_ip_active(self):\n self.flags(lock_path=self.tempdir)\n\n #record set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])\n\n self.mox.ReplayAll()\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.253')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_get_iscsi_ip_active", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@login_required(redirect_field_name='', login_url='/403')\n@require_POST\n@require_AJAX\n@transaction.atomic\ndef batch_edit_translations(request):\n \"\"\"Perform an action on a list of translations.\n\n Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view\n are defined in `models.BatchActionsForm`.\n\n \"\"\"\n form = forms.BatchActionsForm(request.POST)\n if not form.is_valid():\n return HttpResponseBadRequest(form.errors.as_json(escape_html=True))\n\n locale = get_object_or_404(Locale, code=form.cleaned_data['locale'])\n entities = Entity.objects.filter(pk__in=form.cleaned_data['entities'])\n\n if not entities.exists():\n return JsonResponse({'count': 0})\n\n # Batch editing is only available to translators. Check if user has\n # translate permissions for all of the projects in passed entities.\n # Also make sure projects are not enabled in read-only mode for a locale.\n projects_pk = entities.values_list('resource__project__pk', flat=True)\n projects = Project.objects.filter(pk__in=projects_pk.distinct())\n\n for project in projects:\n if (\n not request.user.can_translate(project=project, locale=locale)\n or readonly_exists(projects, locale)\n ):\n return HttpResponseForbidden(\n \"Forbidden: You don't have permission for batch editing\"\n )\n\n # Find all impacted active translations, including plural forms.\n active_translations = Translation.objects.filter(\n active=True,\n locale=locale,\n entity__in=entities,\n )\n\n # Execute the actual action.\n action_function = ACTIONS_FN_MAP[form.cleaned_data['action']]\n action_status = action_function(\n form,\n request.user,\n active_translations,\n locale,\n )\n\n if action_status.get('error'):\n return JsonResponse(action_status)\n\n invalid_translation_count = len(action_status.get('invalid_translation_pks', []))\n if action_status['count'] == 0:\n return JsonResponse({\n 'count': 0,\n 'invalid_translation_count': invalid_translation_count,\n })\n\n update_stats(action_status['translated_resources'], locale)\n mark_changed_translation(action_status['changed_entities'], locale)\n\n # Update latest translation.\n if action_status['latest_translation_pk']:\n Translation.objects.get(\n pk=action_status['latest_translation_pk']\n ).update_latest_translation()\n\n update_translation_memory(\n action_status['changed_translation_pks'],\n project,\n locale\n )\n\n return JsonResponse({\n 'count': action_status['count'],\n 'invalid_translation_count': invalid_translation_count,\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "batch_edit_translations", "_file_name": "pontoon/batch/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index > glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[211, 259]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[211, 259]]}, "_func_name": "glyph_cache_put", "_file_name": "libfreerdp/cache/glyph.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, \n AP4_UI08 version,\n AP4_UI32 flags,\n AP4_ByteStream& stream) :\n AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)\n{\n AP4_UI32 predefined;\n stream.ReadUI32(predefined);\n stream.ReadUI32(m_HandlerType);\n stream.ReadUI32(m_Reserved[0]);\n stream.ReadUI32(m_Reserved[1]);\n stream.ReadUI32(m_Reserved[2]);\n \n // read the name unless it is empty\n if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;\n AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n char* name = new char[name_size+1];\n if (name == NULL) return;\n stream.Read(name, name_size);\n name[name_size] = '\\0'; // force a null termination\n // handle a special case: the Quicktime files have a pascal\n // string here, but ISO MP4 files have a C string.\n // we try to detect a pascal encoding and correct it.\n if (name[0] == name_size-1) {\n m_HandlerName = name+1;\n } else {\n m_HandlerName = name;\n }\n delete[] name;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "AP4_HdlrAtom::AP4_HdlrAtom", "_file_name": "Source/C++/Core/Ap4HdlrAtom.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/')\ndef render_page_name(page_name):\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n wiki_page = query.namedresult()\n has_content = False\n page_is_taken = False\n if len(wiki_page) < 1:\n content = \"\"\n else:\n page_is_taken = True\n content = wiki_page[0].content\n if len(content) > 0:\n has_content = True\n else:\n pass\n content = markdown.markdown(wiki_linkify(content))\n return render_template(\n 'pageholder.html',\n page_is_taken = page_is_taken,\n page_name = page_name,\n markdown = markdown,\n wiki_linkify = wiki_linkify,\n has_content = has_content,\n content = content\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[60, 300]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[60, 300]]}, "_func_name": "render_page_name", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,\n\t\t\t const struct host_cmd_ds_command *resp)\n{\n\tu8 *curr = (u8 *) &resp->params.get_wmm_status;\n\tuint16_t resp_len = le16_to_cpu(resp->size), tlv_len;\n\tint mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;\n\tbool valid = true;\n\n\tstruct mwifiex_ie_types_data *tlv_hdr;\n\tstruct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;\n\tstruct ieee_types_wmm_parameter *wmm_param_ie = NULL;\n\tstruct mwifiex_wmm_ac_status *ac_status;\n\n\tmwifiex_dbg(priv->adapter, INFO,\n\t\t \"info: WMM: WMM_GET_STATUS cmdresp received: %d\\n\",\n\t\t resp_len);\n\n\twhile ((resp_len >= sizeof(tlv_hdr->header)) && valid) {\n\t\ttlv_hdr = (struct mwifiex_ie_types_data *) curr;\n\t\ttlv_len = le16_to_cpu(tlv_hdr->header.len);\n\n\t\tif (resp_len < tlv_len + sizeof(tlv_hdr->header))\n\t\t\tbreak;\n\n\t\tswitch (le16_to_cpu(tlv_hdr->header.type)) {\n\t\tcase TLV_TYPE_WMMQSTATUS:\n\t\t\ttlv_wmm_qstatus =\n\t\t\t\t(struct mwifiex_ie_types_wmm_queue_status *)\n\t\t\t\ttlv_hdr;\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"QSTATUS TLV: %d, %d, %d\\n\",\n\t\t\t\t tlv_wmm_qstatus->queue_index,\n\t\t\t\t tlv_wmm_qstatus->flow_required,\n\t\t\t\t tlv_wmm_qstatus->disabled);\n\n\t\t\tac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->\n\t\t\t\t\t\t\t queue_index];\n\t\t\tac_status->disabled = tlv_wmm_qstatus->disabled;\n\t\t\tac_status->flow_required =\n\t\t\t\t\t\ttlv_wmm_qstatus->flow_required;\n\t\t\tac_status->flow_created = tlv_wmm_qstatus->flow_created;\n\t\t\tbreak;\n\n\t\tcase WLAN_EID_VENDOR_SPECIFIC:\n\t\t\t/*\n\t\t\t * Point the regular IEEE IE 2 bytes into the Marvell IE\n\t\t\t * and setup the IEEE IE type and length byte fields\n\t\t\t */\n\n\t\t\twmm_param_ie =\n\t\t\t\t(struct ieee_types_wmm_parameter *) (curr +\n\t\t\t\t\t\t\t\t 2);\n\t\t\twmm_param_ie->vend_hdr.len = (u8) tlv_len;\n\t\t\twmm_param_ie->vend_hdr.element_id =\n\t\t\t\t\t\tWLAN_EID_VENDOR_SPECIFIC;\n\n\t\t\tmwifiex_dbg(priv->adapter, CMD,\n\t\t\t\t \"info: CMD_RESP: WMM_GET_STATUS:\\t\"\n\t\t\t\t \"WMM Parameter Set Count: %d\\n\",\n\t\t\t\t wmm_param_ie->qos_info_bitmap & mask);\n\n\t\t\tmemcpy((u8 *) &priv->curr_bss_params.bss_descriptor.\n\t\t\t wmm_ie, wmm_param_ie,\n\t\t\t wmm_param_ie->vend_hdr.len + 2);\n\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tvalid = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tcurr += (tlv_len + sizeof(tlv_hdr->header));\n\t\tresp_len -= (tlv_len + sizeof(tlv_hdr->header));\n\t}\n\n\tmwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);\n\tmwifiex_wmm_setup_ac_downgrade(priv);\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[2014, 2070]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2014, 2070]]}, "_func_name": "mwifiex_ret_wmm_get_status", "_file_name": "drivers/net/wireless/marvell/mwifiex/wmm.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *avpkt)\n{\n EXRContext *s = avctx->priv_data;\n ThreadFrame frame = { .f = data };\n AVFrame *picture = data;\n uint8_t *ptr;\n\n int i, y, ret, ymax;\n int planes;\n int out_line_size;\n int nb_blocks; /* nb scanline or nb tile */\n uint64_t start_offset_table;\n uint64_t start_next_scanline;\n PutByteContext offset_table_writer;\n\n bytestream2_init(&s->gb, avpkt->data, avpkt->size);\n\n if ((ret = decode_header(s, picture)) < 0)\n return ret;\n\n switch (s->pixel_type) {\n case EXR_FLOAT:\n case EXR_HALF:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n } else {\n /* todo: change this when a floating point pixel format with luma with alpha is implemented */\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRPF32;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAYF32;\n }\n }\n break;\n case EXR_UINT:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGBA64;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_YA16;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGB48;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAY16;\n }\n }\n break;\n default:\n av_log(avctx, AV_LOG_ERROR, \"Missing channel list.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)\n avctx->color_trc = s->apply_trc_type;\n\n switch (s->compression) {\n case EXR_RAW:\n case EXR_RLE:\n case EXR_ZIP1:\n s->scan_lines_per_block = 1;\n break;\n case EXR_PXR24:\n case EXR_ZIP16:\n s->scan_lines_per_block = 16;\n break;\n case EXR_PIZ:\n case EXR_B44:\n case EXR_B44A:\n s->scan_lines_per_block = 32;\n break;\n default:\n avpriv_report_missing_feature(avctx, \"Compression %d\", s->compression);\n return AVERROR_PATCHWELCOME;\n }\n\n /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.\n * It's possible for the data window can larger or outside the display window */\n if (s->xmin > s->xmax || s->ymin > s->ymax ||\n s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {\n av_log(avctx, AV_LOG_ERROR, \"Wrong or missing size information.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)\n return ret;\n\n s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);\n if (!s->desc)\n return AVERROR_INVALIDDATA;\n\n if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {\n planes = s->desc->nb_components;\n out_line_size = avctx->width * 4;\n } else {\n planes = 1;\n out_line_size = avctx->width * 2 * s->desc->nb_components;\n }\n\n if (s->is_tile) {\n nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *\n ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);\n } else { /* scanline */\n nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /\n s->scan_lines_per_block;\n }\n\n if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)\n return ret;\n\n if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks)\n return AVERROR_INVALIDDATA;\n\n // check offset table and recreate it if need\n if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {\n av_log(s->avctx, AV_LOG_DEBUG, \"recreating invalid scanline offset table\\n\");\n\n start_offset_table = bytestream2_tell(&s->gb);\n start_next_scanline = start_offset_table + nb_blocks * 8;\n bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);\n\n for (y = 0; y < nb_blocks; y++) {\n /* write offset of prev scanline in offset table */\n bytestream2_put_le64(&offset_table_writer, start_next_scanline);\n\n /* get len of next scanline */\n bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */\n start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);\n }\n bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);\n }\n\n // save pointer we are going to use in decode_block\n s->buf = avpkt->data;\n s->buf_size = avpkt->size;\n\n // Zero out the start if ymin is not 0\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i];\n for (y = 0; y < s->ymin; y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n s->picture = picture;\n\n avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);\n\n ymax = FFMAX(0, s->ymax + 1);\n // Zero out the end if ymax+1 is not h\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i] + (ymax * picture->linesize[i]);\n for (y = ymax; y < avctx->height; y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n picture->pict_type = AV_PICTURE_TYPE_I;\n *got_frame = 1;\n\n return avpkt->size;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[4801, 4841]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[4801, 4841]]}, "_func_name": "decode_frame", "_file_name": "libavcodec/exr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += (srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[3001, 3058]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3001, 3058]]}, "_func_name": "rfbScaledScreenUpdateRect", "_file_name": "libvncserver/scale.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def getGameCountInSeriesSoFar(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?\", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0]\n database.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getGameCountInSeriesSoFar", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/get_markets')\ndef get_markets():\n asset_id = request.args.get('asset_id')\n\n if not isObject(asset_id):\n ws.send('{\"id\":1, \"method\":\"call\", \"params\":[0,\"lookup_asset_symbols\",[[\"' + asset_id + '\"], 0]]}')\n result_l = ws.recv()\n j_l = json.loads(result_l)\n asset_id = j_l[\"result\"][0][\"id\"]\n\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT * FROM markets WHERE aid=%s\"\n cur.execute(query, (asset_id,))\n results = cur.fetchall()\n con.close()\n return jsonify(results)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_markets", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " */\nstatic void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)\n{\n\tst_entry ent;\n\twddx_stack *stack = (wddx_stack *)user_data;\n\n\tif (!strcmp(name, EL_PACKET)) {\n\t\tint i;\n\n\t\tif (atts) for (i=0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_VERSION)) {\n\t\t\t\t/* nothing for now */\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_STRING)) {\n\t\tent.type = ST_STRING;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_STRING;\n\t\tZ_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();\n\t\tZ_STRLEN_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_BINARY)) {\n\t\tent.type = ST_BINARY;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_STRING;\n\t\tZ_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();\n\t\tZ_STRLEN_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_CHAR)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tchar tmp_buf[2];\n\n\t\t\t\tsnprintf(tmp_buf, sizeof(tmp_buf), \"%c\", (char)strtol(atts[i+1], NULL, 16));\n\t\t\t\tphp_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_NUMBER)) {\n\t\tent.type = ST_NUMBER;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_LONG;\n\t\tZ_LVAL_P(ent.data) = 0;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_BOOLEAN)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tent.type = ST_BOOLEAN;\n\t\t\t\tSET_STACK_VARNAME;\n\n\t\t\t\tALLOC_ZVAL(ent.data);\n\t\t\t\tINIT_PZVAL(ent.data);\n\t\t\t\tZ_TYPE_P(ent.data) = IS_BOOL;\n\t\t\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t\t\t\tphp_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_NULL)) {\n\t\tent.type = ST_NULL;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZVAL_NULL(ent.data);\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_ARRAY)) {\n\t\tent.type = ST_ARRAY;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_STRUCT)) {\n\t\tent.type = ST_STRUCT;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_VAR)) {\n\t\tint i;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tif (stack->varname) efree(stack->varname);\n\t\t\t\tstack->varname = estrdup(atts[i+1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(name, EL_RECORDSET)) {\n\t\tint i;\n\n\t\tent.type = ST_RECORDSET;\n\t\tSET_STACK_VARNAME;\n\t\tMAKE_STD_ZVAL(ent.data);\n\t\tarray_init(ent.data);\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], \"fieldNames\") && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tzval *tmp;\n\t\t\t\tchar *key;\n\t\t\t\tchar *p1, *p2, *endp;\n\n\t\t\t\ti++;\n\t\t\t\tendp = (char *)atts[i] + strlen(atts[i]);\n\t\t\t\tp1 = (char *)atts[i];\n\t\t\t\twhile ((p2 = php_memnstr(p1, \",\", sizeof(\",\")-1, endp)) != NULL) {\n\t\t\t\t\tkey = estrndup(p1, p2 - p1);\n\t\t\t\t\tMAKE_STD_ZVAL(tmp);\n\t\t\t\t\tarray_init(tmp);\n\t\t\t\t\tadd_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);\n\t\t\t\t\tp1 = p2 + sizeof(\",\")-1;\n\t\t\t\t\tefree(key);\n\t\t\t\t}\n\n\t\t\t\tif (p1 <= endp) {\n\t\t\t\t\tMAKE_STD_ZVAL(tmp);\n\t\t\t\t\tarray_init(tmp);\n\t\t\t\t\tadd_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tint i;\n\t\tst_entry ent;\n\n\t\tent.type = ST_FIELD;\n\t\tent.varname = NULL;\n\t\tent.data = NULL;\n\n\t\tif (atts) for (i = 0; atts[i]; i++) {\n\t\t\tif (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {\n\t\t\t\tst_entry *recordset;\n\t\t\t\tzval **field;\n\n\t\t\t\tif (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&\n\t\t\t\t\trecordset->type == ST_RECORDSET &&\n\t\t\t\t\tzend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {\n\t\t\t\t\tent.data = *field;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t} else if (!strcmp(name, EL_DATETIME)) {\n\t\tent.type = ST_DATETIME;\n\t\tSET_STACK_VARNAME;\n\n\t\tALLOC_ZVAL(ent.data);\n\t\tINIT_PZVAL(ent.data);\n\t\tZ_TYPE_P(ent.data) = IS_LONG;\n\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1972, 1976]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1972, 1976]]}, "_func_name": "php_wddx_push_element", "_file_name": "ext/wddx/wddx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_vdisk_fc_mappings(self, vdisk_name):\n \"\"\"Return FlashCopy mappings that this vdisk is associated with.\"\"\"\n\n ssh_cmd = 'svcinfo lsvdiskfcmappings -nohdr %s' % vdisk_name\n out, err = self._run_ssh(ssh_cmd)\n\n mapping_ids = []\n if (len(out.strip())):\n lines = out.strip().split('\\n')\n mapping_ids = [line.split()[0] for line in lines]\n return mapping_ids", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[127, 196]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[127, 196]]}, "_func_name": "_get_vdisk_fc_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PHYSICALPATH_FUNC(mod_alias_physical_handler) {\n\tplugin_data *p = p_d;\n\tint uri_len, basedir_len;\n\tchar *uri_ptr;\n\tsize_t k;\n\n\tif (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;\n\n\tmod_alias_patch_connection(srv, con, p);\n\n\t/* not to include the tailing slash */\n\tbasedir_len = buffer_string_length(con->physical.basedir);\n\tif ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;\n\turi_len = buffer_string_length(con->physical.path) - basedir_len;\n\turi_ptr = con->physical.path->ptr + basedir_len;\n\n\tfor (k = 0; k < p->conf.alias->used; k++) {\n\t\tdata_string *ds = (data_string *)p->conf.alias->data[k];\n\t\tint alias_len = buffer_string_length(ds->key);\n\n\t\tif (alias_len > uri_len) continue;\n\t\tif (buffer_is_empty(ds->key)) continue;\n\n\t\tif (0 == (con->conf.force_lowercase_filenames ?\n\t\t\t\t\tstrncasecmp(uri_ptr, ds->key->ptr, alias_len) :\n\t\t\t\t\tstrncmp(uri_ptr, ds->key->ptr, alias_len))) {\n\t\t\t/* matched */\n\n\t\t\t/* check for path traversal in url-path following alias if key\n\t\t\t * does not end in slash, but replacement value ends in slash */\n\t\t\tif (uri_ptr[alias_len] == '.') {\n\t\t\t\tchar *s = uri_ptr + alias_len + 1;\n\t\t\t\tif (*s == '.') ++s;\n\t\t\t\tif (*s == '/' || *s == '\\0') {\n\t\t\t\t\tsize_t vlen = buffer_string_length(ds->value);\n\t\t\t\t\tif (0 != alias_len && ds->key->ptr[alias_len-1] != '/'\n\t\t\t\t\t && 0 != vlen && ds->value->ptr[vlen-1] == '/') {\n\t\t\t\t\t\tcon->http_status = 403;\n\t\t\t\t\t\treturn HANDLER_FINISHED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuffer_copy_buffer(con->physical.basedir, ds->value);\n\t\t\tbuffer_copy_buffer(srv->tmp_buf, ds->value);\n\t\t\tbuffer_append_string(srv->tmp_buf, uri_ptr + alias_len);\n\t\t\tbuffer_copy_buffer(con->physical.path, srv->tmp_buf);\n\n\t\t\treturn HANDLER_GO_ON;\n\t\t}\n\t}\n\n\t/* not found */\n\treturn HANDLER_GO_ON;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PHYSICALPATH_FUNC", "_file_name": "src/mod_alias.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int TNEFParse(TNEFStruct *TNEF) {\n WORD key;\n DWORD type;\n DWORD size;\n DWORD signature;\n BYTE *data;\n WORD checksum, header_checksum;\n int i;\n\n if (TNEF->IO.ReadProc == NULL) {\n printf(\"ERROR: Setup incorrectly: No ReadProc\\n\");\n return YTNEF_INCORRECT_SETUP;\n }\n\n if (TNEF->IO.InitProc != NULL) {\n DEBUG(TNEF->Debug, 2, \"About to initialize\");\n if (TNEF->IO.InitProc(&TNEF->IO) != 0) {\n return YTNEF_CANNOT_INIT_DATA;\n }\n DEBUG(TNEF->Debug, 2, \"Initialization finished\");\n }\n\n DEBUG(TNEF->Debug, 2, \"Reading Signature\");\n if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {\n printf(\"ERROR: Error reading signature\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_ERROR_READING_DATA;\n }\n\n DEBUG(TNEF->Debug, 2, \"Checking Signature\");\n if (TNEFCheckForSignature(signature) < 0) {\n printf(\"ERROR: Signature does not match. Not TNEF.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_NOT_TNEF_STREAM;\n }\n\n DEBUG(TNEF->Debug, 2, \"Reading Key.\");\n\n if (TNEFGetKey(TNEF, &key) < 0) {\n printf(\"ERROR: Unable to retrieve key.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_NO_KEY;\n }\n\n DEBUG(TNEF->Debug, 2, \"Starting Full Processing.\");\n\n while (TNEFGetHeader(TNEF, &type, &size) == 0) {\n DEBUG2(TNEF->Debug, 2, \"Header says type=0x%X, size=%u\", type, size);\n DEBUG2(TNEF->Debug, 2, \"Header says type=%u, size=%u\", type, size);\n data = calloc(size, sizeof(BYTE));\n ALLOCCHECK(data);\n if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {\n printf(\"ERROR: Unable to read data.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_ERROR_READING_DATA;\n }\n if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {\n printf(\"ERROR: Unable to read checksum.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_ERROR_READING_DATA;\n }\n checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));\n if (checksum != header_checksum) {\n printf(\"ERROR: Checksum mismatch. Data corruption?:\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_BAD_CHECKSUM;\n }\n for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {\n if (TNEFList[i].id == type) {\n if (TNEFList[i].handler != NULL) {\n if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {\n free(data);\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_ERROR_IN_HANDLER;\n } else {\n // Found our handler and processed it. now time to get out\n break;\n }\n } else {\n DEBUG2(TNEF->Debug, 1, \"No handler for %s: %u bytes\",\n TNEFList[i].name, size);\n }\n }\n }\n\n free(data);\n }\n\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return 0;\n\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1563, 1602]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1563, 1602]]}, "_func_name": "TNEFParse", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/test', methods=['GET', 'POST'])\ndef test():\n user_id = session['logged_id']\n cursor.execute('SELECT * FROM message where user_id = %s ORDER BY c_time DESC', (user_id,))\n m = cursor.fetchall()\n print(m)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/lookup_assets')\ndef lookup_assets():\n start = request.args.get('start')\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT aname FROM assets WHERE aname LIKE %s\"\n cur.execute(query, (start+'%',))\n results = cur.fetchall()\n con.close()\n return jsonify(results)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "lookup_assets", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "updateDevice(const struct header * headers, time_t t)\n{\n\tstruct device ** pp = &devlist;\n\tstruct device * p = *pp;\t/* = devlist; */\n\twhile(p)\n\t{\n\t\tif( p->headers[HEADER_NT].l == headers[HEADER_NT].l\n\t\t && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))\n\t\t && p->headers[HEADER_USN].l == headers[HEADER_USN].l\n\t\t && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )\n\t\t{\n\t\t\t/*printf(\"found! %d\\n\", (int)(t - p->t));*/\n\t\t\tsyslog(LOG_DEBUG, \"device updated : %.*s\", headers[HEADER_USN].l, headers[HEADER_USN].p);\n\t\t\tp->t = t;\n\t\t\t/* update Location ! */\n\t\t\tif(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)\n\t\t\t{\n\t\t\t\tstruct device * tmp;\n\t\t\t\ttmp = realloc(p, sizeof(struct device)\n\t\t\t\t + headers[0].l+headers[1].l+headers[2].l);\n\t\t\t\tif(!tmp)\t/* allocation error */\n\t\t\t\t{\n\t\t\t\t\tsyslog(LOG_ERR, \"updateDevice() : memory allocation error\");\n\t\t\t\t\t*pp = p->next;\t/* remove \"p\" from the list */\n\t\t\t\t\tfree(p);\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tp = tmp;\n\t\t\t\t*pp = p;\n\t\t\t}\n\t\t\tmemcpy(p->data + p->headers[0].l + p->headers[1].l,\n\t\t\t headers[2].p, headers[2].l);\n\t\t\t/* TODO : check p->headers[HEADER_LOCATION].l */\n\t\t\treturn 0;\n\t\t}\n\t\tpp = &p->next;\n\t\tp = *pp;\t/* p = p->next; */\n\t}\n\tsyslog(LOG_INFO, \"new device discovered : %.*s\",\n\t headers[HEADER_USN].l, headers[HEADER_USN].p);\n\t/* add */\n\t{\n\t\tchar * pc;\n\t\tint i;\n\t\tp = malloc( sizeof(struct device)\n\t\t + headers[0].l+headers[1].l+headers[2].l );\n\t\tif(!p) {\n\t\t\tsyslog(LOG_ERR, \"updateDevice(): cannot allocate memory\");\n\t\t\treturn -1;\n\t\t}\n\t\tp->next = devlist;\n\t\tp->t = t;\n\t\tpc = p->data;\n\t\tfor(i = 0; i < 3; i++)\n\t\t{\n\t\t\tp->headers[i].p = pc;\n\t\t\tp->headers[i].l = headers[i].l;\n\t\t\tmemcpy(pc, headers[i].p, headers[i].l);\n\t\t\tpc += headers[i].l;\n\t\t}\n\t\tdevlist = p;\n\t\tsendNotifications(NOTIF_NEW, p, NULL);\n\t}\n\treturn 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "updateDevice", "_file_name": "minissdpd/minissdpd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int decode_frame(AVCodecContext *avctx,\n void *data, int *got_frame,\n AVPacket *avpkt)\n{\n PicContext *s = avctx->priv_data;\n AVFrame *frame = data;\n uint32_t *palette;\n int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;\n int i, x, y, plane, tmp, ret, val;\n\n bytestream2_init(&s->g, avpkt->data, avpkt->size);\n\n if (bytestream2_get_bytes_left(&s->g) < 11)\n return AVERROR_INVALIDDATA;\n\n if (bytestream2_get_le16u(&s->g) != 0x1234)\n return AVERROR_INVALIDDATA;\n\n s->width = bytestream2_get_le16u(&s->g);\n s->height = bytestream2_get_le16u(&s->g);\n bytestream2_skip(&s->g, 4);\n tmp = bytestream2_get_byteu(&s->g);\n bits_per_plane = tmp & 0xF;\n s->nb_planes = (tmp >> 4) + 1;\n bpp = bits_per_plane * s->nb_planes;\n if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {\n avpriv_request_sample(avctx, \"Unsupported bit depth\");\n return AVERROR_PATCHWELCOME;\n }\n\n if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {\n bytestream2_skip(&s->g, 2);\n etype = bytestream2_get_le16(&s->g);\n esize = bytestream2_get_le16(&s->g);\n if (bytestream2_get_bytes_left(&s->g) < esize)\n return AVERROR_INVALIDDATA;\n } else {\n etype = -1;\n esize = 0;\n }\n\n avctx->pix_fmt = AV_PIX_FMT_PAL8;\n\n if (av_image_check_size(s->width, s->height, 0, avctx) < 0)\n return -1;\n if (s->width != avctx->width && s->height != avctx->height) {\n ret = ff_set_dimensions(avctx, s->width, s->height);\n if (ret < 0)\n return ret;\n }\n\n if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)\n return ret;\n memset(frame->data[0], 0, s->height * frame->linesize[0]);\n frame->pict_type = AV_PICTURE_TYPE_I;\n frame->palette_has_changed = 1;\n\n pos_after_pal = bytestream2_tell(&s->g) + esize;\n palette = (uint32_t*)frame->data[1];\n if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {\n int idx = bytestream2_get_byte(&s->g);\n npal = 4;\n for (i = 0; i < npal; i++)\n palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];\n } else if (etype == 2) {\n npal = FFMIN(esize, 16);\n for (i = 0; i < npal; i++) {\n int pal_idx = bytestream2_get_byte(&s->g);\n palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];\n }\n } else if (etype == 3) {\n npal = FFMIN(esize, 16);\n for (i = 0; i < npal; i++) {\n int pal_idx = bytestream2_get_byte(&s->g);\n palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];\n }\n } else if (etype == 4 || etype == 5) {\n npal = FFMIN(esize / 3, 256);\n for (i = 0; i < npal; i++) {\n palette[i] = bytestream2_get_be24(&s->g) << 2;\n palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;\n }\n } else {\n if (bpp == 1) {\n npal = 2;\n palette[0] = 0xFF000000;\n palette[1] = 0xFFFFFFFF;\n } else if (bpp == 2) {\n npal = 4;\n for (i = 0; i < npal; i++)\n palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];\n } else {\n npal = 16;\n memcpy(palette, ff_cga_palette, npal * 4);\n }\n }\n // fill remaining palette entries\n memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);\n // skip remaining palette bytes\n bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);\n\n val = 0;\n y = s->height - 1;\n if (bytestream2_get_le16(&s->g)) {\n x = 0;\n plane = 0;\n while (bytestream2_get_bytes_left(&s->g) >= 6) {\n int stop_size, marker, t1, t2;\n\n t1 = bytestream2_get_bytes_left(&s->g);\n t2 = bytestream2_get_le16(&s->g);\n stop_size = t1 - FFMIN(t1, t2);\n // ignore uncompressed block size\n bytestream2_skip(&s->g, 2);\n marker = bytestream2_get_byte(&s->g);\n\n while (plane < s->nb_planes &&\n bytestream2_get_bytes_left(&s->g) > stop_size) {\n int run = 1;\n val = bytestream2_get_byte(&s->g);\n if (val == marker) {\n run = bytestream2_get_byte(&s->g);\n if (run == 0)\n run = bytestream2_get_le16(&s->g);\n val = bytestream2_get_byte(&s->g);\n }\n if (!bytestream2_get_bytes_left(&s->g))\n break;\n\n if (bits_per_plane == 8) {\n picmemset_8bpp(s, frame, val, run, &x, &y);\n if (y < 0)\n goto finish;\n } else {\n picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);\n }\n }\n }\n\n if (x < avctx->width) {\n int run = (y + 1) * avctx->width - x;\n if (bits_per_plane == 8)\n picmemset_8bpp(s, frame, val, run, &x, &y);\n else\n picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);\n }\n } else {\n while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {\n memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));\n bytestream2_skip(&s->g, avctx->width);\n y--;\n }\n }\nfinish:\n\n *got_frame = 1;\n return avpkt->size;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1512, 1578]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1512, 1578]]}, "_func_name": "decode_frame", "_file_name": "libavcodec/pictordec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def whitelist(channel: discord.TextChannel, users: str):\n for user in users.split():\n if not re.match(r'^[A-Za-z0-9_]{3,16}$', user): # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408\n await channel.send('\\'{}\\' is not a valid Minecraft username'.format(user))\n else:\n call(WHITELIST_COMMAND_TEMPLATE.format(user))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "whitelist", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) {\n setupUi(this);\n if (size == 1)\n label->setText(tr(\"Are you sure you want to delete '%1' from the transfer list?\", \"Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?\").arg(name));\n else\n label->setText(tr(\"Are you sure you want to delete these %1 torrents from the transfer list?\", \"Are you sure you want to delete these 5 torrents from the transfer list?\").arg(QString::number(size)));\n // Icons\n lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(\"dialog-warning\").pixmap(lbl_warn->height()));\n lbl_warn->setFixedWidth(lbl_warn->height());\n rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(\"object-locked\"));\n\n move(Utils::Misc::screenCenter(this));\n checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault());\n connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));\n buttonBox->button(QDialogButtonBox::Cancel)->setFocus();\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[163, 341]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[163, 341]]}, "_func_name": "DeletionConfirmationDlg::DeletionConfirmationDlg", "_file_name": "src/gui/deletionconfirmationdlg.h", "lang": "c", "label_confidence": "diff-derived"} {"code": " def all_deposits(self,coin):\n sql = \"SELECT * FROM deposits WHERE coin='%s'\" % coin\n self.cursor.execute(sql)\n return self.cursor.fetchall()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[33, 95]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[33, 95]]}, "_func_name": "all_deposits", "_file_name": "deposit.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/like/', methods=['GET', 'POST'])\ndef like(msg_id):\n if request.method == 'GET':\n user_id = session['logged_id']\n c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n sql = \"INSERT INTO like_msg(msg_id, user_id,c_time) \" + \\\n \"VALUES(%d,'%s','%s');\" % (msg_id, user_id, c_time)\n cursor.execute(sql)\n conn.commit()\n return redirect(url_for('show_entries'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[209, 371]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[209, 371]]}, "_func_name": "like", "_file_name": "flaskr/flaskr/views/like_msg.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_first_month(db, scene):\n sql = \"select date from matches where scene='{scene}' order by date limit 1;\"\n args = {'scene': scene}\n res = db.exec(sql, args)\n date = res[0][0]\n return date", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_first_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_vvset_from_3par(self, volume_name):\n \"\"\"Get Virtual Volume Set from 3PAR.\n\n The only way to do this currently is to try and delete the volume\n to get the error message.\n\n NOTE(walter-boring): don't call this unless you know the volume is\n already in a vvset!\n \"\"\"\n cmd = ['removevv', '-f', volume_name]\n LOG.debug(\"Issuing remove command to find vvset name %s\" % cmd)\n out = self._cli_run(cmd)\n vvset_name = None\n if out and len(out) > 1:\n if out[1].startswith(\"Attempt to delete \"):\n words = out[1].split(\" \")\n vvset_name = words[len(words) - 1]\n\n return vvset_name", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_vvset_from_3par", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "\tdef add_input(self, data):\n\t\tconnection = self.connect()\n\t\ttry:\n\t\t\t# The following introduces a deliberate security flaw.See section on SQL injection below\n\t\t\tquery = \"INSERT INTO crimes (description) VALUES (%s);\"\n\t\t\twith connection.cursor() as cursor:\n\t\t\t\tcursor.execute(query, data)\n\t\t\t\tconnection.commit()\n\t\tfinally:\n\t\t\tconnection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PHPAPI PHP_FUNCTION(fread)\n{\n\tzval *arg1;\n\tlong len;\n\tphp_stream *stream;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rl\", &arg1, &len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tPHP_STREAM_TO_ZVAL(stream, &arg1);\n\n\tif (len <= 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be greater than 0\");\n\t\tRETURN_FALSE;\n\t}\n\n\tif (len > INT_MAX) {\n\t\t/* string length is int in 5.x so we can not read more than int */\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be no more than %d\", INT_MAX);\n\t\tRETURN_FALSE;\n\t}\n\n\tZ_STRVAL_P(return_value) = emalloc(len + 1);\n\tZ_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);\n\n\t/* needed because recv/read/gzread doesnt put a null at the end*/\n\tZ_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;\n\tZ_TYPE_P(return_value) = IS_STRING;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/standard/file.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "mark_context_stack(mrb_state *mrb, struct mrb_context *c)\n{\n size_t i;\n size_t e;\n\n if (c->stack == NULL) return;\n e = c->stack - c->stbase;\n if (c->ci) e += c->ci->nregs;\n if (c->stbase + e > c->stend) e = c->stend - c->stbase;\n for (i=0; istbase[i];\n\n if (!mrb_immediate_p(v)) {\n if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) {\n c->stbase[i] = mrb_nil_value();\n }\n else {\n mrb_gc_mark(mrb, mrb_basic_ptr(v));\n }\n }\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[323, 491]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[323, 491]]}, "_func_name": "mark_context_stack", "_file_name": "src/gc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/api/uploads//logs')\ndef get_logs(sid):\n if utils.sid_is_valid(sid):\n path = join(app.config['UPLOAD_FOLDER'], sid)\n\n if os.path.isfile(join(path, app.config['LOG_FILE'])):\n return send_from_directory(directory=path,\n filename=app.config['LOG_FILE'])\n else:\n abort(404)\n else:\n abort(404)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_logs", "_file_name": "app/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def set(self, key, value, replace=False):\n path = os.path.join(self.namespace, key)\n try:\n self.etcd.write(path, value, prevExist=replace)\n except etcd.EtcdAlreadyExist as err:\n raise CSStoreExists(str(err))\n except etcd.EtcdException as err:\n log_error(\"Error storing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to store key')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[46, 95]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[46, 95]]}, "_func_name": "set", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_month_data_row(self, inverter_serial, ts, etoday, etotal):\n\n y = datetime.fromtimestamp(ts) - timedelta(days=1)\n y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp())\n\n query = '''\n INSERT INTO MonthData (\n TimeStamp,\n Serial,\n DayYield,\n TotalYield \n ) VALUES (\n ?,\n ?,\n ?,\n ?\n );\n '''\n self.c.execute(query, (y_ts, inverter_serial, etoday, etotal))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_month_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {\n\tif (*begin > strlen (str)) {\n\t\treturn TT_EOF;\n\t}\n\t// Skip whitespace\n\twhile (begin && str[*begin] && isspace ((ut8)str[*begin])) {\n\t\t++(*begin);\n\t}\n\n\tif (!str[*begin]) { // null byte\n\t\t*end = *begin;\n\t\treturn TT_EOF;\n\t}\n\tif (isalpha ((ut8)str[*begin])) { // word token\n\t\t*end = *begin;\n\t\twhile (end && str[*end] && isalnum ((ut8)str[*end])) {\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_WORD;\n\t}\n\tif (isdigit ((ut8)str[*begin])) { // number token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_NUMBER;\n\t} else { // special character: [, ], +, *, ...\n\t\t*end = *begin + 1;\n\t\treturn TT_SPECIAL;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getToken", "_file_name": "libr/asm/p/asm_x86_nz.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _start_fc_map(self, fc_map_id, source, target):\n try:\n out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])\n except exception.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_start_fc_map: Failed to start FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source,\n 'target': target,\n 'out': e.stdout,\n 'err': e.stderr})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_start_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _start_fc_map(self, fc_map_id, source, target):\n try:\n out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)\n except exception.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_start_fc_map: Failed to start FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source,\n 'target': target,\n 'out': e.stdout,\n 'err': e.stderr})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[69, 143]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[69, 143]]}, "_func_name": "_start_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,\n size_t size)\n{\n GetBitContext gb;\n AC3HeaderInfo *hdr;\n int err;\n\n if (!*phdr)\n *phdr = av_mallocz(sizeof(AC3HeaderInfo));\n if (!*phdr)\n return AVERROR(ENOMEM);\n hdr = *phdr;\n\n err = init_get_bits8(&gb, buf, size);\n if (err < 0)\n return AVERROR_INVALIDDATA;\n err = ff_ac3_parse_header(&gb, hdr);\n if (err < 0)\n return AVERROR_INVALIDDATA;\n\n return get_bits_count(&gb);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "avpriv_ac3_parse_header", "_file_name": "libavcodec/ac3_parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/test', methods=['GET', 'POST'])\ndef test():\n user_id = session['logged_id']\n sql = 'SELECT * FROM message where user_id = %d ORDER BY c_time DESC' \\\n % (user_id)\n cursor.execute(sql)\n m = cursor.fetchall()\n print(m)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[92, 212]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[92, 212]]}, "_func_name": "test", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getGameCountInSeriesSoFar(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = '\" + getTitle(submission) + \"' AND Date <= '\" + getSubmissionDateFromDatabase(submission) + \"'\").fetchone()[0]\n database.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[120, 317]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[120, 317]]}, "_func_name": "getGameCountInSeriesSoFar", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,\n size_t minimum)\n{\n\tstruct _7zip *zip = (struct _7zip *)a->format->data;\n\tssize_t bytes_avail;\n\n\tif (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {\n\t\t/* Copy mode. */\n\n\t\t/*\n\t\t * Note: '1' here is a performance optimization.\n\t\t * Recall that the decompression layer returns a count of\n\t\t * available bytes; asking for more than that forces the\n\t\t * decompressor to combine reads by copying data.\n\t\t */\n\t\t*buff = __archive_read_ahead(a, 1, &bytes_avail);\n\t\tif (bytes_avail <= 0) {\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Truncated 7-Zip file data\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif ((size_t)bytes_avail >\n\t\t zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\tif ((size_t)bytes_avail > size)\n\t\t\tbytes_avail = (ssize_t)size;\n\n\t\tzip->pack_stream_bytes_unconsumed = bytes_avail;\n\t} else if (zip->uncompressed_buffer_pointer == NULL) {\n\t\t/* Decompression has failed. */\n\t\tarchive_set_error(&(a->archive),\n\t\t ARCHIVE_ERRNO_MISC, \"Damaged 7-Zip archive\");\n\t\treturn (ARCHIVE_FATAL);\n\t} else {\n\t\t/* Packed mode. */\n\t\tif (minimum > zip->uncompressed_buffer_bytes_remaining) {\n\t\t\t/*\n\t\t\t * If remaining uncompressed data size is less than\n\t\t\t * the minimum size, fill the buffer up to the\n\t\t\t * minimum size.\n\t\t\t */\n\t\t\tif (extract_pack_stream(a, minimum) < 0)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif (size > zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\telse\n\t\t\tbytes_avail = (ssize_t)size;\n\t\t*buff = zip->uncompressed_buffer_pointer;\n\t\tzip->uncompressed_buffer_pointer += bytes_avail;\n\t}\n\tzip->uncompressed_buffer_bytes_remaining -= bytes_avail;\n\treturn (bytes_avail);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[264, 549]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[264, 549]]}, "_func_name": "get_uncompressed_data", "_file_name": "libarchive/archive_read_support_format_7zip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static PyObject* patch(PyObject* self, PyObject* args)\n{\n char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;\n Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;\n PyObject *controlTuples, *tuple, *results;\n off_t oldpos, newpos, x, y, z;\n int i, j, numTuples;\n\n if (!PyArg_ParseTuple(args, \"s#nO!s#s#\",\n &origData, &origDataLength, &newDataLength,\n &PyList_Type, &controlTuples,\n &diffBlock, &diffBlockLength,\n &extraBlock, &extraBlockLength))\n return NULL;\n\n /* allocate the memory for the new data */\n newData = PyMem_Malloc(newDataLength + 1);\n if (!newData)\n return PyErr_NoMemory();\n\n oldpos = 0;\n newpos = 0;\n diffPtr = diffBlock;\n extraPtr = extraBlock;\n numTuples = PyList_GET_SIZE(controlTuples);\n for (i = 0; i < numTuples; i++) {\n tuple = PyList_GET_ITEM(controlTuples, i);\n if (!PyTuple_Check(tuple)) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple\");\n return NULL;\n }\n if (PyTuple_GET_SIZE(tuple) != 3) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_TypeError, \"expecting tuple of size 3\");\n return NULL;\n }\n x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));\n y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));\n z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));\n if (newpos + x > newDataLength ||\n diffPtr + x > diffBlock + diffBlockLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }\n memcpy(newData + newpos, diffPtr, x);\n diffPtr += x;\n for (j = 0; j < x; j++)\n if ((oldpos + j >= 0) && (oldpos + j < origDataLength))\n newData[newpos + j] += origData[oldpos + j];\n newpos += x;\n oldpos += x;\n memcpy(newData + newpos, extraPtr, y);\n extraPtr += y;\n newpos += y;\n oldpos += z;\n }\n\n /* confirm that a valid patch was applied */\n if (newpos != newDataLength ||\n diffPtr != diffBlock + diffBlockLength ||\n extraPtr != extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (underflow)\");\n return NULL;\n }\n\n results = PyBytes_FromStringAndSize(newData, newDataLength);\n PyMem_Free(newData);\n return results;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1561, 1686]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1561, 1686]]}, "_func_name": "patch", "_file_name": "bsdiff4/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def delete_event(self, event_id):\n sql = \"\"\"\n DELETE FROM events\n WHERE event_id = %s\n \"\"\"\n affected_count = self.cur.execute(sql, (event_id,))\n self.conn.commit()\n return affected_count", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_event", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "lexer_process_char_literal (parser_context_t *context_p, /**< context */\n const uint8_t *char_p, /**< characters */\n size_t length, /**< length of string */\n uint8_t literal_type, /**< final literal type */\n bool has_escape) /**< has escape sequences */\n{\n parser_list_iterator_t literal_iterator;\n lexer_literal_t *literal_p;\n uint32_t literal_index = 0;\n\n JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL\n || literal_type == LEXER_STRING_LITERAL);\n\n JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);\n JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);\n\n parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);\n\n while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (literal_p->type == literal_type\n && literal_p->prop.length == length\n && memcmp (literal_p->u.char_p, char_p, length) == 0)\n {\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);\n return;\n }\n\n literal_index++;\n }\n\n JERRY_ASSERT (literal_index == context_p->literal_count);\n\n if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)\n {\n parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);\n }\n\n if (length == 0)\n {\n has_escape = false;\n }\n\n literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);\n literal_p->prop.length = (uint16_t) length;\n literal_p->type = literal_type;\n literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;\n\n if (has_escape)\n {\n literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);\n memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);\n }\n else\n {\n literal_p->u.char_p = char_p;\n }\n\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n context_p->literal_count++;\n} /* lexer_process_char_literal */", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "lexer_process_char_literal", "_file_name": "jerry-core/parser/js/js-lexer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,\n const Quantum pixel,const MagickEvaluateOperator op,\n const MagickRealType value)\n{\n MagickRealType\n result;\n\n result=0.0;\n switch (op)\n {\n case UndefinedEvaluateOperator:\n break;\n case AbsEvaluateOperator:\n {\n result=(MagickRealType) fabs((double) (pixel+value));\n break;\n }\n case AddEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case AddModulusEvaluateOperator:\n {\n /*\n This returns a 'floored modulus' of the addition which is a\n positive result. It differs from % or fmod() which returns a\n 'truncated modulus' result, where floor() is replaced by trunc()\n and could return a negative result (which is clipped).\n */\n result=pixel+value;\n result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));\n break;\n }\n case AndEvaluateOperator:\n {\n result=(MagickRealType) ((ssize_t) pixel & (ssize_t) (value+0.5));\n break;\n }\n case CosineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case DivideEvaluateOperator:\n {\n result=pixel/(value == 0.0 ? 1.0 : value);\n break;\n }\n case ExponentialEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*\n pixel)));\n break;\n }\n case GaussianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n GaussianNoise,value);\n break;\n }\n case ImpulseNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n ImpulseNoise,value);\n break;\n }\n case LaplacianNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n LaplacianNoise,value);\n break;\n }\n case LeftShiftEvaluateOperator:\n {\n result=(MagickRealType) ((ssize_t) pixel << (ssize_t) (value+0.5));\n break;\n }\n case LogEvaluateOperator:\n {\n if ((QuantumScale*pixel) >= MagickEpsilon)\n result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*\n pixel+1.0))/log((double) (value+1.0)));\n break;\n }\n case MaxEvaluateOperator:\n {\n result=(MagickRealType) EvaluateMax((double) pixel,value);\n break;\n }\n case MeanEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MedianEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case MinEvaluateOperator:\n {\n result=(MagickRealType) MagickMin((double) pixel,value);\n break;\n }\n case MultiplicativeNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n MultiplicativeGaussianNoise,value);\n break;\n }\n case MultiplyEvaluateOperator:\n {\n result=(MagickRealType) (value*pixel);\n break;\n }\n case OrEvaluateOperator:\n {\n result=(MagickRealType) ((ssize_t) pixel | (ssize_t) (value+0.5));\n break;\n }\n case PoissonNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n PoissonNoise,value);\n break;\n }\n case PowEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),\n (double) value));\n break;\n }\n case RightShiftEvaluateOperator:\n {\n result=(MagickRealType) ((ssize_t) pixel >> (ssize_t) (value+0.5));\n break;\n }\n case RootMeanSquareEvaluateOperator:\n {\n result=(MagickRealType) (pixel*pixel+value);\n break;\n }\n case SetEvaluateOperator:\n {\n result=value;\n break;\n }\n case SineEvaluateOperator:\n {\n result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*\n QuantumScale*pixel*value))+0.5));\n break;\n }\n case SubtractEvaluateOperator:\n {\n result=(MagickRealType) (pixel-value);\n break;\n }\n case SumEvaluateOperator:\n {\n result=(MagickRealType) (pixel+value);\n break;\n }\n case ThresholdEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :\n QuantumRange);\n break;\n }\n case ThresholdBlackEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);\n break;\n }\n case ThresholdWhiteEvaluateOperator:\n {\n result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :\n pixel);\n break;\n }\n case UniformNoiseEvaluateOperator:\n {\n result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,\n UniformNoise,value);\n break;\n }\n case XorEvaluateOperator:\n {\n result=(MagickRealType) ((ssize_t) pixel ^ (ssize_t) (value+0.5));\n break;\n }\n }\n return(result);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ApplyEvaluateOperator", "_file_name": "magick/statistic.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def getPlayer(player):\n\tdb.execute(\"SELECT * FROM players WHERE Name = '%s' COLLATE NOCASE\" % player)\n\tplayerstats = dict(db.fetchone())\n\treturn playerstats", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[23, 102]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[23, 102]]}, "_func_name": "getPlayer", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width)\n{\n int i;\n GlyphInfo *cur, *s1, *e1, *s2, *s3;\n int last_space;\n int break_type;\n int exit;\n double pen_shift_x;\n double pen_shift_y;\n int cur_line;\n int run_offset;\n TextInfo *text_info = &render_priv->text_info;\n\n last_space = -1;\n text_info->n_lines = 1;\n break_type = 0;\n s1 = text_info->glyphs; // current line start\n for (i = 0; i < text_info->length; ++i) {\n int break_at = -1;\n double s_offset, len;\n cur = text_info->glyphs + i;\n s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x);\n len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset;\n\n if (cur->symbol == '\\n') {\n break_type = 2;\n break_at = i;\n ass_msg(render_priv->library, MSGL_DBG2,\n \"forced line break at %d\", break_at);\n } else if (cur->symbol == ' ') {\n last_space = i;\n } else if (len >= max_text_width\n && (render_priv->state.wrap_style != 2)) {\n break_type = 1;\n break_at = last_space;\n if (break_at >= 0)\n ass_msg(render_priv->library, MSGL_DBG2, \"line break at %d\",\n break_at);\n }\n\n if (break_at != -1) {\n // need to use one more line\n // marking break_at+1 as start of a new line\n int lead = break_at + 1; // the first symbol of the new line\n if (text_info->n_lines >= text_info->max_lines) {\n // Raise maximum number of lines\n text_info->max_lines *= 2;\n text_info->lines = realloc(text_info->lines,\n sizeof(LineInfo) *\n text_info->max_lines);\n }\n if (lead < text_info->length) {\n text_info->glyphs[lead].linebreak = break_type;\n last_space = -1;\n s1 = text_info->glyphs + lead;\n text_info->n_lines++;\n }\n }\n }\n#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))\n exit = 0;\n while (!exit && render_priv->state.wrap_style != 1) {\n exit = 1;\n s3 = text_info->glyphs;\n s1 = s2 = 0;\n for (i = 0; i <= text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if ((i == text_info->length) || cur->linebreak) {\n s1 = s2;\n s2 = s3;\n s3 = cur;\n if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'\n double l1, l2, l1_new, l2_new;\n GlyphInfo *w = s2;\n\n do {\n --w;\n } while ((w > s1) && (w->symbol == ' '));\n while ((w > s1) && (w->symbol != ' ')) {\n --w;\n }\n e1 = w;\n while ((e1 > s1) && (e1->symbol == ' ')) {\n --e1;\n }\n if (w->symbol == ' ')\n ++w;\n\n l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (s2->bbox.xMin + s2->pos.x));\n l1_new = d6_to_double(\n (e1->bbox.xMax + e1->pos.x) -\n (s1->bbox.xMin + s1->pos.x));\n l2_new = d6_to_double(\n ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) -\n (w->bbox.xMin + w->pos.x));\n\n if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) {\n if (w->linebreak)\n text_info->n_lines--;\n w->linebreak = 1;\n s2->linebreak = 0;\n exit = 0;\n }\n }\n }\n if (i == text_info->length)\n break;\n }\n\n }\n assert(text_info->n_lines >= 1);\n#undef DIFF\n\n measure_text(render_priv);\n trim_whitespace(render_priv);\n\n cur_line = 1;\n run_offset = 0;\n\n i = 0;\n cur = text_info->glyphs + i;\n while (i < text_info->length && cur->skip)\n cur = text_info->glyphs + ++i;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y = 0.;\n\n for (i = 0; i < text_info->length; ++i) {\n cur = text_info->glyphs + i;\n if (cur->linebreak) {\n while (i < text_info->length && cur->skip && cur->symbol != '\\n')\n cur = text_info->glyphs + ++i;\n double height =\n text_info->lines[cur_line - 1].desc +\n text_info->lines[cur_line].asc;\n text_info->lines[cur_line - 1].len = i -\n text_info->lines[cur_line - 1].offset;\n text_info->lines[cur_line].offset = i;\n cur_line++;\n run_offset++;\n pen_shift_x = d6_to_double(-cur->pos.x);\n pen_shift_y += height + render_priv->settings.line_spacing;\n }\n cur->pos.x += double_to_d6(pen_shift_x);\n cur->pos.y += double_to_d6(pen_shift_y);\n }\n text_info->lines[cur_line - 1].len =\n text_info->length - text_info->lines[cur_line - 1].offset;\n\n#if 0\n // print line info\n for (i = 0; i < text_info->n_lines; i++) {\n printf(\"line %d offset %d length %d\\n\", i, text_info->lines[i].offset,\n text_info->lines[i].len);\n }\n#endif\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "wrap_lines_smart", "_file_name": "libass/ass_render.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int b_unpack (lua_State *L) {\n Header h;\n const char *fmt = luaL_checkstring(L, 1);\n size_t ld;\n const char *data = luaL_checklstring(L, 2, &ld);\n size_t pos = luaL_optinteger(L, 3, 1) - 1;\n int n = 0; /* number of results */\n defaultoptions(&h);\n while (*fmt) {\n int opt = *fmt++;\n size_t size = optsize(L, opt, &fmt);\n pos += gettoalign(pos, &h, opt, size);\n luaL_argcheck(L, pos+size <= ld, 2, \"data string too short\");\n /* stack space for item + next position */\n luaL_checkstack(L, 2, \"too many results\");\n switch (opt) {\n case 'b': case 'B': case 'h': case 'H':\n case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */\n int issigned = islower(opt);\n lua_Number res = getinteger(data+pos, h.endian, issigned, size);\n lua_pushnumber(L, res); n++;\n break;\n }\n case 'x': {\n break;\n }\n case 'f': {\n float f;\n memcpy(&f, data+pos, size);\n correctbytes((char *)&f, sizeof(f), h.endian);\n lua_pushnumber(L, f); n++;\n break;\n }\n case 'd': {\n double d;\n memcpy(&d, data+pos, size);\n correctbytes((char *)&d, sizeof(d), h.endian);\n lua_pushnumber(L, d); n++;\n break;\n }\n case 'c': {\n if (size == 0) {\n if (n == 0 || !lua_isnumber(L, -1))\n luaL_error(L, \"format 'c0' needs a previous size\");\n size = lua_tonumber(L, -1);\n lua_pop(L, 1); n--;\n luaL_argcheck(L, size <= ld && pos <= ld - size,\n 2, \"data string too short\");\n }\n lua_pushlstring(L, data+pos, size); n++;\n break;\n }\n case 's': {\n const char *e = (const char *)memchr(data+pos, '\\0', ld - pos);\n if (e == NULL)\n luaL_error(L, \"unfinished string in data\");\n size = (e - (data+pos)) + 1;\n lua_pushlstring(L, data+pos, size - 1); n++;\n break;\n }\n default: controloptions(L, opt, &fmt, &h);\n }\n pos += size;\n }\n lua_pushinteger(L, pos + 1); /* next position */\n return n + 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[157, 202], [385, 451]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[157, 202], [385, 451]]}, "_func_name": "b_unpack", "_file_name": "deps/lua/src/lua_struct.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def write_section(self, section_name, section_data):\n self.write_line(\"\")\n self.write_line(\"define %s {\" % section_name)\n sorted_keys = section_data.keys()\n sorted_keys.sort()\n for key in sorted_keys:\n value = section_data[key]\n self.icinga_lines.append((\"%s%-45s%s\" % (self.indent, key, self.value_to_icinga(value))))\n self.write_line(\"}\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[278, 380]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[278, 380]]}, "_func_name": "write_section", "_file_name": "src/main/python/monitoring_config_generator/MonitoringConfigGenerator.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('//edit')\ndef render_page_edit(page_name):\n query = db.query(\"select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n wiki_page = query.namedresult()\n if len(wiki_page) > 0:\n content = wiki_page[0].content\n else:\n content = \"\"\n return render_template(\n 'edit_page.html',\n page_name = page_name,\n content = content\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[65, 254]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[65, 254]]}, "_func_name": "render_page_edit", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int snd_timer_open(struct snd_timer_instance **ti,\n\t\t char *owner, struct snd_timer_id *tid,\n\t\t unsigned int slave_id)\n{\n\tstruct snd_timer *timer;\n\tstruct snd_timer_instance *timeri = NULL;\n\tstruct device *card_dev_to_put = NULL;\n\tint err;\n\n\tmutex_lock(®ister_mutex);\n\tif (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {\n\t\t/* open a slave instance */\n\t\tif (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||\n\t\t tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {\n\t\t\tpr_debug(\"ALSA: timer: invalid slave class %i\\n\",\n\t\t\t\t tid->dev_sclass);\n\t\t\terr = -EINVAL;\n\t\t\tgoto unlock;\n\t\t}\n\t\ttimeri = snd_timer_instance_new(owner, NULL);\n\t\tif (!timeri) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto unlock;\n\t\t}\n\t\ttimeri->slave_class = tid->dev_sclass;\n\t\ttimeri->slave_id = tid->device;\n\t\ttimeri->flags |= SNDRV_TIMER_IFLG_SLAVE;\n\t\tlist_add_tail(&timeri->open_list, &snd_timer_slave_list);\n\t\terr = snd_timer_check_slave(timeri);\n\t\tif (err < 0) {\n\t\t\tsnd_timer_close_locked(timeri, &card_dev_to_put);\n\t\t\ttimeri = NULL;\n\t\t}\n\t\tgoto unlock;\n\t}\n\n\t/* open a master instance */\n\ttimer = snd_timer_find(tid);\n#ifdef CONFIG_MODULES\n\tif (!timer) {\n\t\tmutex_unlock(®ister_mutex);\n\t\tsnd_timer_request(tid);\n\t\tmutex_lock(®ister_mutex);\n\t\ttimer = snd_timer_find(tid);\n\t}\n#endif\n\tif (!timer) {\n\t\terr = -ENODEV;\n\t\tgoto unlock;\n\t}\n\tif (!list_empty(&timer->open_list_head)) {\n\t\tstruct snd_timer_instance *t =\n\t\t\tlist_entry(timer->open_list_head.next,\n\t\t\t\t struct snd_timer_instance, open_list);\n\t\tif (t->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {\n\t\t\terr = -EBUSY;\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\tif (timer->num_instances >= timer->max_instances) {\n\t\terr = -EBUSY;\n\t\tgoto unlock;\n\t}\n\ttimeri = snd_timer_instance_new(owner, timer);\n\tif (!timeri) {\n\t\terr = -ENOMEM;\n\t\tgoto unlock;\n\t}\n\t/* take a card refcount for safe disconnection */\n\tif (timer->card)\n\t\tget_device(&timer->card->card_dev);\n\ttimeri->slave_class = tid->dev_sclass;\n\ttimeri->slave_id = slave_id;\n\n\tif (list_empty(&timer->open_list_head) && timer->hw.open) {\n\t\terr = timer->hw.open(timer);\n\t\tif (err) {\n\t\t\tkfree(timeri->owner);\n\t\t\tkfree(timeri);\n\t\t\ttimeri = NULL;\n\n\t\t\tif (timer->card)\n\t\t\t\tcard_dev_to_put = &timer->card->card_dev;\n\t\t\tmodule_put(timer->module);\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\n\tlist_add_tail(&timeri->open_list, &timer->open_list_head);\n\ttimer->num_instances++;\n\terr = snd_timer_check_master(timeri);\n\tif (err < 0) {\n\t\tsnd_timer_close_locked(timeri, &card_dev_to_put);\n\t\ttimeri = NULL;\n\t}\n\n unlock:\n\tmutex_unlock(®ister_mutex);\n\t/* put_device() is called after unlock for avoiding deadlock */\n\tif (card_dev_to_put)\n\t\tput_device(card_dev_to_put);\n\t*ti = timeri;\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "snd_timer_open", "_file_name": "sound/core/timer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _add_to_db(user):\n \"\"\"\n Adds User object to the database\n :param user: User object with info about user\n :return: None\n \"\"\"\n query = (\"INSERT INTO users (chat_id, first_name, nickname, \"\n \"last_name, language) \"\n f\"VALUES (%s, %s, %s, %s, %s)\")\n\n parameters = (user.chat_id, user.first_name, user.nickname,\n user.last_name, user.language)\n\n try:\n db.add(query, parameters)\n except DatabaseError:\n log.error(\"Cannot add user to the database\")\n else:\n log.info(f\"User {user} was successfully added to the users db\")", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_add_to_db", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getKey(client):\n\t\"\"\"Retrieves the specified key for the specified client\n\tReturns an error if the key doesn't exist, obviously.\n\t\"\"\"\n\tglobal SERVER_JWT_PRIVATE_KEY\n\tglobal BAD_REQUEST\n\n\tvalidateClient(client)\n\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\n\t# Keys may only have alpha-numeric names\n\ttry:\n\t\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n\t\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')\n\t\trequested_key = open('keys/%s/%s.key' % (client, token_data['key']), 'r').read()\n\texcept KeyError:\n\t\traise FoxlockError(BAD_REQUEST, \"JWT did not contain attribute 'key'\")\n\texcept IOError:\n\t\traise FoxlockError(BAD_REQUEST, \"Key '%s' not found\" % token_data['key'])\n\n\t# Key is returned in a JWT encrypted with the client's public key, so only they can decrypt it\n\tkeytoken = packJWT({'key': requested_key}, SERVER_JWT_PRIVATE_KEY, client_pub_key)\n\n\treturn keytoken", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[213, 214], [363, 480]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[213, 214], [363, 480]]}, "_func_name": "getKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getKey(client):\n\t\"\"\"Retrieves the specified key for the specified client\n\tReturns an error if the key doesn't exist, obviously.\n\t\"\"\"\n\tglobal SERVER_JWT_PRIVATE_KEY\n\tglobal BAD_REQUEST\n\n\tvalidateClient(client)\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateKeyName(token_data['key'])\n\n\t# Keys may only have alpha-numeric names\n\ttry:\n\t\trequested_key = open('keys/%s/%s.key' % (client, token_data['key']), 'r').read()\n\texcept KeyError:\n\t\traise FoxlockError(BAD_REQUEST, \"JWT did not contain attribute 'key'\")\n\texcept IOError:\n\t\traise FoxlockError(BAD_REQUEST, \"Key '%s' not found\" % token_data['key'])\n\n\t# Key is returned in a JWT encrypted with the client's public key, so only they can decrypt it\n\tkeytoken = packJWT({'key': requested_key}, SERVER_JWT_PRIVATE_KEY, client_pub_key)\n\n\treturn keytoken", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "tcpmss_mangle_packet(struct sk_buff *skb,\n\t\t const struct xt_action_param *par,\n\t\t unsigned int family,\n\t\t unsigned int tcphoff,\n\t\t unsigned int minlen)\n{\n\tconst struct xt_tcpmss_info *info = par->targinfo;\n\tstruct tcphdr *tcph;\n\tint len, tcp_hdrlen;\n\tunsigned int i;\n\t__be16 oldval;\n\tu16 newmss;\n\tu8 *opt;\n\n\t/* This is a fragment, no TCP header is available */\n\tif (par->fragoff != 0)\n\t\treturn 0;\n\n\tif (!skb_make_writable(skb, skb->len))\n\t\treturn -1;\n\n\tlen = skb->len - tcphoff;\n\tif (len < (int)sizeof(struct tcphdr))\n\t\treturn -1;\n\n\ttcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);\n\ttcp_hdrlen = tcph->doff * 4;\n\n\tif (len < tcp_hdrlen)\n\t\treturn -1;\n\n\tif (info->mss == XT_TCPMSS_CLAMP_PMTU) {\n\t\tstruct net *net = xt_net(par);\n\t\tunsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family);\n\t\tunsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu);\n\n\t\tif (min_mtu <= minlen) {\n\t\t\tnet_err_ratelimited(\"unknown or invalid path-MTU (%u)\\n\",\n\t\t\t\t\t min_mtu);\n\t\t\treturn -1;\n\t\t}\n\t\tnewmss = min_mtu - minlen;\n\t} else\n\t\tnewmss = info->mss;\n\n\topt = (u_int8_t *)tcph;\n\tfor (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) {\n\t\tif (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) {\n\t\t\tu_int16_t oldmss;\n\n\t\t\toldmss = (opt[i+2] << 8) | opt[i+3];\n\n\t\t\t/* Never increase MSS, even when setting it, as\n\t\t\t * doing so results in problems for hosts that rely\n\t\t\t * on MSS being set correctly.\n\t\t\t */\n\t\t\tif (oldmss <= newmss)\n\t\t\t\treturn 0;\n\n\t\t\topt[i+2] = (newmss & 0xff00) >> 8;\n\t\t\topt[i+3] = newmss & 0x00ff;\n\n\t\t\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t\t\t htons(oldmss), htons(newmss),\n\t\t\t\t\t\t false);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/* There is data after the header so the option can't be added\n\t * without moving it, and doing so may make the SYN packet\n\t * itself too large. Accept the packet unmodified instead.\n\t */\n\tif (len > tcp_hdrlen)\n\t\treturn 0;\n\n\t/*\n\t * MSS Option not found ?! add it..\n\t */\n\tif (skb_tailroom(skb) < TCPOLEN_MSS) {\n\t\tif (pskb_expand_head(skb, 0,\n\t\t\t\t TCPOLEN_MSS - skb_tailroom(skb),\n\t\t\t\t GFP_ATOMIC))\n\t\t\treturn -1;\n\t\ttcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);\n\t}\n\n\tskb_put(skb, TCPOLEN_MSS);\n\n\t/*\n\t * IPv4: RFC 1122 states \"If an MSS option is not received at\n\t * connection setup, TCP MUST assume a default send MSS of 536\".\n\t * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum\n\t * length IPv6 header of 60, ergo the default MSS value is 1220\n\t * Since no MSS was provided, we must use the default values\n\t */\n\tif (xt_family(par) == NFPROTO_IPV4)\n\t\tnewmss = min(newmss, (u16)536);\n\telse\n\t\tnewmss = min(newmss, (u16)1220);\n\n\topt = (u_int8_t *)tcph + sizeof(struct tcphdr);\n\tmemmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr));\n\n\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t htons(len), htons(len + TCPOLEN_MSS), true);\n\topt[0] = TCPOPT_MSS;\n\topt[1] = TCPOLEN_MSS;\n\topt[2] = (newmss & 0xff00) >> 8;\n\topt[3] = newmss & 0x00ff;\n\n\tinet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false);\n\n\toldval = ((__be16 *)tcph)[6];\n\ttcph->doff += TCPOLEN_MSS/4;\n\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t oldval, ((__be16 *)tcph)[6], false);\n\treturn TCPOLEN_MSS;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[642, 665]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[642, 665]]}, "_func_name": "tcpmss_mangle_packet", "_file_name": "net/netfilter/xt_TCPMSS.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def insertNPC(name, race,classe,sex,level,image,legit):\n\tc, conn = getConnection()\n\tdate = now()\n\tc.execute(\"INSERT INTO npc VALUES ('\"+date+\"','\"+str(name)+\"','\"+race+\"','\"+classe+\"','\"+sex+\"','\"+str(level)+\"','\"+image+\"','\"+str(legit)+\"')\")\n\tconn.commit()\n\tconn.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[97, 243]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[97, 243]]}, "_func_name": "insertNPC", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def history_data(start_time, offset=None):\n \"\"\"Return history data.\n\n Arguments:\n start_time: select history starting from this timestamp.\n offset: number of items to skip\n \"\"\"\n # history atimes are stored as ints, ensure start_time is not a float\n start_time = int(start_time)\n hist = objreg.get('web-history')\n if offset is not None:\n entries = hist.entries_before(start_time, limit=1000, offset=offset)\n else:\n # end is 24hrs earlier than start\n end_time = start_time - 24*60*60\n entries = hist.entries_between(end_time, start_time)\n\n return [{\"url\": html.escape(e.url),\n \"title\": html.escape(e.title) or html.escape(e.url),\n \"time\": e.atime} for e in entries]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "history_data", "_file_name": "qutebrowser/browser/qutescheme.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet,\n\t\t\t\t char *buf, u_int8_t client_hash) {\n u_int16_t offset = 22, buf_out_len = 0;\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n offset += 4;\n\n /* -1 for ';' */\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n /* ssh.kex_algorithms [C/S] */\n strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len);\n buf[buf_out_len++] = ';';\n offset += len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.server_host_key_algorithms [None] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n offset += 4 + len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.encryption_algorithms_client_to_server [C] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.encryption_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.mac_algorithms_client_to_server [C] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.mac_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.compression_algorithms_client_to_server [C] */\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n offset += len;\n } else\n offset += 4 + len;\n\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n /* ssh.compression_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.languages_client_to_server [None] */\n\n /* ssh.languages_server_to_client [None] */\n\n#ifdef SSH_DEBUG\n printf(\"[SSH] %s\\n\", buf);\n#endif\n\n return(buf_out_len);\n\ninvalid_payload:\n\n#ifdef SSH_DEBUG\n printf(\"[SSH] Invalid packet payload\\n\");\n#endif\n\n return(0);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "concat_hash_string", "_file_name": "src/lib/protocols/ssh.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,\n\t\t\t int class_index, int *methods, int *sym_count) {\n\tstruct r_bin_t *rbin = binfile->rbin;\n\n\tchar *class_name;\n\tint z;\n\tconst ut8 *p, *p_end;\n\n\tif (!c) {\n\t\treturn;\n\t}\n\n\tclass_name = dex_class_name (bin, c);\n\tclass_name = r_str_replace (class_name, \";\", \"\", 0); //TODO: move to func\n\n\tif (!class_name || !*class_name) {\n\t\treturn;\n\t}\n\n\tRBinClass *cls = R_NEW0 (RBinClass);\n\tif (!cls) {\n\t\treturn;\n\t}\n\tcls->name = class_name;\n\tcls->index = class_index;\n\tcls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;\n\tcls->methods = r_list_new ();\n\tif (!cls->methods) {\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tcls->fields = r_list_new ();\n\tif (!cls->fields) {\n\t\tr_list_free (cls->methods);\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tr_list_append (bin->classes_list, cls);\n\tif (dexdump) {\n\t\trbin->cb_printf (\" Class descriptor : '%s;'\\n\", class_name);\n\t\trbin->cb_printf (\n\t\t\t\" Access flags : 0x%04x (%s)\\n\", c->access_flags,\n\t\t\tcreateAccessFlagStr (c->access_flags, kAccessForClass));\n\t\trbin->cb_printf (\" Superclass : '%s'\\n\",\n\t\t\t\t dex_class_super_name (bin, c));\n\t\trbin->cb_printf (\" Interfaces -\\n\");\n\t}\n\n\tif (c->interfaces_offset > 0 &&\n\t bin->header.data_offset < c->interfaces_offset &&\n\t c->interfaces_offset <\n\t\t bin->header.data_offset + bin->header.data_size) {\n\t\tp = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);\n\t\tint types_list_size = r_read_le32(p);\n\t\tif (types_list_size < 0 || types_list_size >= bin->header.types_size ) {\n\t\t\treturn;\n\t\t}\n\t\tfor (z = 0; z < types_list_size; z++) {\n\t\t\tint t = r_read_le16 (p + 4 + z * 2);\n\t\t\tif (t > 0 && t < bin->header.types_size ) {\n\t\t\t\tint tid = bin->types[t].descriptor_id;\n\t\t\t\tif (dexdump) {\n\t\t\t\t\trbin->cb_printf (\n\t\t\t\t\t\t\" #%d : '%s'\\n\",\n\t\t\t\t\t\tz, getstr (bin, tid));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: this is quite ugly\n\tif (!c || !c->class_data_offset) {\n\t\tif (dexdump) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" Static fields -\\n Instance fields \"\n\t\t\t\t\"-\\n Direct methods -\\n Virtual methods \"\n\t\t\t\t\"-\\n\");\n\t\t}\n\t} else {\n\t\t// TODO: move to func, def or inline\n\t\t// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]\n\t\tif (bin->header.class_offset > c->class_data_offset ||\n\t\t c->class_data_offset <\n\t\t\t bin->header.class_offset +\n\t\t\t\t bin->header.class_size * DEX_CLASS_SIZE) {\n\t\t\treturn;\n\t\t}\n\n\t\tp = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);\n\t\tp_end = p + binfile->buf->length - c->class_data_offset;\n\t\t//XXX check for NULL!!\n\t\tc->class_data = (struct dex_class_data_item_t *)malloc (\n\t\t\tsizeof (struct dex_class_data_item_t));\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Static fields -\\n\"); \n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->static_fields_size, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Instance fields -\\n\");\n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->instance_fields_size, false);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Direct methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->direct_methods_size, methods, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Virtual methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->virtual_methods_size, methods, false);\n\t}\n\n\tif (dexdump) { \n\t\tchar *source_file = getstr (bin, c->source_file);\n\t\tif (!source_file) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" source_file_idx : %d (unknown)\\n\\n\",\n\t\t\t\tc->source_file);\n\t\t} else {\n\t\t\trbin->cb_printf (\" source_file_idx : %d (%s)\\n\\n\",\n\t\t\t\t\t c->source_file, source_file);\n\t\t}\n\t}\n\t// TODO:!!!!\n\t// FIX: FREE BEFORE ALLOCATE!!!\n\t//free (class_name);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1421, 1461]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1421, 1461]]}, "_func_name": "parse_class", "_file_name": "libr/bin/p/bin_dex.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):\n \"\"\"Create a 3PAR host.\n\n Create a 3PAR host, if there is already a host on the 3par using\n the same wwn but with a different hostname, return the hostname\n used by 3PAR.\n \"\"\"\n out = self.common._cli_run('createhost -persona %s -domain %s %s %s'\n % (persona_id, domain,\n hostname, \" \".join(wwn)), None)\n if out and len(out) > 1:\n return self.common.parse_create_host_error(hostname, out)\n\n return hostname", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[289, 494]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[289, 494]]}, "_func_name": "_create_3par_fibrechan_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_fc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route(\"/search\", methods = [\"POST\"])\ndef search_pages():\n search = request.form.get(\"search\")\n page = db.query(\"select title from page where title = '%s'\" % search).namedresult()\n if len(page) == 0:\n return redirect(\"/%s\" % search)\n else:\n return place_holder(search)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[102, 190]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[102, 190]]}, "_func_name": "search_pages", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status)\n{\n\tGF_M2TS_Program *prog;\n\tGF_M2TS_SECTION_ES *pmt;\n\tu32 i, nb_progs, evt_type;\n\tu32 nb_sections;\n\tu32 data_size;\n\tunsigned char *data;\n\tGF_M2TS_Section *section;\n\n\t/*wait for the last section */\n\tif (!(status&GF_M2TS_TABLE_END)) return;\n\n\t/*skip if already received*/\n\tif (status&GF_M2TS_TABLE_REPEAT) {\n\t\tif (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL);\n\t\treturn;\n\t}\n\n\tnb_sections = gf_list_count(sections);\n\tif (nb_sections > 1) {\n\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"PAT on multiple sections not supported\\n\"));\n\t}\n\n\tsection = (GF_M2TS_Section *)gf_list_get(sections, 0);\n\tdata = section->data;\n\tdata_size = section->data_size;\n\n\tif (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) {\n\t\tif (ts->pat->demux_restarted) {\n\t\t\tts->pat->demux_restarted = 0;\n\t\t} else {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\\n\", table_id, ex_table_id));\n\t\t}\n\t\treturn;\n\t}\n\tnb_progs = data_size / 4;\n\n\tfor (i=0; init) {\n\t\t\t\tts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tGF_SAFEALLOC(prog, GF_M2TS_Program);\n\t\t\tif (!prog) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate program for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprog->streams = gf_list_new();\n\t\t\tprog->pmt_pid = pid;\n\t\t\tprog->number = number;\n\t\t\tprog->ts = ts;\n\t\t\tgf_list_add(ts->programs, prog);\n\t\t\tGF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES);\n\t\t\tif (!pmt) {\n\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"Fail to allocate pmt filter for pid %d\\n\", pid));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpmt->flags = GF_M2TS_ES_IS_SECTION;\n\t\t\tgf_list_add(prog->streams, pmt);\n\t\t\tpmt->pid = prog->pmt_pid;\n\t\t\tpmt->program = prog;\n\t\t\tts->ess[pmt->pid] = (GF_M2TS_ES *)pmt;\n\t\t\tpmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0);\n\t\t}\n\t}\n\n\tevt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND;\n\tif (ts->on_event) ts->on_event(ts, evt_type, NULL);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1458, 1469]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1458, 1469]]}, "_func_name": "gf_m2ts_process_pat", "_file_name": "src/media_tools/mpegts.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *avpkt)\n{\n EXRContext *s = avctx->priv_data;\n ThreadFrame frame = { .f = data };\n AVFrame *picture = data;\n uint8_t *ptr;\n\n int i, y, ret, ymax;\n int planes;\n int out_line_size;\n int nb_blocks; /* nb scanline or nb tile */\n uint64_t start_offset_table;\n uint64_t start_next_scanline;\n PutByteContext offset_table_writer;\n\n bytestream2_init(&s->gb, avpkt->data, avpkt->size);\n\n if ((ret = decode_header(s, picture)) < 0)\n return ret;\n\n switch (s->pixel_type) {\n case EXR_FLOAT:\n case EXR_HALF:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n } else {\n /* todo: change this when a floating point pixel format with luma with alpha is implemented */\n avctx->pix_fmt = AV_PIX_FMT_GBRAPF32;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_GBRPF32;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAYF32;\n }\n }\n break;\n case EXR_UINT:\n if (s->channel_offsets[3] >= 0) {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGBA64;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_YA16;\n }\n } else {\n if (!s->is_luma) {\n avctx->pix_fmt = AV_PIX_FMT_RGB48;\n } else {\n avctx->pix_fmt = AV_PIX_FMT_GRAY16;\n }\n }\n break;\n default:\n av_log(avctx, AV_LOG_ERROR, \"Missing channel list.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED)\n avctx->color_trc = s->apply_trc_type;\n\n switch (s->compression) {\n case EXR_RAW:\n case EXR_RLE:\n case EXR_ZIP1:\n s->scan_lines_per_block = 1;\n break;\n case EXR_PXR24:\n case EXR_ZIP16:\n s->scan_lines_per_block = 16;\n break;\n case EXR_PIZ:\n case EXR_B44:\n case EXR_B44A:\n s->scan_lines_per_block = 32;\n break;\n default:\n avpriv_report_missing_feature(avctx, \"Compression %d\", s->compression);\n return AVERROR_PATCHWELCOME;\n }\n\n /* Verify the xmin, xmax, ymin and ymax before setting the actual image size.\n * It's possible for the data window can larger or outside the display window */\n if (s->xmin > s->xmax || s->ymin > s->ymax ||\n s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) {\n av_log(avctx, AV_LOG_ERROR, \"Wrong or missing size information.\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0)\n return ret;\n\n s->desc = av_pix_fmt_desc_get(avctx->pix_fmt);\n if (!s->desc)\n return AVERROR_INVALIDDATA;\n\n if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) {\n planes = s->desc->nb_components;\n out_line_size = avctx->width * 4;\n } else {\n planes = 1;\n out_line_size = avctx->width * 2 * s->desc->nb_components;\n }\n\n if (s->is_tile) {\n nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) *\n ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize);\n } else { /* scanline */\n nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) /\n s->scan_lines_per_block;\n }\n\n if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)\n return ret;\n\n if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks)\n return AVERROR_INVALIDDATA;\n\n // check offset table and recreate it if need\n if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) {\n av_log(s->avctx, AV_LOG_DEBUG, \"recreating invalid scanline offset table\\n\");\n\n start_offset_table = bytestream2_tell(&s->gb);\n start_next_scanline = start_offset_table + nb_blocks * 8;\n bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8);\n\n for (y = 0; y < nb_blocks; y++) {\n /* write offset of prev scanline in offset table */\n bytestream2_put_le64(&offset_table_writer, start_next_scanline);\n\n /* get len of next scanline */\n bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */\n start_next_scanline += (bytestream2_get_le32(&s->gb) + 8);\n }\n bytestream2_seek(&s->gb, start_offset_table, SEEK_SET);\n }\n\n // save pointer we are going to use in decode_block\n s->buf = avpkt->data;\n s->buf_size = avpkt->size;\n\n // Zero out the start if ymin is not 0\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i];\n for (y = 0; y < FFMIN(s->ymin, s->h); y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n s->picture = picture;\n\n avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks);\n\n ymax = FFMAX(0, s->ymax + 1);\n // Zero out the end if ymax+1 is not h\n for (i = 0; i < planes; i++) {\n ptr = picture->data[i] + (ymax * picture->linesize[i]);\n for (y = ymax; y < avctx->height; y++) {\n memset(ptr, 0, out_line_size);\n ptr += picture->linesize[i];\n }\n }\n\n picture->pict_type = AV_PICTURE_TYPE_I;\n *got_frame = 1;\n\n return avpkt->size;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_frame", "_file_name": "libavcodec/exr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,\n const TfLiteNode* node, int index) {\n return GetInput(context, node, index);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tflite::GetOptionalInputTensor", "_file_name": "tensorflow/lite/kernels/kernel_util.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def process_form():\n # see https://docs.python.org/3.4/library/cgi.html for the basic usage\n # here.\n form = cgi.FieldStorage()\n\n\n # connect to the database\n conn = MySQLdb.connect(host = pnsdp.SQL_HOST,\n user = pnsdp.SQL_USER,\n passwd = pnsdp.SQL_PASSWD,\n db = pnsdp.SQL_DB)\n\n\n if \"user\" not in form or \"game\" not in form:\n raise FormError(\"Invalid parameters.\")\n if \"pos\" not in form and \"resign\" not in form:\n raise FormError(\"Invalid parameters.\")\n\n game = int(form[\"game\"].value)\n\n\n (players,size,state) = get_game_info(conn, game)\n\n user = form[\"user\"].value\n if user not in players:\n raise FormError(\"Invalid player ID - player is not part of this game\")\n\n\n if \"resign\" in form:\n resign = True\n else:\n resign = False\n pos = form[\"pos\"].value.split(\",\")\n assert len(pos) == 2\n x = int(pos[0])\n y = int(pos[1])\n\n\n (board,nextPlayer,letter) = build_board(conn, game,size)\n\n if user != players[nextPlayer]:\n raise FormError(\"Internal error, incorrect player is attempting to move.\")\n\n\n if resign:\n # this user is choosing to resign. Update the game state to reflect that.\n other_player_name = players[1-nextPlayer]\n\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE games SET state=\"%s:resignation\" WHERE id=%d;\"\"\", (other_player_name,game))\n cursor.close()\n\n else:\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert board[x][y] == \"\"\n board[x][y] = \"XO\"[nextPlayer]\n\n # we've done all of our sanity checks. We now know enough to say that\n # it's safe to add a new move.\n cursor = conn.cursor()\n cursor.execute(\"\"\"INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,\"%s\",NOW());\"\"\", (game,x,y,letter))\n\n if cursor.rowcount != 1:\n raise FormError(\"Could not make move, reason unknown.\")\n\n cursor.close()\n\n result = analyze_board(board)\n if result != \"\":\n if result == \"win\":\n result = players[nextPlayer]+\":win\"\n\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE games SET state=\"%s\" WHERE id=%d;\"\"\", (result,game))\n cursor.close()\n\n # we've made changes, make sure to commit them!\n conn.commit()\n conn.close()\n\n\n # return the parms to the caller, so that they can build a good redirect\n return (user,game)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_form", "_file_name": "cgi/move.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char* dd_load_text_ext(const struct dump_dir *dd, const char *name, unsigned flags)\n{\n// if (!dd->locked)\n// error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n /* Compat with old abrt dumps. Remove in abrt-2.1 */\n if (strcmp(name, \"release\") == 0)\n name = FILENAME_OS_RELEASE;\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n char *ret = load_text_file(full_path, flags);\n free(full_path);\n\n return ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[175, 232]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[175, 232]]}, "_func_name": "dd_load_text_ext", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n conn = connect()\n cursor = conn.cursor()\n query = \"INSERT INTO players (name) VALUES (%s);\"\n cursor.execute(query, (name,))\n conn.commit()\n conn.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "registerPlayer", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def cut(self, key):\n try:\n self.etcd.delete(os.path.join(self.namespace, key))\n except etcd.EtcdKeyNotFound:\n return False\n except etcd.EtcdException as err:\n log_error(\"Error removing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to cut key')\n return True", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[37, 101]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[37, 101]]}, "_func_name": "cut", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n socklen_t size) {\n if (!src || !dst) {\n errno = EFAULT;\n return nullptr;\n }\n size_t src_size = 0;\n if (af == AF_INET) {\n src_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n src_size = sizeof(struct in6_addr);\n } else {\n errno = EAFNOSUPPORT;\n return nullptr;\n }\n\n MessageWriter input;\n input.Push(TokLinuxAfFamily(af));\n input.PushByReference(Extent{reinterpret_cast(src), src_size});\n input.Push(size);\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetNtopHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_ntop\", 2);\n\n auto result = output.next();\n int klinux_errno = output.next();\n if (result.empty()) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return nullptr;\n }\n\n memcpy(dst, result.data(),\n std::min(static_cast(size),\n static_cast(INET6_ADDRSTRLEN)));\n return dst;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[982, 1086]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[982, 1086]]}, "_func_name": "enc_untrusted_inet_ntop", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/overview/')\ndef overview(classNum):\n\tif 'username' in session:\n\t\tclassNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]\n\n\t\t#Save the current course as a session variable.\n\t\tsession['currentCourse'] = classNoSpace\n\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor()\n\n\t\tcursor.execute(\"SELECT courseName,courseOverview from courses where courseAbbreviation=%s\", (classNoSpace))\n\t\tdata = cursor.fetchone()\n\n\t\treturn render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])\n\n\treturn redirect(url_for('index'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "overview", "_file_name": "src/tech_track.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "String StringUtil::Implode(const Variant& items, const String& delim,\n const bool checkIsContainer /* = true */) {\n if (checkIsContainer && !isContainer(items)) {\n throw_param_is_not_container();\n }\n int size = getContainerSize(items);\n if (size == 0) return empty_string();\n\n req::vector sitems;\n sitems.reserve(size);\n int len = 0;\n int lenDelim = delim.size();\n for (ArrayIter iter(items); iter; ++iter) {\n sitems.emplace_back(iter.second().toString());\n len += sitems.back().size() + lenDelim;\n }\n len -= lenDelim; // always one delimiter less than count of items\n assert(sitems.size() == size);\n\n String s = String(len, ReserveString);\n char *buffer = s.mutableData();\n const char *sdelim = delim.data();\n char *p = buffer;\n String &init_str = sitems[0];\n int init_len = init_str.size();\n memcpy(p, init_str.data(), init_len);\n p += init_len;\n for (int i = 1; i < size; i++) {\n String &item = sitems[i];\n memcpy(p, sdelim, lenDelim);\n p += lenDelim;\n int lenItem = item.size();\n memcpy(p, item.data(), lenItem);\n p += lenItem;\n }\n assert(p - buffer == len);\n s.setSize(len);\n return s;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[363, 409]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[363, 409]]}, "_func_name": "HPHP::StringUtil::Implode", "_file_name": "hphp/runtime/base/string-util.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,\n\tstruct dvb_diseqc_master_cmd *d)\n{\n\tstruct cx24116_state *state = fe->demodulator_priv;\n\tint i, ret;\n\n\t/* Validate length */\n\tif (d->msg_len > sizeof(d->msg))\n return -EINVAL;\n\n\t/* Dump DiSEqC message */\n\tif (debug) {\n\t\tprintk(KERN_INFO \"cx24116: %s(\", __func__);\n\t\tfor (i = 0 ; i < d->msg_len ;) {\n\t\t\tprintk(KERN_INFO \"0x%02x\", d->msg[i]);\n\t\t\tif (++i < d->msg_len)\n\t\t\t\tprintk(KERN_INFO \", \");\n\t\t}\n\t\tprintk(\") toneburst=%d\\n\", toneburst);\n\t}\n\n\t/* DiSEqC message */\n\tfor (i = 0; i < d->msg_len; i++)\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];\n\n\t/* DiSEqC message length */\n\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;\n\n\t/* Command length */\n\tstate->dsec_cmd.len = CX24116_DISEQC_MSGOFS +\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_MSGLEN];\n\n\t/* DiSEqC toneburst */\n\tif (toneburst == CX24116_DISEQC_MESGCACHE)\n\t\t/* Message is cached */\n\t\treturn 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONEOFF)\n\t\t/* Message is sent without burst */\n\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;\n\n\telse if (toneburst == CX24116_DISEQC_TONECACHE) {\n\t\t/*\n\t\t * Message is sent with derived else cached burst\n\t\t *\n\t\t * WRITE PORT GROUP COMMAND 38\n\t\t *\n\t\t * 0/A/A: E0 10 38 F0..F3\n\t\t * 1/B/B: E0 10 38 F4..F7\n\t\t * 2/C/A: E0 10 38 F8..FB\n\t\t * 3/D/B: E0 10 38 FC..FF\n\t\t *\n\t\t * databyte[3]= 8421:8421\n\t\t * ABCD:WXYZ\n\t\t * CLR :SET\n\t\t *\n\t\t * WX= PORT SELECT 0..3 (X=TONEBURST)\n\t\t * Y = VOLTAGE (0=13V, 1=18V)\n\t\t * Z = BAND (0=LOW, 1=HIGH(22K))\n\t\t */\n\t\tif (d->msg_len >= 4 && d->msg[2] == 0x38)\n\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST] =\n\t\t\t\t((d->msg[3] & 4) >> 2);\n\t\tif (debug)\n\t\t\tdprintk(\"%s burst=%d\\n\", __func__,\n\t\t\t\tstate->dsec_cmd.args[CX24116_DISEQC_BURST]);\n\t}\n\n\t/* Wait for LNB ready */\n\tret = cx24116_wait_for_lnb(fe);\n\tif (ret != 0)\n\t\treturn ret;\n\n\t/* Wait for voltage/min repeat delay */\n\tmsleep(100);\n\n\t/* Command */\n\tret = cx24116_cmd_execute(fe, &state->dsec_cmd);\n\tif (ret != 0)\n\t\treturn ret;\n\t/*\n\t * Wait for send\n\t *\n\t * Eutelsat spec:\n\t * >15ms delay + (XXX determine if FW does this, see set_tone)\n\t * 13.5ms per byte +\n\t * >15ms delay +\n\t * 12.5ms burst +\n\t * >15ms delay (XXX determine if FW does this, see set_tone)\n\t */\n\tmsleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +\n\t\t((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cx24116_send_diseqc_msg", "_file_name": "drivers/media/dvb-frontends/cx24116.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void ttm_put_pages(struct page **pages, unsigned npages, int flags,\n\t\t\t enum ttm_caching_state cstate)\n{\n\tstruct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tstruct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);\n#endif\n\tunsigned long irq_flags;\n\tunsigned i;\n\n\tif (pool == NULL) {\n\t\t/* No pool for this memory type so free the pages */\n\t\ti = 0;\n\t\twhile (i < npages) {\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tstruct page *p = pages[i];\n#endif\n\t\t\tunsigned order = 0, j;\n\n\t\t\tif (!pages[i]) {\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\t\t\tif (!(flags & TTM_PAGE_FLAG_DMA32) &&\n\t\t\t (npages - i) >= HPAGE_PMD_NR) {\n\t\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\t\tif (p++ != pages[i + j])\n\t\t\t\t\t break;\n\n\t\t\t\tif (j == HPAGE_PMD_NR)\n\t\t\t\t\torder = HPAGE_PMD_ORDER;\n\t\t\t}\n#endif\n\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\t__free_pages(pages[i], order);\n\n\t\t\tj = 1 << order;\n\t\t\twhile (j) {\n\t\t\t\tpages[i++] = NULL;\n\t\t\t\t--j;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\ti = 0;\n#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n\tif (huge) {\n\t\tunsigned max_size, n2free;\n\n\t\tspin_lock_irqsave(&huge->lock, irq_flags);\n\t\twhile ((npages - i) >= HPAGE_PMD_NR) {\n\t\t\tstruct page *p = pages[i];\n\t\t\tunsigned j;\n\n\t\t\tif (!p)\n\t\t\t\tbreak;\n\n\t\t\tfor (j = 1; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tif (p++ != pages[i + j])\n\t\t\t\t break;\n\n\t\t\tif (j != HPAGE_PMD_NR)\n\t\t\t\tbreak;\n\n\t\t\tlist_add_tail(&pages[i]->lru, &huge->list);\n\n\t\t\tfor (j = 0; j < HPAGE_PMD_NR; ++j)\n\t\t\t\tpages[i++] = NULL;\n\t\t\thuge->npages++;\n\t\t}\n\n\t\t/* Check that we don't go over the pool limit */\n\t\tmax_size = _manager->options.max_size;\n\t\tmax_size /= HPAGE_PMD_NR;\n\t\tif (huge->npages > max_size)\n\t\t\tn2free = huge->npages - max_size;\n\t\telse\n\t\t\tn2free = 0;\n\t\tspin_unlock_irqrestore(&huge->lock, irq_flags);\n\t\tif (n2free)\n\t\t\tttm_page_pool_free(huge, n2free, false);\n\t}\n#endif\n\n\tspin_lock_irqsave(&pool->lock, irq_flags);\n\twhile (i < npages) {\n\t\tif (pages[i]) {\n\t\t\tif (page_count(pages[i]) != 1)\n\t\t\t\tpr_err(\"Erroneous page count. Leaking pages.\\n\");\n\t\t\tlist_add_tail(&pages[i]->lru, &pool->list);\n\t\t\tpages[i] = NULL;\n\t\t\tpool->npages++;\n\t\t}\n\t\t++i;\n\t}\n\t/* Check that we don't go over the pool limit */\n\tnpages = 0;\n\tif (pool->npages > _manager->options.max_size) {\n\t\tnpages = pool->npages - _manager->options.max_size;\n\t\t/* free at least NUM_PAGES_TO_ALLOC number of pages\n\t\t * to reduce calls to set_memory_wb */\n\t\tif (npages < NUM_PAGES_TO_ALLOC)\n\t\t\tnpages = NUM_PAGES_TO_ALLOC;\n\t}\n\tspin_unlock_irqrestore(&pool->lock, irq_flags);\n\tif (npages)\n\t\tttm_page_pool_free(pool, npages, false);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[736, 766], [1344, 1373]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[736, 766], [1344, 1373]]}, "_func_name": "ttm_put_pages", "_file_name": "drivers/gpu/drm/ttm/ttm_page_alloc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "validate_as_request(kdc_realm_t *kdc_active_realm,\n register krb5_kdc_req *request, krb5_db_entry client,\n krb5_db_entry server, krb5_timestamp kdc_time,\n const char **status, krb5_pa_data ***e_data)\n{\n int errcode;\n krb5_error_code ret;\n\n /*\n * If an option is set that is only allowed in TGS requests, complain.\n */\n if (request->kdc_options & AS_INVALID_OPTIONS) {\n *status = \"INVALID AS OPTIONS\";\n return KDC_ERR_BADOPTION;\n }\n\n /* The client must not be expired */\n if (client.expiration && client.expiration < kdc_time) {\n *status = \"CLIENT EXPIRED\";\n if (vague_errors)\n return(KRB_ERR_GENERIC);\n else\n return(KDC_ERR_NAME_EXP);\n }\n\n /* The client's password must not be expired, unless the server is\n a KRB5_KDC_PWCHANGE_SERVICE. */\n if (client.pw_expiration && client.pw_expiration < kdc_time &&\n !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {\n *status = \"CLIENT KEY EXPIRED\";\n if (vague_errors)\n return(KRB_ERR_GENERIC);\n else\n return(KDC_ERR_KEY_EXP);\n }\n\n /* The server must not be expired */\n if (server.expiration && server.expiration < kdc_time) {\n *status = \"SERVICE EXPIRED\";\n return(KDC_ERR_SERVICE_EXP);\n }\n\n /*\n * If the client requires password changing, then only allow the\n * pwchange service.\n */\n if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) &&\n !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {\n *status = \"REQUIRED PWCHANGE\";\n return(KDC_ERR_KEY_EXP);\n }\n\n /* Client and server must allow postdating tickets */\n if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) ||\n isflagset(request->kdc_options, KDC_OPT_POSTDATED)) &&\n (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) ||\n isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) {\n *status = \"POSTDATE NOT ALLOWED\";\n return(KDC_ERR_CANNOT_POSTDATE);\n }\n\n /*\n * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of\n * KDC_ERR_POLICY in the following case:\n *\n * - KDC_OPT_FORWARDABLE is set in KDCOptions but local\n * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the\n * client, and;\n * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but\n * preauthentication data is absent in the request.\n *\n * Hence, this check most be done after the check for preauth\n * data, and is now performed by validate_forwardable() (the\n * contents of which were previously below).\n */\n\n /* Client and server must allow proxiable tickets */\n if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) &&\n (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) ||\n isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) {\n *status = \"PROXIABLE NOT ALLOWED\";\n return(KDC_ERR_POLICY);\n }\n\n /* Check to see if client is locked out */\n if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {\n *status = \"CLIENT LOCKED OUT\";\n return(KDC_ERR_CLIENT_REVOKED);\n }\n\n /* Check to see if server is locked out */\n if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {\n *status = \"SERVICE LOCKED OUT\";\n return(KDC_ERR_S_PRINCIPAL_UNKNOWN);\n }\n\n /* Check to see if server is allowed to be a service */\n if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) {\n *status = \"SERVICE NOT ALLOWED\";\n return(KDC_ERR_MUST_USE_USER2USER);\n }\n\n if (check_anon(kdc_active_realm, request->client, request->server) != 0) {\n *status = \"ANONYMOUS NOT ALLOWED\";\n return(KDC_ERR_POLICY);\n }\n\n /* Perform KDB module policy checks. */\n ret = krb5_db_check_policy_as(kdc_context, request, &client, &server,\n kdc_time, status, e_data);\n if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP)\n return errcode_to_protocol(ret);\n\n /* Check against local policy. */\n errcode = against_local_policy_as(request, client, server,\n kdc_time, status, e_data);\n if (errcode)\n return errcode;\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[3679, 3758]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3679, 3758]]}, "_func_name": "validate_as_request", "_file_name": "src/kdc/kdc_util.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Array HHVM_METHOD(Memcache, getextendedstats,\n const String& /*type*/ /* = null_string */,\n int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) {\n auto data = Native::data(this_);\n memcached_return_t ret;\n memcached_stat_st *stats;\n\n stats = memcached_stat(&data->m_memcache, nullptr, &ret);\n if (ret != MEMCACHED_SUCCESS) {\n return Array();\n }\n\n int server_count = memcached_server_count(&data->m_memcache);\n\n Array return_val;\n\n for (int server_id = 0; server_id < server_count; server_id++) {\n memcached_stat_st *stat;\n char stats_key[30] = {0};\n size_t key_len;\n\n LMCD_SERVER_POSITION_INSTANCE_TYPE instance =\n memcached_server_instance_by_position(&data->m_memcache, server_id);\n const char *hostname = LMCD_SERVER_HOSTNAME(instance);\n in_port_t port = LMCD_SERVER_PORT(instance);\n\n stat = stats + server_id;\n\n Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret);\n if (ret != MEMCACHED_SUCCESS) {\n continue;\n }\n\n key_len = snprintf(stats_key, sizeof(stats_key), \"%s:%d\", hostname, port);\n\n return_val.set(String(stats_key, key_len, CopyString), server_stats);\n }\n\n free(stats);\n return return_val;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[607, 708], [1060, 1214]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[607, 708], [1060, 1214]]}, "_func_name": "HPHP::HHVM_METHOD", "_file_name": "hphp/runtime/ext/memcache/ext_memcache.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def save(self):\n # copy the user's input from plain text to description to be processed\n # uses bleach to remove potentially harmful HTML code\n self.description = bleach.clean(str(self.description_plain_text),\n tags=CE.settings.bleach_allowed,\n strip=True)\n if CE.settings.auto_cross_reference:\n self.auto_cross_ref()\n else:\n self.find_tag()\n self.slug = slugify(self.title)\n super().save()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "save", "_file_name": "CE/models.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def usage(args=None):\n '''\n Return usage information for volumes mounted on this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' disk.usage\n '''\n if __grains__['kernel'] == 'Linux':\n cmd = 'df -P'\n elif __grains__['kernel'] == 'OpenBSD':\n cmd = 'df -kP'\n else:\n cmd = 'df'\n if args:\n cmd = cmd + ' -' + args\n ret = {}\n out = __salt__['cmd.run'](cmd).splitlines()\n for line in out:\n if not line:\n continue\n if line.startswith('Filesystem'):\n continue\n comps = line.split()\n while not comps[1].isdigit():\n comps[0] = '{0} {1}'.format(comps[0], comps[1])\n comps.pop(1)\n try:\n if __grains__['kernel'] == 'Darwin':\n ret[comps[8]] = {\n 'filesystem': comps[0],\n '512-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n 'iused': comps[5],\n 'ifree': comps[6],\n '%iused': comps[7],\n }\n else:\n ret[comps[5]] = {\n 'filesystem': comps[0],\n '1K-blocks': comps[1],\n 'used': comps[2],\n 'available': comps[3],\n 'capacity': comps[4],\n }\n except IndexError:\n log.warn(\"Problem parsing disk usage information\")\n ret = {}\n return ret", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[346, 378]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[346, 378]]}, "_func_name": "usage", "_file_name": "salt/modules/disk.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_video_positions(removed_position, db):\n db.execute(\"UPDATE video SET position = position - 1 WHERE position > %s\", (removed_position,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_video_positions", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_paths(root: str, sub_path: str) \\\n -> typing.Tuple[pathlib.Path, pathlib.Path]:\n base_path = flask.safe_join(root, sub_path)\n data_file = pathlib.Path(base_path + \".data\")\n metadata_file = pathlib.Path(base_path + \".meta\")\n\n return data_file, metadata_file", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_paths", "_file_name": "xhu.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)\n{\n\tint r;\n\t/* Assume we're using HV mode when the HV module is loaded */\n\tint hv_enabled = kvmppc_hv_ops ? 1 : 0;\n\n\tif (kvm) {\n\t\t/*\n\t\t * Hooray - we know which VM type we're running on. Depend on\n\t\t * that rather than the guess above.\n\t\t */\n\t\thv_enabled = is_kvmppc_hv_enabled(kvm);\n\t}\n\n\tswitch (ext) {\n#ifdef CONFIG_BOOKE\n\tcase KVM_CAP_PPC_BOOKE_SREGS:\n\tcase KVM_CAP_PPC_BOOKE_WATCHDOG:\n\tcase KVM_CAP_PPC_EPR:\n#else\n\tcase KVM_CAP_PPC_SEGSTATE:\n\tcase KVM_CAP_PPC_HIOR:\n\tcase KVM_CAP_PPC_PAPR:\n#endif\n\tcase KVM_CAP_PPC_UNSET_IRQ:\n\tcase KVM_CAP_PPC_IRQ_LEVEL:\n\tcase KVM_CAP_ENABLE_CAP:\n\tcase KVM_CAP_ENABLE_CAP_VM:\n\tcase KVM_CAP_ONE_REG:\n\tcase KVM_CAP_IOEVENTFD:\n\tcase KVM_CAP_DEVICE_CTRL:\n\tcase KVM_CAP_IMMEDIATE_EXIT:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_PPC_PAIRED_SINGLES:\n\tcase KVM_CAP_PPC_OSI:\n\tcase KVM_CAP_PPC_GET_PVINFO:\n#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)\n\tcase KVM_CAP_SW_TLB:\n#endif\n\t\t/* We support this only for PR */\n\t\tr = !hv_enabled;\n\t\tbreak;\n#ifdef CONFIG_KVM_MPIC\n\tcase KVM_CAP_IRQ_MPIC:\n\t\tr = 1;\n\t\tbreak;\n#endif\n\n#ifdef CONFIG_PPC_BOOK3S_64\n\tcase KVM_CAP_SPAPR_TCE:\n\tcase KVM_CAP_SPAPR_TCE_64:\n\t\t/* fallthrough */\n\tcase KVM_CAP_SPAPR_TCE_VFIO:\n\tcase KVM_CAP_PPC_RTAS:\n\tcase KVM_CAP_PPC_FIXUP_HCALL:\n\tcase KVM_CAP_PPC_ENABLE_HCALL:\n#ifdef CONFIG_KVM_XICS\n\tcase KVM_CAP_IRQ_XICS:\n#endif\n\t\tr = 1;\n\t\tbreak;\n\n\tcase KVM_CAP_PPC_ALLOC_HTAB:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif /* CONFIG_PPC_BOOK3S_64 */\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_SMT:\n\t\tr = 0;\n\t\tif (kvm) {\n\t\t\tif (kvm->arch.emul_smt_mode > 1)\n\t\t\t\tr = kvm->arch.emul_smt_mode;\n\t\t\telse\n\t\t\t\tr = kvm->arch.smt_mode;\n\t\t} else if (hv_enabled) {\n\t\t\tif (cpu_has_feature(CPU_FTR_ARCH_300))\n\t\t\t\tr = 1;\n\t\t\telse\n\t\t\t\tr = threads_per_subcore;\n\t\t}\n\t\tbreak;\n\tcase KVM_CAP_PPC_SMT_POSSIBLE:\n\t\tr = 1;\n\t\tif (hv_enabled) {\n\t\t\tif (!cpu_has_feature(CPU_FTR_ARCH_300))\n\t\t\t\tr = ((threads_per_subcore << 1) - 1);\n\t\t\telse\n\t\t\t\t/* P9 can emulate dbells, so allow any mode */\n\t\t\t\tr = 8 | 4 | 2 | 1;\n\t\t}\n\t\tbreak;\n\tcase KVM_CAP_PPC_RMA:\n\t\tr = 0;\n\t\tbreak;\n\tcase KVM_CAP_PPC_HWRNG:\n\t\tr = kvmppc_hwrng_present();\n\t\tbreak;\n\tcase KVM_CAP_PPC_MMU_RADIX:\n\t\tr = !!(hv_enabled && radix_enabled());\n\t\tbreak;\n\tcase KVM_CAP_PPC_MMU_HASH_V3:\n\t\tr = !!(hv_enabled && !radix_enabled() &&\n\t\t cpu_has_feature(CPU_FTR_ARCH_300));\n\t\tbreak;\n#endif\n\tcase KVM_CAP_SYNC_MMU:\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\t\tr = hv_enabled;\n#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)\n\t\tr = 1;\n#else\n\t\tr = 0;\n#endif\n\t\tbreak;\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_HTAB_FD:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif\n\tcase KVM_CAP_NR_VCPUS:\n\t\t/*\n\t\t * Recommending a number of CPUs is somewhat arbitrary; we\n\t\t * return the number of present CPUs for -HV (since a host\n\t\t * will have secondary threads \"offline\"), and for other KVM\n\t\t * implementations just count online CPUs.\n\t\t */\n\t\tif (hv_enabled)\n\t\t\tr = num_present_cpus();\n\t\telse\n\t\t\tr = num_online_cpus();\n\t\tbreak;\n\tcase KVM_CAP_NR_MEMSLOTS:\n\t\tr = KVM_USER_MEM_SLOTS;\n\t\tbreak;\n\tcase KVM_CAP_MAX_VCPUS:\n\t\tr = KVM_MAX_VCPUS;\n\t\tbreak;\n#ifdef CONFIG_PPC_BOOK3S_64\n\tcase KVM_CAP_PPC_GET_SMMU_INFO:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_SPAPR_MULTITCE:\n\t\tr = 1;\n\t\tbreak;\n\tcase KVM_CAP_SPAPR_RESIZE_HPT:\n\t\t/* Disable this on POWER9 until code handles new HPTE format */\n\t\tr = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);\n\t\tbreak;\n#endif\n#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE\n\tcase KVM_CAP_PPC_FWNMI:\n\t\tr = hv_enabled;\n\t\tbreak;\n#endif\n\tcase KVM_CAP_PPC_HTM:\n\t\tr = cpu_has_feature(CPU_FTR_TM_COMP) && hv_enabled;\n\t\tbreak;\n\tdefault:\n\t\tr = 0;\n\t\tbreak;\n\t}\n\treturn r;\n\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "kvm_vm_ioctl_check_extension", "_file_name": "arch/powerpc/kvm/powerpc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n int linesize_align[AV_NUM_DATA_POINTERS])\n{\n int i;\n int w_align = 1;\n int h_align = 1;\n AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);\n\n if (desc) {\n w_align = 1 << desc->log2_chroma_w;\n h_align = 1 << desc->log2_chroma_h;\n }\n\n switch (s->pix_fmt) {\n case AV_PIX_FMT_YUV420P:\n case AV_PIX_FMT_YUYV422:\n case AV_PIX_FMT_YVYU422:\n case AV_PIX_FMT_UYVY422:\n case AV_PIX_FMT_YUV422P:\n case AV_PIX_FMT_YUV440P:\n case AV_PIX_FMT_YUV444P:\n case AV_PIX_FMT_GBRP:\n case AV_PIX_FMT_GBRAP:\n case AV_PIX_FMT_GRAY8:\n case AV_PIX_FMT_GRAY16BE:\n case AV_PIX_FMT_GRAY16LE:\n case AV_PIX_FMT_YUVJ420P:\n case AV_PIX_FMT_YUVJ422P:\n case AV_PIX_FMT_YUVJ440P:\n case AV_PIX_FMT_YUVJ444P:\n case AV_PIX_FMT_YUVA420P:\n case AV_PIX_FMT_YUVA422P:\n case AV_PIX_FMT_YUVA444P:\n case AV_PIX_FMT_YUV420P9LE:\n case AV_PIX_FMT_YUV420P9BE:\n case AV_PIX_FMT_YUV420P10LE:\n case AV_PIX_FMT_YUV420P10BE:\n case AV_PIX_FMT_YUV420P12LE:\n case AV_PIX_FMT_YUV420P12BE:\n case AV_PIX_FMT_YUV420P14LE:\n case AV_PIX_FMT_YUV420P14BE:\n case AV_PIX_FMT_YUV420P16LE:\n case AV_PIX_FMT_YUV420P16BE:\n case AV_PIX_FMT_YUVA420P9LE:\n case AV_PIX_FMT_YUVA420P9BE:\n case AV_PIX_FMT_YUVA420P10LE:\n case AV_PIX_FMT_YUVA420P10BE:\n case AV_PIX_FMT_YUVA420P16LE:\n case AV_PIX_FMT_YUVA420P16BE:\n case AV_PIX_FMT_YUV422P9LE:\n case AV_PIX_FMT_YUV422P9BE:\n case AV_PIX_FMT_YUV422P10LE:\n case AV_PIX_FMT_YUV422P10BE:\n case AV_PIX_FMT_YUV422P12LE:\n case AV_PIX_FMT_YUV422P12BE:\n case AV_PIX_FMT_YUV422P14LE:\n case AV_PIX_FMT_YUV422P14BE:\n case AV_PIX_FMT_YUV422P16LE:\n case AV_PIX_FMT_YUV422P16BE:\n case AV_PIX_FMT_YUVA422P9LE:\n case AV_PIX_FMT_YUVA422P9BE:\n case AV_PIX_FMT_YUVA422P10LE:\n case AV_PIX_FMT_YUVA422P10BE:\n case AV_PIX_FMT_YUVA422P16LE:\n case AV_PIX_FMT_YUVA422P16BE:\n case AV_PIX_FMT_YUV440P10LE:\n case AV_PIX_FMT_YUV440P10BE:\n case AV_PIX_FMT_YUV440P12LE:\n case AV_PIX_FMT_YUV440P12BE:\n case AV_PIX_FMT_YUV444P9LE:\n case AV_PIX_FMT_YUV444P9BE:\n case AV_PIX_FMT_YUV444P10LE:\n case AV_PIX_FMT_YUV444P10BE:\n case AV_PIX_FMT_YUV444P12LE:\n case AV_PIX_FMT_YUV444P12BE:\n case AV_PIX_FMT_YUV444P14LE:\n case AV_PIX_FMT_YUV444P14BE:\n case AV_PIX_FMT_YUV444P16LE:\n case AV_PIX_FMT_YUV444P16BE:\n case AV_PIX_FMT_YUVA444P9LE:\n case AV_PIX_FMT_YUVA444P9BE:\n case AV_PIX_FMT_YUVA444P10LE:\n case AV_PIX_FMT_YUVA444P10BE:\n case AV_PIX_FMT_YUVA444P16LE:\n case AV_PIX_FMT_YUVA444P16BE:\n case AV_PIX_FMT_GBRP9LE:\n case AV_PIX_FMT_GBRP9BE:\n case AV_PIX_FMT_GBRP10LE:\n case AV_PIX_FMT_GBRP10BE:\n case AV_PIX_FMT_GBRP12LE:\n case AV_PIX_FMT_GBRP12BE:\n case AV_PIX_FMT_GBRP14LE:\n case AV_PIX_FMT_GBRP14BE:\n case AV_PIX_FMT_GBRP16LE:\n case AV_PIX_FMT_GBRP16BE:\n case AV_PIX_FMT_GBRAP12LE:\n case AV_PIX_FMT_GBRAP12BE:\n case AV_PIX_FMT_GBRAP16LE:\n case AV_PIX_FMT_GBRAP16BE:\n w_align = 16; //FIXME assume 16 pixel per macroblock\n h_align = 16 * 2; // interlaced needs 2 macroblocks height\n break;\n case AV_PIX_FMT_YUV411P:\n case AV_PIX_FMT_YUVJ411P:\n case AV_PIX_FMT_UYYVYY411:\n w_align = 32;\n h_align = 16 * 2;\n break;\n case AV_PIX_FMT_YUV410P:\n if (s->codec_id == AV_CODEC_ID_SVQ1) {\n w_align = 64;\n h_align = 64;\n }\n break;\n case AV_PIX_FMT_RGB555:\n if (s->codec_id == AV_CODEC_ID_RPZA) {\n w_align = 4;\n h_align = 4;\n }\n break;\n case AV_PIX_FMT_PAL8:\n case AV_PIX_FMT_BGR8:\n case AV_PIX_FMT_RGB8:\n if (s->codec_id == AV_CODEC_ID_SMC ||\n s->codec_id == AV_CODEC_ID_CINEPAK) {\n w_align = 4;\n h_align = 4;\n }\n if (s->codec_id == AV_CODEC_ID_JV) {\n w_align = 8;\n h_align = 8;\n }\n break;\n case AV_PIX_FMT_BGR24:\n if ((s->codec_id == AV_CODEC_ID_MSZH) ||\n (s->codec_id == AV_CODEC_ID_ZLIB)) {\n w_align = 4;\n h_align = 4;\n }\n break;\n case AV_PIX_FMT_RGB24:\n if (s->codec_id == AV_CODEC_ID_CINEPAK) {\n w_align = 4;\n h_align = 4;\n }\n break;\n default:\n break;\n }\n\n if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {\n w_align = FFMAX(w_align, 8);\n }\n\n *width = FFALIGN(*width, w_align);\n *height = FFALIGN(*height, h_align);\n if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {\n // some of the optimized chroma MC reads one line too much\n // which is also done in mpeg decoders with lowres > 0\n *height += 2;\n\n // H.264 uses edge emulation for out of frame motion vectors, for this\n // it requires a temporary area large enough to hold a 21x21 block,\n // increasing witdth ensure that the temporary area is large enough,\n // the next rounded up width is 32\n *width = FFMAX(*width, 32);\n }\n\n for (i = 0; i < 4; i++)\n linesize_align[i] = STRIDE_ALIGN;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[3941, 3986]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3941, 3986]]}, "_func_name": "avcodec_align_dimensions2", "_file_name": "libavcodec/utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "struct net *get_net_ns_by_id(struct net *net, int id)\n{\n\tstruct net *peer;\n\n\tif (id < 0)\n\t\treturn NULL;\n\n\trcu_read_lock();\n\tspin_lock_bh(&net->nsid_lock);\n\tpeer = idr_find(&net->netns_ids, id);\n\tif (peer)\n\t\tget_net(peer);\n\tspin_unlock_bh(&net->nsid_lock);\n\trcu_read_unlock();\n\n\treturn peer;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[205, 222]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[205, 222]]}, "_func_name": "get_net_ns_by_id", "_file_name": "net/core/net_namespace.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Array HHVM_METHOD(Memcache, getextendedstats,\n const String& /*type*/ /* = null_string */,\n int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) {\n auto data = Native::data(this_);\n memcached_return_t ret;\n memcached_stat_st *stats;\n\n stats = memcached_stat(&data->m_memcache, nullptr, &ret);\n if (ret != MEMCACHED_SUCCESS) {\n return Array();\n }\n\n int server_count = memcached_server_count(&data->m_memcache);\n\n Array return_val;\n\n for (int server_id = 0; server_id < server_count; server_id++) {\n memcached_stat_st *stat;\n LMCD_SERVER_POSITION_INSTANCE_TYPE instance =\n memcached_server_instance_by_position(&data->m_memcache, server_id);\n const char *hostname = LMCD_SERVER_HOSTNAME(instance);\n in_port_t port = LMCD_SERVER_PORT(instance);\n\n stat = stats + server_id;\n\n Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret);\n if (ret != MEMCACHED_SUCCESS) {\n continue;\n }\n\n auto const port_str = folly::to(port);\n auto const key_len = strlen(hostname) + 1 + port_str.length();\n auto key = String(key_len, ReserveString);\n key += hostname;\n key += \":\";\n key += port_str;\n return_val.set(key, server_stats);\n }\n\n free(stats);\n return return_val;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::HHVM_METHOD", "_file_name": "hphp/runtime/ext/memcache/ext_memcache.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)\n{\n uint32_t *input_u32;\n uint8_t *input_u8, *output_u8;\n size_t length;\n int rc;\n\n if (!input)\n {\n if (output)\n\t*output = 0;\n return IDN2_OK;\n }\n\n input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));\n if (!input_u32)\n return IDN2_MALLOC;\n\n u32_cpy (input_u32, input, inlen);\n input_u32[inlen] = 0;\n\n input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);\n free (input_u32);\n if (!input_u8)\n {\n if (errno == ENOMEM)\n\treturn IDN2_MALLOC;\n return IDN2_ENCODING_ERROR;\n }\n\n rc = idn2_lookup_u8 (input_u8, &output_u8, flags);\n free (input_u8);\n\n if (rc == IDN2_OK)\n {\n /* wow, this is ugly, but libidn manpage states:\n * char * out output zero terminated string that must have room for at\n * least 63 characters plus the terminating zero.\n */\n size_t len = strlen ((char *) output_u8);\n\n if (len > 63)\n {\n\t free (output_u8);\n\t return IDN2_TOO_BIG_DOMAIN;\n }\n\n if (output)\n\tstrcpy (output, (char *) output_u8);\n\n free (output_u8);\n }\n\n return rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "idn2_to_ascii_4i", "_file_name": "lib/lookup.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_bundle(request):\n bundle_id = request.GET.get('bundle')\n doc = None\n \n if bundle_id:\n doc = Document2.objects.get(id=bundle_id)\n bundle = Bundle(document=doc)\n else:\n bundle = Bundle()\n\n coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')]\n\n return render('editor/bundle_editor.mako', request, {\n 'bundle_json': bundle.json,\n 'coordinators_json': json.dumps(coordinators),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) \n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[498, 585]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[498, 585]]}, "_func_name": "edit_bundle", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_game_info(conn, game):\n # get the basic game properties\n cursor = conn.cursor()\n cursor.execute(\"SELECT player1,player2,size,state FROM games WHERE id = %d;\", (game,))\n if cursor.rowcount != 1:\n raise FormError(\"Invalid game ID\")\n\n row = cursor.fetchall()[0]\n players = [row[0],row[1]]\n size = row[2]\n state = row[3]\n\n if state is None:\n state = \"Active\"\n\n cursor.close()\n\n return (players,size,state)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_game_info", "_file_name": "cgi/common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n int swap, uint32_t namesz, uint32_t descsz,\n size_t noff, size_t doff, int *flags, size_t size, int clazz)\n{\n#ifdef ELFCORE\n\tint os_style = -1;\n\t/*\n\t * Sigh. The 2.0.36 kernel in Debian 2.1, at\n\t * least, doesn't correctly implement name\n\t * sections, in core dumps, as specified by\n\t * the \"Program Linking\" section of \"UNIX(R) System\n\t * V Release 4 Programmer's Guide: ANSI C and\n\t * Programming Support Tools\", because my copy\n\t * clearly says \"The first 'namesz' bytes in 'name'\n\t * contain a *null-terminated* [emphasis mine]\n\t * character representation of the entry's owner\n\t * or originator\", but the 2.0.36 kernel code\n\t * doesn't include the terminating null in the\n\t * name....\n\t */\n\tif ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) ||\n\t (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) {\n\t\tos_style = OS_STYLE_SVR4;\n\t} \n\n\tif ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) {\n\t\tos_style = OS_STYLE_FREEBSD;\n\t}\n\n\tif ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11)\n\t == 0)) {\n\t\tos_style = OS_STYLE_NETBSD;\n\t}\n\n\tif (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {\n\t\tif (file_printf(ms, \", %s-style\", os_style_names[os_style])\n\t\t == -1)\n\t\t\treturn 1;\n\t\t*flags |= FLAGS_DID_CORE_STYLE;\n\t\t*flags |= os_style;\n\t}\n\n\tswitch (os_style) {\n\tcase OS_STYLE_NETBSD:\n\t\tif (type == NT_NETBSD_CORE_PROCINFO) {\n\t\t\tchar sbuf[512];\n\t\t\tstruct NetBSD_elfcore_procinfo pi;\n\t\t\tmemset(&pi, 0, sizeof(pi));\n\t\t\tmemcpy(&pi, nbuf + doff, descsz);\n\n\t\t\tif (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \"\n\t\t\t \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\",\n\t\t\t file_printable(sbuf, sizeof(sbuf),\n\t\t\t CAST(char *, pi.cpi_name)),\n\t\t\t elf_getu32(swap, (uint32_t)pi.cpi_pid),\n\t\t\t elf_getu32(swap, pi.cpi_euid),\n\t\t\t elf_getu32(swap, pi.cpi_egid),\n\t\t\t elf_getu32(swap, pi.cpi_nlwps),\n\t\t\t elf_getu32(swap, (uint32_t)pi.cpi_siglwp),\n\t\t\t elf_getu32(swap, pi.cpi_signo),\n\t\t\t elf_getu32(swap, pi.cpi_sigcode)) == -1)\n\t\t\t\treturn 1;\n\n\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\treturn 1;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {\n\t\t\tsize_t i, j;\n\t\t\tunsigned char c;\n\t\t\t/*\n\t\t\t * Extract the program name. We assume\n\t\t\t * it to be 16 characters (that's what it\n\t\t\t * is in SunOS 5.x and Linux).\n\t\t\t *\n\t\t\t * Unfortunately, it's at a different offset\n\t\t\t * in various OSes, so try multiple offsets.\n\t\t\t * If the characters aren't all printable,\n\t\t\t * reject it.\n\t\t\t */\n\t\t\tfor (i = 0; i < NOFFSETS; i++) {\n\t\t\t\tunsigned char *cname, *cp;\n\t\t\t\tsize_t reloffset = prpsoffsets(i);\n\t\t\t\tsize_t noffset = doff + reloffset;\n\t\t\t\tsize_t k;\n\t\t\t\tfor (j = 0; j < 16; j++, noffset++,\n\t\t\t\t reloffset++) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the buffer; if\n\t\t\t\t\t * we are, just give up.\n\t\t\t\t\t */\n\t\t\t\t\tif (noffset >= size)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the contents;\n\t\t\t\t\t * if we are, this obviously\n\t\t\t\t\t * isn't the right offset.\n\t\t\t\t\t */\n\t\t\t\t\tif (reloffset >= descsz)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\tc = nbuf[noffset];\n\t\t\t\t\tif (c == '\\0') {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A '\\0' at the\n\t\t\t\t\t\t * beginning is\n\t\t\t\t\t\t * obviously wrong.\n\t\t\t\t\t\t * Any other '\\0'\n\t\t\t\t\t\t * means we're done.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A nonprintable\n\t\t\t\t\t\t * character is also\n\t\t\t\t\t\t * wrong.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!isprint(c) || isquote(c))\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Well, that worked.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Try next offsets, in case this match is\n\t\t\t\t * in the middle of a string.\n\t\t\t\t */\n\t\t\t\tfor (k = i + 1 ; k < NOFFSETS; k++) {\n\t\t\t\t\tsize_t no;\n\t\t\t\t\tint adjust = 1;\n\t\t\t\t\tif (prpsoffsets(k) >= prpsoffsets(i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor (no = doff + prpsoffsets(k);\n\t\t\t\t\t no < doff + prpsoffsets(i); no++)\n\t\t\t\t\t\tadjust = adjust\n\t\t\t\t\t\t && isprint(nbuf[no]);\n\t\t\t\t\tif (adjust)\n\t\t\t\t\t\ti = k;\n\t\t\t\t}\n\n\t\t\t\tcname = (unsigned char *)\n\t\t\t\t &nbuf[doff + prpsoffsets(i)];\n\t\t\t\tfor (cp = cname; cp < nbuf + size && *cp\n\t\t\t\t && isprint(*cp); cp++)\n\t\t\t\t\tcontinue;\n\t\t\t\t/*\n\t\t\t\t * Linux apparently appends a space at the end\n\t\t\t\t * of the command line: remove it.\n\t\t\t\t */\n\t\t\t\twhile (cp > cname && isspace(cp[-1]))\n\t\t\t\t\tcp--;\n\t\t\t\tif (file_printf(ms, \", from '%.*s'\",\n\t\t\t\t (int)(cp - cname), cname) == -1)\n\t\t\t\t\treturn 1;\n\t\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\t\treturn 1;\n\n\t\t\ttryanother:\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n#endif\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "do_core_note", "_file_name": "src/readelf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_paths(base_path: pathlib.Path):\n data_file = pathlib.Path(str(base_path) + \".data\")\n metadata_file = pathlib.Path(str(base_path) + \".meta\")\n\n return data_file, metadata_file", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[0, 154]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 154]]}, "_func_name": "get_paths", "_file_name": "xhu.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int nsv_read_chunk(AVFormatContext *s, int fill_header)\n{\n NSVContext *nsv = s->priv_data;\n AVIOContext *pb = s->pb;\n AVStream *st[2] = {NULL, NULL};\n NSVStream *nst;\n AVPacket *pkt;\n int i, err = 0;\n uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */\n uint32_t vsize;\n uint16_t asize;\n uint16_t auxsize;\n\n if (nsv->ahead[0].data || nsv->ahead[1].data)\n return 0; //-1; /* hey! eat what you've in your plate first! */\n\nnull_chunk_retry:\n if (pb->eof_reached)\n return -1;\n\n for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)\n err = nsv_resync(s);\n if (err < 0)\n return err;\n if (nsv->state == NSV_FOUND_NSVS)\n err = nsv_parse_NSVs_header(s);\n if (err < 0)\n return err;\n if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)\n return -1;\n\n auxcount = avio_r8(pb);\n vsize = avio_rl16(pb);\n asize = avio_rl16(pb);\n vsize = (vsize << 4) | (auxcount >> 4);\n auxcount &= 0x0f;\n av_log(s, AV_LOG_TRACE, \"NSV CHUNK %\"PRIu8\" aux, %\"PRIu32\" bytes video, %\"PRIu16\" bytes audio\\n\",\n auxcount, vsize, asize);\n /* skip aux stuff */\n for (i = 0; i < auxcount; i++) {\n uint32_t av_unused auxtag;\n auxsize = avio_rl16(pb);\n auxtag = avio_rl32(pb);\n avio_skip(pb, auxsize);\n vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */\n }\n\n if (pb->eof_reached)\n return -1;\n if (!vsize && !asize) {\n nsv->state = NSV_UNSYNC;\n goto null_chunk_retry;\n }\n\n /* map back streams to v,a */\n if (s->nb_streams > 0)\n st[s->streams[0]->id] = s->streams[0];\n if (s->nb_streams > 1)\n st[s->streams[1]->id] = s->streams[1];\n\n if (vsize && st[NSV_ST_VIDEO]) {\n nst = st[NSV_ST_VIDEO]->priv_data;\n pkt = &nsv->ahead[NSV_ST_VIDEO];\n av_get_packet(pb, pkt, vsize);\n pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;\n pkt->dts = nst->frame_offset;\n pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */\n for (i = 0; i < FFMIN(8, vsize); i++)\n av_log(s, AV_LOG_TRACE, \"NSV video: [%d] = %02\"PRIx8\"\\n\",\n i, pkt->data[i]);\n }\n if(st[NSV_ST_VIDEO])\n ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;\n\n if (asize && st[NSV_ST_AUDIO]) {\n nst = st[NSV_ST_AUDIO]->priv_data;\n pkt = &nsv->ahead[NSV_ST_AUDIO];\n /* read raw audio specific header on the first audio chunk... */\n /* on ALL audio chunks ?? seems so! */\n if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {\n uint8_t bps;\n uint8_t channels;\n uint16_t samplerate;\n bps = avio_r8(pb);\n channels = avio_r8(pb);\n samplerate = avio_rl16(pb);\n if (!channels || !samplerate)\n return AVERROR_INVALIDDATA;\n asize-=4;\n av_log(s, AV_LOG_TRACE, \"NSV RAWAUDIO: bps %\"PRIu8\", nchan %\"PRIu8\", srate %\"PRIu16\"\\n\",\n bps, channels, samplerate);\n if (fill_header) {\n st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */\n if (bps != 16) {\n av_log(s, AV_LOG_TRACE, \"NSV AUDIO bit/sample != 16 (%\"PRIu8\")!!!\\n\", bps);\n }\n bps /= channels; // ???\n if (bps == 8)\n st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;\n samplerate /= 4;/* UGH ??? XXX */\n channels = 1;\n st[NSV_ST_AUDIO]->codecpar->channels = channels;\n st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;\n av_log(s, AV_LOG_TRACE, \"NSV RAWAUDIO: bps %\"PRIu8\", nchan %\"PRIu8\", srate %\"PRIu16\"\\n\",\n bps, channels, samplerate);\n }\n }\n av_get_packet(pb, pkt, asize);\n pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;\n pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */\n if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {\n /* on a nsvs frame we have new information on a/v sync */\n pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);\n pkt->dts *= (int64_t)1000 * nsv->framerate.den;\n pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;\n av_log(s, AV_LOG_TRACE, \"NSV AUDIO: sync:%\"PRId16\", dts:%\"PRId64,\n nsv->avsync, pkt->dts);\n }\n nst->frame_offset++;\n }\n\n nsv->state = NSV_UNSYNC;\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1938, 1977], [4074, 4113]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1938, 1977], [4074, 4113]]}, "_func_name": "nsv_read_chunk", "_file_name": "libavformat/nsvdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "\tdef get_secrets(self, from_date_added=0):\n\t\tsecrets = []\n\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)):\n\t\t\taes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]\n\t\t\tif aes_key != None:\n\t\t\t\tsecrets.append([aes_key, json_id])\n\t\t\tfrom_date_added = max(from_date_added, date_added)\n\t\treturn (secrets, from_date_added)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_secrets", "_file_name": "zeromail.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_item(self, item):\n \"\"\"\"Add new item.\"\"\"\n if self.connection:\n t = (item[0], item[1], )\n self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t)\n self.connection.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_item", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int string_rfind(const char *input, int len, const char *s, int s_len,\n int pos, bool case_sensitive) {\n assertx(input);\n assertx(s);\n if (!s_len || pos < -len || pos > len) {\n return -1;\n }\n void *ptr;\n if (case_sensitive) {\n if (pos >= 0) {\n ptr = bstrrstr(input + pos, len - pos, s, s_len);\n } else {\n ptr = bstrrstr(input, len + pos + s_len, s, s_len);\n }\n } else {\n if (pos >= 0) {\n ptr = bstrrcasestr(input + pos, len - pos, s, s_len);\n } else {\n ptr = bstrrcasestr(input, len + pos + s_len, s, s_len);\n }\n }\n if (ptr != nullptr) {\n return (int)((const char *)ptr - input);\n }\n return -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[340, 398], [508, 570]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[340, 398], [508, 570]]}, "_func_name": "HPHP::string_rfind", "_file_name": "hphp/runtime/base/zend-string.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "mapi_attr_read (size_t len, unsigned char *buf)\n{\n size_t idx = 0;\n uint32 i,j;\n assert(len > 4);\n uint32 num_properties = GETINT32(buf+idx);\n assert((num_properties+1) != 0);\n MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));\n\n idx += 4;\n\n if (!attrs) return NULL;\n for (i = 0; i < num_properties; i++)\n {\n\tMAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);\n\tMAPI_Value* v = NULL;\n\n\tCHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;\n\tCHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;\n\n\t/* handle special case of GUID prefixed properties */\n\tif (a->name & GUID_EXISTS_FLAG)\n\t{\n\t /* copy GUID */\n\t a->guid = CHECKED_XMALLOC(GUID, 1);\n\t copy_guid_from_buf(a->guid, buf+idx, len);\n\t idx += sizeof (GUID);\n\n\t CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;\n\t if (a->num_names > 0)\n\t {\n\t\t/* FIXME: do something useful here! */\n\t\tsize_t i;\n\n\t\ta->names = CHECKED_XCALLOC(VarLenData, a->num_names);\n\n\t\tfor (i = 0; i < a->num_names; i++)\n\t\t{\n\t\t size_t j;\n\n\t\t CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;\n\n\t\t /* read the data into a buffer */\n\t\t a->names[i].data \n\t\t\t= CHECKED_XMALLOC(unsigned char, a->names[i].len);\n\t\t assert((idx+(a->names[i].len*2)) <= len);\n\t\t for (j = 0; j < (a->names[i].len >> 1); j++)\n\t\t\ta->names[i].data[j] = (buf+idx)[j*2];\n\n\t\t /* But what are we going to do with it? */\n\t\t \n\t\t idx += pad_to_4byte(a->names[i].len);\n\t\t}\n\t }\n\t else\n\t {\n\t\t/* get the 'real' name */\n\t\tCHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;\n\t }\n\t}\n\n\t/* \n\t * Multi-value types and string/object/binary types have\n\t * multiple values \n\t */\n\tif (a->type & MULTI_VALUE_FLAG ||\n\t a->type == szMAPI_STRING ||\n\t a->type == szMAPI_UNICODE_STRING ||\n\t a->type == szMAPI_OBJECT ||\n\t a->type == szMAPI_BINARY)\n\t{\n\t CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);\n\t idx += 4;\n\t}\n else\n {\n\t a->num_values = 1;\n }\n\n\t/* Amend the type in case of multi-value type */\n\tif (a->type & MULTI_VALUE_FLAG)\n\t{\n\t a->type -= MULTI_VALUE_FLAG;\n\t}\n\n\n\tv = alloc_mapi_values (a);\n\n\tfor (j = 0; j < a->num_values; j++) \n\t{\n\t switch (a->type)\n\t {\n\t case szMAPI_SHORT:\t/* 2 bytes */\n\t\tv->len = 2;\n\t\tCHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);\n\t\tidx += 4;\t/* assume padding of 2, advance by 4! */\n\t\tbreak;\n\n\t case szMAPI_INT:\t/* 4 bytes */\n\t\tv->len = 4;\n\t\tCHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);\n\t\tidx += 4;\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_FLOAT:\t/* 4 bytes */\n\t case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */\n\t\tv->len = 4;\n\t\tCHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_SYSTIME: /* 8 bytes */\n\t\tv->len = 8;\n\t\tCHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);\n\t\tCHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);\n\t\tidx += 8;\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_DOUBLE:\t/* 8 bytes */\n\t case szMAPI_APPTIME:\n\t case szMAPI_CURRENCY:\n\t case szMAPI_INT8BYTE:\n\t\tv->len = 8;\n\t\tCHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);\n\t\tCHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_CLSID:\n\t\tv->len = sizeof (GUID);\n\t\tcopy_guid_from_buf(&v->data.guid, buf+idx, len);\n\t\tidx += v->len;\n\t\tbreak;\n\n\t case szMAPI_STRING:\n\t case szMAPI_UNICODE_STRING:\n\t case szMAPI_OBJECT:\n\t case szMAPI_BINARY:\n\t\tCHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;\n\n\t\tassert(v->len + idx <= len);\n\n\t\tif (a->type == szMAPI_UNICODE_STRING)\n\t\t{\n\t\t assert(v->len != 0);\n\t\t v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);\n\t\t}\n\t\telse\n\t\t{\n\t\t v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);\n\t\t memmove (v->data.buf, buf+idx, v->len);\n\t\t}\n\n\t\tidx += pad_to_4byte(v->len);\n\t\tv++;\n\t\tbreak;\n\n\t case szMAPI_NULL:\t/* illegal in input tnef streams */\n\t case szMAPI_ERROR:\n\t case szMAPI_UNSPECIFIED:\n\t\tfprintf (stderr,\n\t\t\t \"Invalid attribute, input file may be corrupted\\n\");\n\t\tif (!ENCODE_SKIP) exit (1);\n\n\t\treturn NULL;\n\n\t default:\t\t/* should never get here */\n\t\tfprintf (stderr,\n\t\t\t \"Undefined attribute, input file may be corrupted\\n\");\n\t\tif (!ENCODE_SKIP) exit (1);\n\n\t\treturn NULL;\n\n\t }\n\t if (DEBUG_ON) mapi_attr_dump (attrs[i]);\n\t}\n }\n attrs[i] = NULL;\n\n return attrs;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mapi_attr_read", "_file_name": "src/mapi_attr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type)\n{\n const char\n *artifact;\n\n ImageInfo\n *image_info;\n\n MagickBooleanType\n status;\n\n QuantizeInfo\n *quantize_info;\n\n assert(image != (Image *) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(image->signature == MagickSignature);\n status=MagickTrue;\n image_info=AcquireImageInfo();\n image_info->dither=image->dither;\n artifact=GetImageArtifact(image,\"dither\");\n if (artifact != (const char *) NULL)\n (void) SetImageOption(image_info,\"dither\",artifact);\n switch (type)\n {\n case BilevelType:\n {\n if (SetImageMonochrome(image,&image->exception) == MagickFalse)\n {\n status=TransformImageColorspace(image,GRAYColorspace);\n (void) NormalizeImage(image);\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->number_colors=2;\n quantize_info->colorspace=GRAYColorspace;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n }\n image->colors=2;\n image->matte=MagickFalse;\n break;\n }\n case GrayscaleType:\n {\n if (SetImageGray(image,&image->exception) == MagickFalse)\n status=TransformImageColorspace(image,GRAYColorspace);\n image->matte=MagickFalse;\n break;\n }\n case GrayscaleMatteType:\n {\n if (SetImageGray(image,&image->exception) == MagickFalse)\n status=TransformImageColorspace(image,GRAYColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case PaletteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n {\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->number_colors=256;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n }\n image->matte=MagickFalse;\n break;\n }\n case PaletteBilevelMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n (void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0);\n quantize_info=AcquireQuantizeInfo(image_info);\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n break;\n }\n case PaletteMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->colorspace=TransparentColorspace;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n break;\n }\n case TrueColorType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n image->matte=MagickFalse;\n break;\n }\n case TrueColorMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case ColorSeparationType:\n {\n if (image->colorspace != CMYKColorspace)\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace);\n status=TransformImageColorspace(image,CMYKColorspace);\n }\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n image->matte=MagickFalse;\n break;\n }\n case ColorSeparationMatteType:\n {\n if (image->colorspace != CMYKColorspace)\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace);\n status=TransformImageColorspace(image,CMYKColorspace);\n }\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case OptimizeType:\n case UndefinedType:\n break;\n }\n image_info=DestroyImageInfo(image_info);\n if (status == MagickFalse)\n return(MagickFalse);\n image->type=type;\n return(MagickTrue);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1127, 1150]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1127, 1150]]}, "_func_name": "SetImageType", "_file_name": "magick/attribute.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "str_lower_case_match(OnigEncoding enc, int case_fold_flag,\n const UChar* t, const UChar* tend,\n const UChar* p, const UChar* end)\n{\n int lowlen;\n UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];\n\n while (t < tend) {\n lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);\n q = lowbuf;\n while (lowlen > 0) {\n if (*t++ != *q++) return 0;\n lowlen--;\n }\n }\n\n return 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[373, 407]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[373, 407]]}, "_func_name": "str_lower_case_match", "_file_name": "src/regexec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _remove_volume_set(self, vvs_name):\n # Must first clear the QoS rules before removing the volume set\n self._cli_run('setqos -clear vvset:%s' % (vvs_name), None)\n self._cli_run('removevvset -f %s' % (vvs_name), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[116, 244]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[116, 244]]}, "_func_name": "_remove_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CURLcode Curl_close(struct Curl_easy *data)\n{\n struct Curl_multi *m;\n\n if(!data)\n return CURLE_OK;\n\n Curl_expire_clear(data); /* shut off timers */\n\n m = data->multi;\n if(m)\n /* This handle is still part of a multi handle, take care of this first\n and detach this handle from there. */\n curl_multi_remove_handle(data->multi, data);\n\n if(data->multi_easy)\n /* when curl_easy_perform() is used, it creates its own multi handle to\n use and this is the one */\n curl_multi_cleanup(data->multi_easy);\n\n /* Destroy the timeout list that is held in the easy handle. It is\n /normally/ done by curl_multi_remove_handle() but this is \"just in\n case\" */\n Curl_llist_destroy(&data->state.timeoutlist, NULL);\n\n data->magic = 0; /* force a clear AFTER the possibly enforced removal from\n the multi handle, since that function uses the magic\n field! */\n\n if(data->state.rangestringalloc)\n free(data->state.range);\n\n /* freed here just in case DONE wasn't called */\n Curl_free_request_state(data);\n\n /* Close down all open SSL info and sessions */\n Curl_ssl_close_all(data);\n Curl_safefree(data->state.first_host);\n Curl_safefree(data->state.scratch);\n Curl_ssl_free_certinfo(data);\n\n /* Cleanup possible redirect junk */\n free(data->req.newurl);\n data->req.newurl = NULL;\n\n if(data->change.referer_alloc) {\n Curl_safefree(data->change.referer);\n data->change.referer_alloc = FALSE;\n }\n data->change.referer = NULL;\n\n Curl_up_free(data);\n Curl_safefree(data->state.buffer);\n Curl_safefree(data->state.headerbuff);\n Curl_safefree(data->state.ulbuf);\n Curl_flush_cookies(data, 1);\n Curl_digest_cleanup(data);\n Curl_safefree(data->info.contenttype);\n Curl_safefree(data->info.wouldredirect);\n\n /* this destroys the channel and we cannot use it anymore after this */\n Curl_resolver_cleanup(data->state.resolver);\n\n Curl_http2_cleanup_dependencies(data);\n Curl_convert_close(data);\n\n /* No longer a dirty share, if it exists */\n if(data->share) {\n Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);\n data->share->dirty--;\n Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);\n }\n\n /* destruct wildcard structures if it is needed */\n Curl_wildcard_dtor(&data->wildcard);\n Curl_freeset(data);\n free(data);\n return CURLE_OK;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[353, 376]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[353, 376]]}, "_func_name": "Curl_close", "_file_name": "lib/url.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& val = ctx->input(0);\n int64 id = ctx->session_state()->GetNewId();\n TensorStore::TensorAndKey tk{val, id, requested_device()};\n OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));\n\n Tensor* handle = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n if (ctx->expected_output_dtype(0) == DT_RESOURCE) {\n ResourceHandle resource_handle = MakeResourceHandle(\n ctx, SessionState::kTensorHandleResourceTypeName,\n tk.GetHandle(name()));\n resource_handle.set_maybe_type_name(\n SessionState::kTensorHandleResourceTypeName);\n handle->scalar()() = resource_handle;\n } else {\n // Legacy behavior in V1.\n handle->flat().setConstant(tk.GetHandle(name()));\n }\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[87, 136]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[87, 136]]}, "_func_name": "tensorflow::GetSessionHandleOp::Compute", "_file_name": "tensorflow/core/kernels/session_ops.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def talk(myText):\r\n if( myText.find( \"twitter\" ) >= 0 ):\r\n myText += \"0\"\r\n myText = myText[7:-1]\r\n try:\r\n\t myText = twitter.getTweet( myText )\r\n\texcept:\r\n\t print( \"!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.\")\r\n return\r\n \r\n os.system( \"espeak \\\",...\\\" 2>/dev/null\" ) # Sometimes the beginning of audio can get cut off. Insert silence.\r\n time.sleep( 0.5 )\r\n os.system( \"espeak -w speech.wav \\\"\" + myText + \"\\\" -s 130\" )\r\n audio.play(\"speech.wav\")\r\n return myText", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[441, 508]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[441, 508]]}, "_func_name": "talk", "_file_name": "chippyRuxpin.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getPlayer(player):\n\tdb.execute(\"SELECT * FROM players WHERE Name = ? COLLATE NOCASE\", player)\n\tplayerstats = dict(db.fetchone())\n\treturn playerstats", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getPlayer", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "Mat_VarReadNextInfo4(mat_t *mat)\n{\n int M,O,data_type,class_type;\n mat_int32_t tmp;\n long nBytes;\n size_t readresult;\n matvar_t *matvar = NULL;\n union {\n mat_uint32_t u;\n mat_uint8_t c[4];\n } endian;\n\n if ( mat == NULL || mat->fp == NULL )\n return NULL;\n else if ( NULL == (matvar = Mat_VarCalloc()) )\n return NULL;\n\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n endian.u = 0x01020304;\n\n /* See if MOPT may need byteswapping */\n if ( tmp < 0 || tmp > 4052 ) {\n if ( Mat_int32Swap(&tmp) > 4052 ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n }\n\n M = (int)floor(tmp / 1000.0);\n switch ( M ) {\n case 0:\n /* IEEE little endian */\n mat->byteswap = endian.c[0] != 4;\n break;\n case 1:\n /* IEEE big endian */\n mat->byteswap = endian.c[0] != 1;\n break;\n default:\n /* VAX, Cray, or bogus */\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= M*1000;\n O = (int)floor(tmp / 100.0);\n /* O must be zero */\n if ( 0 != O ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= O*100;\n data_type = (int)floor(tmp / 10.0);\n /* Convert the V4 data type */\n switch ( data_type ) {\n case 0:\n matvar->data_type = MAT_T_DOUBLE;\n break;\n case 1:\n matvar->data_type = MAT_T_SINGLE;\n break;\n case 2:\n matvar->data_type = MAT_T_INT32;\n break;\n case 3:\n matvar->data_type = MAT_T_INT16;\n break;\n case 4:\n matvar->data_type = MAT_T_UINT16;\n break;\n case 5:\n matvar->data_type = MAT_T_UINT8;\n break;\n default:\n Mat_VarFree(matvar);\n return NULL;\n }\n\n tmp -= data_type*10;\n class_type = (int)floor(tmp / 1.0);\n switch ( class_type ) {\n case 0:\n matvar->class_type = MAT_C_DOUBLE;\n break;\n case 1:\n matvar->class_type = MAT_C_CHAR;\n break;\n case 2:\n matvar->class_type = MAT_C_SPARSE;\n break;\n default:\n Mat_VarFree(matvar);\n return NULL;\n }\n\n matvar->rank = 2;\n matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));\n if ( NULL == matvar->dims ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n matvar->dims[0] = tmp;\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n matvar->dims[1] = tmp;\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);\n if ( 1 != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n if ( mat->byteswap )\n Mat_int32Swap(&tmp);\n /* Check that the length of the variable name is at least 1 */\n if ( tmp < 1 ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n matvar->name = (char*)malloc(tmp);\n if ( NULL == matvar->name ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);\n if ( tmp != readresult ) {\n Mat_VarFree(matvar);\n return NULL;\n }\n\n matvar->internal->datapos = ftell((FILE*)mat->fp);\n if ( matvar->internal->datapos == -1L ) {\n Mat_VarFree(matvar);\n Mat_Critical(\"Couldn't determine file position\");\n return NULL;\n }\n {\n int err;\n size_t tmp2 = Mat_SizeOf(matvar->data_type);\n if ( matvar->isComplex )\n tmp2 *= 2;\n err = SafeMulDims(matvar, &tmp2);\n if ( err ) {\n Mat_VarFree(matvar);\n Mat_Critical(\"Integer multiplication overflow\");\n return NULL;\n }\n\n nBytes = (long)tmp2;\n }\n (void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);\n\n return matvar;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[3941, 3947]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3941, 3947]]}, "_func_name": "Mat_VarReadNextInfo4", "_file_name": "src/mat4.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool Utility::UnZip(const QString &zippath, const QString &destpath)\n{\n int res = 0;\n QDir dir(destpath);\n if (!cp437) {\n cp437 = new QCodePage437Codec();\n }\n#ifdef Q_OS_WIN32\n zlib_filefunc64_def ffunc;\n fill_win32_filefunc64W(&ffunc);\n unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc);\n#else\n unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData());\n#endif\n\n if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) {\n return false;\n }\n\n res = unzGoToFirstFile(zfile);\n\n if (res == UNZ_OK) {\n do {\n // Get the name of the file in the archive.\n char file_name[MAX_PATH] = {0};\n unz_file_info64 file_info;\n unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);\n QString qfile_name;\n QString cp437_file_name;\n qfile_name = QString::fromUtf8(file_name);\n if (!(file_info.flag & (1<<11))) {\n // General purpose bit 11 says the filename is utf-8 encoded. If not set then\n // IBM 437 encoding might be used.\n cp437_file_name = cp437->toUnicode(file_name);\n }\n\n // If there is no file name then we can't do anything with it.\n if (!qfile_name.isEmpty()) {\n\n\t // for security reasons against maliciously crafted zip archives\n\t // we need the file path to always be inside the target folder \n\t // and not outside, so we will remove all illegal backslashes\n\t // and all relative upward paths segments \"/../\" from the zip's local \n\t // file name/path before prepending the target folder to create \n\t // the final path\n\n\t QString original_path = qfile_name;\n\t bool evil_or_corrupt_epub = false;\n\n\t if (qfile_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n\t qfile_name = \"/\" + qfile_name.replace(\"\\\\\",\"\");\n\n\t if (qfile_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n\t qfile_name = qfile_name.replace(\"/../\",\"/\");\n\n\t while(qfile_name.startsWith(\"/\")) { \n\t\t qfile_name = qfile_name.remove(0,1);\n\t }\n \n\t if (cp437_file_name.contains(\"\\\\\")) evil_or_corrupt_epub = true; \n\t cp437_file_name = \"/\" + cp437_file_name.replace(\"\\\\\",\"\");\n\n\t if (cp437_file_name.contains(\"/../\")) evil_or_corrupt_epub = true;\n\t cp437_file_name = cp437_file_name.replace(\"/../\",\"/\");\n\n\t while(cp437_file_name.startsWith(\"/\")) { \n\t\t cp437_file_name = cp437_file_name.remove(0,1);\n\t }\n\n\t if (evil_or_corrupt_epub) {\n\t\t unzCloseCurrentFile(zfile);\n\t\t unzClose(zfile);\n\t\t // throw (UNZIPLoadParseError(QString(QObject::tr(\"Possible evil or corrupt zip file name: %1\")).arg(original_path).toStdString()));\n return false;\n\t }\n\n // We use the dir object to create the path in the temporary directory.\n // Unfortunately, we need a dir ojbect to do this as it's not a static function.\n // Full file path in the temporary directory.\n QString file_path = destpath + \"/\" + qfile_name;\n QFileInfo qfile_info(file_path);\n\n // Is this entry a directory?\n if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {\n dir.mkpath(qfile_name);\n continue;\n } else {\n dir.mkpath(qfile_info.path());\n }\n\n // Open the file entry in the archive for reading.\n if (unzOpenCurrentFile(zfile) != UNZ_OK) {\n unzClose(zfile);\n return false;\n }\n\n // Open the file on disk to write the entry in the archive to.\n QFile entry(file_path);\n\n if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n return false;\n }\n\n // Buffered reading and writing.\n char buff[BUFF_SIZE] = {0};\n int read = 0;\n\n while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {\n entry.write(buff, read);\n }\n\n entry.close();\n\n // Read errors are marked by a negative read amount.\n if (read < 0) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n return false;\n }\n\n // The file was read but the CRC did not match.\n // We don't check the read file size vs the uncompressed file size\n // because if they're different there should be a CRC error.\n if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {\n unzClose(zfile);\n return false;\n }\n\n if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {\n QString cp437_file_path = destpath + \"/\" + cp437_file_name;\n QFile::copy(file_path, cp437_file_path);\n }\n }\n } while ((res = unzGoToNextFile(zfile)) == UNZ_OK);\n }\n\n if (res != UNZ_END_OF_LIST_OF_FILE) {\n unzClose(zfile);\n return false;\n }\n\n unzClose(zfile);\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Utility::UnZip", "_file_name": "src/Misc/Utility.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;\n\n\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;\n\n\tif (args->nr_local == 0)\n\t\treturn -EINVAL;\n\n\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;\n\n\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;\n\n\t\ttot_pages += nr_pages;\n\n\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}\n\n\treturn tot_pages * sizeof(struct scatterlist);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rds_rdma_extra_size", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int expand_downwards(struct vm_area_struct *vma,\n\t\t\t\t unsigned long address)\n{\n\tstruct mm_struct *mm = vma->vm_mm;\n\tstruct vm_area_struct *prev;\n\tint error;\n\n\taddress &= PAGE_MASK;\n\terror = security_mmap_addr(address);\n\tif (error)\n\t\treturn error;\n\n\t/* Enforce stack_guard_gap */\n\tprev = vma->vm_prev;\n\t/* Check that both stack segments have the same anon_vma? */\n\tif (prev && !(prev->vm_flags & VM_GROWSDOWN) &&\n\t\t\t(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {\n\t\tif (address - prev->vm_end < stack_guard_gap)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/* We must make sure the anon_vma is allocated. */\n\tif (unlikely(anon_vma_prepare(vma)))\n\t\treturn -ENOMEM;\n\n\t/*\n\t * vma->vm_start/vm_end cannot change under us because the caller\n\t * is required to hold the mmap_sem in read mode. We need the\n\t * anon_vma lock to serialize against concurrent expand_stacks.\n\t */\n\tanon_vma_lock_write(vma->anon_vma);\n\n\t/* Somebody else might have raced and expanded it already */\n\tif (address < vma->vm_start) {\n\t\tunsigned long size, grow;\n\n\t\tsize = vma->vm_end - address;\n\t\tgrow = (vma->vm_start - address) >> PAGE_SHIFT;\n\n\t\terror = -ENOMEM;\n\t\tif (grow <= vma->vm_pgoff) {\n\t\t\terror = acct_stack_growth(vma, size, grow);\n\t\t\tif (!error) {\n\t\t\t\t/*\n\t\t\t\t * vma_gap_update() doesn't support concurrent\n\t\t\t\t * updates, but we only hold a shared mmap_sem\n\t\t\t\t * lock here, so we need to protect against\n\t\t\t\t * concurrent vma expansions.\n\t\t\t\t * anon_vma_lock_write() doesn't help here, as\n\t\t\t\t * we don't guarantee that all growable vmas\n\t\t\t\t * in a mm share the same root anon vma.\n\t\t\t\t * So, we reuse mm->page_table_lock to guard\n\t\t\t\t * against concurrent vma expansions.\n\t\t\t\t */\n\t\t\t\tspin_lock(&mm->page_table_lock);\n\t\t\t\tif (vma->vm_flags & VM_LOCKED)\n\t\t\t\t\tmm->locked_vm += grow;\n\t\t\t\tvm_stat_account(mm, vma->vm_flags, grow);\n\t\t\t\tanon_vma_interval_tree_pre_update_vma(vma);\n\t\t\t\tvma->vm_start = address;\n\t\t\t\tvma->vm_pgoff -= grow;\n\t\t\t\tanon_vma_interval_tree_post_update_vma(vma);\n\t\t\t\tvma_gap_update(vma);\n\t\t\t\tspin_unlock(&mm->page_table_lock);\n\n\t\t\t\tperf_event_mmap(vma);\n\t\t\t}\n\t\t}\n\t}\n\tanon_vma_unlock_write(vma->anon_vma);\n\tkhugepaged_enter_vma_merge(vma, vma->vm_flags);\n\tvalidate_mm(mm);\n\treturn error;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[183, 249]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[183, 249]]}, "_func_name": "expand_downwards", "_file_name": "mm/mmap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _inject_key_into_fs(key, fs, execute=None):\n \"\"\"Add the given public ssh key to root's authorized_keys.\n\n key is an ssh key string.\n fs is the path to the base of the filesystem into which to inject the key.\n \"\"\"\n sshdir = os.path.join(fs, 'root', '.ssh')\n utils.execute('mkdir', '-p', sshdir, run_as_root=True)\n utils.execute('chown', 'root', sshdir, run_as_root=True)\n utils.execute('chmod', '700', sshdir, run_as_root=True)\n keyfile = os.path.join(sshdir, 'authorized_keys')\n key_data = [\n '\\n',\n '# The following ssh key was injected by Nova',\n '\\n',\n key.strip(),\n '\\n',\n ]\n utils.execute('tee', '-a', keyfile,\n process_input=''.join(key_data), run_as_root=True)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[229, 275], [455, 509], [651, 759]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[229, 275], [455, 509], [651, 759]]}, "_func_name": "_inject_key_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connect()\n try:\n # The following introduces a deliberate security flaw - SQL Injection\n query = \"INSERT INTO crimes (description) VALUES ('{}');\".format(data)\n with connection.cursor() as cursor:\n cursor.execute(query)\n connection.commit()\n finally:\n connection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[162, 245]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[162, 245]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int mpeg4video_probe(AVProbeData *probe_packet)\n{\n uint32_t temp_buffer = -1;\n int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;\n int i;\n\n for (i = 0; i < probe_packet->buf_size; i++) {\n temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];\n if (temp_buffer & 0xfffffe00)\n continue;\n if (temp_buffer < 2)\n continue;\n\n if (temp_buffer == VOP_START_CODE)\n VOP++;\n else if (temp_buffer == VISUAL_OBJECT_START_CODE)\n VISO++;\n else if (temp_buffer >= 0x100 && temp_buffer < 0x120)\n VO++;\n else if (temp_buffer >= 0x120 && temp_buffer < 0x130)\n VOL++;\n else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&\n !(0x1B9 < temp_buffer && temp_buffer < 0x1C4))\n res++;\n }\n\n if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)\n return AVPROBE_SCORE_EXTENSION;\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mpeg4video_probe", "_file_name": "libavformat/m4vdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "wiki_handle_rest_call(HttpRequest *req, \n\t\t HttpResponse *res,\n\t\t char *func)\n{\n\n if (func != NULL && *func != '\\0')\n {\n if (!strcmp(func, \"page/get\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n\t {\n\t http_response_printf(res, \"%s\", file_read(page));\n\t http_response_send(res);\n\t return;\n\t } \n\t}\n else if (!strcmp(func, \"page/set\"))\n\t{\n\t char *wikitext = NULL, *page = NULL;\n\t if( ( (wikitext = http_request_param_get(req, \"text\")) != NULL)\n\t && ( (page = http_request_param_get(req, \"page\")) != NULL))\n\t {\n\t if (page_name_is_good(page))\n\t {\n\t file_write(page, wikitext);\n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return;\n\t }\n\t }\n\t}\n else if (!strcmp(func, \"page/delete\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && page_name_is_good(page) && (unlink(page) > 0))\n\t {\n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n else if (!strcmp(func, \"page/exists\"))\n\t{\n\t char *page = http_request_param_get(req, \"page\");\n\n\t if (page == NULL)\n\t page = http_request_get_query_string(req);\n\n\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n\t {\n\t http_response_printf(res, \"success\");\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n else if (!strcmp(func, \"pages\") || !strcmp(func, \"search\"))\n\t{\n\t WikiPageList **pages = NULL;\n\t int n_pages, i;\n\t char *expr = http_request_param_get(req, \"expr\");\n\n\t if (expr == NULL)\n\t expr = http_request_get_query_string(req);\n\t \n\t pages = wiki_get_pages(&n_pages, expr);\n\n\t if (pages)\n\t {\n\t for (i=0; imtime);\n\t\t strftime(datebuf, sizeof(datebuf), \"%Y-%m-%d %H:%M\", pTm);\n\t\t http_response_printf(res, \"%s\\t%s\\n\", pages[i]->name, datebuf);\n\t\t}\n\n\t http_response_send(res);\n\t return; \n\t }\n\t}\n }\n\n http_response_set_status(res, 500, \"Error\");\n http_response_printf(res, \"Failed\\n\");\n http_response_send(res);\n\n return; \n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "wiki_handle_rest_call", "_file_name": "src/wiki.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/wins\")\ndef wins():\n if db == None:\n init()\n\n player = request.args.get('tag', default=\"christmasmike\")\n sql = \"SELECT * FROM matches WHERE winner = '{player}' ORDER BY date DESC;\"\n args = {'player': player}\n result = db.exec(sql, args)\n\n result = [str(x) for x in result]\n result = '\\n'.join(result)\n return json.dumps(result)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "wins", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp)\n{\n\tchar* path = NULL;\n\tint status;\n\tWCHAR* ptr;\n\tUINT32 PathLength;\n\tif (!Stream_SafeSeek(irp->input, 28))\n\t\treturn ERROR_INVALID_DATA;\n\t/* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */\n\t/* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */\n\tif (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\tStream_Read_UINT32(irp->input, PathLength);\n\tptr = (WCHAR*)Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, PathLength))\n\t\treturn ERROR_INVALID_DATA;\n\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n\n\tif (status < 1)\n\t\tif (!(path = (char*)calloc(1, 1)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}\n\n\tparallel->id = irp->devman->id_sequence++;\n\tparallel->file = open(parallel->path, O_RDWR);\n\n\tif (parallel->file < 0)\n\t{\n\t\tirp->IoStatus = STATUS_ACCESS_DENIED;\n\t\tparallel->id = 0;\n\t}\n\telse\n\t{\n\t\t/* all read and write operations should be non-blocking */\n\t\tif (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1)\n\t\t{\n\t\t}\n\t}\n\n\tStream_Write_UINT32(irp->output, parallel->id);\n\tStream_Write_UINT8(irp->output, 0);\n\tfree(path);\n\treturn irp->Complete(irp);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "parallel_process_irp_create", "_file_name": "channels/parallel/client/parallel_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end,\n OnigCompileInfo* ci, OnigErrorInfo* einfo)\n{\n int r;\n UChar *cpat, *cpat_end;\n\n if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL;\n\n if (ci->pattern_enc != ci->target_enc) {\n return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION;\n }\n else {\n cpat = (UChar* )pattern;\n cpat_end = (UChar* )pattern_end;\n }\n\n *reg = (regex_t* )xmalloc(sizeof(regex_t));\n if (IS_NULL(*reg)) {\n r = ONIGERR_MEMORY;\n goto err2;\n }\n\n r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc,\n ci->syntax);\n if (r != 0) goto err;\n\n r = onig_compile(*reg, cpat, cpat_end, einfo);\n if (r != 0) {\n err:\n onig_free(*reg);\n *reg = NULL;\n }\n\n err2:\n if (cpat != pattern) xfree(cpat);\n\n return r;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "onig_new_deluxe", "_file_name": "src/regext.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/delete/', methods=['GET', 'POST'])\ndef delete(cmt_id):\n if request.method == 'GET':\n cursor.execute(\"SELECT msg_id FROM comment where cmt_id = %s;\", (cmt_id,))\n m = cursor.fetchone()\n cursor.execute(\"DELETE FROM comment where cmt_id = %s;\", (cmt_id,))\n conn.commit()\n flash('Delete Success!')\n return redirect(url_for('comment.show', msg_id=m[0]))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(field);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n switch (PB_HTYPE(field->type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (!check_wire_type(wire_type, field))\n PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n /* FIXME: Does this work correctly for oneofs? */\n pb_release_single_field(field);\n }\n \n if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)field->pSize = field->tag;\n }\n\n if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||\n PB_LTYPE(field->type) == PB_LTYPE_BYTES)\n {\n /* pb_dec_string and pb_dec_bytes handle allocation themselves */\n field->pData = field->pField;\n return decode_basic_field(stream, field);\n }\n else\n {\n if (!allocate_field(stream, field->pField, field->data_size, 1))\n return false;\n \n field->pData = *(void**)field->pField;\n initialize_pointer_field(field->pData, field);\n return decode_basic_field(stream, field);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)field->pSize;\n size_t allocated_size = *size;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / field->data_size + 1;\n \n if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n field->pData = *(char**)field->pField + field->data_size * (*size);\n initialize_pointer_field(field->pData, field);\n if (!decode_basic_field(&substream, field))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)field->pSize;\n\n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n if (!check_wire_type(wire_type, field))\n PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n if (!allocate_field(stream, field->pField, field->data_size, (size_t)(*size + 1)))\n return false;\n \n field->pData = *(char**)field->pField + field->data_size * (*size);\n (*size)++;\n initialize_pointer_field(field->pData, field);\n return decode_basic_field(stream, field);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_pointer_field", "_file_name": "pb_decode.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_roster(self, server_id):\n sql = \"\"\"\n SELECT username, role\n FROM roles\n WHERE roles.server_id = %s;\n \"\"\"\n self.cur.execute(sql, (server_id,))\n return self.cur.fetchall()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_roster", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def update_date_modified(self):\n sql = \"UPDATE jdk_entries \" + \\\n \"SET date_last_modified = \" + CURRENT_DATESTAMP + \" \" + \\\n \"WHERE jdk_entries.id = '\" + self.entry_id + \"';\"\n \n db_execute(sql)\n\n return None", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[70, 190]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[70, 190]]}, "_func_name": "update_date_modified", "_file_name": "entry.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def fetch_resultSet(self, session, id):\n self._openContainer(session)\n\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT class, data FROM %s WHERE identifier = $1;\" %\n (self.table)\n )\n res = self._query(query, sid)\n try:\n rdict = res.dictresult()[0]\n except IndexError:\n raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))\n\n data = rdict['data']\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # Insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000', '\\x00')\n ndata = ndata.replace('\\\\012', '\\n')\n # data is res.dictresult()\n cl = rdict['class']\n rset = dynamic.buildObject(session, cl, [[]])\n rset.deserialize(session, ndata)\n rset.id = id\n\n # Update expires\n now = time.time()\n nowStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(now))\n expires = now + self.get_default(session, 'expires', 600)\n rset.timeExpires = expires\n expiresStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(expires))\n\n query = (\"UPDATE %s SET timeAccessed = $1, expires = $2 \"\n \"WHERE identifier = $3;\" % (self.table)\n )\n self._query(query, nowStr, expiresStr, sid)\n return rset", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "fetch_resultSet", "_file_name": "cheshire3/sql/resultSetStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def updateKey(client):\n\t\"\"\"Updates the contents of a key that already exists in our system.\n\tReturns an error if the specified key doesn't exist for the specified user.\n\t\"\"\"\n\tglobal NOT_FOUND\n\tglobal CREATED\n\n\tvalidateClient(client)\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateNewKeyData(token_data)\n\tvalidateKeyName(token_data['name'])\n\n\t# Use 'w' flag to replace existing key file with the new key data\n\tif os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])):\n\t\twith open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f:\n\t\t\tf.write(token_data['key'])\n\telse:\n\t\traise FoxlockError(NOT_FOUND, \"Key '%s' not found\" % token_data['name'])\n\n\treturn 'Key successfully updated', CREATED", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "updateKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int usb_audio_probe(struct usb_interface *intf,\n\t\t\t const struct usb_device_id *usb_id)\n{\n\tstruct usb_device *dev = interface_to_usbdev(intf);\n\tconst struct snd_usb_audio_quirk *quirk =\n\t\t(const struct snd_usb_audio_quirk *)usb_id->driver_info;\n\tstruct snd_usb_audio *chip;\n\tint i, err;\n\tstruct usb_host_interface *alts;\n\tint ifnum;\n\tu32 id;\n\n\talts = &intf->altsetting[0];\n\tifnum = get_iface_desc(alts)->bInterfaceNumber;\n\tid = USB_ID(le16_to_cpu(dev->descriptor.idVendor),\n\t\t le16_to_cpu(dev->descriptor.idProduct));\n\tif (get_alias_id(dev, &id))\n\t\tquirk = get_alias_quirk(dev, id);\n\tif (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)\n\t\treturn -ENXIO;\n\n\terr = snd_usb_apply_boot_quirk(dev, intf, quirk, id);\n\tif (err < 0)\n\t\treturn err;\n\n\t/*\n\t * found a config. now register to ALSA\n\t */\n\n\t/* check whether it's already registered */\n\tchip = NULL;\n\tmutex_lock(®ister_mutex);\n\tfor (i = 0; i < SNDRV_CARDS; i++) {\n\t\tif (usb_chip[i] && usb_chip[i]->dev == dev) {\n\t\t\tif (atomic_read(&usb_chip[i]->shutdown)) {\n\t\t\t\tdev_err(&dev->dev, \"USB device is in the shutdown state, cannot create a card instance\\n\");\n\t\t\t\terr = -EIO;\n\t\t\t\tgoto __error;\n\t\t\t}\n\t\t\tchip = usb_chip[i];\n\t\t\tatomic_inc(&chip->active); /* avoid autopm */\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (! chip) {\n\t\t/* it's a fresh one.\n\t\t * now look for an empty slot and create a new card instance\n\t\t */\n\t\tfor (i = 0; i < SNDRV_CARDS; i++)\n\t\t\tif (!usb_chip[i] &&\n\t\t\t (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&\n\t\t\t (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {\n\t\t\t\tif (enable[i]) {\n\t\t\t\t\terr = snd_usb_audio_create(intf, dev, i, quirk,\n\t\t\t\t\t\t\t\t id, &chip);\n\t\t\t\t\tif (err < 0)\n\t\t\t\t\t\tgoto __error;\n\t\t\t\t\tchip->pm_intf = intf;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (vid[i] != -1 || pid[i] != -1) {\n\t\t\t\t\tdev_info(&dev->dev,\n\t\t\t\t\t\t \"device (%04x:%04x) is disabled\\n\",\n\t\t\t\t\t\t USB_ID_VENDOR(id),\n\t\t\t\t\t\t USB_ID_PRODUCT(id));\n\t\t\t\t\terr = -ENOENT;\n\t\t\t\t\tgoto __error;\n\t\t\t\t}\n\t\t\t}\n\t\tif (!chip) {\n\t\t\tdev_err(&dev->dev, \"no available usb audio device\\n\");\n\t\t\terr = -ENODEV;\n\t\t\tgoto __error;\n\t\t}\n\t}\n\tdev_set_drvdata(&dev->dev, chip);\n\n\t/*\n\t * For devices with more than one control interface, we assume the\n\t * first contains the audio controls. We might need a more specific\n\t * check here in the future.\n\t */\n\tif (!chip->ctrl_intf)\n\t\tchip->ctrl_intf = alts;\n\n\tchip->txfr_quirk = 0;\n\terr = 1; /* continue */\n\tif (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {\n\t\t/* need some special handlings */\n\t\terr = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\tif (err > 0) {\n\t\t/* create normal USB audio interfaces */\n\t\terr = snd_usb_create_streams(chip, ifnum);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t\terr = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);\n\t\tif (err < 0)\n\t\t\tgoto __error;\n\t}\n\n\t/* we are allowed to call snd_card_register() many times */\n\terr = snd_card_register(chip->card);\n\tif (err < 0)\n\t\tgoto __error;\n\n\tusb_chip[chip->index] = chip;\n\tchip->num_interfaces++;\n\tusb_set_intfdata(intf, chip);\n\tatomic_dec(&chip->active);\n\tmutex_unlock(®ister_mutex);\n\treturn 0;\n\n __error:\n\tif (chip) {\n\t\tif (!chip->num_interfaces)\n\t\t\tsnd_card_free(chip->card);\n\t\tatomic_dec(&chip->active);\n\t}\n\tmutex_unlock(®ister_mutex);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[3085, 3144]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3085, 3144]]}, "_func_name": "usb_audio_probe", "_file_name": "sound/usb/card.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid)\n{\n\tint frameSize = afGetVirtualFrameSize(infile, trackid, 1);\n\n\tint kBufferFrameCount = 65536;\n\tint bufferSize;\n\twhile (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize))\n\t\tkBufferFrameCount /= 2;\n\tvoid *buffer = malloc(bufferSize);\n\n\tAFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);\n\tAFframecount totalFramesWritten = 0;\n\n\tbool success = true;\n\n\twhile (totalFramesWritten < totalFrames)\n\t{\n\t\tAFframecount framesToRead = totalFrames - totalFramesWritten;\n\t\tif (framesToRead > kBufferFrameCount)\n\t\t\tframesToRead = kBufferFrameCount;\n\n\t\tAFframecount framesRead = afReadFrames(infile, trackid, buffer,\n\t\t\tframesToRead);\n\n\t\tif (framesRead < framesToRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad read of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tAFframecount framesWritten = afWriteFrames(outfile, trackid, buffer,\n\t\t\tframesRead);\n\n\t\tif (framesWritten < framesRead)\n\t\t{\n\t\t\tfprintf(stderr, \"Bad write of audio track data.\\n\");\n\t\t\tsuccess = false;\n\t\t\tbreak;\n\t\t}\n\n\t\ttotalFramesWritten += framesWritten;\n\t}\n\n\tfree(buffer);\n\n\treturn success;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "copyaudiodata", "_file_name": "sfcommands/sfconvert.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getAllComments(self):\n sqlText=\"select comment from comments where userid=%s order by date;\"\n params = [self.userid]\n allposts=sql.queryDB(self.conn,sqlText,params)\n return allposts;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getAllComments", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'POST':\n msg_id = int(request.form['msg_id'])\n user_id = session['logged_id']\n content = request.form['content']\n c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n sql = \"INSERT INTO comment(msg_id,user_id,content,c_time) \" + \\\n \"VALUES(%d,%d,'%s','%s');\" % (msg_id, user_id, content, c_time)\n cursor.execute(sql)\n conn.commit()\n return redirect(url_for('comment.show', msg_id=msg_id))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[276, 456]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[276, 456]]}, "_func_name": "add", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_post(content):\n \"\"\"Add a post to the 'database' with the current timestamp.\"\"\"\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n c.execute(\"insert into posts values(%s)\",(content,))\n db.commit()\n db.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_post", "_file_name": "vagrant/forum/forumdb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/view/')\ndef view(sid):\n if '/' not in sid:\n path = os.path.join(app.config['UPLOAD_FOLDER'], sid)\n if os.path.isdir(path):\n using_firebase = 'true' if app.config['FIREBASE'] else 'false'\n return render_template('view.html',\n sid=sid, title=\"Progress for %s\" % sid, using_firebase=using_firebase)\n else:\n abort(404)\n else:\n abort(403)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[41, 126], [281, 364]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[41, 126], [281, 364]]}, "_func_name": "view", "_file_name": "app/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_context_data(self, *args, **kwargs):\n data = super().get_context_data(*args, **kwargs)\n\n back = self.request.GET.get('back', None)\n parsed_back_url = urllib.parse.urlparse(back)\n\n # We only allow blank scheme, e.g. relative urls to avoid reflected XSS\n if back is not None and parsed_back_url.scheme == \"\":\n data['back_link'] = back\n\n return data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_context_data", "_file_name": "socialsystem/core/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, struct kvec *iov, int n_vec)\n{\n\tstruct smb_rqst rqst;\n\tint rc = 0;\n\tstruct smb2_write_req *req = NULL;\n\tstruct smb2_write_rsp *rsp = NULL;\n\tint resp_buftype;\n\tstruct kvec rsp_iov;\n\tint flags = 0;\n\tunsigned int total_len;\n\n\t*nbytes = 0;\n\n\tif (n_vec < 1)\n\t\treturn rc;\n\n\trc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,\n\t\t\t &total_len);\n\tif (rc)\n\t\treturn rc;\n\n\tif (io_parms->tcon->ses->server == NULL)\n\t\treturn -ECONNABORTED;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\treq->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);\n\n\treq->PersistentFileId = io_parms->persistent_fid;\n\treq->VolatileFileId = io_parms->volatile_fid;\n\treq->WriteChannelInfoOffset = 0;\n\treq->WriteChannelInfoLength = 0;\n\treq->Channel = 0;\n\treq->Length = cpu_to_le32(io_parms->length);\n\treq->Offset = cpu_to_le64(io_parms->offset);\n\treq->DataOffset = cpu_to_le16(\n\t\t\t\toffsetof(struct smb2_write_req, Buffer));\n\treq->RemainingBytes = 0;\n\n\ttrace_smb3_write_enter(xid, io_parms->persistent_fid,\n\t\tio_parms->tcon->tid, io_parms->tcon->ses->Suid,\n\t\tio_parms->offset, io_parms->length);\n\n\tiov[0].iov_base = (char *)req;\n\t/* 1 for Buffer */\n\tiov[0].iov_len = total_len - 1;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = n_vec + 1;\n\n\trc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,\n\t\t\t &resp_buftype, flags, &rsp_iov);\n\trsp = (struct smb2_write_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\ttrace_smb3_write_err(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length, rc);\n\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);\n\t\tcifs_dbg(VFS, \"Send error in write = %d\\n\", rc);\n\t} else {\n\t\t*nbytes = le32_to_cpu(rsp->DataLength);\n\t\ttrace_smb3_write_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, *nbytes);\n\t}\n\n\tcifs_small_buf_release(req);\n\tfree_rsp_buf(resp_buftype, rsp);\n\treturn rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "SMB2_write", "_file_name": "fs/cifs/smb2pdu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_flashcopy_mapping_attributes(self, fc_map_id):\n LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s')\n % fc_map_id)\n\n fc_ls_map_cmd = 'svcinfo lsfcmap -filtervalue id=%s -delim !' % \\\n fc_map_id\n out, err = self._run_ssh(fc_ls_map_cmd)\n if not len(out.strip()):\n return None\n\n # Get list of FlashCopy mappings\n # We expect zero or one line if mapping does not exist,\n # two lines if it does exist, otherwise error\n lines = out.strip().split('\\n')\n self._assert_ssh_return(len(lines) <= 2,\n '_get_flashcopy_mapping_attributes',\n fc_ls_map_cmd, out, err)\n\n if len(lines) == 2:\n attributes = self._get_hdr_dic(lines[0], lines[1], '!')\n else: # 0 or 1 lines\n attributes = None\n\n LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping '\n '%(fc_map_id)s, attributes %(attributes)s') %\n {'fc_map_id': fc_map_id, 'attributes': attributes})\n\n return attributes", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[168, 242]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[168, 242]]}, "_func_name": "_get_flashcopy_mapping_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int TNEFParse(TNEFStruct *TNEF) {\n WORD key;\n DWORD type;\n DWORD size;\n DWORD signature;\n BYTE *data;\n WORD checksum, header_checksum;\n int i;\n\n if (TNEF->IO.ReadProc == NULL) {\n printf(\"ERROR: Setup incorrectly: No ReadProc\\n\");\n return YTNEF_INCORRECT_SETUP;\n }\n\n if (TNEF->IO.InitProc != NULL) {\n DEBUG(TNEF->Debug, 2, \"About to initialize\");\n if (TNEF->IO.InitProc(&TNEF->IO) != 0) {\n return YTNEF_CANNOT_INIT_DATA;\n }\n DEBUG(TNEF->Debug, 2, \"Initialization finished\");\n }\n\n DEBUG(TNEF->Debug, 2, \"Reading Signature\");\n if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {\n printf(\"ERROR: Error reading signature\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_ERROR_READING_DATA;\n }\n\n DEBUG(TNEF->Debug, 2, \"Checking Signature\");\n if (TNEFCheckForSignature(signature) < 0) {\n printf(\"ERROR: Signature does not match. Not TNEF.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_NOT_TNEF_STREAM;\n }\n\n DEBUG(TNEF->Debug, 2, \"Reading Key.\");\n\n if (TNEFGetKey(TNEF, &key) < 0) {\n printf(\"ERROR: Unable to retrieve key.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_NO_KEY;\n }\n\n DEBUG(TNEF->Debug, 2, \"Starting Full Processing.\");\n\n while (TNEFGetHeader(TNEF, &type, &size) == 0) {\n DEBUG2(TNEF->Debug, 2, \"Header says type=0x%X, size=%u\", type, size);\n DEBUG2(TNEF->Debug, 2, \"Header says type=%u, size=%u\", type, size);\n if(size == 0) {\n printf(\"ERROR: Field with size of 0\\n\");\n return YTNEF_ERROR_READING_DATA;\n }\n data = calloc(size, sizeof(BYTE));\n ALLOCCHECK(data);\n if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {\n printf(\"ERROR: Unable to read data.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_ERROR_READING_DATA;\n }\n if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {\n printf(\"ERROR: Unable to read checksum.\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_ERROR_READING_DATA;\n }\n checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));\n if (checksum != header_checksum) {\n printf(\"ERROR: Checksum mismatch. Data corruption?:\\n\");\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n free(data);\n return YTNEF_BAD_CHECKSUM;\n }\n for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {\n if (TNEFList[i].id == type) {\n if (TNEFList[i].handler != NULL) {\n if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {\n free(data);\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return YTNEF_ERROR_IN_HANDLER;\n } else {\n // Found our handler and processed it. now time to get out\n break;\n }\n } else {\n DEBUG2(TNEF->Debug, 1, \"No handler for %s: %u bytes\",\n TNEFList[i].name, size);\n }\n }\n }\n\n free(data);\n }\n\n if (TNEF->IO.CloseProc != NULL) {\n TNEF->IO.CloseProc(&TNEF->IO);\n }\n return 0;\n\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TNEFParse", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def handle(self, keepalive=True, initial_timeout=None):\n # we are requested to skip processing and keep the previous values\n if self.skip:\n return self.response.handle()\n\n # default to no keepalive in case something happens while even trying ensure we have a request\n self.keepalive = False\n\n self.headers = HTTPHeaders()\n\n # if initial_timeout is set, only wait that long for the initial request line\n if initial_timeout:\n self.connection.settimeout(initial_timeout)\n else:\n self.connection.settimeout(self.timeout)\n\n # get request line\n try:\n # ignore empty lines waiting on request\n request = '\\r\\n'\n while request == '\\r\\n':\n request = self.rfile.readline(max_line_size + 1).decode(http_encoding)\n # if read hits timeout or has some other error, ignore the request\n except Exception:\n return True\n\n # ignore empty requests\n if not request:\n return True\n\n # we have a request, go back to normal timeout\n if initial_timeout:\n self.connection.settimeout(self.timeout)\n\n # remove \\r\\n from the end\n self.request_line = request[:-2]\n\n # set some reasonable defaults in case the worst happens and we need to tell the client\n self.method = ''\n self.resource = '/'\n\n try:\n # HTTP Status 414\n if len(request) > max_line_size:\n raise HTTPError(414)\n\n # HTTP Status 400\n if request[-2:] != '\\r\\n':\n raise HTTPError(400)\n\n # try the request line and error out if can't parse it\n try:\n self.method, resource, self.request_http = self.request_line.split()\n self.resource = urllib.parse.unquote(resource)\n # HTTP Status 400\n except ValueError:\n raise HTTPError(400)\n\n # HTTP Status 505\n if self.request_http != http_version:\n raise HTTPError(505)\n\n # read and parse request headers\n while True:\n line = self.rfile.readline(max_line_size + 1).decode(http_encoding)\n\n # hit end of headers\n if line == '\\r\\n':\n break\n\n self.headers.add(line)\n\n # if we are requested to close the connection after we finish, do so\n if self.headers.get('Connection') == 'close':\n self.keepalive = False\n # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed)\n else:\n self.keepalive = keepalive\n\n # find a matching regex to handle the request with\n for regex, handler in self.server.routes.items():\n match = regex.match(self.resource)\n if match:\n # create a dictionary of groups\n groups = match.groupdict()\n values = groups.values()\n\n for idx, group in enumerate(match.groups()):\n if group not in values:\n groups[idx] = group\n\n # create handler\n self.handler = handler(self, self.response, groups)\n break\n # HTTP Status 404\n # if loop is not broken (handler is not found), raise a 404\n else:\n raise HTTPError(404)\n # use DummyHandler so the error is raised again when ready for response\n except Exception as error:\n self.handler = DummyHandler(self, self.response, (), error)\n finally:\n # we finished listening and handling early errors and so let a response class now finish up the job of talking\n return self.response.handle()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle", "_file_name": "fooster/web/web.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int dd_exist(const struct dump_dir *dd, const char *path)\n{\n if (!str_is_correct_filename(path))\n error_msg_and_die(\"Cannot test existence. '%s' is not a valid file name\", path);\n\n char *full_path = concat_path_file(dd->dd_dirname, path);\n int ret = exist_file_dir(full_path);\n free(full_path);\n return ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_exist", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {\n\tOPCODE_DESC *opcode_desc;\n\tif (len < 2) {\n\t\treturn NULL;\n\t}\n\tut16 ins = (buf[1] << 8) | buf[0];\n\tint fail;\n\tchar *t;\n\n\t// initialize op struct\n\tmemset (op, 0, sizeof (RAnalOp));\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->jump = UT64_MAX;\n\tr_strbuf_init (&op->esil);\n\n\t// process opcode\n\tfor (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {\n\t\tif ((ins & opcode_desc->mask) == opcode_desc->selector) {\n\t\t\tfail = 0;\n\n\t\t\t// copy default cycles/size values\n\t\t\top->cycles = opcode_desc->cycles;\n\t\t\top->size = opcode_desc->size;\n\t\t\top->type = opcode_desc->type;\n\t\t\top->jump = UT64_MAX;\n\t\t\top->fail = UT64_MAX;\n\t\t\t// op->fail = addr + op->size;\n\t\t\top->addr = addr;\n\n\t\t\t// start void esil expression\n\t\t\tr_strbuf_setf (&op->esil, \"\");\n\n\t\t\t// handle opcode\n\t\t\topcode_desc->handler (anal, op, buf, len, &fail, cpu);\n\t\t\tif (fail) {\n\t\t\t\tgoto INVALID_OP;\n\t\t\t}\n\t\t\tif (op->cycles <= 0) {\n\t\t\t\t// eprintf (\"opcode %s @%\"PFMT64x\" returned 0 cycles.\\n\", opcode_desc->name, op->addr);\n\t\t\t\topcode_desc->cycles = 2;\n\t\t\t}\n\t\t\top->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);\n\n\t\t\t// remove trailing coma (COMETE LA COMA)\n\t\t\tt = r_strbuf_get (&op->esil);\n\t\t\tif (t && strlen (t) > 1) {\n\t\t\t\tt += strlen (t) - 1;\n\t\t\t\tif (*t == ',') {\n\t\t\t\t\t*t = '\\0';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn opcode_desc;\n\t\t}\n\t}\n\n\t// ignore reserved opcodes (if they have not been caught by the previous loop)\n\tif ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {\n\t\tgoto INVALID_OP;\n\t}\n\nINVALID_OP:\n\t// An unknown or invalid option has appeared.\n\t// -- Throw pokeball!\n\top->family = R_ANAL_OP_FAMILY_UNKNOWN;\n\top->type = R_ANAL_OP_TYPE_UNK;\n\top->addr = addr;\n\top->fail = UT64_MAX;\n\top->jump = UT64_MAX;\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->nopcode = 1;\n\top->cycles = 1;\n\top->size = 2;\n\t// launch esil trap (for communicating upper layers about this weird\n\t// and stinky situation\n\tr_strbuf_set (&op->esil, \"1,$\");\n\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "avr_op_analyze", "_file_name": "libr/anal/p/anal_avr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)\n{\n FILE *f = NULL;\n int w, h, prec;\n int i, numcomps, max;\n OPJ_COLOR_SPACE color_space;\n opj_image_cmptparm_t cmptparm; /* maximum of 1 component */\n opj_image_t * image = NULL;\n int adjustS, ushift, dshift, force8;\n\n char endian1, endian2, sign;\n char signtmp[32];\n\n char temp[32];\n int bigendian;\n opj_image_comp_t *comp = NULL;\n\n numcomps = 1;\n color_space = OPJ_CLRSPC_GRAY;\n\n memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));\n\n max = 0;\n\n f = fopen(filename, \"rb\");\n if (!f) {\n fprintf(stderr, \"Failed to open %s for reading !\\n\", filename);\n return NULL;\n }\n\n fseek(f, 0, SEEK_SET);\n if (fscanf(f, \"PG%31[ \\t]%c%c%31[ \\t+-]%d%31[ \\t]%d%31[ \\t]%d\", temp, &endian1,\n &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {\n fclose(f);\n fprintf(stderr,\n \"ERROR: Failed to read the right number of element from the fscanf() function!\\n\");\n return NULL;\n }\n\n i = 0;\n sign = '+';\n while (signtmp[i] != '\\0') {\n if (signtmp[i] == '-') {\n sign = '-';\n }\n i++;\n }\n\n fgetc(f);\n if (endian1 == 'M' && endian2 == 'L') {\n bigendian = 1;\n } else if (endian2 == 'M' && endian1 == 'L') {\n bigendian = 0;\n } else {\n fclose(f);\n fprintf(stderr, \"Bad pgx header, please check input file\\n\");\n return NULL;\n }\n\n /* initialize image component */\n\n cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;\n cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;\n cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +\n 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx\n + 1;\n cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +\n 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy\n + 1;\n\n if (sign == '-') {\n cmptparm.sgnd = 1;\n } else {\n cmptparm.sgnd = 0;\n }\n if (prec < 8) {\n force8 = 1;\n ushift = 8 - prec;\n dshift = prec - ushift;\n if (cmptparm.sgnd) {\n adjustS = (1 << (prec - 1));\n } else {\n adjustS = 0;\n }\n cmptparm.sgnd = 0;\n prec = 8;\n } else {\n ushift = dshift = force8 = adjustS = 0;\n }\n\n cmptparm.prec = (OPJ_UINT32)prec;\n cmptparm.bpp = (OPJ_UINT32)prec;\n cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;\n cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;\n\n /* create the image */\n image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);\n if (!image) {\n fclose(f);\n return NULL;\n }\n /* set image offset and reference grid */\n image->x0 = cmptparm.x0;\n image->y0 = cmptparm.x0;\n image->x1 = cmptparm.w;\n image->y1 = cmptparm.h;\n\n /* set image data */\n\n comp = &image->comps[0];\n\n for (i = 0; i < w * h; i++) {\n int v;\n if (force8) {\n v = readuchar(f) + adjustS;\n v = (v << ushift) + (v >> dshift);\n comp->data[i] = (unsigned char)v;\n\n if (v > max) {\n max = v;\n }\n\n continue;\n }\n if (comp->prec == 8) {\n if (!comp->sgnd) {\n v = readuchar(f);\n } else {\n v = (char) readuchar(f);\n }\n } else if (comp->prec <= 16) {\n if (!comp->sgnd) {\n v = readushort(f, bigendian);\n } else {\n v = (short) readushort(f, bigendian);\n }\n } else {\n if (!comp->sgnd) {\n v = (int)readuint(f, bigendian);\n } else {\n v = (int) readuint(f, bigendian);\n }\n }\n if (v > max) {\n max = v;\n }\n comp->data[i] = v;\n }\n fclose(f);\n comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;\n\n return image;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "pgxtoimage", "_file_name": "src/bin/jp2/convert.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)\n{\n\tdouble width_d;\n\tdouble scale_f_d = 1.0;\n\tconst double filter_width_d = DEFAULT_BOX_RADIUS;\n\tint windows_size;\n\tunsigned int u;\n\tLineContribType *res;\n\n\tif (scale_d < 1.0) {\n\t\twidth_d = filter_width_d / scale_d;\n\t\tscale_f_d = scale_d;\n\t} else {\n\t\twidth_d= filter_width_d;\n\t}\n\n\twindows_size = 2 * (int)ceil(width_d) + 1;\n\tres = _gdContributionsAlloc(line_size, windows_size);\n\n\tfor (u = 0; u < line_size; u++) {\n\t\tconst double dCenter = (double)u / scale_d;\n\t\t/* get the significant edge points affecting the pixel */\n\t\tregister int iLeft = MAX(0, (int)floor (dCenter - width_d));\n\t\tint iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);\n\t\tdouble dTotalWeight = 0.0;\n\t\tint iSrc;\n\n\t\t/* Cut edge points to fit in filter window in case of spill-off */\n\t\tif (iRight - iLeft + 1 > windows_size) {\n\t\t\tif (iLeft < ((int)src_size - 1 / 2)) {\n\t\t\t\tiLeft++;\n\t\t\t} else {\n\t\t\t\tiRight--;\n\t\t\t}\n\t\t}\n\n\t\tres->ContribRow[u].Left = iLeft;\n\t\tres->ContribRow[u].Right = iRight;\n\n\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\tdTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));\n\t\t}\n\n\t\tif (dTotalWeight < 0.0) {\n\t\t\t_gdContributionsFree(res);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (dTotalWeight > 0.0) {\n\t\t\tfor (iSrc = iLeft; iSrc <= iRight; iSrc++) {\n\t\t\t\tres->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_gdContributionsCalc", "_file_name": "src/gd_interpolation.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def retrieve_video(id, playlist_id, db):\n db.execute(\n \"SELECT id, position from video WHERE id=%s and playlist_id=%s;\", (id, playlist_id))\n row = db.fetchone()\n return row", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "retrieve_video", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,\n xkb_mod_mask_t *mods_rtrn, CompatInfo *info)\n{\n if (expr == NULL) {\n *pred_rtrn = MATCH_ANY_OR_NONE;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n *pred_rtrn = MATCH_EXACTLY;\n if (expr->expr.op == EXPR_ACTION_DECL) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);\n if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||\n !expr->action.args) {\n log_err(info->ctx,\n \"Illegal modifier predicate \\\"%s\\\"; Ignored\\n\", pred_txt);\n return false;\n }\n expr = expr->action.args;\n }\n else if (expr->expr.op == EXPR_IDENT) {\n const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);\n if (pred_txt && istreq(pred_txt, \"any\")) {\n *pred_rtrn = MATCH_ANY;\n *mods_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n }\n\n return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,\n mods_rtrn);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ResolveStateAndPredicate", "_file_name": "src/xkbcomp/compat.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_ask(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute(\n ''' SELECT karma FROM people WHERE name='{}' '''.format(name))\n karma = cursor.fetchone()\n if karma is None:\n logger.debug('No karma found for name {}'.format(name))\n db.close()\n return karma\n else:\n karma = karma[0]\n logger.debug('karma of {} found for name {}'.format(karma, name))\n db.close()\n return karma\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[77, 176]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[77, 176]]}, "_func_name": "karma_ask", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getGameID(ID):\n\tdb.execute(\"SELECT * FROM games WHERE ID = %i\" % ID)\n\tID = db.fetchone()\n\treturn ID", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[19, 73]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[19, 73]]}, "_func_name": "getGameID", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def candidate_paths_for_url(self, url):\n for root, prefix in self.directories:\n if url.startswith(prefix):\n yield os.path.join(root, url[len(prefix):])", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[129, 188]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[129, 188]]}, "_func_name": "candidate_paths_for_url", "_file_name": "whitenoise/base.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_value(self):\n field = getattr(self.object, self.column.field_name) if self.column.field_name else None\n if self.column.render_function:\n template = self.column.render_function(self.object)\n if not self.is_template_instance(template):\n raise SmartListException(\n 'Your render_function {} should return django.template.Template or django.template.backends.django.Template object instead of {}'.format(\n self.column.render_function.__name__,\n type(template),\n )\n )\n value = template.render()\n elif type(self.object) == dict:\n value = self.object.get(self.column.field_name)\n elif callable(field):\n value = field() if getattr(field, 'do_not_call_in_templates', False) else field\n else:\n display_function = getattr(self.object, 'get_%s_display' % self.column.field_name, False)\n value = display_function() if display_function else field\n\n return value", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_value", "_file_name": "smart_lists/helpers.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)\n{\n WavpackHeader *wphdr = (WavpackHeader *) buffer;\n uint32_t checksum_passed = 0, bcount, meta_bc;\n unsigned char *dp, meta_id, c1, c2;\n\n if (strncmp (wphdr->ckID, \"wvpk\", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))\n return FALSE;\n\n bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;\n dp = (unsigned char *)(wphdr + 1);\n\n while (bcount >= 2) {\n meta_id = *dp++;\n c1 = *dp++;\n\n meta_bc = c1 << 1;\n bcount -= 2;\n\n if (meta_id & ID_LARGE) {\n if (bcount < 2)\n return FALSE;\n\n c1 = *dp++;\n c2 = *dp++;\n meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);\n bcount -= 2;\n }\n\n if (bcount < meta_bc)\n return FALSE;\n\n if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {\n#ifdef BITSTREAM_SHORTS\n uint16_t *csptr = (uint16_t*) buffer;\n#else\n unsigned char *csptr = buffer;\n#endif\n int wcount = (int)(dp - 2 - buffer) >> 1;\n uint32_t csum = (uint32_t) -1;\n\n if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)\n return FALSE;\n\n#ifdef BITSTREAM_SHORTS\n while (wcount--)\n csum = (csum * 3) + *csptr++;\n#else\n WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);\n\n while (wcount--) {\n csum = (csum * 3) + csptr [0] + (csptr [1] << 8);\n csptr += 2;\n }\n\n WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);\n#endif\n\n if (meta_bc == 4) {\n if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff))\n return FALSE;\n }\n else {\n csum ^= csum >> 16;\n\n if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff))\n return FALSE;\n }\n\n checksum_passed++;\n }\n\n bcount -= meta_bc;\n dp += meta_bc;\n }\n\n return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WavpackVerifySingleBlock", "_file_name": "src/open_utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n int max_index = -1;\n const int segment_id_size = segment_ids->dims->data[0];\n if (segment_id_size > 0) {\n max_index = segment_ids->data.i32[segment_id_size - 1];\n }\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;\n for (int i = 1; i < data_rank; ++i) {\n output_shape->data[i] = data->dims->data[i];\n }\n return context->ResizeTensor(context, output, output_shape);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[235, 257], [344, 408]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[235, 257], [344, 408]]}, "_func_name": "tflite::ops::builtin::segment_sum::ResizeOutputTensor", "_file_name": "tensorflow/lite/kernels/segment_sum.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def get_requested_month_for_inverter(self, inverter_serial, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, DayYield AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN %s AND %s AND Serial = %s\n '''\n\n data['data'] = list()\n for row in self.c.execute(query % (month_start, month_end, inverter_serial)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM MonthData \n WHERE Serial = %s;\n ''' % inverter_serial\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[444, 506], [553, 639], [942, 1007]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[444, 506], [553, 639], [942, 1007]]}, "_func_name": "get_requested_month_for_inverter", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n 'fakehost 123456789012345 123456789054321')\n create_host_ret = pack(CLI_CR +\n 'already used by host fakehost.foo (19)')\n _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, ''])\n\n show_3par_cmd = 'showhost -verbose fakehost.foo'\n _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[639, 716]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[639, 716]]}, "_func_name": "test_create_invalid_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpc_pi_nextcprl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->compno = pchg->compnostart, pi->picomp =\n\t &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,\n\t ++pi->picomp) {\n\t\tpirlvl = pi->picomp->pirlvls;\n\t\tpi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +\n\t\t pi->picomp->numrlvls - 1));\n\t\tpi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +\n\t\t pi->picomp->numrlvls - 1));\n\t\tfor (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];\n\t\t rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\tpi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<\n\t\t\t (pirlvl->prcwidthexpn + pi->picomp->numrlvls -\n\t\t\t rlvlno - 1)));\n\t\t\tpi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<\n\t\t\t (pirlvl->prcheightexpn + pi->picomp->numrlvls -\n\t\t\t rlvlno - 1)));\n\t\t}\n\t\tfor (pi->y = pi->ystart; pi->y < pi->yend;\n\t\t pi->y += pi->ystep - (pi->y % pi->ystep)) {\n\t\t\tfor (pi->x = pi->xstart; pi->x < pi->xend;\n\t\t\t pi->x += pi->xstep - (pi->x % pi->xstep)) {\n\t\t\t\tfor (pi->rlvlno = pchg->rlvlnostart,\n\t\t\t\t pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <\n\t\t\t\t pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\tif (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||\n\t\t\t\t\t !(pi->x % (pi->picomp->hsamp << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||\n\t\t\t\t\t !(pi->y % (pi->picomp->vsamp << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,\n\t\t\t\t\t\t pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,\n\t\t\t\t\t\t pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind *\n\t\t\t\t\t\t pi->pirlvl->numhprcs +\n\t\t\t\t\t\t prchind;\n\t\t\t\t\t\tassert(pi->prcno <\n\t\t\t\t\t\t pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno <\n\t\t\t\t\t\t pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[564, 757], [867, 1132]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[564, 757], [867, 1132]]}, "_func_name": "jpc_pi_nextcprl", "_file_name": "src/libjasper/jpc/jpc_t2cod.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void gps_tracker( void )\n{\n\tssize_t unused;\n int gpsd_sock;\n char line[256], *temp;\n struct sockaddr_in gpsd_addr;\n int ret, is_json, pos;\n fd_set read_fd;\n struct timeval timeout;\n\n /* attempt to connect to localhost, port 2947 */\n\n pos = 0;\n gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 );\n\n if( gpsd_sock < 0 ) {\n return;\n }\n\n gpsd_addr.sin_family = AF_INET;\n gpsd_addr.sin_port = htons( 2947 );\n gpsd_addr.sin_addr.s_addr = inet_addr( \"127.0.0.1\" );\n\n if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr,\n sizeof( gpsd_addr ) ) < 0 ) {\n return;\n }\n\n // Check if it's GPSd < 2.92 or the new one\n // 2.92+ immediately send stuff\n // < 2.92 requires to send PVTAD command\n FD_ZERO(&read_fd);\n FD_SET(gpsd_sock, &read_fd);\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout);\n if (is_json) {\n \t/*\n\t\t\t{\"class\":\"VERSION\",\"release\":\"2.95\",\"rev\":\"2010-11-16T21:12:35\",\"proto_major\":3,\"proto_minor\":3}\n\t\t\t?WATCH={\"json\":true};\n\t\t\t{\"class\":\"DEVICES\",\"devices\":[]}\n \t */\n\n\n \t// Get the crap and ignore it: {\"class\":\"VERSION\",\"release\":\"2.95\",\"rev\":\"2010-11-16T21:12:35\",\"proto_major\":3,\"proto_minor\":3}\n \tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n \t\treturn;\n\n \tis_json = (line[0] == '{');\n \tif (is_json) {\n\t\t\t// Send ?WATCH={\"json\":true};\n\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\tstrcpy(line, \"?WATCH={\\\"json\\\":true};\\n\");\n\t\t\tif( send( gpsd_sock, line, 22, 0 ) != 22 )\n\t\t\t\treturn;\n\n\t\t\t// Check that we have devices\n\t\t\tmemset(line, 0, sizeof(line));\n\t\t\tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n\t\t\t\treturn;\n\n\t\t\t// Stop processing if there is no device\n\t\t\tif (strncmp(line, \"{\\\"class\\\":\\\"DEVICES\\\",\\\"devices\\\":[]}\", 32) == 0) {\n\t\t\t\tclose(gpsd_sock);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tpos = strlen(line);\n\t\t\t}\n \t}\n }\n\n /* loop reading the GPS coordinates */\n\n while( G.do_exit == 0 )\n {\n usleep( 500000 );\n memset( G.gps_loc, 0, sizeof( float ) * 5 );\n\n /* read position, speed, heading, altitude */\n if (is_json) {\n \t// Format definition: http://catb.org/gpsd/gpsd_json.html\n\n \tif (pos == sizeof( line )) {\n \t\tmemset(line, 0, sizeof(line));\n \t\tpos = 0;\n \t}\n\n \t// New version, JSON\n \tif( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 )\n \t\treturn;\n\n \t// search for TPV class: {\"class\":\"TPV\"\n \ttemp = strstr(line, \"{\\\"class\\\":\\\"TPV\\\"\");\n \tif (temp == NULL) {\n \t\tcontinue;\n \t}\n\n \t// Make sure the data we have is complete\n \tif (strchr(temp, '}') == NULL) {\n \t\t// Move the data at the beginning of the buffer;\n \t\tpos = strlen(temp);\n \t\tif (temp != line) {\n \t\t\tmemmove(line, temp, pos);\n \t\t\tmemset(line + pos, 0, sizeof(line) - pos);\n \t\t}\n \t}\n\n\t\t\t// Example line: {\"class\":\"TPV\",\"tag\":\"MID2\",\"device\":\"/dev/ttyUSB0\",\"time\":1350957517.000,\"ept\":0.005,\"lat\":46.878936576,\"lon\":-115.832602964,\"alt\":1968.382,\"track\":0.0000,\"speed\":0.000,\"climb\":0.000,\"mode\":3}\n\n \t// Latitude\n \ttemp = strstr(temp, \"\\\"lat\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[0]);\n\n\t\t\t// Longitude\n\t\t\ttemp = strstr(temp, \"\\\"lon\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[1]);\n\n\t\t\t// Altitude\n\t\t\ttemp = strstr(temp, \"\\\"alt\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[4]);\n\n\t\t\t// Speed\n\t\t\ttemp = strstr(temp, \"\\\"speed\\\":\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret = sscanf(temp + 6, \"%f\", &G.gps_loc[2]);\n\n\t\t\t// No more heading\n\n\t\t\t// Get the next TPV class\n\t\t\ttemp = strstr(temp, \"{\\\"class\\\":\\\"TPV\\\"\");\n\t\t\tif (temp == NULL) {\n\t\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\t\tpos = 0;\n\t\t\t} else {\n\t\t\t\tpos = strlen(temp);\n\t\t\t\tmemmove(line, temp, pos);\n\t\t\t\tmemset(line + pos, 0, sizeof(line) - pos);\n\t\t\t}\n\n } else {\n \tmemset( line, 0, sizeof( line ) );\n\n\t\t\tsnprintf( line, sizeof( line ) - 1, \"PVTAD\\r\\n\" );\n\t\t\tif( send( gpsd_sock, line, 7, 0 ) != 7 )\n\t\t\t\treturn;\n\n\t\t\tmemset( line, 0, sizeof( line ) );\n\t\t\tif( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )\n\t\t\t\treturn;\n\n\t\t\tif( memcmp( line, \"GPSD,P=\", 7 ) != 0 )\n\t\t\t\tcontinue;\n\n\t\t\t/* make sure the coordinates are present */\n\n\t\t\tif( line[7] == '?' )\n\t\t\t\tcontinue;\n\n\t\t\tret = sscanf( line + 7, \"%f %f\", &G.gps_loc[0], &G.gps_loc[1] );\n\n\t\t\tif( ( temp = strstr( line, \"V=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[2] ); /* speed */\n\n\t\t\tif( ( temp = strstr( line, \"T=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[3] ); /* heading */\n\n\t\t\tif( ( temp = strstr( line, \"A=\" ) ) == NULL ) continue;\n\t\t\tret = sscanf( temp + 2, \"%f\", &G.gps_loc[4] ); /* altitude */\n }\n\n if (G.record_data)\n\t\t\tfputs( line, G.f_gps );\n\n\t\tG.save_gps = 1;\n\n if (G.do_exit == 0)\n\t\t{\n\t\t\tunused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 );\n\t\t\tkill( getppid(), SIGUSR2 );\n\t\t}\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "gps_tracker", "_file_name": "src/airodump-ng.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,\n\t\t enum CCSTATE* state, ScanEnv* env)\n{\n int r;\n\n if (*state == CCS_RANGE)\n return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;\n\n if (*state == CCS_VALUE && *type != CCV_CLASS) {\n if (*type == CCV_SB)\n BITSET_SET_BIT(cc->bs, (int )(*vs));\n else if (*type == CCV_CODE_POINT) {\n r = add_code_range(&(cc->mbuf), env, *vs, *vs);\n if (r < 0) return r;\n }\n }\n\n if (*state != CCS_START)\n *state = CCS_VALUE;\n\n *type = CCV_CLASS;\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "next_state_class", "_file_name": "src/regparse.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& val = ctx->input(0);\n auto session_state = ctx->session_state();\n OP_REQUIRES(ctx, session_state != nullptr,\n errors::FailedPrecondition(\n \"GetSessionHandle called on null session state\"));\n int64 id = session_state->GetNewId();\n TensorStore::TensorAndKey tk{val, id, requested_device()};\n OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(name(), tk));\n\n Tensor* handle = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));\n if (ctx->expected_output_dtype(0) == DT_RESOURCE) {\n ResourceHandle resource_handle = MakeResourceHandle(\n ctx, SessionState::kTensorHandleResourceTypeName,\n tk.GetHandle(name()));\n resource_handle.set_maybe_type_name(\n SessionState::kTensorHandleResourceTypeName);\n handle->scalar()() = resource_handle;\n } else {\n // Legacy behavior in V1.\n handle->flat().setConstant(tk.GetHandle(name()));\n }\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tensorflow::GetSessionHandleOp::Compute", "_file_name": "tensorflow/core/kernels/session_ops.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/players//achievements')\ndef achievements_list_player(player_id):\n \"\"\"Lists the progress of achievements for a player.\n\n :param player_id: ID of the player.\n\n :return:\n If successful, this method returns a response body with the following structure::\n\n {\n \"items\": [\n {\n \"achievement_id\": string,\n \"state\": string,\n \"current_steps\": integer,\n \"create_time\": long,\n \"update_time\": long\n }\n ]\n }\n \"\"\"\n with db.connection:\n cursor = db.connection.cursor(db.pymysql.cursors.DictCursor)\n cursor.execute(\"\"\"SELECT\n achievement_id,\n current_steps,\n state,\n UNIX_TIMESTAMP(create_time) as create_time,\n UNIX_TIMESTAMP(update_time) as update_time\n FROM player_achievements\n WHERE player_id = %s\"\"\", player_id)\n\n return flask.jsonify(items=cursor.fetchall())", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "achievements_list_player", "_file_name": "api/achievements.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def compare_and_update(user, message):\n \"\"\"\n This method compare a user object from the bot and his info from\n the Telegram message to check whether a user has changed his bio\n or not. If yes, the user object that represents him in the bot will\n be updated accordingly. Now this function is called only when a user\n asks the bot for showing the most popular cams\n\n :param user: user object that represents a Telegram user in this bot\n :param message: object from Telegram that contains info about user's\n message and about himself\n :return: None\n \"\"\"\n\n log.info('Checking whether user have changed his info or not...')\n msg = message.from_user\n usr_from_message = User(message.chat.id, msg.first_name, msg.username,\n msg.last_name)\n\n if user.chat_id != usr_from_message.chat_id:\n log.error(\"Wrong user to compare!\")\n return\n\n if user.first_name != usr_from_message.first_name:\n user.first_name = usr_from_message.first_name\n\n elif user.nickname != usr_from_message.nickname:\n user.nickname = usr_from_message.nickname\n\n elif user.last_name != usr_from_message.last_name:\n user.last_name = usr_from_message.last_name\n\n else:\n log.debug(\"User's info hasn't changed\")\n return\n\n log.info(\"User has changed his info\")\n log.debug(\"Updating user's info in the database...\")\n query = (f\"UPDATE users \"\n f\"SET first_name=%s, \"\n f\"nickname=%s, \"\n f\"last_name=%s \"\n f\"WHERE chat_id=%s\")\n\n parameters = (user.first_name, user.nickname, user.last_name,\n user.chat_id)\n\n try:\n db.add(query, parameters)\n except DatabaseError:\n log.error(\"Could not update info about %s in the database\",\n user)\n else:\n log.debug(\"User's info has been updated\")", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "compare_and_update", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/sloka')\ndef sloka():\n\n sloka_number = request.args.get('sloka_number')\n\n sloka_number_parts = sloka_number.split('.')\n\n sloka_number_previous = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])-1)\n sloka_number_next = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])+1)\n\n try:\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from mula where sloka_number = '%s' order by sloka_line;\" % sloka_number)\n mula = cur.fetchall();\n\n cur.execute(\"select * from pada where sloka_number = '%s' order by id;\" % sloka_number)\n pada = cur.fetchall();\n\n varga = \"\"\n if len(pada) > 0:\n varga = pada[0][\"varga\"]\n\n return render_template('sloka.html', mula=mula, pada=pada, varga=varga, sloka_number=sloka_number, sloka_number_previous=sloka_number_previous, sloka_number_next=sloka_number_next)\n finally:\n con.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[494, 602], [638, 738]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[494, 602], [638, 738]]}, "_func_name": "sloka", "_file_name": "docker/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int tcp_test(const char* ip_str, const short port)\n{\n int sock, i;\n struct sockaddr_in s_in;\n int packetsize = 1024;\n unsigned char packet[packetsize];\n struct timeval tv, tv2, tv3;\n int caplen = 0;\n int times[REQUESTS];\n int min, avg, max, len;\n struct net_hdr nh;\n\n tv3.tv_sec=0;\n tv3.tv_usec=1;\n\n s_in.sin_family = PF_INET;\n s_in.sin_port = htons(port);\n if (!inet_aton(ip_str, &s_in.sin_addr))\n return -1;\n\n if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)\n return -1;\n\n /* avoid blocking on reading the socket */\n if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )\n {\n perror( \"fcntl(O_NONBLOCK) failed\" );\n return( 1 );\n }\n\n gettimeofday( &tv, NULL );\n\n while (1) //waiting for relayed packet\n {\n if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)\n {\n if(errno != EINPROGRESS && errno != EALREADY)\n {\n perror(\"connect\");\n close(sock);\n\n printf(\"Failed to connect\\n\");\n\n return -1;\n }\n }\n else\n {\n gettimeofday( &tv2, NULL );\n break;\n }\n\n gettimeofday( &tv2, NULL );\n //wait 3000ms for a successful connect\n if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000))\n {\n printf(\"Connection timed out\\n\");\n close(sock);\n return(-1);\n }\n usleep(10);\n }\n\n PCT; printf(\"TCP connection successful\\n\");\n\n //trying to identify airserv-ng\n memset(&nh, 0, sizeof(nh));\n// command: GET_CHAN\n nh.nh_type\t= 2;\n nh.nh_len\t= htonl(0);\n\n if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))\n {\n perror(\"send\");\n return -1;\n }\n\n gettimeofday( &tv, NULL );\n i=0;\n\n while (1) //waiting for GET_CHAN answer\n {\n caplen = read(sock, &nh, sizeof(nh));\n\n if(caplen == -1)\n {\n if( errno != EAGAIN )\n {\n perror(\"read\");\n return -1;\n }\n }\n\n if( (unsigned)caplen == sizeof(nh))\n {\n len = ntohl(nh.nh_len);\n if (len > 1024 || len < 0)\n continue;\n if( nh.nh_type == 1 && i==0 )\n {\n i=1;\n caplen = read(sock, packet, len);\n if(caplen == len)\n {\n i=2;\n break;\n }\n else\n {\n i=0;\n }\n }\n else\n {\n caplen = read(sock, packet, len);\n }\n }\n\n gettimeofday( &tv2, NULL );\n //wait 1000ms for an answer\n if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))\n {\n break;\n }\n if(caplen == -1)\n usleep(10);\n }\n\n if(i==2)\n {\n PCT; printf(\"airserv-ng found\\n\");\n }\n else\n {\n PCT; printf(\"airserv-ng NOT found\\n\");\n }\n\n close(sock);\n\n for(i=0; i (1000*1000))\n {\n break;\n }\n //simple \"high-precision\" usleep\n select(1, NULL, NULL, NULL, &tv3);\n }\n times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec));\n printf( \"\\r%d/%d\\r\", i, REQUESTS);\n fflush(stdout);\n close(sock);\n }\n\n min = INT_MAX;\n avg = 0;\n max = 0;\n\n for(i=0; i max) max = times[i];\n avg += times[i];\n }\n avg /= REQUESTS;\n\n PCT; printf(\"ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\\n\", ip_str, port, min/1000.0, avg/1000.0, max/1000.0);\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tcp_test", "_file_name": "src/aireplay-ng.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,\n enum expr_value_type type, xkb_mod_mask_t *val_rtrn)\n{\n const char *str;\n xkb_mod_index_t ndx;\n const LookupModMaskPriv *arg = priv;\n const struct xkb_mod_set *mods = arg->mods;\n enum mod_type mod_type = arg->mod_type;\n\n if (type != EXPR_TYPE_INT)\n return false;\n\n str = xkb_atom_text(ctx, field);\n if (!str)\n return false;\n\n if (istreq(str, \"all\")) {\n *val_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n if (istreq(str, \"none\")) {\n *val_rtrn = 0;\n return true;\n }\n\n ndx = XkbModNameToIndex(mods, field, mod_type);\n if (ndx == XKB_MOD_INVALID)\n return false;\n\n *val_rtrn = (1u << ndx);\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "LookupModMask", "_file_name": "src/xkbcomp/expr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_bracket_graph_data(db, tag):\n # First, we have to find out which scenes this player has brackets in\n sql = \"SELECT DISTINCT scene FROM ranks WHERE player='{}'\".format(tag)\n scenes = db.exec(sql)\n scenes = [s[0] for s in scenes]\n\n bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes}\n\n return bracket_placings_by_scene", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[111, 186]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[111, 186]]}, "_func_name": "get_bracket_graph_data", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_max_task_id_for_project(project_id: int):\n \"\"\"Gets the nights task id currently in use on a project\"\"\"\n sql = \"\"\"select max(id) from tasks where project_id = :project_id GROUP BY project_id\"\"\"\n result = db.engine.execute(text(sql), project_id=project_id)\n if result.rowcount == 0:\n raise NotFound()\n for row in result:\n return row[0]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_max_task_id_for_project", "_file_name": "server/models/postgis/task.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ng_pkt(git_pkt **out, const char *line, size_t len)\n{\n\tgit_pkt_ng *pkt;\n\tconst char *ptr;\n\tsize_t alloclen;\n\n\tpkt = git__malloc(sizeof(*pkt));\n\tGITERR_CHECK_ALLOC(pkt);\n\n\tpkt->ref = NULL;\n\tpkt->type = GIT_PKT_NG;\n\n\tif (len < 3)\n\t\tgoto out_err;\n\tline += 3; /* skip \"ng \" */\n\tlen -= 3;\n\tif (!(ptr = memchr(line, ' ', len)))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->ref = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->ref);\n\n\tmemcpy(pkt->ref, line, len);\n\tpkt->ref[len] = '\\0';\n\n\tif (len < 1)\n\t\tgoto out_err;\n\tline = ptr + 1;\n\tlen -= 1;\n\tif (!(ptr = memchr(line, '\\n', len)))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->msg = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->msg);\n\n\tmemcpy(pkt->msg, line, len);\n\tpkt->msg[len] = '\\0';\n\n\t*out = (git_pkt *)pkt;\n\treturn 0;\n\nout_err:\n\tgiterr_set(GITERR_NET, \"invalid packet line\");\n\tgit__free(pkt->ref);\n\tgit__free(pkt);\n\treturn -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ng_pkt", "_file_name": "src/transports/smart_pkt.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def index(request, is_mobile=False):\n hue_collections = DashboardController(request.user).get_search_collections()\n collection_id = request.GET.get('collection')\n\n if not hue_collections or not collection_id:\n return admin_collections(request, True, is_mobile)\n\n try:\n collection_doc = Document2.objects.get(id=collection_id)\n if USE_NEW_EDITOR.get():\n collection_doc.can_read_or_exception(request.user)\n else:\n collection_doc.doc.get().can_read_or_exception(request.user)\n collection = Collection2(request.user, document=collection_doc)\n except Exception, e:\n raise PopupException(e, title=_(\"Dashboard does not exist or you don't have the permission to access it.\"))\n\n query = {'qs': [{'q': ''}], 'fqs': [], 'start': 0}\n\n if request.method == 'GET':\n if 'q' in request.GET:\n query['qs'][0]['q'] = request.GET.get('q')\n if 'qd' in request.GET:\n query['qd'] = request.GET.get('qd')\n\n template = 'search.mako'\n if is_mobile:\n template = 'search_m.mako'\n\n return render(template, request, {\n 'collection': collection,\n 'query': json.dumps(query),\n 'initial': json.dumps({\n 'collections': [],\n 'layout': DEFAULT_LAYOUT,\n 'is_latest': LATEST.get(),\n 'engines': get_engines(request.user)\n }),\n 'is_owner': collection_doc.doc.get().can_write(request.user),\n 'can_edit_index': can_edit_index(request.user),\n 'is_embeddable': request.GET.get('is_embeddable', False),\n 'mobile': is_mobile,\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[814, 863], [891, 933], [1285, 1351]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[814, 863], [891, 933], [1285, 1351]]}, "_func_name": "index", "_file_name": "desktop/libs/dashboard/src/dashboard/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_fc_wwpns(self):\n for key in self._storage_nodes:\n node = self._storage_nodes[key]\n ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']]\n raw = self._run_ssh(ssh_cmd)\n resp = CLIResponse(raw, delim='!', with_header=False)\n wwpns = set(node['WWPN'])\n for i, s in resp.select('port_id', 'port_status'):\n if 'unconfigured' != s:\n wwpns.add(i)\n node['WWPN'] = list(wwpns)\n LOG.info(_('WWPN on node %(node)s: %(wwpn)s')\n % {'node': node['id'], 'wwpn': node['WWPN']})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_fc_wwpns", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ape_decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame_ptr, AVPacket *avpkt)\n{\n AVFrame *frame = data;\n const uint8_t *buf = avpkt->data;\n APEContext *s = avctx->priv_data;\n uint8_t *sample8;\n int16_t *sample16;\n int32_t *sample24;\n int i, ch, ret;\n int blockstodecode;\n uint64_t decoded_buffer_size;\n\n /* this should never be negative, but bad things will happen if it is, so\n check it just to make sure. */\n av_assert0(s->samples >= 0);\n\n if(!s->samples){\n uint32_t nblocks, offset;\n int buf_size;\n\n if (!avpkt->size) {\n *got_frame_ptr = 0;\n return 0;\n }\n if (avpkt->size < 8) {\n av_log(avctx, AV_LOG_ERROR, \"Packet is too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n buf_size = avpkt->size & ~3;\n if (buf_size != avpkt->size) {\n av_log(avctx, AV_LOG_WARNING, \"packet size is not a multiple of 4. \"\n \"extra bytes at the end will be skipped.\\n\");\n }\n if (s->fileversion < 3950) // previous versions overread two bytes\n buf_size += 2;\n av_fast_padded_malloc(&s->data, &s->data_size, buf_size);\n if (!s->data)\n return AVERROR(ENOMEM);\n s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,\n buf_size >> 2);\n memset(s->data + (buf_size & ~3), 0, buf_size & 3);\n s->ptr = s->data;\n s->data_end = s->data + buf_size;\n\n nblocks = bytestream_get_be32(&s->ptr);\n offset = bytestream_get_be32(&s->ptr);\n if (s->fileversion >= 3900) {\n if (offset > 3) {\n av_log(avctx, AV_LOG_ERROR, \"Incorrect offset passed\\n\");\n s->data = NULL;\n return AVERROR_INVALIDDATA;\n }\n if (s->data_end - s->ptr < offset) {\n av_log(avctx, AV_LOG_ERROR, \"Packet is too small\\n\");\n return AVERROR_INVALIDDATA;\n }\n s->ptr += offset;\n } else {\n if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)\n return ret;\n if (s->fileversion > 3800)\n skip_bits_long(&s->gb, offset * 8);\n else\n skip_bits_long(&s->gb, offset);\n }\n\n if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {\n av_log(avctx, AV_LOG_ERROR, \"Invalid sample count: %\"PRIu32\".\\n\",\n nblocks);\n return AVERROR_INVALIDDATA;\n }\n\n /* Initialize the frame decoder */\n if (init_frame_decoder(s) < 0) {\n av_log(avctx, AV_LOG_ERROR, \"Error reading frame header\\n\");\n return AVERROR_INVALIDDATA;\n }\n s->samples = nblocks;\n }\n\n if (!s->data) {\n *got_frame_ptr = 0;\n return avpkt->size;\n }\n\n blockstodecode = FFMIN(s->blocks_per_loop, s->samples);\n // for old files coefficients were not interleaved,\n // so we need to decode all of them at once\n if (s->fileversion < 3930)\n blockstodecode = s->samples;\n\n /* reallocate decoded sample buffer if needed */\n decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);\n av_assert0(decoded_buffer_size <= INT_MAX);\n av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);\n if (!s->decoded_buffer)\n return AVERROR(ENOMEM);\n memset(s->decoded_buffer, 0, s->decoded_size);\n s->decoded[0] = s->decoded_buffer;\n s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);\n\n /* get output buffer */\n frame->nb_samples = blockstodecode;\n if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)\n return ret;\n\n s->error=0;\n\n if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))\n ape_unpack_mono(s, blockstodecode);\n else\n ape_unpack_stereo(s, blockstodecode);\n emms_c();\n\n if (s->error) {\n s->samples=0;\n av_log(avctx, AV_LOG_ERROR, \"Error decoding frame\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n switch (s->bps) {\n case 8:\n for (ch = 0; ch < s->channels; ch++) {\n sample8 = (uint8_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;\n }\n break;\n case 16:\n for (ch = 0; ch < s->channels; ch++) {\n sample16 = (int16_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample16++ = s->decoded[ch][i];\n }\n break;\n case 24:\n for (ch = 0; ch < s->channels; ch++) {\n sample24 = (int32_t *)frame->data[ch];\n for (i = 0; i < blockstodecode; i++)\n *sample24++ = s->decoded[ch][i] << 8;\n }\n break;\n }\n\n s->samples -= blockstodecode;\n\n *got_frame_ptr = 1;\n\n return !s->samples ? avpkt->size : 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ape_decode_frame", "_file_name": "libavcodec/apedec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_language(self, language):\n \"\"\"\"Add new language for item translations.\"\"\"\n if self.connection:\n t = (language[0], )\n self.cursor.execute('insert into itemlanguage (language) values (?)', t)\n self.connection.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_language", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,\n AVStream *st, char *mime)\n{\n int number_of_streams = avio_rb16(pb);\n int number_of_mdpr;\n int i, ret;\n unsigned size2;\n for (i = 0; i 0) {\n st2 = avformat_new_stream(s, NULL);\n if (!st2) {\n ret = AVERROR(ENOMEM);\n return ret;\n }\n st2->id = st->id + (i<<16);\n st2->codecpar->bit_rate = st->codecpar->bit_rate;\n st2->start_time = st->start_time;\n st2->duration = st->duration;\n st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;\n st2->priv_data = ff_rm_alloc_rmstream();\n if (!st2->priv_data)\n return AVERROR(ENOMEM);\n } else\n st2 = st;\n\n size2 = avio_rb32(pb);\n ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,\n size2, mime);\n if (ret < 0)\n return ret;\n }\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1195, 1249]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1195, 1249]]}, "_func_name": "rm_read_multi", "_file_name": "libavformat/rmdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "decode_bundle(bool load, const struct nx_action_bundle *nab,\n const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,\n struct ofpbuf *ofpacts)\n{\n static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);\n struct ofpact_bundle *bundle;\n uint32_t slave_type;\n size_t slaves_size, i;\n enum ofperr error;\n\n bundle = ofpact_put_BUNDLE(ofpacts);\n\n bundle->n_slaves = ntohs(nab->n_slaves);\n bundle->basis = ntohs(nab->basis);\n bundle->fields = ntohs(nab->fields);\n bundle->algorithm = ntohs(nab->algorithm);\n slave_type = ntohl(nab->slave_type);\n slaves_size = ntohs(nab->len) - sizeof *nab;\n\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n if (!flow_hash_fields_valid(bundle->fields)) {\n VLOG_WARN_RL(&rl, \"unsupported fields %d\", (int) bundle->fields);\n } else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {\n VLOG_WARN_RL(&rl, \"too many slaves\");\n } else if (bundle->algorithm != NX_BD_ALG_HRW\n && bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {\n VLOG_WARN_RL(&rl, \"unsupported algorithm %d\", (int) bundle->algorithm);\n } else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {\n VLOG_WARN_RL(&rl, \"unsupported slave type %\"PRIu16, slave_type);\n } else {\n error = 0;\n }\n\n if (!is_all_zeros(nab->zero, sizeof nab->zero)) {\n VLOG_WARN_RL(&rl, \"reserved field is nonzero\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n\n if (load) {\n bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);\n bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);\n error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,\n &bundle->dst.field, tlv_bitmap);\n if (error) {\n return error;\n }\n\n if (bundle->dst.n_bits < 16) {\n VLOG_WARN_RL(&rl, \"bundle_load action requires at least 16 bit \"\n \"destination.\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n } else {\n if (nab->ofs_nbits || nab->dst) {\n VLOG_WARN_RL(&rl, \"bundle action has nonzero reserved fields\");\n error = OFPERR_OFPBAC_BAD_ARGUMENT;\n }\n }\n\n if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {\n VLOG_WARN_RL(&rl, \"Nicira action %s only has %\"PRIuSIZE\" bytes \"\n \"allocated for slaves. %\"PRIuSIZE\" bytes are required \"\n \"for %\"PRIu16\" slaves.\",\n load ? \"bundle_load\" : \"bundle\", slaves_size,\n bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);\n error = OFPERR_OFPBAC_BAD_LEN;\n }\n\n for (i = 0; i < bundle->n_slaves; i++) {\n ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));\n ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);\n bundle = ofpacts->header;\n }\n\n ofpact_finish_BUNDLE(ofpacts, &bundle);\n if (!error) {\n error = bundle_check(bundle, OFPP_MAX, NULL);\n }\n return error;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2651, 2657]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2651, 2657]]}, "_func_name": "decode_bundle", "_file_name": "lib/ofp-actions.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "IRC_PROTOCOL_CALLBACK(352)\n{\n char *pos_attr, *pos_hopcount, *pos_realname, *str_host;\n int arg_start, length;\n struct t_irc_channel *ptr_channel;\n struct t_irc_nick *ptr_nick;\n\n IRC_PROTOCOL_MIN_ARGS(5);\n\n /* silently ignore malformed 352 message (missing infos) */\n if (argc < 8)\n return WEECHAT_RC_OK;\n\n pos_attr = NULL;\n pos_hopcount = NULL;\n pos_realname = NULL;\n\n if (argc > 8)\n {\n arg_start = (strcmp (argv[8], \"*\") == 0) ? 9 : 8;\n if (argv[arg_start][0] == ':')\n {\n pos_attr = NULL;\n pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;\n pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;\n }\n else\n {\n pos_attr = argv[arg_start];\n pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;\n pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;\n }\n }\n\n ptr_channel = irc_channel_search (server, argv[3]);\n ptr_nick = (ptr_channel) ?\n irc_nick_search (server, ptr_channel, argv[7]) : NULL;\n\n /* update host in nick */\n if (ptr_nick)\n {\n length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;\n str_host = malloc (length);\n if (str_host)\n {\n snprintf (str_host, length, \"%s@%s\", argv[4], argv[5]);\n irc_nick_set_host (ptr_nick, str_host);\n free (str_host);\n }\n }\n\n /* update away flag in nick */\n if (ptr_channel && ptr_nick && pos_attr)\n {\n irc_nick_set_away (server, ptr_channel, ptr_nick,\n (pos_attr[0] == 'G') ? 1 : 0);\n }\n\n /* update realname in nick */\n if (ptr_channel && ptr_nick && pos_realname)\n {\n if (ptr_nick->realname)\n free (ptr_nick->realname);\n if (pos_realname &&\n weechat_hashtable_has_key (server->cap_list, \"extended-join\"))\n {\n ptr_nick->realname = strdup (pos_realname);\n }\n else\n {\n ptr_nick->realname = NULL;\n }\n }\n\n /* display output of who (manual who from user) */\n if (!ptr_channel || (ptr_channel->checking_whox <= 0))\n {\n weechat_printf_date_tags (\n irc_msgbuffer_get_target_buffer (\n server, NULL, command, \"who\", NULL),\n date,\n irc_protocol_tags (command, \"irc_numeric\", NULL, NULL),\n \"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)\",\n weechat_prefix (\"network\"),\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_CHAT_CHANNEL,\n argv[3],\n IRC_COLOR_CHAT_DELIMITERS,\n irc_nick_color_for_msg (server, 1, NULL, argv[7]),\n argv[7],\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_CHAT_HOST,\n argv[4],\n argv[5],\n IRC_COLOR_CHAT_DELIMITERS,\n IRC_COLOR_RESET,\n (pos_attr) ? pos_attr : \"\",\n (pos_attr) ? \" \" : \"\",\n (pos_hopcount) ? pos_hopcount : \"\",\n (pos_hopcount) ? \" \" : \"\",\n (pos_realname) ? pos_realname : \"\");\n }\n\n return WEECHAT_RC_OK;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[430, 488]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[430, 488]]}, "_func_name": "IRC_PROTOCOL_CALLBACK", "_file_name": "src/plugins/irc/irc-protocol.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,\n\t int* vs_israw, int v_israw,\n\t enum CCVALTYPE intype, enum CCVALTYPE* type,\n\t enum CCSTATE* state, ScanEnv* env)\n{\n int r;\n\n switch (*state) {\n case CCS_VALUE:\n if (*type == CCV_SB) {\n if (*vs > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n BITSET_SET_BIT(cc->bs, (int )(*vs));\n }\n else if (*type == CCV_CODE_POINT) {\n r = add_code_range(&(cc->mbuf), env, *vs, *vs);\n if (r < 0) return r;\n }\n break;\n\n case CCS_RANGE:\n if (intype == *type) {\n if (intype == CCV_SB) {\n if (*vs > 0xff || v > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )v);\n }\n else {\n r = add_code_range(&(cc->mbuf), env, *vs, v);\n if (r < 0) return r;\n }\n }\n else {\n#if 0\n if (intype == CCV_CODE_POINT && *type == CCV_SB) {\n#endif\n if (*vs > v) {\n if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))\n goto ccs_range_end;\n else\n return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;\n }\n bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));\n r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);\n if (r < 0) return r;\n#if 0\n }\n else\n return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;\n#endif\n }\n ccs_range_end:\n *state = CCS_COMPLETE;\n break;\n\n case CCS_COMPLETE:\n case CCS_START:\n *state = CCS_VALUE;\n break;\n\n default:\n break;\n }\n\n *vs_israw = v_israw;\n *vs = v;\n *type = intype;\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "next_state_val", "_file_name": "src/regparse.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n header[MagickPathExtent];\n\n const char\n *property;\n\n MagickBooleanType\n status;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n pixel[4],\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n if (IsRGBColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,RGBColorspace,exception);\n /*\n Write header.\n */\n (void) ResetMagickMemory(header,' ',MagickPathExtent);\n length=CopyMagickString(header,\"#?RGBE\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n property=GetImageProperty(image,\"comment\",exception);\n if ((property != (const char *) NULL) &&\n (strchr(property,'\\n') == (char *) NULL))\n {\n count=FormatLocaleString(header,MagickPathExtent,\"#%s\\n\",property);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n property=GetImageProperty(image,\"hdr:exposure\",exception);\n if (property != (const char *) NULL)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"EXPOSURE=%g\\n\",\n strtod(property,(char **) NULL));\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n if (image->gamma != 0.0)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"GAMMA=%g\\n\",image->gamma);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n count=FormatLocaleString(header,MagickPathExtent,\n \"PRIMARIES=%g %g %g %g %g %g %g %g\\n\",\n image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,\n image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,\n image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,\n image->chromaticity.white_point.x,image->chromaticity.white_point.y);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n length=CopyMagickString(header,\"FORMAT=32-bit_rle_rgbe\\n\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n count=FormatLocaleString(header,MagickPathExtent,\"-Y %.20g +X %.20g\\n\",\n (double) image->rows,(double) image->columns);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n /*\n Write HDR pixels.\n */\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*\n sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixel[0]=2;\n pixel[1]=2;\n pixel[2]=(unsigned char) (image->columns >> 8);\n pixel[3]=(unsigned char) (image->columns & 0xff);\n count=WriteBlob(image,4*sizeof(*pixel),pixel);\n if (count != (ssize_t) (4*sizeof(*pixel)))\n break;\n }\n i=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;\n\n pixel[0]=0;\n pixel[1]=0;\n pixel[2]=0;\n pixel[3]=0;\n gamma=QuantumScale*GetPixelRed(image,p);\n if ((QuantumScale*GetPixelGreen(image,p)) > gamma)\n gamma=QuantumScale*GetPixelGreen(image,p);\n if ((QuantumScale*GetPixelBlue(image,p)) > gamma)\n gamma=QuantumScale*GetPixelBlue(image,p);\n if (gamma > MagickEpsilon)\n {\n int\n exponent;\n\n gamma=frexp(gamma,&exponent)*256.0/gamma;\n pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));\n pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));\n pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));\n pixel[3]=(unsigned char) (exponent+128);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixels[x]=pixel[0];\n pixels[x+image->columns]=pixel[1];\n pixels[x+2*image->columns]=pixel[2];\n pixels[x+3*image->columns]=pixel[3];\n }\n else\n {\n pixels[i++]=pixel[0];\n pixels[i++]=pixel[1];\n pixels[i++]=pixel[2];\n pixels[i++]=pixel[3];\n }\n p+=GetPixelChannels(image);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n for (i=0; i < 4; i++)\n length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);\n }\n else\n {\n count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);\n if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))\n break;\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n (void) CloseBlob(image);\n return(MagickTrue);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1901, 1984], [2886, 2952]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1901, 1984], [2886, 2952]]}, "_func_name": "WriteHDRImage", "_file_name": "coders/hdr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/sloka')\ndef sloka():\n\n sloka_number = request.args.get('sloka_number')\n\n sloka_number_parts = sloka_number.split('.')\n\n sloka_number_previous = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])-1)\n sloka_number_next = \"%s.%s.%d\" % (sloka_number_parts[0], sloka_number_parts[1], int(sloka_number_parts[2])+1)\n\n try:\n with sql.connect('amara.db') as con:\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"select * from mula where sloka_number = ? order by sloka_line;\", [sloka_number])\n mula = cur.fetchall();\n\n cur.execute(\"select * from pada where sloka_number = ? order by id;\", [sloka_number])\n pada = cur.fetchall();\n\n varga = \"\"\n if len(pada) > 0:\n varga = pada[0][\"varga\"]\n\n return render_template('sloka.html', mula=mula, pada=pada, varga=varga, sloka_number=sloka_number, sloka_number_previous=sloka_number_previous, sloka_number_next=sloka_number_next)\n finally:\n con.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "sloka", "_file_name": "docker/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def create_cf_base():\n url = 'http://codeforces.com/problemset/'\n r = requests.get(url)\n max_page = 0\n soup = BeautifulSoup(r.text, \"lxml\")\n base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\cf.db\")\n conn = base.cursor()\n conn.execute(\"create table problems (problem INTEGER, diff CHAR)\")\n for i in available_tags:\n conn.execute(\"create table ? (problems INTEGER, diff CHAR)\", (i,))\n\n for link in soup.find_all(attrs={\"class\" : \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[3]))\n\n a = 0\n b = 0\n f = False\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n old = ''\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5 and old != s[3] + s[4]:\n a = s[3]\n b = s[4]\n old = s[3] + s[4]\n if not f:\n f = True\n last_update = old\n conn.execute(\"insert into problems values (?, ?)\", (a, b))\n if len(s) == 4 and s[3] in available_tags:\n conn.execute(\"insert into ? values (?, ?)\", (s[3], a, b))\n\n base.commit()\n base.close()\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)\")\n conn.execute(\"create table last_update_problemset (problem STRING)\")\n conn.execute(\"insert into last_update_problemset values (?)\", (last_update, ))\n settings.commit()\n settings.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_cf_base", "_file_name": "bases/createcfbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route(\"//edit\")\ndef edit_page(page_name):\n query = db.query(\"select * from page where title = '%s'\" % page_name).namedresult()\n if len(query) == 0:\n return render_template(\n \"edit.html\",\n page_name=page_name,\n query=query\n )\n else:\n return render_template(\n \"edit.html\",\n page_name=page_name,\n query=query[0]\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[58, 146]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[58, 146]]}, "_func_name": "edit_page", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {\n\tint name_end = -1;\n\tint j = *idx;\n\tint ptr_count = 0;\n#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)\n#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)\n#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)\n\n\tchar *cp = name_out;\n\tconst char *const end = name_out + name_out_len;\n\n\t/* Normally, names are a series of length prefixed strings terminated */\n\t/* with a length of 0 (the lengths are u8's < 63). */\n\t/* However, the length can start with a pair of 1 bits and that */\n\t/* means that the next 14 bits are a pointer within the current */\n\t/* packet. */\n\n\tfor (;;) {\n\t\tu8 label_len;\n\t\tif (j >= length) return -1;\n\t\tGET8(label_len);\n\t\tif (!label_len) break;\n\t\tif (label_len & 0xc0) {\n\t\t\tu8 ptr_low;\n\t\t\tGET8(ptr_low);\n\t\t\tif (name_end < 0) name_end = j;\n\t\t\tj = (((int)label_len & 0x3f) << 8) + ptr_low;\n\t\t\t/* Make sure that the target offset is in-bounds. */\n\t\t\tif (j < 0 || j >= length) return -1;\n\t\t\t/* If we've jumped more times than there are characters in the\n\t\t\t * message, we must have a loop. */\n\t\t\tif (++ptr_count > length) return -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (label_len > 63) return -1;\n\t\tif (cp != name_out) {\n\t\t\tif (cp + 1 >= end) return -1;\n\t\t\t*cp++ = '.';\n\t\t}\n\t\tif (cp + label_len >= end) return -1;\n\t\tmemcpy(cp, packet + j, label_len);\n\t\tcp += label_len;\n\t\tj += label_len;\n\t}\n\tif (cp >= end) return -1;\n\t*cp = '\\0';\n\tif (name_end < 0)\n\t\t*idx = j;\n\telse\n\t\t*idx = name_end;\n\treturn 0;\n err:\n\treturn -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[830, 879]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[830, 879]]}, "_func_name": "name_parse", "_file_name": "evdns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def getSeriesDateFromDatabase(submission):\n database = sqlite3.connect('database.db')\n cursor = database.cursor()\n return cursor.execute(\"SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?\", [getTitle(submission)]).fetchone()[0]\n database.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getSeriesDateFromDatabase", "_file_name": "CheckAndPostForSeriesSubmissions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def git_hook(strict=False, modify=False):\n \"\"\"\n Git pre-commit hook to check staged files for isort errors\n\n :param bool strict - if True, return number of errors on exit,\n causing the hook to fail. If False, return zero so it will\n just act as a warning.\n :param bool modify - if True, fix the sources if they are not\n sorted properly. If False, only report result without\n modifying anything.\n\n :return number of errors if in strict mode, 0 otherwise.\n \"\"\"\n\n # Get list of files modified and staged\n diff_cmd = [\"git\", \"diff-index\", \"--cached\", \"--name-only\", \"--diff-filter=ACMRTUXB HEAD\"]\n files_modified = get_lines(diff_cmd)\n\n errors = 0\n for filename in files_modified:\n if filename.endswith('.py'):\n # Get the staged contents of the file\n staged_cmd = [\"git\", \"show\", \":%s\" % filename]\n staged_contents = get_output(staged_cmd)\n\n sort = SortImports(\n file_path=filename,\n file_contents=staged_contents,\n check=True\n )\n\n if sort.incorrectly_sorted:\n errors += 1\n if modify:\n SortImports(\n file_path=filename,\n file_contents=staged_contents,\n check=False,\n )\n\n return errors if strict else 0", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "git_hook", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n{\n\tBYTE* newBitMask;\n\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */\n\tStream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */\n\tStream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */\n\n\tif ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))\n\t{\n\t\tWLog_ERR(TAG, \"invalid bpp value %\" PRIu32 \"\", iconInfo->bpp);\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */\n\n\t/* cbColorTable is only present when bpp is 1, 4 or 8 */\n\tswitch (iconInfo->bpp)\n\t{\n\t\tcase 1:\n\t\tcase 4:\n\t\tcase 8:\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t\treturn FALSE;\n\n\t\t\tStream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\ticonInfo->cbColorTable = 0;\n\t\t\tbreak;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 4)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */\n\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n\t\treturn FALSE;\n\n\t/* bitsMask */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsMask);\n\t\ticonInfo->bitsMask = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsMask = newBitMask;\n\tStream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\t/* colorTable */\n\tif (iconInfo->colorTable == NULL)\n\t{\n\t\tif (iconInfo->cbColorTable)\n\t\t{\n\t\t\ticonInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);\n\n\t\t\tif (!iconInfo->colorTable)\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\telse if (iconInfo->cbColorTable)\n\t{\n\t\tBYTE* new_tab;\n\t\tnew_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);\n\n\t\tif (!new_tab)\n\t\t{\n\t\t\tfree(iconInfo->colorTable);\n\t\t\ticonInfo->colorTable = NULL;\n\t\t\treturn FALSE;\n\t\t}\n\n\t\ticonInfo->colorTable = new_tab;\n\t}\n\telse\n\t{\n\t\tfree(iconInfo->colorTable);\n\t\ticonInfo->colorTable = NULL;\n\t}\n\n\tif (iconInfo->colorTable)\n\t\tStream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);\n\n\t/* bitsColor */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsColor);\n\t\ticonInfo->bitsColor = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsColor = newBitMask;\n\tStream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);\n\treturn TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1148, 1263]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1148, 1263]]}, "_func_name": "update_read_icon_info", "_file_name": "libfreerdp/core/window.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def extend_volume(self, volume, new_size):\n volume_name = self._get_3par_vol_name(volume['id'])\n old_size = volume.size\n growth_size = int(new_size) - old_size\n LOG.debug(\"Extending Volume %s from %s to %s, by %s GB.\" %\n (volume_name, old_size, new_size, growth_size))\n try:\n self._cli_run(\"growvv -f %s %sg\" % (volume_name, growth_size),\n None)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error extending volume %s\") % volume)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[331, 438]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[331, 438]]}, "_func_name": "extend_volume", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def process_vote(target,action,chan,mask,db,notice,conn):\n if ' ' in target: \n notice('Invalid nick')\n return\n\n try: votes2kick = database.get(db,'channels','votekick','chan',chan)\n except: votes2kick = 10\n try: votes2ban = database.get(db,'channels','voteban','chan',chan)\n except: votes2ban = 10\n\n if len(target) is 0:\n if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick))\n elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban))\n return\n\n votefinished = False\n global db_ready\n if not db_ready: db_init(db)\n chan = chan.lower()\n target = target.lower()\n voter = user.format_hostmask(mask)\n voters = db.execute(\"SELECT voters FROM votes where chan='{}' and action='{}' and target like '{}'\".format(chan,action,target)).fetchone()\n\n if conn.nick.lower() in target: return \"I dont think so Tim.\"\n\n if voters: \n voters = voters[0]\n if voter in voters: \n notice(\"You have already voted.\")\n return\n else:\n voters = '{} {}'.format(voters,voter).strip()\n notice(\"Thank you for your vote!\")\n else: \n voters = voter\n\n votecount = len(voters.split(' '))\n\n if 'kick' in action: \n votemax = int(votes2kick)\n if votecount >= votemax:\n votefinished = True\n conn.send(\"KICK {} {} :{}\".format(chan, target, \"You have been voted off the island.\"))\n if 'ban' in action:\n votemax = int(votes2ban)\n if votecount >= votemax:\n votefinished = True\n conn.send(\"MODE {} +b {}\".format(chan, user.get_hostmask(target,db)))\n conn.send(\"KICK {} {} :\".format(chan, target, \"You have been voted off the island.\"))\n \n if votefinished: db.execute(\"DELETE FROM votes where chan='{}' and action='{}' and target like '{}'\".format(chan,action,target))\n else: db.execute(\"insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)\", (chan, action, target, voters, time.time()))\n \n db.commit()\n return (\"Votes to {} {}: {}/{}\".format(action, target, votecount,votemax))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[707, 850], [1781, 1914]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[707, 850], [1781, 1914]]}, "_func_name": "process_vote", "_file_name": "plugins/vote.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_game_info(conn, game):\n # get the basic game properties\n cursor = conn.cursor()\n cursor.execute(\"SELECT player1,player2,size,state FROM games WHERE id = %d;\" % game)\n if cursor.rowcount != 1:\n raise FormError(\"Invalid game ID\")\n\n row = cursor.fetchall()[0]\n players = [row[0],row[1]]\n size = row[2]\n state = row[3]\n\n if state is None:\n state = \"Active\"\n\n cursor.close()\n\n return (players,size,state)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[94, 183]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[94, 183]]}, "_func_name": "get_game_info", "_file_name": "cgi/common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "generatePreview (const char inFileName[],\n\t\t float exposure,\n\t\t int previewWidth,\n\t\t int &previewHeight,\n\t\t Array2D &previewPixels)\n{\n //\n // Read the input file\n //\n\n RgbaInputFile in (inFileName);\n\n Box2i dw = in.dataWindow();\n float a = in.pixelAspectRatio();\n int w = dw.max.x - dw.min.x + 1;\n int h = dw.max.y - dw.min.y + 1;\n\n Array2D pixels (h, w);\n in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);\n in.readPixels (dw.min.y, dw.max.y);\n\n //\n // Make a preview image\n //\n\n previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);\n previewPixels.resizeErase (previewHeight, previewWidth);\n\n float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;\n float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;\n float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));\n\n for (int y = 0; y < previewHeight; ++y)\n {\n\tfor (int x = 0; x < previewWidth; ++x)\n\t{\n\t PreviewRgba &preview = previewPixels[y][x];\n\t const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];\n\n\t preview.r = gamma (pixel.r, m);\n\t preview.g = gamma (pixel.g, m);\n\t preview.b = gamma (pixel.b, m);\n\t preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);\n\t}\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[689, 845]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[689, 845]]}, "_func_name": "generatePreview", "_file_name": "OpenEXR/exrmakepreview/makePreview.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def get(self, key):\n try:\n result = self.etcd.get(self._absolute_key(key))\n except etcd.EtcdException as err:\n log_error(\"Error fetching key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to get key')\n return result.value", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@frappe.whitelist(allow_guest=True)\ndef send_message(subject=\"Website Query\", message=\"\", sender=\"\", status=\"Open\"):\n\tfrom frappe.www.contact import send_message as website_send_message\n\tlead = customer = None\n\n\twebsite_send_message(subject, message, sender)\n\n\tcustomer = frappe.db.sql(\"\"\"select distinct dl.link_name from `tabDynamic Link` dl\n\t\tleft join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'\n\t\tand c.email_id = %s\"\"\", sender)\n\n\tif not customer:\n\t\tlead = frappe.db.get_value('Lead', dict(email_id=sender))\n\t\tif not lead:\n\t\t\tnew_lead = frappe.get_doc(dict(\n\t\t\t\tdoctype='Lead',\n\t\t\t\temail_id = sender,\n\t\t\t\tlead_name = sender.split('@')[0].title()\n\t\t\t)).insert(ignore_permissions=True)\n\n\topportunity = frappe.get_doc(dict(\n\t\tdoctype ='Opportunity',\n\t\tenquiry_from = 'Customer' if customer else 'Lead',\n\t\tstatus = 'Open',\n\t\ttitle = subject,\n\t\tcontact_email = sender,\n\t\tto_discuss = message\n\t))\n\n\tif customer:\n\t\topportunity.customer = customer[0][0]\n\telif lead:\n\t\topportunity.lead = lead\n\telse:\n\t\topportunity.lead = new_lead.name\n\n\topportunity.insert(ignore_permissions=True)\n\n\tcomm = frappe.get_doc({\n\t\t\"doctype\":\"Communication\",\n\t\t\"subject\": subject,\n\t\t\"content\": message,\n\t\t\"sender\": sender,\n\t\t\"sent_or_received\": \"Received\",\n\t\t'reference_doctype': 'Opportunity',\n\t\t'reference_name': opportunity.name\n\t})\n\tcomm.insert(ignore_permissions=True)\n\n\treturn \"okay\"", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "send_message", "_file_name": "erpnext/templates/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def addKey(client):\n\t\"\"\"Adds a new key with the specified name and contents.\n\tReturns an error if a key with the specified name already exists.\n\t\"\"\"\n\tglobal BAD_REQUEST\n\tglobal CREATED\n\n\tvalidateClient(client)\n\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateNewKeyData(token_data)\n\n\t# Use 'x' flag so we can throw an error if a key with this name already exists\n\ttry:\n\t\twith open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f:\n\t\t\tf.write(token_data['key'])\n\texcept FileExistsError:\n\t\traise FoxlockError(BAD_REQUEST, \"Key '%s' already exists\" % token_data['name'])\n\n\treturn 'Key successfully created', CREATED", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[210, 211]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[210, 211]]}, "_func_name": "addKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def post(self):\n \"\"\" Returns JWT upon login verification \"\"\"\n json_data = request.get_json()\n if not json_data['email']:\n return jsonify({\"msg\": \"Missing email\"}), 400\n\n data = database_utilities.execute_query(\n f\"\"\"select * from admins where email = '{json_data['email']}'\"\"\")\n if data:\n email = data[0]['email']\n access_token = create_access_token(identity=email)\n refresh_token = create_refresh_token(identity=email)\n\n resp = jsonify({\"login\": True})\n set_access_cookies(resp, access_token)\n set_refresh_cookies(resp, refresh_token)\n return resp\n else:\n return jsonify({\"msg\": \"User is not an admin\"})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[254, 332]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[254, 332]]}, "_func_name": "post", "_file_name": "apis/login.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "AP4_AtomSampleTable::GetSample(AP4_Ordinal index, \n AP4_Sample& sample)\n{\n AP4_Result result;\n\n // check that we have an stsc atom\n if (!m_StscAtom) {\n return AP4_ERROR_INVALID_FORMAT;\n }\n \n // check that we have a chunk offset table\n if (m_StcoAtom == NULL && m_Co64Atom == NULL) {\n return AP4_ERROR_INVALID_FORMAT;\n }\n\n // MP4 uses 1-based indexes internally, so adjust by one\n index++;\n\n // find out in which chunk this sample is located\n AP4_Ordinal chunk, skip, desc;\n result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);\n if (AP4_FAILED(result)) return result;\n \n // check that the result is within bounds\n if (skip > index) return AP4_ERROR_INTERNAL;\n\n // get the atom offset for this chunk\n AP4_UI64 offset;\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n result = m_StcoAtom->GetChunkOffset(chunk, offset_32);\n offset = offset_32;\n } else {\n result = m_Co64Atom->GetChunkOffset(chunk, offset);\n }\n if (AP4_FAILED(result)) return result;\n \n // compute the additional offset inside the chunk\n for (unsigned int i = index-skip; i < index; i++) {\n AP4_Size size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(i, size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(i, size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n offset += size;\n }\n\n // set the description index\n sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes\n\n // set the dts and cts\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n result = m_SttsAtom->GetDts(index, dts, &duration);\n if (AP4_FAILED(result)) return result;\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {\n sample.SetCts(dts);\n } else {\n result = m_CttsAtom->GetCtsOffset(index, cts_offset); \n\t if (AP4_FAILED(result)) return result;\n sample.SetCtsDelta(cts_offset);\n } \n\n // set the size\n AP4_Size sample_size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(index, sample_size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(index, sample_size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n sample.SetSize(sample_size);\n\n // set the sync flag\n if (m_StssAtom == NULL) {\n sample.SetSync(true);\n } else {\n sample.SetSync(m_StssAtom->IsSampleSync(index));\n }\n\n // set the offset\n sample.SetOffset(offset);\n\n // set the data stream\n sample.SetDataStream(m_SampleStream);\n\n\n return AP4_SUCCESS;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1780, 1879]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1780, 1879]]}, "_func_name": "AP4_AtomSampleTable::GetSample", "_file_name": "Source/C++/Core/Ap4AtomSampleTable.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def _make_fc_map(self, source, target, full_copy):\n fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source, '-target',\n target, '-autodelete']\n if not full_copy:\n fc_map_cli_cmd.extend(['-copyrate', '0'])\n out, err = self._run_ssh(fc_map_cli_cmd)\n self._driver_assert(\n len(out.strip()),\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n # Ensure that the output is as expected\n match_obj = re.search('FlashCopy Mapping, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n\n try:\n fc_map_id = match_obj.group(1)\n self._driver_assert(\n fc_map_id is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n except IndexError:\n self._driver_assert(\n False,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source,\n 'target': target,\n 'out': str(out),\n 'err': str(err)})\n return fc_map_id", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_make_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,\n\t\t\t struct netlink_ext_ack *extack)\n{\n\tstruct net *net = sock_net(in_skb->sk);\n\tstruct rtmsg *rtm;\n\tstruct nlattr *tb[RTA_MAX+1];\n\tstruct fib_result res = {};\n\tstruct rtable *rt = NULL;\n\tstruct flowi4 fl4;\n\t__be32 dst = 0;\n\t__be32 src = 0;\n\tu32 iif;\n\tint err;\n\tint mark;\n\tstruct sk_buff *skb;\n\tu32 table_id = RT_TABLE_MAIN;\n\tkuid_t uid;\n\n\terr = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,\n\t\t\t extack);\n\tif (err < 0)\n\t\tgoto errout;\n\n\trtm = nlmsg_data(nlh);\n\n\tskb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);\n\tif (!skb) {\n\t\terr = -ENOBUFS;\n\t\tgoto errout;\n\t}\n\n\t/* Reserve room for dummy headers, this skb can pass\n\t through good chunk of routing engine.\n\t */\n\tskb_reset_mac_header(skb);\n\tskb_reset_network_header(skb);\n\n\tsrc = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;\n\tdst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;\n\tiif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;\n\tmark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;\n\tif (tb[RTA_UID])\n\t\tuid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));\n\telse\n\t\tuid = (iif ? INVALID_UID : current_uid());\n\n\t/* Bugfix: need to give ip_route_input enough of an IP header to\n\t * not gag.\n\t */\n\tip_hdr(skb)->protocol = IPPROTO_UDP;\n\tip_hdr(skb)->saddr = src;\n\tip_hdr(skb)->daddr = dst;\n\n\tskb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));\n\n\tmemset(&fl4, 0, sizeof(fl4));\n\tfl4.daddr = dst;\n\tfl4.saddr = src;\n\tfl4.flowi4_tos = rtm->rtm_tos;\n\tfl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;\n\tfl4.flowi4_mark = mark;\n\tfl4.flowi4_uid = uid;\n\n\trcu_read_lock();\n\n\tif (iif) {\n\t\tstruct net_device *dev;\n\n\t\tdev = dev_get_by_index_rcu(net, iif);\n\t\tif (!dev) {\n\t\t\terr = -ENODEV;\n\t\t\tgoto errout_free;\n\t\t}\n\n\t\tskb->protocol\t= htons(ETH_P_IP);\n\t\tskb->dev\t= dev;\n\t\tskb->mark\t= mark;\n\t\terr = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,\n\t\t\t\t\t dev, &res);\n\n\t\trt = skb_rtable(skb);\n\t\tif (err == 0 && rt->dst.error)\n\t\t\terr = -rt->dst.error;\n\t} else {\n\t\trt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);\n\t\terr = 0;\n\t\tif (IS_ERR(rt))\n\t\t\terr = PTR_ERR(rt);\n\t\telse\n\t\t\tskb_dst_set(skb, &rt->dst);\n\t}\n\n\tif (err)\n\t\tgoto errout_free;\n\n\tif (rtm->rtm_flags & RTM_F_NOTIFY)\n\t\trt->rt_flags |= RTCF_NOTIFY;\n\n\tif (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)\n\t\ttable_id = rt->rt_table_id;\n\n\tif (rtm->rtm_flags & RTM_F_FIB_MATCH) {\n\t\tif (!res.fi) {\n\t\t\terr = fib_props[res.type].error;\n\t\t\tif (!err)\n\t\t\t\terr = -EHOSTUNREACH;\n\t\t\tgoto errout_free;\n\t\t}\n\t\terr = fib_dump_info(skb, NETLINK_CB(in_skb).portid,\n\t\t\t\t nlh->nlmsg_seq, RTM_NEWROUTE, table_id,\n\t\t\t\t rt->rt_type, res.prefix, res.prefixlen,\n\t\t\t\t fl4.flowi4_tos, res.fi, 0);\n\t} else {\n\t\terr = rt_fill_info(net, dst, src, table_id, &fl4, skb,\n\t\t\t\t NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);\n\t}\n\tif (err < 0)\n\t\tgoto errout_free;\n\n\trcu_read_unlock();\n\n\terr = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);\nerrout:\n\treturn err;\n\nerrout_free:\n\trcu_read_unlock();\n\tkfree_skb(skb);\n\tgoto errout;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "inet_rtm_getroute", "_file_name": "net/ipv4/route.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,\n\t\t UChar* range, UChar** low, UChar** high, UChar** low_prev)\n{\n UChar *p, *pprev = (UChar* )NULL;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr, \"forward_search_range: str: %d, end: %d, s: %d, range: %d\\n\",\n\t (int )str, (int )end, (int )s, (int )range);\n#endif\n\n p = s;\n if (reg->dmin > 0) {\n if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {\n p += reg->dmin;\n }\n else {\n UChar *q = p + reg->dmin;\n while (p < q) p += enclen(reg->enc, p);\n }\n }\n\n retry:\n switch (reg->optimize) {\n case ONIG_OPTIMIZE_EXACT:\n p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);\n break;\n case ONIG_OPTIMIZE_EXACT_IC:\n p = slow_search_ic(reg->enc, reg->case_fold_flag,\n reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM:\n p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:\n p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);\n break;\n\n case ONIG_OPTIMIZE_MAP:\n p = map_search(reg->enc, reg->map, p, range);\n break;\n }\n\n if (p && p < range) {\n if (p - reg->dmin < s) {\n retry_gate:\n pprev = p;\n p += enclen(reg->enc, p);\n goto retry;\n }\n\n if (reg->sub_anchor) {\n UChar* prev;\n\n switch (reg->sub_anchor) {\n case ANCHOR_BEGIN_LINE:\n if (!ON_STR_BEGIN(p)) {\n prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n }\n break;\n\n case ANCHOR_END_LINE:\n if (ON_STR_END(p)) {\n#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE\n prev = (UChar* )onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))\n goto retry_gate;\n#endif\n }\n else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)\n#ifdef USE_CRNL_AS_LINE_TERMINATOR\n && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)\n#endif\n )\n goto retry_gate;\n break;\n }\n }\n\n if (reg->dmax == 0) {\n *low = p;\n if (low_prev) {\n if (*low > s)\n *low_prev = onigenc_get_prev_char_head(reg->enc, s, p);\n else\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), p);\n }\n }\n else {\n if (reg->dmax != ONIG_INFINITE_DISTANCE) {\n *low = p - reg->dmax;\n if (*low > s) {\n *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,\n *low, (const UChar** )low_prev);\n if (low_prev && IS_NULL(*low_prev))\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : s), *low);\n }\n else {\n if (low_prev)\n *low_prev = onigenc_get_prev_char_head(reg->enc,\n (pprev ? pprev : str), *low);\n }\n }\n }\n /* no needs to adjust *high, *high is used as range check only */\n *high = p - reg->dmin;\n\n#ifdef ONIG_DEBUG_SEARCH\n fprintf(stderr,\n \"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\\n\",\n\t (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);\n#endif\n return 1; /* success */\n }\n\n return 0; /* fail */\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[493, 539]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[493, 539]]}, "_func_name": "forward_search_range", "_file_name": "src/regexec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n FILE\n *file;\n\n Image\n *image,\n *next_image,\n *pwp_image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n register Image\n *p;\n\n register ssize_t\n i;\n\n size_t\n filesize,\n length;\n\n ssize_t\n count;\n\n unsigned char\n magick[MaxTextExtent];\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n pwp_image=AcquireImage(image_info);\n image=pwp_image;\n status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n count=ReadBlob(pwp_image,5,magick);\n if ((count != 5) || (LocaleNCompare((char *) magick,\"SFW95\",5) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n read_info=CloneImageInfo(image_info);\n (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,\n (void *) NULL);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n unique_file=AcquireUniqueFileResource(read_info->filename);\n for ( ; ; )\n {\n for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))\n {\n for (i=0; i < 17; i++)\n magick[i]=magick[i+1];\n magick[17]=(unsigned char) c;\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) == 0)\n break;\n }\n if (c == EOF)\n break;\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) != 0)\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Dump SFW image to a temporary file.\n */\n file=(FILE *) NULL;\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n length=fwrite(\"SFW94A\",1,6,file);\n (void) length;\n filesize=65535UL*magick[2]+256L*magick[1]+magick[0];\n for (i=0; i < (ssize_t) filesize; i++)\n {\n c=ReadBlobByte(pwp_image);\n (void) fputc(c,file);\n }\n (void) fclose(file);\n next_image=ReadImage(read_info,exception);\n if (next_image == (Image *) NULL)\n break;\n (void) FormatLocaleString(next_image->filename,MaxTextExtent,\n \"slide_%02ld.sfw\",(long) next_image->scene);\n if (image == (Image *) NULL)\n image=next_image;\n else\n {\n /*\n Link image into image list.\n */\n for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;\n next_image->previous=p;\n next_image->scene=p->scene+1;\n p->next=next_image;\n }\n if (image_info->number_scenes != 0)\n if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),\n GetBlobSize(pwp_image));\n if (status == MagickFalse)\n break;\n }\n if (unique_file != -1)\n (void) close(unique_file);\n (void) RelinquishUniqueFileResource(read_info->filename);\n read_info=DestroyImageInfo(read_info);\n if (EOFBlob(image) != MagickFalse)\n {\n char\n *message;\n\n message=GetExceptionMessage(errno);\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"UnexpectedEndOfFile\",\"`%s': %s\",image->filename,message);\n message=DestroyString(message);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ReadPWPImage", "_file_name": "coders/pwp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def set(self, key, value, replace=False):\n path = self._absolute_key(key)\n try:\n self.etcd.write(path, value, prevExist=replace)\n except etcd.EtcdAlreadyExist as err:\n raise CSStoreExists(str(err))\n except etcd.EtcdException as err:\n log_error(\"Error storing key %s: [%r]\" % (key, repr(err)))\n raise CSStoreError('Error occurred while trying to store key')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)\n{\n int count = snprintf(dest, destlen, \"%s.hcache\", path);\n\n /* Strip out any directories in the path */\n char *first = strchr(dest, '/');\n char *last = strrchr(dest, '/');\n if (first && last && (last > first))\n {\n memmove(first, last, strlen(last) + 1);\n count -= (last - first);\n }\n\n return count;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "nntp_hcache_namer", "_file_name": "newsrc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar()();\n auto max_val = input_max_tensor.scalar()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_max_tensor));\n }\n\n if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor f;\n f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor f;\n f(ctx->eigen_device(),\n input.template flat_inner_outer_dims(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims(axis_ - 1));\n }\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[89, 154]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[89, 154]]}, "_func_name": "tensorflow::QuantizeAndDequantizeV2Op::Compute", "_file_name": "tensorflow/core/kernels/quantize_and_dequantize_op.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,\n\t\tunsigned char **out, size_t *out_len,\n\t\tint verify_pin)\n{\n\tstruct sc_context *ctx = p15card->card->ctx;\n\tstruct sc_card *card = p15card->card;\n\tstruct sc_file *file = NULL;\n\tstruct sc_path path;\n\tsize_t sz;\n\tint rv;\n\n\tLOG_FUNC_CALLED(ctx);\n\tif (!in_path || !out || !out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Cannot read oberthur file\");\n\n\tsc_log(ctx, \"read file '%s'; verify_pin:%i\", in_path, verify_pin);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tsc_format_path(in_path, &path);\n\trv = sc_select_file(card, &path, &file);\n\tif (rv != SC_SUCCESS) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot select oberthur file to read\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT)\n\t\tsz = file->size;\n\telse\n\t\tsz = (file->record_length + 2) * file->record_count;\n\n\t*out = calloc(sz, 1);\n\tif (*out == NULL) {\n\t\tsc_file_free(file);\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot read oberthur file\");\n\t}\n\n\tif (file->ef_structure == SC_FILE_EF_TRANSPARENT) {\n\t\trv = sc_read_binary(card, 0, *out, sz, 0);\n\t}\n\telse\t{\n\t\tint rec;\n\t\tint offs = 0;\n\t\tint rec_len = file->record_length;\n\n\t\tfor (rec = 1; ; rec++) {\n\t\t\trv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);\n\t\t\tif (rv == SC_ERROR_RECORD_NOT_FOUND) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (rv < 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\trec_len = rv;\n\n\t\t\t*(*out + offs) = 'R';\n\t\t\t*(*out + offs + 1) = rv;\n\n\t\t\toffs += rv + 2;\n\t\t}\n\n\t\tsz = offs;\n\t}\n\n\tsc_log(ctx, \"read oberthur file result %i\", rv);\n\tif (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tstruct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;\n\t\tconst struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\t\tint ii;\n\n\t\trv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);\n\t\tif (rv != SC_SUCCESS) {\n\t\t\tsc_file_free(file);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Cannot read oberthur file: get AUTH objects error\");\n\t\t}\n\n\t\tfor (ii=0; iidata;\n\t\t\tsc_log(ctx, \"compare PIN/ACL refs:%i/%i, method:%i/%i\",\n\t\t\t\t\tauth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);\n\t\t\tif (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {\n\t\t\t\tpin_obj = objs[ii];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!pin_obj || !pin_obj->content.value) {\n\t\t\trv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;\n\t\t}\n\t\telse {\n\t\t\trv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);\n\t\t\tif (!rv)\n\t\t\t\trv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);\n\t\t}\n\t};\n\n\tsc_file_free(file);\n\n\tif (rv < 0) {\n\t\tfree(*out);\n\t\t*out = NULL;\n\t\t*out_len = 0;\n\t}\n\n\t*out_len = sz;\n\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1107, 1171]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1107, 1171]]}, "_func_name": "sc_oberthur_read_file", "_file_name": "src/libopensc/pkcs15-oberthur.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _create_host(self, connector):\n \"\"\"Create a new host on the storage system.\n\n We create a host name and associate it with the given connection\n information.\n\n \"\"\"\n\n LOG.debug(_('enter: _create_host: host %s') % connector['host'])\n\n rand_id = str(random.randint(0, 99999999)).zfill(8)\n host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),\n rand_id)\n\n # Get all port information from the connector\n ports = []\n if 'initiator' in connector:\n ports.append('-iscsiname %s' % connector['initiator'])\n if 'wwpns' in connector:\n for wwpn in connector['wwpns']:\n ports.append('-hbawwpn %s' % wwpn)\n\n # When creating a host, we need one port\n self._driver_assert(len(ports), _('_create_host: No connector ports'))\n port1 = ports.pop(0)\n ssh_cmd = ('svctask mkhost -force %(port1)s -name \"%(host_name)s\"' %\n {'port1': port1, 'host_name': host_name})\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return('successfully created' in out,\n '_create_host', ssh_cmd, out, err)\n\n # Add any additional ports to the host\n for port in ports:\n ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))\n out, err = self._run_ssh(ssh_cmd)\n\n LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %\n {'host': connector['host'], 'host_name': host_name})\n return host_name", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[916, 1054], [1301, 1380]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[916, 1054], [1301, 1380]]}, "_func_name": "_create_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def write_section(self, section_name, section_data):\n self.write_line(\"\")\n self.write_line(\"define %s {\" % section_name)\n sorted_keys = section_data.keys()\n sorted_keys.sort()\n for key in sorted_keys:\n value = self.value_to_icinga(section_data[key])\n icinga_line = \"%s%-45s%s\" % (self.indent, key, value)\n\n if \"\\n\" in icinga_line or \"}\" in icinga_line:\n msg = \"Found forbidden newline or '}' character in section %r.\"\n raise Exception(msg % section_name)\n\n self.icinga_lines.append(icinga_line)\n self.write_line(\"}\")", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "write_section", "_file_name": "src/main/python/monitoring_config_generator/MonitoringConfigGenerator.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_article(index):\n with conn.cursor(cursor_factory=DictCursor) as cur:\n query = \"SELECT * FROM articles WHERE index=%s\"\n cur.execute(query, (index, ))\n article = cur.fetchone()\n return article", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_article", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_tournaments_during_month(db, scene, date):\n y, m, d = date.split('-')\n ym_date = '{}-{}'.format(y, m)\n sql = \"select url, date from matches where scene='{}' and date like '%{}%' group by url, date order by date\".format(scene, ym_date)\n res = db.exec(sql)\n urls = [r[0] for r in res]\n return urls", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[116, 252]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[116, 252]]}, "_func_name": "get_tournaments_during_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)\n{\n\tstruct sctp_association *asoc = sctp_id2assoc(sk, id);\n\tstruct sctp_sock *sp = sctp_sk(sk);\n\tstruct socket *sock;\n\tint err = 0;\n\n\t/* Do not peel off from one netns to another one. */\n\tif (!net_eq(current->nsproxy->net_ns, sock_net(sk)))\n\t\treturn -EINVAL;\n\n\tif (!asoc)\n\t\treturn -EINVAL;\n\n\t/* If there is a thread waiting on more sndbuf space for\n\t * sending on this asoc, it cannot be peeled.\n\t */\n\tif (waitqueue_active(&asoc->wait))\n\t\treturn -EBUSY;\n\n\t/* An association cannot be branched off from an already peeled-off\n\t * socket, nor is this supported for tcp style sockets.\n\t */\n\tif (!sctp_style(sk, UDP))\n\t\treturn -EINVAL;\n\n\t/* Create a new socket. */\n\terr = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);\n\tif (err < 0)\n\t\treturn err;\n\n\tsctp_copy_sock(sock->sk, sk, asoc);\n\n\t/* Make peeled-off sockets more like 1-1 accepted sockets.\n\t * Set the daddr and initialize id to something more random\n\t */\n\tsp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);\n\n\t/* Populate the fields of the newsk from the oldsk and migrate the\n\t * asoc to the newsk.\n\t */\n\tsctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);\n\n\t*sockp = sock;\n\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "sctp_do_peeloff", "_file_name": "net/sctp/socket.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n{\n\tUINT32 os_major;\n\tUINT32 os_minor;\n\tUINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;\n\twStream* licenseStream = NULL;\n\tBOOL ret = FALSE;\n\tBYTE computedMac[16];\n\tLICENSE_BLOB* calBlob;\n\n\tDEBUG_LICENSE(\"Receiving Server New/Upgrade License Packet\");\n\n\tcalBlob = license_new_binary_blob(BB_DATA_BLOB);\n\tif (!calBlob)\n\t\treturn FALSE;\n\n\t/* EncryptedLicenseInfo */\n\tif (!license_read_encrypted_blob(license, s, calBlob))\n\t\tgoto out_free_blob;\n\n\t/* compute MAC and check it */\n\tif (Stream_GetRemainingLength(s) < 16)\n\t\tgoto out_free_blob;\n\n\tif (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))\n\t\tgoto out_free_blob;\n\n\tif (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)\n\t{\n\t\tWLog_ERR(TAG, \"new or upgrade license MAC mismatch\");\n\t\tgoto out_free_blob;\n\t}\n\n\tif (!Stream_SafeSeek(s, 16))\n\t\tgoto out_free_blob;\n\n\tlicenseStream = Stream_New(calBlob->data, calBlob->length);\n\tif (!licenseStream)\n\t\tgoto out_free_blob;\n\n\tStream_Read_UINT16(licenseStream, os_minor);\n\tStream_Read_UINT16(licenseStream, os_major);\n\n\t/* Scope */\n\tStream_Read_UINT32(licenseStream, cbScope);\n\tif (Stream_GetRemainingLength(licenseStream) < cbScope)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Scope:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);\n#endif\n\tStream_Seek(licenseStream, cbScope);\n\n\t/* CompanyName */\n\tStream_Read_UINT32(licenseStream, cbCompanyName);\n\tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Company name:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);\n#endif\n\tStream_Seek(licenseStream, cbCompanyName);\n\n\t/* productId */\n\tStream_Read_UINT32(licenseStream, cbProductId);\n\tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n\t\tgoto out_free_stream;\n#ifdef WITH_DEBUG_LICENSE\n\tWLog_DBG(TAG, \"Product id:\");\n\twinpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);\n#endif\n\tStream_Seek(licenseStream, cbProductId);\n\n\t/* licenseInfo */\n\tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n\tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n\t\tgoto out_free_stream;\n\n\tlicense->state = LICENSE_STATE_COMPLETED;\n\n\tret = TRUE;\n\tif (!license->rdp->settings->OldLicenseBehaviour)\n\t\tret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,\n\t\t license->rdp->settings->ClientHostname);\n\nout_free_stream:\n\tStream_Free(licenseStream, FALSE);\nout_free_blob:\n\tlicense_free_binary_blob(calBlob);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1054, 1100]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1054, 1100]]}, "_func_name": "license_read_new_or_upgrade_license_packet", "_file_name": "libfreerdp/core/license.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "SWFInput_readSBits(SWFInput input, int number)\n{\n\tint num = SWFInput_readBits(input, number);\n\n\tif ( num & (1<<(number-1)) )\n\t\treturn num - (1<format->data;\n\tssize_t bytes_avail;\n\n\tif (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {\n\t\t/* Copy mode. */\n\n\t\t*buff = __archive_read_ahead(a, minimum, &bytes_avail);\n\t\tif (bytes_avail <= 0) {\n\t\t\tarchive_set_error(&a->archive,\n\t\t\t ARCHIVE_ERRNO_FILE_FORMAT,\n\t\t\t \"Truncated 7-Zip file data\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif ((size_t)bytes_avail >\n\t\t zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\tif ((size_t)bytes_avail > size)\n\t\t\tbytes_avail = (ssize_t)size;\n\n\t\tzip->pack_stream_bytes_unconsumed = bytes_avail;\n\t} else if (zip->uncompressed_buffer_pointer == NULL) {\n\t\t/* Decompression has failed. */\n\t\tarchive_set_error(&(a->archive),\n\t\t ARCHIVE_ERRNO_MISC, \"Damaged 7-Zip archive\");\n\t\treturn (ARCHIVE_FATAL);\n\t} else {\n\t\t/* Packed mode. */\n\t\tif (minimum > zip->uncompressed_buffer_bytes_remaining) {\n\t\t\t/*\n\t\t\t * If remaining uncompressed data size is less than\n\t\t\t * the minimum size, fill the buffer up to the\n\t\t\t * minimum size.\n\t\t\t */\n\t\t\tif (extract_pack_stream(a, minimum) < 0)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tif (size > zip->uncompressed_buffer_bytes_remaining)\n\t\t\tbytes_avail = (ssize_t)\n\t\t\t zip->uncompressed_buffer_bytes_remaining;\n\t\telse\n\t\t\tbytes_avail = (ssize_t)size;\n\t\t*buff = zip->uncompressed_buffer_pointer;\n\t\tzip->uncompressed_buffer_pointer += bytes_avail;\n\t}\n\tzip->uncompressed_buffer_bytes_remaining -= bytes_avail;\n\treturn (bytes_avail);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_uncompressed_data", "_file_name": "libarchive/archive_read_support_format_7zip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def mode_close(self, request):\n \"\"\"\n This is called by render_POST when the client is signalling\n that it is about to be closed.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = cgi.escape(request.args['csessid'][0])\n try:\n sess = self.sessionhandler.sessions_from_csessid(csessid)[0]\n sess.sessionhandler.disconnect(sess)\n except IndexError:\n self.client_disconnect(csessid)\n return '\"\"'", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mode_close", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "long dd_get_item_size(struct dump_dir *dd, const char *name)\n{\n if (!str_is_correct_filename(name))\n error_msg_and_die(\"Cannot get item size. '%s' is not a valid file name\", name);\n\n long size = -1;\n char *iname = concat_path_file(dd->dd_dirname, name);\n struct stat statbuf;\n\n if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode))\n size = statbuf.st_size;\n else\n {\n if (errno == ENOENT)\n size = 0;\n else\n perror_msg(\"Can't get size of file '%s'\", iname);\n }\n\n free(iname);\n\n return size;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dd_get_item_size", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int tcp_test(const char* ip_str, const short port)\n{\n int sock, i;\n struct sockaddr_in s_in;\n int packetsize = 1024;\n unsigned char packet[packetsize];\n struct timeval tv, tv2, tv3;\n int caplen = 0;\n int times[REQUESTS];\n int min, avg, max, len;\n struct net_hdr nh;\n\n tv3.tv_sec=0;\n tv3.tv_usec=1;\n\n s_in.sin_family = PF_INET;\n s_in.sin_port = htons(port);\n if (!inet_aton(ip_str, &s_in.sin_addr))\n return -1;\n\n if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)\n return -1;\n\n /* avoid blocking on reading the socket */\n if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )\n {\n perror( \"fcntl(O_NONBLOCK) failed\" );\n return( 1 );\n }\n\n gettimeofday( &tv, NULL );\n\n while (1) //waiting for relayed packet\n {\n if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)\n {\n if(errno != EINPROGRESS && errno != EALREADY)\n {\n perror(\"connect\");\n close(sock);\n\n printf(\"Failed to connect\\n\");\n\n return -1;\n }\n }\n else\n {\n gettimeofday( &tv2, NULL );\n break;\n }\n\n gettimeofday( &tv2, NULL );\n //wait 3000ms for a successful connect\n if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000))\n {\n printf(\"Connection timed out\\n\");\n close(sock);\n return(-1);\n }\n usleep(10);\n }\n\n PCT; printf(\"TCP connection successful\\n\");\n\n //trying to identify airserv-ng\n memset(&nh, 0, sizeof(nh));\n// command: GET_CHAN\n nh.nh_type\t= 2;\n nh.nh_len\t= htonl(0);\n\n if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))\n {\n perror(\"send\");\n return -1;\n }\n\n gettimeofday( &tv, NULL );\n i=0;\n\n while (1) //waiting for GET_CHAN answer\n {\n caplen = read(sock, &nh, sizeof(nh));\n\n if(caplen == -1)\n {\n if( errno != EAGAIN )\n {\n perror(\"read\");\n return -1;\n }\n }\n\n if( (unsigned)caplen == sizeof(nh))\n {\n len = ntohl(nh.nh_len);\n if( nh.nh_type == 1 && i==0 )\n {\n i=1;\n caplen = read(sock, packet, len);\n if(caplen == len)\n {\n i=2;\n break;\n }\n else\n {\n i=0;\n }\n }\n else\n {\n caplen = read(sock, packet, len);\n }\n }\n\n gettimeofday( &tv2, NULL );\n //wait 1000ms for an answer\n if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))\n {\n break;\n }\n if(caplen == -1)\n usleep(10);\n }\n\n if(i==2)\n {\n PCT; printf(\"airserv-ng found\\n\");\n }\n else\n {\n PCT; printf(\"airserv-ng NOT found\\n\");\n }\n\n close(sock);\n\n for(i=0; i (1000*1000))\n {\n break;\n }\n //simple \"high-precision\" usleep\n select(1, NULL, NULL, NULL, &tv3);\n }\n times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec));\n printf( \"\\r%d/%d\\r\", i, REQUESTS);\n fflush(stdout);\n close(sock);\n }\n\n min = INT_MAX;\n avg = 0;\n max = 0;\n\n for(i=0; i max) max = times[i];\n avg += times[i];\n }\n avg /= REQUESTS;\n\n PCT; printf(\"ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\\n\", ip_str, port, min/1000.0, avg/1000.0, max/1000.0);\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[2251, 2293]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2251, 2293]]}, "_func_name": "tcp_test", "_file_name": "src/aireplay-ng.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;\n\n MagickOffsetType\n offset;\n\n MagickBooleanType\n status;\n\n channel_image=image;\n mask=(Image *) NULL;\n if (layer_info->channel_info[channel].type < -1)\n {\n const char\n *option;\n /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->channel_info[channel].type != -2) ||\n (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)))\n {\n SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);\n return(MagickTrue);\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n if (mask != (Image *) NULL)\n {\n mask->matte=MagickFalse;\n channel_image=mask;\n }\n }\n\n offset=TellBlob(image);\n status=MagickTrue;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,psd_info->channels,\n layer_info->channel_info[channel].type,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;\n\n sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,psd_info,\n layer_info->channel_info[channel].type,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,layer_info->channels,\n layer_info->channel_info[channel].type,compression,\n layer_info->channel_info[channel].size-2,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }\n\n SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n layer_info->mask.image=mask;\n return(status);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ReadPSDChannel", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):\n \"\"\"Create a 3PAR host.\n\n Create a 3PAR host, if there is already a host on the 3par using\n the same wwn but with a different hostname, return the hostname\n used by 3PAR.\n \"\"\"\n command = ['createhost', '-persona', persona_id, '-domain', domain,\n hostname]\n for wwn in wwns:\n command.append(wwn)\n\n out = self.common._cli_run(command)\n if out and len(out) > 1:\n return self.common.parse_create_host_error(hostname, out)\n\n return hostname", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_create_3par_fibrechan_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_fc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void luaD_shrinkstack (lua_State *L) {\n int inuse = stackinuse(L);\n int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;\n if (goodsize > LUAI_MAXSTACK)\n goodsize = LUAI_MAXSTACK; /* respect stack limit */\n /* if thread is currently not handling a stack overflow and its\n good size is smaller than current size, shrink its stack */\n if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&\n goodsize < L->stacksize)\n luaD_reallocstack(L, goodsize, 0); /* ok if that fails */\n else /* don't change stack */\n condmovestack(L,{},{}); /* (change only for debugging) */\n luaE_shrinkCI(L); /* shrink CI list */\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[68, 122], [342, 421]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[68, 122], [342, 421]]}, "_func_name": "luaD_shrinkstack", "_file_name": "ldo.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "\tdef render(self, request):\n\t\taction = \"download\"\n\t\tif \"action\" in request.args:\n\t\t\taction = request.args[\"action\"][0]\n\n\t\tif \"file\" in request.args:\n\t\t\tfilename = lenient_force_utf_8(request.args[\"file\"][0])\n\t\t\tfilename = sanitise_filename_slashes(os.path.realpath(filename))\n\n\t\t\tif not os.path.exists(filename):\n\t\t\t\treturn \"File '%s' not found\" % (filename)\n\n\t\t\tif action == \"stream\":\n\t\t\t\tname = \"stream\"\n\t\t\t\tif \"name\" in request.args:\n\t\t\t\t\tname = request.args[\"name\"][0]\n\n\t\t\t\tport = config.OpenWebif.port.value\n\t\t\t\tproto = 'http'\n\t\t\t\tif request.isSecure():\n\t\t\t\t\tport = config.OpenWebif.https_port.value\n\t\t\t\t\tproto = 'https'\n\t\t\t\tourhost = request.getHeader('host')\n\t\t\t\tm = re.match('.+\\:(\\d+)$', ourhost)\n\t\t\t\tif m is not None:\n\t\t\t\t\tport = m.group(1)\n\n\t\t\t\tresponse = \"#EXTM3U\\n#EXTVLCOPT--http-reconnect=true\\n#EXTINF:-1,%s\\n%s://%s:%s/file?action=download&file=%s\" % (name, proto, request.getRequestHostname(), port, quote(filename))\n\t\t\t\trequest.setHeader(\"Content-Disposition\", 'attachment;filename=\"%s.m3u\"' % name)\n\t\t\t\trequest.setHeader(\"Content-Type\", \"application/x-mpegurl\")\n\t\t\t\treturn response\n\t\t\telif action == \"delete\":\n\t\t\t\trequest.setResponseCode(http.OK)\n\t\t\t\treturn \"TODO: DELETE FILE: %s\" % (filename)\n\t\t\telif action == \"download\":\n\t\t\t\trequest.setHeader(\"Content-Disposition\", \"attachment;filename=\\\"%s\\\"\" % (filename.split('/')[-1]))\n\t\t\t\trfile = static.File(filename, defaultType = \"application/octet-stream\")\n\t\t\t\treturn rfile.render(request)\n\t\t\telse: \n\t\t\t\treturn \"wrong action parameter\"\n\n\t\tif \"dir\" in request.args:\n\t\t\tpath = request.args[\"dir\"][0]\n\t\t\tpattern = '*'\n\t\t\tdata = []\n\t\t\tif \"pattern\" in request.args:\n\t\t\t\tpattern = request.args[\"pattern\"][0]\n\t\t\tdirectories = []\n\t\t\tfiles = []\n\t\t\tif fileExists(path):\n\t\t\t\ttry:\n\t\t\t\t\tfiles = glob.glob(path+'/'+pattern)\n\t\t\t\texcept:\n\t\t\t\t\tfiles = []\n\t\t\t\tfiles.sort()\n\t\t\t\ttmpfiles = files[:]\n\t\t\t\tfor x in tmpfiles:\n\t\t\t\t\tif os.path.isdir(x):\n\t\t\t\t\t\tdirectories.append(x + '/')\n\t\t\t\t\t\tfiles.remove(x)\n\t\t\t\tdata.append({\"result\": True,\"dirs\": directories,\"files\": files})\n\t\t\telse:\n\t\t\t\tdata.append({\"result\": False,\"message\": \"path %s not exits\" % (path)})\n\t\t\trequest.setHeader(\"content-type\", \"application/json; charset=utf-8\")\n\t\t\treturn json.dumps(data, indent=2)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "render", "_file_name": "plugin/controllers/file.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PHP_FUNCTION(imagegammacorrect)\n{\n\tzval *IM;\n\tgdImagePtr im;\n\tint i;\n\tdouble input, output;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rdd\", &IM, &input, &output) == FAILURE) {\n\t\treturn;\n\t}\n\n\tZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, \"Image\", le_gd);\n\n\tif (gdImageTrueColor(im))\t{\n\t\tint x, y, c;\n\n\t\tfor (y = 0; y < gdImageSY(im); y++)\t{\n\t\t\tfor (x = 0; x < gdImageSX(im); x++)\t{\n\t\t\t\tc = gdImageGetPixel(im, x, y);\n\t\t\t\tgdImageSetPixel(im, x, y,\n\t\t\t\t\tgdTrueColorAlpha(\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\tgdTrueColorGetAlpha(c)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tRETURN_TRUE;\n\t}\n\n\tfor (i = 0; i < gdImageColorsTotal(im); i++) {\n\t\tim->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t\tim->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t\tim->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t}\n\n\tRETURN_TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[204, 267]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[204, 267]]}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/gd/gd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@csrf.csrf_protect\ndef subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "subscribe_for_tags", "_file_name": "askbot/views/commands.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_top_popular(top_num):\r\n \"\"\" query the top(top_num) popular articles\r\n top_num => list of [title, count]\r\n \"\"\"\r\n cmd = \"\"\"SELECT title, views FROM articles\r\n INNER JOIN (\r\n SELECT path, count(path) AS views\r\n FROM log GROUP BY log.path\r\n ) AS log\r\n ON log.path = '/article/' || articles.slug\r\n ORDER BY views DESC\r\n LIMIT {}\"\"\".format(top_num)\r\n return execute_query(cmd)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[410, 452]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[410, 452]]}, "_func_name": "get_top_popular", "_file_name": "logAnalyzerDb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def action_save_user(request: HttpRequest, default_forward_url: str = \"/admin/users\"):\n \"\"\"\n This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse\n :param request: the HttpRequest\n :param default_forward_url: The URL to forward to if nothing was specified\n :return: The crafted HttpResponse\n \"\"\"\n forward_url = default_forward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if not request.user.is_authenticated:\n return HttpResponseForbidden()\n profile = Profile.objects.get(authuser=request.user)\n if profile.rights < 2:\n return HttpResponseForbidden()\n try:\n if request.GET.get(\"user_id\"):\n pid = int(request.GET[\"user_id\"])\n displayname = str(request.POST[\"display_name\"])\n dect = int(request.POST[\"dect\"])\n notes = str(request.POST[\"notes\"])\n pw1 = str(request.POST[\"password\"])\n pw2 = str(request.POST[\"confirm_password\"])\n mail = str(request.POST[\"email\"])\n rights = int(request.POST[\"rights\"])\n user: Profile = Profile.objects.get(pk=pid)\n user.displayName = displayname\n user.dect = dect\n user.notes = notes\n user.rights = rights\n user.number_of_allowed_reservations = int(request.POST[\"allowed_reservations\"])\n if request.POST.get(\"active\"):\n user.active = magic.parse_bool(request.POST[\"active\"])\n au: User = user.authuser\n if check_password_conformity(pw1, pw2):\n logging.log(logging.INFO, \"Set password for user: \" + user.displayName)\n au.set_password(pw1)\n else:\n logging.log(logging.INFO, \"Failed to set password for: \" + user.displayName)\n au.email = mail\n au.save()\n user.save()\n else:\n # assume new user\n username = str(request.POST[\"username\"])\n displayname = str(request.POST[\"display_name\"])\n dect = int(request.POST[\"dect\"])\n notes = str(request.POST[\"notes\"])\n pw1 = str(request.POST[\"password\"])\n pw2 = str(request.POST[\"confirm_password\"])\n mail = str(request.POST[\"email\"])\n rights = int(request.POST[\"rights\"])\n if not check_password_conformity(pw1, pw2):\n recreate_form('password mismatch')\n auth_user: User = User.objects.create_user(username=username, email=mail, password=pw1)\n auth_user.save()\n user: Profile = Profile()\n user.rights = rights\n user.number_of_allowed_reservations = int(request.POST[\"allowed_reservations\"])\n user.displayName = displayname\n user.authuser = auth_user\n user.dect = dect\n user.notes = notes\n user.active = True\n user.save()\n pass\n pass\n except Exception as e:\n return HttpResponseBadRequest(str(e))\n return redirect(forward_url)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1188, 1231], [1260, 1291], [1855, 1883], [2484, 2584], [2776, 2819], [2886, 2917]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1188, 1231], [1260, 1291], [1855, 1883], [2484, 2584], [2776, 2819], [2886, 2917]]}, "_func_name": "action_save_user", "_file_name": "c3shop/frontpage/management/edit_user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def build_board(conn, game,size):\n # we'll build the empty board, and then fill in with the move list that\n # we get from the DB.\n board = []\n for i in range(size):\n board.append([\"\"]*size)\n\n\n # search for all moves that have happenend during this game.\n cursor = conn.cursor()\n cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\" % game)\n\n counts = {\"X\":0, \"O\":0}\n for move in cursor.fetchall():\n (x,y,letter) = move\n\n x = int(x)\n y = int(y)\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert letter in \"XO\"\n\n assert board[x][y] == \"\"\n board[x][y] = letter\n\n counts[letter] += 1\n\n cursor.close()\n\n assert counts[\"X\"] >= counts[\"O\"]\n assert counts[\"X\"] <= counts[\"O\"]+1\n\n if counts[\"X\"] == counts[\"O\"]:\n nextPlayer = 0\n else:\n nextPlayer = 1\n letter = \"XO\"[nextPlayer]\n\n return (board,nextPlayer,letter)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[303, 380]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[303, 380]]}, "_func_name": "build_board", "_file_name": "cgi/common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def process_statistics(self, metadata, _):\n args = [metadata.hostname, '-p', metadata.profile, '-g',\n ':'.join([g for g in metadata.groups])]\n self.debug_log(\"running triggers\")\n for notifier in os.listdir(self.data):\n self.debug_log(\"running %s\" % notifier)\n if ((notifier[-1] == '~') or\n (notifier[:2] == '.#') or\n (notifier[-4:] == '.swp') or\n (notifier in ['SCCS', '.svn', '4913'])):\n continue\n npath = os.path.join(self.data, notifier)\n self.async_run([npath] + args)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_statistics", "_file_name": "src/lib/Server/Plugins/Trigger.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)\n{\n\tstruct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);\n\tstruct skcipher_alg *alg = crypto_skcipher_alg(skcipher);\n\n\tif (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)\n\t\treturn crypto_init_skcipher_ops_blkcipher(tfm);\n\n\tif (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||\n\t tfm->__crt_alg->cra_type == &crypto_givcipher_type)\n\t\treturn crypto_init_skcipher_ops_ablkcipher(tfm);\n\n\tskcipher->setkey = skcipher_setkey;\n\tskcipher->encrypt = alg->encrypt;\n\tskcipher->decrypt = alg->decrypt;\n\tskcipher->ivsize = alg->ivsize;\n\tskcipher->keysize = alg->max_keysize;\n\n\tif (alg->exit)\n\t\tskcipher->base.exit = crypto_skcipher_exit_tfm;\n\n\tif (alg->init)\n\t\treturn alg->init(skcipher);\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "crypto_skcipher_init_tfm", "_file_name": "crypto/skcipher.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "PHPAPI PHP_FUNCTION(fread)\n{\n\tzval *arg1;\n\tlong len;\n\tphp_stream *stream;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rl\", &arg1, &len) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tPHP_STREAM_TO_ZVAL(stream, &arg1);\n\n\tif (len <= 0) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be greater than 0\");\n\t\tRETURN_FALSE;\n\t}\n\n\tZ_STRVAL_P(return_value) = emalloc(len + 1);\n\tZ_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);\n\n\t/* needed because recv/read/gzread doesnt put a null at the end*/\n\tZ_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;\n\tZ_TYPE_P(return_value) = IS_STRING;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[346, 392]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[346, 392]]}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/standard/file.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int snd_seq_device_dev_free(struct snd_device *device)\n{\n\tstruct snd_seq_device *dev = device->device_data;\n\n\tcancel_autoload_drivers();\n\tput_device(&dev->dev);\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "snd_seq_device_dev_free", "_file_name": "sound/core/seq_device.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_extra_args(self, args=None):\n \"\"\"Add more args depending on how known args are set.\"\"\"\n parsed = vars(self.parse_known_args(args, nohelp=True)[0])\n\n # find which image mode specified if any, and add additional arguments\n image_mode = parsed.get('image_mode', None)\n if image_mode is not None and image_mode != 'none':\n self.add_image_args(image_mode)\n\n # find which task specified if any, and add its specific arguments\n task = parsed.get('task', None)\n if task is not None:\n self.add_task_args(task)\n evaltask = parsed.get('evaltask', None)\n if evaltask is not None:\n self.add_task_args(evaltask)\n\n # find which model specified if any, and add its specific arguments\n model = parsed.get('model', None)\n if model is not None:\n self.add_model_subargs(model)\n\n # reset parser-level defaults over any model-level defaults\n try:\n self.set_defaults(**self._defaults)\n except AttributeError:\n raise RuntimeError('Please file an issue on github that argparse '\n 'got an attribute error when parsing.')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_extra_args", "_file_name": "parlai/core/params.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def on_message( self, profile_id, profile_name, level, message, timeout ):\n if 1 == level:\n cmd = ['notify-send']\n if timeout > 0:\n cmd.extend(['-t', str(1000 * timeout)])\n\n title = \"Back In Time (%s) : %s\" % (self.user, profile_name)\n message = message.replace(\"\\n\", ' ')\n message = message.replace(\"\\r\", '')\n\n cmd.append(title)\n cmd.append(message)\n subprocess.Popen(cmd).communicate()\n return", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "on_message", "_file_name": "qt4/plugins/notifyplugin.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_item(self, item):\n \"\"\"\"Add new item.\"\"\"\n if self.connection:\n self.cursor.execute('insert into item (name, shoppinglistid) values (\"%s\", \"%s\")' % (item[0], item[1]))\n self.connection.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[87, 203]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[87, 203]]}, "_func_name": "add_item", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def redirect(self, url, **kwargs):\n \"\"\"Explicitly converts url to 'str', because webapp2.RequestHandler.redirect\n strongly requires 'str' but url might be an unicode string.\"\"\"\n super(Handler, self).redirect(str(url), **kwargs)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[185, 238]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[185, 238]]}, "_func_name": "redirect", "_file_name": "src/appengine/handlers/base_handler.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n int linesize_align[AV_NUM_DATA_POINTERS])\n{\n int i;\n int w_align = 1;\n int h_align = 1;\n AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);\n\n if (desc) {\n w_align = 1 << desc->log2_chroma_w;\n h_align = 1 << desc->log2_chroma_h;\n }\n\n switch (s->pix_fmt) {\n case AV_PIX_FMT_YUV420P:\n case AV_PIX_FMT_YUYV422:\n case AV_PIX_FMT_YVYU422:\n case AV_PIX_FMT_UYVY422:\n case AV_PIX_FMT_YUV422P:\n case AV_PIX_FMT_YUV440P:\n case AV_PIX_FMT_YUV444P:\n case AV_PIX_FMT_GBRP:\n case AV_PIX_FMT_GBRAP:\n case AV_PIX_FMT_GRAY8:\n case AV_PIX_FMT_GRAY16BE:\n case AV_PIX_FMT_GRAY16LE:\n case AV_PIX_FMT_YUVJ420P:\n case AV_PIX_FMT_YUVJ422P:\n case AV_PIX_FMT_YUVJ440P:\n case AV_PIX_FMT_YUVJ444P:\n case AV_PIX_FMT_YUVA420P:\n case AV_PIX_FMT_YUVA422P:\n case AV_PIX_FMT_YUVA444P:\n case AV_PIX_FMT_YUV420P9LE:\n case AV_PIX_FMT_YUV420P9BE:\n case AV_PIX_FMT_YUV420P10LE:\n case AV_PIX_FMT_YUV420P10BE:\n case AV_PIX_FMT_YUV420P12LE:\n case AV_PIX_FMT_YUV420P12BE:\n case AV_PIX_FMT_YUV420P14LE:\n case AV_PIX_FMT_YUV420P14BE:\n case AV_PIX_FMT_YUV420P16LE:\n case AV_PIX_FMT_YUV420P16BE:\n case AV_PIX_FMT_YUVA420P9LE:\n case AV_PIX_FMT_YUVA420P9BE:\n case AV_PIX_FMT_YUVA420P10LE:\n case AV_PIX_FMT_YUVA420P10BE:\n case AV_PIX_FMT_YUVA420P16LE:\n case AV_PIX_FMT_YUVA420P16BE:\n case AV_PIX_FMT_YUV422P9LE:\n case AV_PIX_FMT_YUV422P9BE:\n case AV_PIX_FMT_YUV422P10LE:\n case AV_PIX_FMT_YUV422P10BE:\n case AV_PIX_FMT_YUV422P12LE:\n case AV_PIX_FMT_YUV422P12BE:\n case AV_PIX_FMT_YUV422P14LE:\n case AV_PIX_FMT_YUV422P14BE:\n case AV_PIX_FMT_YUV422P16LE:\n case AV_PIX_FMT_YUV422P16BE:\n case AV_PIX_FMT_YUVA422P9LE:\n case AV_PIX_FMT_YUVA422P9BE:\n case AV_PIX_FMT_YUVA422P10LE:\n case AV_PIX_FMT_YUVA422P10BE:\n case AV_PIX_FMT_YUVA422P16LE:\n case AV_PIX_FMT_YUVA422P16BE:\n case AV_PIX_FMT_YUV440P10LE:\n case AV_PIX_FMT_YUV440P10BE:\n case AV_PIX_FMT_YUV440P12LE:\n case AV_PIX_FMT_YUV440P12BE:\n case AV_PIX_FMT_YUV444P9LE:\n case AV_PIX_FMT_YUV444P9BE:\n case AV_PIX_FMT_YUV444P10LE:\n case AV_PIX_FMT_YUV444P10BE:\n case AV_PIX_FMT_YUV444P12LE:\n case AV_PIX_FMT_YUV444P12BE:\n case AV_PIX_FMT_YUV444P14LE:\n case AV_PIX_FMT_YUV444P14BE:\n case AV_PIX_FMT_YUV444P16LE:\n case AV_PIX_FMT_YUV444P16BE:\n case AV_PIX_FMT_YUVA444P9LE:\n case AV_PIX_FMT_YUVA444P9BE:\n case AV_PIX_FMT_YUVA444P10LE:\n case AV_PIX_FMT_YUVA444P10BE:\n case AV_PIX_FMT_YUVA444P16LE:\n case AV_PIX_FMT_YUVA444P16BE:\n case AV_PIX_FMT_GBRP9LE:\n case AV_PIX_FMT_GBRP9BE:\n case AV_PIX_FMT_GBRP10LE:\n case AV_PIX_FMT_GBRP10BE:\n case AV_PIX_FMT_GBRP12LE:\n case AV_PIX_FMT_GBRP12BE:\n case AV_PIX_FMT_GBRP14LE:\n case AV_PIX_FMT_GBRP14BE:\n case AV_PIX_FMT_GBRP16LE:\n case AV_PIX_FMT_GBRP16BE:\n case AV_PIX_FMT_GBRAP12LE:\n case AV_PIX_FMT_GBRAP12BE:\n case AV_PIX_FMT_GBRAP16LE:\n case AV_PIX_FMT_GBRAP16BE:\n w_align = 16; //FIXME assume 16 pixel per macroblock\n h_align = 16 * 2; // interlaced needs 2 macroblocks height\n break;\n case AV_PIX_FMT_YUV411P:\n case AV_PIX_FMT_YUVJ411P:\n case AV_PIX_FMT_UYYVYY411:\n w_align = 32;\n h_align = 16 * 2;\n break;\n case AV_PIX_FMT_YUV410P:\n if (s->codec_id == AV_CODEC_ID_SVQ1) {\n w_align = 64;\n h_align = 64;\n }\n break;\n case AV_PIX_FMT_RGB555:\n if (s->codec_id == AV_CODEC_ID_RPZA) {\n w_align = 4;\n h_align = 4;\n }\n if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }\n break;\n case AV_PIX_FMT_PAL8:\n case AV_PIX_FMT_BGR8:\n case AV_PIX_FMT_RGB8:\n if (s->codec_id == AV_CODEC_ID_SMC ||\n s->codec_id == AV_CODEC_ID_CINEPAK) {\n w_align = 4;\n h_align = 4;\n }\n if (s->codec_id == AV_CODEC_ID_JV ||\n s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }\n break;\n case AV_PIX_FMT_BGR24:\n if ((s->codec_id == AV_CODEC_ID_MSZH) ||\n (s->codec_id == AV_CODEC_ID_ZLIB)) {\n w_align = 4;\n h_align = 4;\n }\n break;\n case AV_PIX_FMT_RGB24:\n if (s->codec_id == AV_CODEC_ID_CINEPAK) {\n w_align = 4;\n h_align = 4;\n }\n break;\n default:\n break;\n }\n\n if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {\n w_align = FFMAX(w_align, 8);\n }\n\n *width = FFALIGN(*width, w_align);\n *height = FFALIGN(*height, h_align);\n if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {\n // some of the optimized chroma MC reads one line too much\n // which is also done in mpeg decoders with lowres > 0\n *height += 2;\n\n // H.264 uses edge emulation for out of frame motion vectors, for this\n // it requires a temporary area large enough to hold a 21x21 block,\n // increasing witdth ensure that the temporary area is large enough,\n // the next rounded up width is 32\n *width = FFMAX(*width, 32);\n }\n\n for (i = 0; i < 4; i++)\n linesize_align[i] = STRIDE_ALIGN;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "avcodec_align_dimensions2", "_file_name": "libavcodec/utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route(\"/search\", methods = [\"POST\"])\ndef search_pages():\n search = request.form.get(\"search\")\n page = db.query(\"select title from page where title = $1\", search).namedresult()\n if len(page) == 0:\n return redirect(\"/%s\" % search)\n else:\n return place_holder(search)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "search_pages", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _cmd_to_dict(self, cmd):\n arg_list = cmd.split()\n no_param_args = [\n 'autodelete',\n 'autoexpand',\n 'bytes',\n 'compressed',\n 'force',\n 'nohdr',\n ]\n one_param_args = [\n 'chapsecret',\n 'cleanrate',\n 'copyrate',\n 'delim',\n 'filtervalue',\n 'grainsize',\n 'hbawwpn',\n 'host',\n 'iogrp',\n 'iscsiname',\n 'mdiskgrp',\n 'name',\n 'rsize',\n 'scsi',\n 'size',\n 'source',\n 'target',\n 'unit',\n 'easytier',\n 'warning',\n 'wwpn',\n ]\n\n # Handle the special case of lsnode which is a two-word command\n # Use the one word version of the command internally\n if arg_list[0] in ('svcinfo', 'svctask'):\n if arg_list[1] == 'lsnode':\n if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! \n ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}\n else:\n ret = {'cmd': 'lsnodecanister'}\n else:\n ret = {'cmd': arg_list[1]}\n arg_list.pop(0)\n else:\n ret = {'cmd': arg_list[0]}\n\n skip = False\n for i in range(1, len(arg_list)):\n if skip:\n skip = False\n continue\n if arg_list[i][0] == '-':\n if arg_list[i][1:] in no_param_args:\n ret[arg_list[i][1:]] = True\n elif arg_list[i][1:] in one_param_args:\n ret[arg_list[i][1:]] = arg_list[i + 1]\n skip = True\n else:\n raise exception.InvalidInput(\n reason=_('unrecognized argument %s') % arg_list[i])\n else:\n ret['obj'] = arg_list[i]\n return ret", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 64]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 64]]}, "_func_name": "_cmd_to_dict", "_file_name": "cinder/tests/test_storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getResults(poll_name):\n conn, c = connectDB()\n req = \"SELECT options from {} where name=?\".format(CFG(\"poll_table_name\"))\n options_str = queryOne(c, req, (poll_name,))\n\n if not options_str:\n raise LookupError(\"Poll '{}' not found in DB\".format(poll_name))\n\n total = 0\n options = options_str.split(\",\")\n results = dict()\n for opt in options:\n count = getOptionCount(c, poll_name, opt)\n total += int(count)\n results.update({opt:count})\n\n conn.close()\n return (results, total)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getResults", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @auth.public\n def get(self, build_id):\n try:\n build_id = int(build_id)\n except ValueError as ex:\n self.response.write(ex.message)\n self.abort(400)\n\n build = model.Build.get_by_id(build_id)\n can_view = build and user.can_view_build_async(build).get_result()\n\n if not can_view:\n if auth.get_current_identity().is_anonymous:\n return self.redirect(gae_users.create_login_url(self.request.url))\n self.response.write('build %d not found' % build_id)\n self.abort(404)\n\n return self.redirect(str(build.url))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[82, 149], [360, 435]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[82, 149], [360, 435]]}, "_func_name": "get", "_file_name": "appengine/cr-buildbucket/handlers.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit', methods=['GET', 'POST'])\ndef edit():\n sql = \"SELECT * FROM users where email = '%s';\" % (session['logged_email'])\n cursor.execute(sql)\n u = cursor.fetchone()\n if request.method == 'POST':\n sql = \"UPDATE users SET nickname = '%s' where email = '%s'\" \\\n % (request.form['nickname'], session['logged_email'])\n cursor.execute(sql)\n sql = \"SELECT * FROM users where email = '%s';\" \\\n % (session['logged_email'])\n cursor.execute(sql)\n u = cursor.fetchone()\n conn.commit()\n flash('Edit Nickname Success!')\n return render_template('users/edit.html', u=u)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[57, 161], [220, 506]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[57, 161], [220, 506]]}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int decode_frame(AVCodecContext *avctx,\n void *data, int *got_frame,\n AVPacket *avpkt)\n{\n PicContext *s = avctx->priv_data;\n AVFrame *frame = data;\n uint32_t *palette;\n int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;\n int i, x, y, plane, tmp, ret, val;\n\n bytestream2_init(&s->g, avpkt->data, avpkt->size);\n\n if (bytestream2_get_bytes_left(&s->g) < 11)\n return AVERROR_INVALIDDATA;\n\n if (bytestream2_get_le16u(&s->g) != 0x1234)\n return AVERROR_INVALIDDATA;\n\n s->width = bytestream2_get_le16u(&s->g);\n s->height = bytestream2_get_le16u(&s->g);\n bytestream2_skip(&s->g, 4);\n tmp = bytestream2_get_byteu(&s->g);\n bits_per_plane = tmp & 0xF;\n s->nb_planes = (tmp >> 4) + 1;\n bpp = bits_per_plane * s->nb_planes;\n if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {\n avpriv_request_sample(avctx, \"Unsupported bit depth\");\n return AVERROR_PATCHWELCOME;\n }\n\n if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {\n bytestream2_skip(&s->g, 2);\n etype = bytestream2_get_le16(&s->g);\n esize = bytestream2_get_le16(&s->g);\n if (bytestream2_get_bytes_left(&s->g) < esize)\n return AVERROR_INVALIDDATA;\n } else {\n etype = -1;\n esize = 0;\n }\n\n avctx->pix_fmt = AV_PIX_FMT_PAL8;\n\n if (av_image_check_size(s->width, s->height, 0, avctx) < 0)\n return -1;\n if (s->width != avctx->width || s->height != avctx->height) {\n ret = ff_set_dimensions(avctx, s->width, s->height);\n if (ret < 0)\n return ret;\n }\n\n if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)\n return ret;\n memset(frame->data[0], 0, s->height * frame->linesize[0]);\n frame->pict_type = AV_PICTURE_TYPE_I;\n frame->palette_has_changed = 1;\n\n pos_after_pal = bytestream2_tell(&s->g) + esize;\n palette = (uint32_t*)frame->data[1];\n if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {\n int idx = bytestream2_get_byte(&s->g);\n npal = 4;\n for (i = 0; i < npal; i++)\n palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];\n } else if (etype == 2) {\n npal = FFMIN(esize, 16);\n for (i = 0; i < npal; i++) {\n int pal_idx = bytestream2_get_byte(&s->g);\n palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];\n }\n } else if (etype == 3) {\n npal = FFMIN(esize, 16);\n for (i = 0; i < npal; i++) {\n int pal_idx = bytestream2_get_byte(&s->g);\n palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];\n }\n } else if (etype == 4 || etype == 5) {\n npal = FFMIN(esize / 3, 256);\n for (i = 0; i < npal; i++) {\n palette[i] = bytestream2_get_be24(&s->g) << 2;\n palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;\n }\n } else {\n if (bpp == 1) {\n npal = 2;\n palette[0] = 0xFF000000;\n palette[1] = 0xFFFFFFFF;\n } else if (bpp == 2) {\n npal = 4;\n for (i = 0; i < npal; i++)\n palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];\n } else {\n npal = 16;\n memcpy(palette, ff_cga_palette, npal * 4);\n }\n }\n // fill remaining palette entries\n memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);\n // skip remaining palette bytes\n bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);\n\n val = 0;\n y = s->height - 1;\n if (bytestream2_get_le16(&s->g)) {\n x = 0;\n plane = 0;\n while (bytestream2_get_bytes_left(&s->g) >= 6) {\n int stop_size, marker, t1, t2;\n\n t1 = bytestream2_get_bytes_left(&s->g);\n t2 = bytestream2_get_le16(&s->g);\n stop_size = t1 - FFMIN(t1, t2);\n // ignore uncompressed block size\n bytestream2_skip(&s->g, 2);\n marker = bytestream2_get_byte(&s->g);\n\n while (plane < s->nb_planes &&\n bytestream2_get_bytes_left(&s->g) > stop_size) {\n int run = 1;\n val = bytestream2_get_byte(&s->g);\n if (val == marker) {\n run = bytestream2_get_byte(&s->g);\n if (run == 0)\n run = bytestream2_get_le16(&s->g);\n val = bytestream2_get_byte(&s->g);\n }\n if (!bytestream2_get_bytes_left(&s->g))\n break;\n\n if (bits_per_plane == 8) {\n picmemset_8bpp(s, frame, val, run, &x, &y);\n if (y < 0)\n goto finish;\n } else {\n picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);\n }\n }\n }\n\n if (x < avctx->width) {\n int run = (y + 1) * avctx->width - x;\n if (bits_per_plane == 8)\n picmemset_8bpp(s, frame, val, run, &x, &y);\n else\n picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);\n }\n } else {\n while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {\n memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));\n bytestream2_skip(&s->g, avctx->width);\n y--;\n }\n }\nfinish:\n\n *got_frame = 1;\n return avpkt->size;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_frame", "_file_name": "libavcodec/pictordec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)\n{\n\tstatic const char module[] = \"NeXTDecode\";\n\tunsigned char *bp, *op;\n\ttmsize_t cc;\n\tuint8* row;\n\ttmsize_t scanline, n;\n\n\t(void) s;\n\t/*\n\t * Each scanline is assumed to start off as all\n\t * white (we assume a PhotometricInterpretation\n\t * of ``min-is-black'').\n\t */\n\tfor (op = (unsigned char*) buf, cc = occ; cc-- > 0;)\n\t\t*op++ = 0xff;\n\n\tbp = (unsigned char *)tif->tif_rawcp;\n\tcc = tif->tif_rawcc;\n\tscanline = tif->tif_scanlinesize;\n\tif (occ % scanline)\n\t{\n\t\tTIFFErrorExt(tif->tif_clientdata, module, \"Fractional scanlines cannot be read\");\n\t\treturn (0);\n\t}\n\tfor (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {\n\t\tn = *bp++, cc--;\n\t\tswitch (n) {\n\t\tcase LITERALROW:\n\t\t\t/*\n\t\t\t * The entire scanline is given as literal values.\n\t\t\t */\n\t\t\tif (cc < scanline)\n\t\t\t\tgoto bad;\n\t\t\t_TIFFmemcpy(row, bp, scanline);\n\t\t\tbp += scanline;\n\t\t\tcc -= scanline;\n\t\t\tbreak;\n\t\tcase LITERALSPAN: {\n\t\t\ttmsize_t off;\n\t\t\t/*\n\t\t\t * The scanline has a literal span that begins at some\n\t\t\t * offset.\n\t\t\t */\n\t\t\tif( cc < 4 )\n\t\t\t\tgoto bad;\n\t\t\toff = (bp[0] * 256) + bp[1];\n\t\t\tn = (bp[2] * 256) + bp[3];\n\t\t\tif (cc < 4+n || off+n > scanline)\n\t\t\t\tgoto bad;\n\t\t\t_TIFFmemcpy(row+off, bp+4, n);\n\t\t\tbp += 4+n;\n\t\t\tcc -= 4+n;\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tuint32 npixels = 0, grey;\n\t\t\tuint32 imagewidth = tif->tif_dir.td_imagewidth;\n if( isTiled(tif) )\n imagewidth = tif->tif_dir.td_tilewidth;\n tmsize_t op_offset = 0;\n\n\t\t\t/*\n\t\t\t * The scanline is composed of a sequence of constant\n\t\t\t * color ``runs''. We shift into ``run mode'' and\n\t\t\t * interpret bytes as codes of the form\n\t\t\t * until we've filled the scanline.\n\t\t\t */\n\t\t\top = row;\n\t\t\tfor (;;) {\n\t\t\t\tgrey = (uint32)((n>>6) & 0x3);\n\t\t\t\tn &= 0x3f;\n\t\t\t\t/*\n\t\t\t\t * Ensure the run does not exceed the scanline\n\t\t\t\t * bounds, potentially resulting in a security\n\t\t\t\t * issue.\n\t\t\t\t */\n\t\t\t\twhile (n-- > 0 && npixels < imagewidth && op_offset < scanline)\n\t\t\t\t\tSETPIXEL(op, grey);\n\t\t\t\tif (npixels >= imagewidth)\n\t\t\t\t\tbreak;\n if (op_offset >= scanline ) {\n TIFFErrorExt(tif->tif_clientdata, module, \"Invalid data for scanline %ld\",\n (long) tif->tif_row);\n return (0);\n }\n\t\t\t\tif (cc == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tn = *bp++, cc--;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t}\n\ttif->tif_rawcp = (uint8*) bp;\n\ttif->tif_rawcc = cc;\n\treturn (1);\nbad:\n\tTIFFErrorExt(tif->tif_clientdata, module, \"Not enough data for scanline %ld\",\n\t (long) tif->tif_row);\n\treturn (0);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "NeXTDecode", "_file_name": "libtiff/tif_next.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (buf->currentLine == NULL ||\n\t spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (l == NULL)\n\t\tbreak;\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len ||\n\t\tspos < 0 || epos < 0 || COLPOS(l, epos) < col)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "formUpdateBuffer", "_file_name": "form.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getCommentsByPostid(self,postid,userid):\n sqlText=\"select (select Count(*) from comment_like where \\\n comments.commentid = comment_like.commentid) as like,(select Count(*) \\\n from comment_like where comments.commentid = \\\n comment_like.commentid and comment_like.userid=%s) as \\\n flag,commentid,name,comment from users,comments where \\\n users.userid=comments.userid and postid=%s order by date desc;\"\n params=[userid,postid]\n result=sql.queryDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getCommentsByPostid", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CURLcode Curl_close(struct Curl_easy *data)\n{\n struct Curl_multi *m;\n\n if(!data)\n return CURLE_OK;\n\n Curl_expire_clear(data); /* shut off timers */\n\n m = data->multi;\n if(m)\n /* This handle is still part of a multi handle, take care of this first\n and detach this handle from there. */\n curl_multi_remove_handle(data->multi, data);\n\n if(data->multi_easy) {\n /* when curl_easy_perform() is used, it creates its own multi handle to\n use and this is the one */\n curl_multi_cleanup(data->multi_easy);\n data->multi_easy = NULL;\n }\n\n /* Destroy the timeout list that is held in the easy handle. It is\n /normally/ done by curl_multi_remove_handle() but this is \"just in\n case\" */\n Curl_llist_destroy(&data->state.timeoutlist, NULL);\n\n data->magic = 0; /* force a clear AFTER the possibly enforced removal from\n the multi handle, since that function uses the magic\n field! */\n\n if(data->state.rangestringalloc)\n free(data->state.range);\n\n /* freed here just in case DONE wasn't called */\n Curl_free_request_state(data);\n\n /* Close down all open SSL info and sessions */\n Curl_ssl_close_all(data);\n Curl_safefree(data->state.first_host);\n Curl_safefree(data->state.scratch);\n Curl_ssl_free_certinfo(data);\n\n /* Cleanup possible redirect junk */\n free(data->req.newurl);\n data->req.newurl = NULL;\n\n if(data->change.referer_alloc) {\n Curl_safefree(data->change.referer);\n data->change.referer_alloc = FALSE;\n }\n data->change.referer = NULL;\n\n Curl_up_free(data);\n Curl_safefree(data->state.buffer);\n Curl_safefree(data->state.headerbuff);\n Curl_safefree(data->state.ulbuf);\n Curl_flush_cookies(data, 1);\n Curl_digest_cleanup(data);\n Curl_safefree(data->info.contenttype);\n Curl_safefree(data->info.wouldredirect);\n\n /* this destroys the channel and we cannot use it anymore after this */\n Curl_resolver_cleanup(data->state.resolver);\n\n Curl_http2_cleanup_dependencies(data);\n Curl_convert_close(data);\n\n /* No longer a dirty share, if it exists */\n if(data->share) {\n Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);\n data->share->dirty--;\n Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);\n }\n\n /* destruct wildcard structures if it is needed */\n Curl_wildcard_dtor(&data->wildcard);\n Curl_freeset(data);\n free(data);\n return CURLE_OK;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Curl_close", "_file_name": "lib/url.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)\n{\n SSL_CTX *ssl_ctx = NULL;\n SSL *ssl = NULL;\n int n, finished = 0;\n X509_VERIFY_PARAM *param;\n uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;\n\n if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))\n {\n rfbClientLog(\"Could not create new SSL context.\\n\");\n return NULL;\n }\n\n param = X509_VERIFY_PARAM_new();\n\n /* Setup verification if not anonymous */\n if (!anonTLS)\n {\n if (cred->x509Credential.x509CACertFile)\n {\n if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))\n {\n rfbClientLog(\"Failed to load CA certificate from %s.\\n\",\n cred->x509Credential.x509CACertFile);\n goto error_free_ctx;\n }\n } else {\n rfbClientLog(\"Using default paths for certificate verification.\\n\");\n SSL_CTX_set_default_verify_paths (ssl_ctx);\n }\n\n if (cred->x509Credential.x509CACrlFile)\n {\n if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))\n {\n rfbClientLog(\"CRLs could not be loaded.\\n\");\n goto error_free_ctx;\n }\n if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;\n }\n\n if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)\n {\n if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)\n {\n rfbClientLog(\"Client certificate could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,\n SSL_FILETYPE_PEM) != 1)\n {\n rfbClientLog(\"Client private key could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_check_private_key(ssl_ctx) == 0) {\n rfbClientLog(\"Client certificate and private key do not match.\\n\");\n goto error_free_ctx;\n }\n }\n\n SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);\n\n if (verify_crls == rfbX509CrlVerifyClient) \n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);\n else if (verify_crls == rfbX509CrlVerifyAll)\n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);\n\n if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))\n {\n rfbClientLog(\"Could not set server name for verification.\\n\");\n goto error_free_ctx;\n }\n SSL_CTX_set1_param(ssl_ctx, param);\n }\n\n if (!(ssl = SSL_new (ssl_ctx)))\n {\n rfbClientLog(\"Could not create a new SSL session.\\n\");\n goto error_free_ctx;\n }\n\n /* TODO: finetune this list, take into account anonTLS bool */\n SSL_set_cipher_list(ssl, \"ALL\");\n\n SSL_set_fd (ssl, sockfd);\n SSL_CTX_set_app_data (ssl_ctx, client);\n\n do\n {\n n = SSL_connect(ssl);\n\t\t\n if (n != 1) \n {\n if (wait_for_data(ssl, n, 1) != 1) \n {\n finished = 1;\n SSL_shutdown(ssl);\n\n goto error_free_ssl;\n }\n }\n } while( n != 1 && finished != 1 );\n\n X509_VERIFY_PARAM_free(param);\n return ssl;\n\nerror_free_ssl:\n SSL_free(ssl);\n\nerror_free_ctx:\n X509_VERIFY_PARAM_free(param);\n SSL_CTX_free(ssl_ctx);\n\n return NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[189, 253]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[189, 253]]}, "_func_name": "open_ssl_connection", "_file_name": "libvncclient/tls_openssl.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _check_camera_tags(tags):\n \"\"\"\n Function that convert stupid code name of a smartphone or camera\n from EXIF to meaningful one by looking a collation in a special MySQL\n table For example instead of just Nikon there can be\n NIKON CORPORATION in EXIF\n\n :param tags: name of a camera and lens from EXIF\n :return: list with one or two strings which are name of\n camera and/or lens. If there is not better name for the gadget\n in database, function just returns name how it is\n \"\"\"\n checked_tags = []\n\n for tag in tags:\n if tag: # If there was this information inside EXIF of the photo\n tag = str(tag).strip()\n log.info('Looking up collation for %s', tag)\n query = ('SELECT right_tag '\n 'FROM tag_table '\n 'WHERE wrong_tag=%s')\n parameters = tag,\n cursor = db.execute_query(query, parameters)\n if not cursor:\n log.error(\"Can't check the tag because of the db error\")\n log.warning(\"Tag will stay as is.\")\n continue\n if cursor.rowcount:\n # Get appropriate tag from the table\n tag = cursor.fetchone()[0]\n log.info('Tag after looking up in tag_tables - %s.', tag)\n\n checked_tags.append(tag)\n return checked_tags", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_check_camera_tags", "_file_name": "photogpsbot/process_image.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @jwt_required\n def delete(self, user_id):\n \"\"\" Deletes user with the corresponding user_id \"\"\"\n return database_utilities.execute_query(f\"\"\"delete from users where user_id = %s\"\"\", (user_id, ))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _exec_cmd(self, args, shell):\n \"\"\"Executes adb commands.\n\n Args:\n args: string or list of strings, program arguments.\n See subprocess.Popen() documentation.\n shell: bool, True to run this command through the system shell,\n False to invoke it directly. See subprocess.Popen() docs.\n\n Returns:\n The output of the adb command run if exit code is 0.\n\n Raises:\n AdbError is raised if the adb command exit code is not 0.\n \"\"\"\n proc = subprocess.Popen(\n args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)\n (out, err) = proc.communicate()\n ret = proc.returncode\n logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out,\n err, ret)\n if ret == 0:\n return out\n else:\n raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_exec_cmd", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)\n{\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n mrb_value value;\n\n fiber_check_cfunc(mrb, c);\n if (resume && c->status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n if (c->status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n if (c->status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n\n if (len >= c->stend - c->stack) {\n mrb_raise(mrb, E_FIBER_ERROR, \"too many arguments to fiber\");\n }\n b = c->stack+1;\n e = b + len;\n while (bcibase->argc = (int)len;\n value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];\n }\n else {\n value = fiber_result(mrb, a, len);\n }\n fiber_switch_context(mrb, c);\n\n if (vmexec) {\n c->vmexec = TRUE;\n value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);\n mrb->c = old_c;\n }\n else {\n MARK_CONTEXT_MODIFY(c);\n }\n return value;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[251, 305], [374, 448], [510, 553], [615, 686], [751, 791], [814, 926], [1153, 1189]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[251, 305], [374, 448], [510, 553], [615, 686], [751, 791], [814, 926], [1153, 1189]]}, "_func_name": "fiber_switch", "_file_name": "mrbgems/mruby-fiber/src/fiber.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def fetch_resultSet(self, session, id):\n self._openContainer(session)\n\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT class, data FROM %s WHERE identifier = '%s';\" %\n (self.table, sid)\n )\n res = self._query(query)\n try:\n rdict = res.dictresult()[0]\n except IndexError:\n raise ObjectDoesNotExistException('%s/%s' % (self.id, sid))\n\n data = rdict['data']\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # Insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000', '\\x00')\n ndata = ndata.replace('\\\\012', '\\n')\n # data is res.dictresult()\n cl = rdict['class']\n rset = dynamic.buildObject(session, cl, [[]])\n rset.deserialize(session, ndata)\n rset.id = id\n\n # Update expires\n now = time.time()\n nowStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(now))\n expires = now + self.get_default(session, 'expires', 600)\n rset.timeExpires = expires\n expiresStr = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(expires))\n\n query = (\"UPDATE %s SET timeAccessed = '%s', expires = '%s' \"\n \"WHERE identifier = '%s';\" %\n (self.table, nowStr, expiresStr, sid)\n )\n self._query(query)\n return rset", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[213, 321], [1291, 1462]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[213, 321], [1291, 1462]]}, "_func_name": "fetch_resultSet", "_file_name": "cheshire3/sql/resultSetStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool extractFileTo(zip* zip, const std::string &file, std::string& to,\n char* buf, size_t len) {\n auto sep = file.rfind('/');\n if (sep != std::string::npos) {\n auto path = to + file.substr(0, sep);\n if (!HHVM_FN(is_dir)(path) && !HHVM_FN(mkdir)(path, 0777, true)) {\n return false;\n }\n\n if (sep == file.length() - 1) {\n return true;\n }\n }\n\n to.append(file);\n struct zip_stat zipStat;\n if (zip_stat(zip, file.c_str(), 0, &zipStat) != 0) {\n return false;\n }\n\n auto zipFile = zip_fopen_index(zip, zipStat.index, 0);\n FAIL_IF_INVALID_PTR(zipFile);\n\n auto outFile = fopen(to.c_str(), \"wb\");\n if (outFile == nullptr) {\n zip_fclose(zipFile);\n return false;\n }\n\n for (auto n = zip_fread(zipFile, buf, len); n != 0;\n n = zip_fread(zipFile, buf, len)) {\n if (n < 0 || fwrite(buf, sizeof(char), n, outFile) != n) {\n zip_fclose(zipFile);\n fclose(outFile);\n remove(to.c_str());\n return false;\n }\n }\n\n zip_fclose(zipFile);\n if (fclose(outFile) != 0) {\n return false;\n }\n\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[129, 159], [193, 235], [333, 369], [394, 522]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[129, 159], [193, 235], [333, 369], [394, 522]]}, "_func_name": "HPHP::extractFileTo", "_file_name": "hphp/runtime/ext/zip/ext_zip.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "wiki_handle_http_request(HttpRequest *req)\n{\n HttpResponse *res = http_response_new(req);\n char *page = http_request_get_path_info(req); \n char *command = http_request_get_query_string(req); \n char *wikitext = \"\";\n\n util_dehttpize(page); \t/* remove any encoding on the requested\n\t\t\t\t page name. */\n\n if (!strcmp(page, \"/\"))\n {\n if (access(\"WikiHome\", R_OK) != 0)\n\twiki_redirect(res, \"/WikiHome?create\");\n page = \"/WikiHome\";\n }\n\n if (!strcmp(page, \"/styles.css\"))\n {\n /* Return CSS page */\n http_response_set_content_type(res, \"text/css\");\n http_response_printf(res, \"%s\", CssData);\n http_response_send(res);\n exit(0);\n }\n\n if (!strcmp(page, \"/favicon.ico\"))\n {\n /* Return favicon */\n http_response_set_content_type(res, \"image/ico\");\n http_response_set_data(res, FaviconData, FaviconDataLen);\n http_response_send(res);\n exit(0);\n }\n\n\n page = page + 1; \t\t/* skip slash */\n\n if (!strncmp(page, \"api/\", 4))\n {\n char *p;\n\n page += 4; \n for (p=page; *p != '\\0'; p++)\n\tif (*p=='?') { *p ='\\0'; break; }\n \n wiki_handle_rest_call(req, res, page); \n exit(0);\n }\n\n /* A little safety. issue a malformed request for any paths,\n * There shouldn't need to be any..\n */\n if (strchr(page, '/'))\n {\n http_response_set_status(res, 404, \"Not Found\");\n http_response_printf(res, \"404 Not Found\\n\");\n http_response_send(res);\n exit(0);\n }\n\n if (!strcmp(page, \"Changes\"))\n {\n wiki_show_changes_page(res);\n }\n else if (!strcmp(page, \"ChangesRss\"))\n {\n wiki_show_changes_page_rss(res);\n }\n else if (!strcmp(page, \"Search\"))\n {\n wiki_show_search_results_page(res, http_request_param_get(req, \"expr\"));\n }\n else if (!strcmp(page, \"Create\"))\n {\n if ( (wikitext = http_request_param_get(req, \"title\")) != NULL)\n\t{\n\t /* create page and redirect */\n\t wiki_redirect(res, http_request_param_get(req, \"title\"));\n\t}\n else\n\t{\n\t /* show create page form */\n\t wiki_show_create_page(res);\n\t}\n }\n else\n {\n /* TODO: dont blindly write wikitext data to disk */\n if ( (wikitext = http_request_param_get(req, \"wikitext\")) != NULL)\n\t{\n\t file_write(page, wikitext);\t \n\t}\n\n if (access(page, R_OK) == 0) \t/* page exists */\n\t{\n\t wikitext = file_read(page);\n\t \n\t if (!strcmp(command, \"edit\"))\n\t {\n\t /* print edit page */\n\t wiki_show_edit_page(res, wikitext, page);\n\t }\n\t else\n\t {\n\t wiki_show_page(res, wikitext, page);\n\t }\n\t}\n else\n\t{\n\t if (!strcmp(command, \"create\"))\n\t {\n\t wiki_show_edit_page(res, NULL, page);\n\t }\n\t else\n\t {\n\t char buf[1024];\n\t snprintf(buf, 1024, \"%s?create\", page);\n\t wiki_redirect(res, buf);\n\t }\n\t}\n }\n\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1350, 1375]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1350, 1375]]}, "_func_name": "wiki_handle_http_request", "_file_name": "src/wiki.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int __get_data_block(struct inode *inode, sector_t iblock,\n\t\t\tstruct buffer_head *bh, int create, int flag,\n\t\t\tpgoff_t *next_pgofs)\n{\n\tstruct f2fs_map_blocks map;\n\tint err;\n\n\tmap.m_lblk = iblock;\n\tmap.m_len = bh->b_size >> inode->i_blkbits;\n\tmap.m_next_pgofs = next_pgofs;\n\n\terr = f2fs_map_blocks(inode, &map, create, flag);\n\tif (!err) {\n\t\tmap_bh(bh, inode->i_sb, map.m_pblk);\n\t\tbh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;\n\t\tbh->b_size = (u64)map.m_len << inode->i_blkbits;\n\t}\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__get_data_block", "_file_name": "fs/f2fs/data.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void gmc_mmx(uint8_t *dst, uint8_t *src,\n int stride, int h, int ox, int oy,\n int dxx, int dxy, int dyx, int dyy,\n int shift, int r, int width, int height)\n{\n const int w = 8;\n const int ix = ox >> (16 + shift);\n const int iy = oy >> (16 + shift);\n const int oxs = ox >> 4;\n const int oys = oy >> 4;\n const int dxxs = dxx >> 4;\n const int dxys = dxy >> 4;\n const int dyxs = dyx >> 4;\n const int dyys = dyy >> 4;\n const uint16_t r4[4] = { r, r, r, r };\n const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };\n const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };\n const uint64_t shift2 = 2 * shift;\n#define MAX_STRIDE 4096U\n#define MAX_H 8U\n uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];\n int x, y;\n\n const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);\n const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);\n const int dxh = dxy * (h - 1);\n const int dyw = dyx * (w - 1);\n int need_emu = (unsigned) ix >= width - w || width < w ||\n (unsigned) iy >= height - h || height< h\n ;\n\n if ( // non-constant fullpel offset (3% of blocks)\n ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |\n (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||\n // uses more than 16 bits of subpel mv (only at huge resolution)\n (dxx | dxy | dyx | dyy) & 15 ||\n (need_emu && (h > MAX_H || stride > MAX_STRIDE))) {\n // FIXME could still use mmx for some of the rows\n ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,\n shift, r, width, height);\n return;\n }\n\n src += ix + iy * stride;\n if (need_emu) {\n ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);\n src = edge_buf;\n }\n\n __asm__ volatile (\n \"movd %0, %%mm6 \\n\\t\"\n \"pxor %%mm7, %%mm7 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n :: \"r\" (1 << shift));\n\n for (x = 0; x < w; x += 4) {\n uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),\n oxs - dxys + dxxs * (x + 1),\n oxs - dxys + dxxs * (x + 2),\n oxs - dxys + dxxs * (x + 3) };\n uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),\n oys - dyys + dyxs * (x + 1),\n oys - dyys + dyxs * (x + 2),\n oys - dyys + dyxs * (x + 3) };\n\n for (y = 0; y < h; y++) {\n __asm__ volatile (\n \"movq %0, %%mm4 \\n\\t\"\n \"movq %1, %%mm5 \\n\\t\"\n \"paddw %2, %%mm4 \\n\\t\"\n \"paddw %3, %%mm5 \\n\\t\"\n \"movq %%mm4, %0 \\n\\t\"\n \"movq %%mm5, %1 \\n\\t\"\n \"psrlw $12, %%mm4 \\n\\t\"\n \"psrlw $12, %%mm5 \\n\\t\"\n : \"+m\" (*dx4), \"+m\" (*dy4)\n : \"m\" (*dxy4), \"m\" (*dyy4));\n\n __asm__ volatile (\n \"movq %%mm6, %%mm2 \\n\\t\"\n \"movq %%mm6, %%mm1 \\n\\t\"\n \"psubw %%mm4, %%mm2 \\n\\t\"\n \"psubw %%mm5, %%mm1 \\n\\t\"\n \"movq %%mm2, %%mm0 \\n\\t\"\n \"movq %%mm4, %%mm3 \\n\\t\"\n \"pmullw %%mm1, %%mm0 \\n\\t\" // (s - dx) * (s - dy)\n \"pmullw %%mm5, %%mm3 \\n\\t\" // dx * dy\n \"pmullw %%mm5, %%mm2 \\n\\t\" // (s - dx) * dy\n \"pmullw %%mm4, %%mm1 \\n\\t\" // dx * (s - dy)\n\n \"movd %4, %%mm5 \\n\\t\"\n \"movd %3, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm3 \\n\\t\" // src[1, 1] * dx * dy\n \"pmullw %%mm4, %%mm2 \\n\\t\" // src[0, 1] * (s - dx) * dy\n\n \"movd %2, %%mm5 \\n\\t\"\n \"movd %1, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm1 \\n\\t\" // src[1, 0] * dx * (s - dy)\n \"pmullw %%mm4, %%mm0 \\n\\t\" // src[0, 0] * (s - dx) * (s - dy)\n \"paddw %5, %%mm1 \\n\\t\"\n \"paddw %%mm3, %%mm2 \\n\\t\"\n \"paddw %%mm1, %%mm0 \\n\\t\"\n \"paddw %%mm2, %%mm0 \\n\\t\"\n\n \"psrlw %6, %%mm0 \\n\\t\"\n \"packuswb %%mm0, %%mm0 \\n\\t\"\n \"movd %%mm0, %0 \\n\\t\"\n\n : \"=m\" (dst[x + y * stride])\n : \"m\" (src[0]), \"m\" (src[1]),\n \"m\" (src[stride]), \"m\" (src[stride + 1]),\n \"m\" (*r4), \"m\" (shift2));\n src += stride;\n }\n src += 4 - h * stride;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "gmc_mmx", "_file_name": "libavcodec/x86/mpegvideodsp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n if (length > end - start)\n return AVERROR_INVALIDDATA;\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0)\n return err;\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "cbs_jpeg_split_fragment", "_file_name": "libavcodec/cbs_jpeg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void AllocateDataSet(cmsIT8* it8)\n{\n TABLE* t = GetTable(it8);\n\n if (t -> Data) return; // Already allocated\n\n t-> nSamples = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_FIELDS\"));\n t-> nPatches = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_SETS\"));\n\n t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));\n if (t->Data == NULL) {\n\n SynError(it8, \"AllocateDataSet: Unable to allocate data array\");\n }\n\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[260, 392]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[260, 392]]}, "_func_name": "AllocateDataSet", "_file_name": "src/cmscgats.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void ffs_user_copy_worker(struct work_struct *work)\n{\n\tstruct ffs_io_data *io_data = container_of(work, struct ffs_io_data,\n\t\t\t\t\t\t work);\n\tint ret = io_data->req->status ? io_data->req->status :\n\t\t\t\t\t io_data->req->actual;\n\tbool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;\n\n\tif (io_data->read && ret > 0) {\n\t\tuse_mm(io_data->mm);\n\t\tret = copy_to_iter(io_data->buf, ret, &io_data->data);\n\t\tif (iov_iter_count(&io_data->data))\n\t\t\tret = -EFAULT;\n\t\tunuse_mm(io_data->mm);\n\t}\n\n\tio_data->kiocb->ki_complete(io_data->kiocb, ret, ret);\n\n\tif (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)\n\t\teventfd_signal(io_data->ffs->ffs_eventfd, 1);\n\n\tusb_ep_free_request(io_data->ep, io_data->req);\n\n\tif (io_data->read)\n\t\tkfree(io_data->to_free);\n\tkfree(io_data->buf);\n\tkfree(io_data);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ffs_user_copy_worker", "_file_name": "drivers/usb/gadget/function/f_fs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void rds_tcp_kill_sock(struct net *net)\n{\n\tstruct rds_tcp_connection *tc, *_tc;\n\tstruct sock *sk;\n\tLIST_HEAD(tmp_list);\n\tstruct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);\n\n\trds_tcp_listen_stop(rtn->rds_tcp_listen_sock);\n\trtn->rds_tcp_listen_sock = NULL;\n\tflush_work(&rtn->rds_tcp_accept_w);\n\tspin_lock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {\n\t\tstruct net *c_net = read_pnet(&tc->conn->c_net);\n\n\t\tif (net != c_net)\n\t\t\tcontinue;\n\t\tlist_move_tail(&tc->t_tcp_node, &tmp_list);\n\t}\n\tspin_unlock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) {\n\t\tsk = tc->t_sock->sk;\n\t\tsk->sk_prot->disconnect(sk, 0);\n\t\ttcp_done(sk);\n\t\tif (tc->conn->c_passive)\n\t\t\trds_conn_destroy(tc->conn->c_passive);\n\t\trds_conn_destroy(tc->conn);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[644, 717]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[644, 717]]}, "_func_name": "rds_tcp_kill_sock", "_file_name": "net/rds/tcp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def update_history_and_sourcebyinstitution(conn, sqlite, k10plus, ai):\n \"\"\"\n Get all current sources and title numbers from Solr and log them into database.\n \"\"\"\n current_sources = get_all_current_sources(k10plus, ai)\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_sourcebyinstitutions = get_all_old_sourcebyinstitutions(conn, sqlite)\n current_sourcebyinstitutions = []\n\n for source in current_sources:\n\n for institution in current_institutions:\n\n if not institution or institution == \" \" or '\"' in institution:\n continue\n\n sourcebyinstitution = \"SID \" + str(source) + \" (\" + institution + \")\"\n current_sourcebyinstitutions.append(sourcebyinstitution)\n\n params = {\n \"q\": 'source_id:%s AND institution:\"%s\"' % (source, institution),\n \"rows\": 0,\n \"wt\": \"json\"\n }\n\n # check k10plus\n result = get_solr_result(k10plus, params)\n number = result[\"response\"][\"numFound\"]\n if number != 0:\n sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (?, ?)'\n sqlite.execute(sql, (sourcebyinstitution, number))\n conn.commit()\n else:\n # check ai\n result = get_solr_result(ai, params)\n number = result[\"response\"][\"numFound\"]\n if number != 0:\n # TODO: escape via sqlite\n sql = 'INSERT INTO history (sourcebyinstitution, titles) VALUES (?, ?)'\n sqlite.execute(sql, (sourcebyinstitution, number))\n conn.commit()\n\n if sourcebyinstitution not in old_sourcebyinstitutions:\n logging.info(\"The %s is now connected to SID %s.\", institution, source)\n sql = \"INSERT INTO sourcebyinstitution (sourcebyinstitution) VALUES (?)\"\n sqlite.execute(sql, (sourcebyinstitution))\n conn.commit()\n\n if number != 0:\n old_sourcebyinstitution_number = get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution)\n if number < old_sourcebyinstitution_number:\n message = \"Die Anzahl der Titel hat sich bei %s gegenueber einem frueheren Import verringert.\" % (sourcebyinstitution)\n send_message(message)\n\n # requests.exceptions.ConnectionError: HTTPConnectionPool(XXXXXX): Max retries exceeded\n time.sleep(0.25)\n\n for old_sourcebyinstitution in old_sourcebyinstitutions:\n if old_sourcebyinstitution not in current_sourcebyinstitutions:\n message = \"Die %s ist nicht laenger für die SID %s angesigelt.\" % (institution, source)\n send_message(message)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_history_and_sourcebyinstitution", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int __init big_key_init(void)\n{\n\tstruct crypto_skcipher *cipher;\n\tstruct crypto_rng *rng;\n\tint ret;\n\n\trng = crypto_alloc_rng(big_key_rng_name, 0, 0);\n\tif (IS_ERR(rng)) {\n\t\tpr_err(\"Can't alloc rng: %ld\\n\", PTR_ERR(rng));\n\t\treturn PTR_ERR(rng);\n\t}\n\n\tbig_key_rng = rng;\n\n\t/* seed RNG */\n\tret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));\n\tif (ret) {\n\t\tpr_err(\"Can't reset rng: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\t/* init block cipher */\n\tcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(cipher)) {\n\t\tret = PTR_ERR(cipher);\n\t\tpr_err(\"Can't alloc crypto: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\tbig_key_skcipher = cipher;\n\n\tret = register_key_type(&key_type_big_key);\n\tif (ret < 0) {\n\t\tpr_err(\"Can't register type: %d\\n\", ret);\n\t\tgoto error_cipher;\n\t}\n\n\treturn 0;\n\nerror_cipher:\n\tcrypto_free_skcipher(big_key_skcipher);\nerror_rng:\n\tcrypto_free_rng(big_key_rng);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "big_key_init", "_file_name": "security/keys/big_key.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_last_active_users(limit):\n \"\"\"\n Get from the database a tuple of users who have been recently using\n the bot\n :param limit: integer that specifies how much users to get\n :return: tuple of tuples with users info\n \"\"\"\n log.info('Evaluating last active users with date of '\n 'last time when they used bot...')\n\n # From photo_queries_table2 we take chat_id of the last\n # active users and from 'users' table we take info about these\n # users by chat_id which is a foreign key\n query = ('SELECT p.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'FROM photo_queries_table2 p '\n 'INNER JOIN users u '\n 'ON p.chat_id = u.chat_id '\n 'GROUP BY u.chat_id, u.first_name, u.nickname, u.last_name, '\n 'u.language '\n 'ORDER BY MAX(time)'\n f'DESC LIMIT %s')\n\n parameters = limit,\n\n try:\n cursor = db.execute_query(query, parameters)\n except DatabaseConnectionError:\n log.error(\"Cannot get the last active users because of some \"\n \"problems with the database\")\n raise\n\n last_active_users = cursor.fetchall()\n return last_active_users", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_last_active_users", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType load_tile(Image *image,Image *tile_image,\n XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,\n ExceptionInfo *exception)\n{\n ssize_t\n y;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n ssize_t\n count;\n\n unsigned char\n *graydata;\n\n XCFPixelInfo\n *xcfdata,\n *xcfodata;\n\n xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));\n if (xcfdata == (XCFPixelInfo *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n xcfodata=xcfdata;\n graydata=(unsigned char *) xcfdata; /* used by gray and indexed */\n count=ReadBlob(image,data_length,(unsigned char *) xcfdata);\n if (count != (ssize_t) data_length)\n ThrowBinaryException(CorruptImageError,\"NotEnoughPixelData\",\n image->filename);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (inDocInfo->image_type == GIMP_GRAY)\n {\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);\n SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)\n inLayerInfo->alpha),q);\n graydata++;\n q+=GetPixelChannels(tile_image);\n }\n }\n else\n if (inDocInfo->image_type == GIMP_RGB)\n {\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);\n SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);\n SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);\n SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :\n ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);\n xcfdata++;\n q+=GetPixelChannels(tile_image);\n }\n }\n if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)\n break;\n }\n xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);\n return MagickTrue;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[339, 418]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[339, 418]]}, "_func_name": "load_tile", "_file_name": "coders/xcf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def add_user(username, password):\n encPass = crypt.crypt(password,\"22\")\n #subprocess escapes the username stopping code injection\n subprocess.call(['useradd','-G','docker,wheel','-p',encPass,username])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_user", "_file_name": "vuedj/configtitania/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_list_context(context=None):\n\tlist_context = frappe._dict(\n\t\ttemplate = \"templates/includes/blog/blog.html\",\n\t\tget_list = get_blog_list,\n\t\thide_filters = True,\n\t\tchildren = get_children(),\n\t\t# show_search = True,\n\t\ttitle = _('Blog')\n\t)\n\n\tcategory = frappe.local.form_dict.blog_category or frappe.local.form_dict.category\n\tif category:\n\t\tcategory_title = get_blog_category(category)\n\t\tlist_context.sub_title = _(\"Posts filed under {0}\").format(category_title)\n\t\tlist_context.title = category_title\n\n\telif frappe.local.form_dict.blogger:\n\t\tblogger = frappe.db.get_value(\"Blogger\", {\"name\": frappe.local.form_dict.blogger}, \"full_name\")\n\t\tlist_context.sub_title = _(\"Posts by {0}\").format(blogger)\n\t\tlist_context.title = blogger\n\n\telif frappe.local.form_dict.txt:\n\t\tlist_context.sub_title = _('Filtered by \"{0}\"').format(frappe.local.form_dict.txt)\n\n\tif list_context.sub_title:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"},\n\t\t\t\t\t\t\t\t{\"name\": \"Blog\", \"route\": \"/blog\"}]\n\telse:\n\t\tlist_context.parents = [{\"name\": _(\"Home\"), \"route\": \"/\"}]\n\n\tlist_context.update(frappe.get_doc(\"Blog Settings\", \"Blog Settings\").as_dict(no_default_fields=True))\n\treturn list_context", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[244, 328], [768, 853]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[244, 328], [768, 853]]}, "_func_name": "get_list_context", "_file_name": "frappe/website/doctype/blog_post/blog_post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tcp_forward(self, host_port, device_port):\n \"\"\"Starts tcp forwarding.\n\n Args:\n host_port: Port number to use on the computer.\n device_port: Port number to use on the android device.\n \"\"\"\n self.forward(['tcp:%d' % host_port, 'tcp:%d' % device_port])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tcp_forward", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def test_settings_path_skip_issue_909(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'skip =\\n'\n ' file_to_be_skipped.py\\n'\n 'skip_glob =\\n'\n ' *glob_skip*\\n')\n\n base_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n base_dir.join('file_to_be_skipped.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors\n check_output(['isort', '--check-only'])\n results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])\n os.chdir(str(test_run_directory))\n\n assert b'skipped 2' in results.lower()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1201, 1338]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1201, 1338]]}, "_func_name": "test_settings_path_skip_issue_909", "_file_name": "test_isort.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void Magick::Image::read(MagickCore::Image *image,\n MagickCore::ExceptionInfo *exceptionInfo)\n{\n // Ensure that multiple image frames were not read.\n if (image != (MagickCore::Image *) NULL &&\n image->next != (MagickCore::Image *) NULL)\n {\n MagickCore::Image\n *next;\n\n // Destroy any extra image frames\n next=image->next;\n image->next=(MagickCore::Image *) NULL;\n next->previous=(MagickCore::Image *) NULL;\n DestroyImageList(next);\n }\n replaceImage(image);\n if (exceptionInfo->severity == MagickCore::UndefinedException &&\n image == (MagickCore::Image *) NULL)\n {\n (void) MagickCore::DestroyExceptionInfo(exceptionInfo);\n if (!quiet())\n throwExceptionExplicit(MagickCore::ImageWarning,\n \"No image was loaded.\");\n }\n ThrowImageException;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[799, 805]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[799, 805]]}, "_func_name": "Magick::Image::read", "_file_name": "Magick++/lib/Image.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "bool WddxPacket::recursiveAddVar(const String& varName,\n const Variant& varVariant,\n bool hasVarTag) {\n\n bool isArray = varVariant.isArray();\n bool isObject = varVariant.isObject();\n\n if (isArray || isObject) {\n if (hasVarTag) {\n m_packetString += \"\";\n }\n\n Array varAsArray;\n Object varAsObject = varVariant.toObject();\n if (isArray) varAsArray = varVariant.toArray();\n if (isObject) varAsArray = varAsObject.toArray();\n\n int length = varAsArray.length();\n if (length > 0) {\n ArrayIter it = ArrayIter(varAsArray);\n if (it.first().isString()) isObject = true;\n if (isObject) {\n m_packetString += \"\";\n if (!isArray) {\n m_packetString += \"\";\n m_packetString += varAsObject->o_getClassName().c_str();\n m_packetString += \"\";\n }\n } else {\n m_packetString += \"\";\n }\n for (ArrayIter it(varAsArray); it; ++it) {\n Variant key = it.first();\n Variant value = it.second();\n recursiveAddVar(key.toString(), value, isObject);\n }\n if (isObject) {\n m_packetString += \"\";\n }\n else {\n m_packetString += \"\";\n }\n }\n else {\n //empty object\n if (isObject) {\n m_packetString += \"\";\n if (!isArray) {\n m_packetString += \"\";\n m_packetString += varAsObject->o_getClassName().c_str();\n m_packetString += \"\";\n }\n m_packetString += \"\";\n }\n }\n if (hasVarTag) {\n m_packetString += \"\";\n }\n return true;\n }\n\n std::string varType = getDataTypeString(varVariant.getType()).data();\n if (!getWddxEncoded(varType, \"\", varName, false).empty()) {\n std::string varValue;\n if (varType.compare(\"boolean\") == 0) {\n varValue = varVariant.toBoolean() ? \"true\" : \"false\";\n } else {\n varValue = StringUtil::HtmlEncode(varVariant.toString(),\n StringUtil::QuoteStyle::Double,\n \"UTF-8\", false, false).toCppString();\n }\n m_packetString += getWddxEncoded(varType, varValue, varName, hasVarTag);\n return true;\n }\n\n return false;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::WddxPacket::recursiveAddVar", "_file_name": "hphp/runtime/ext/wddx/ext_wddx.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static OPJ_BOOL opj_j2k_write_mco( opj_j2k_t *p_j2k,\n struct opj_stream_private *p_stream,\n struct opj_event_mgr * p_manager\n )\n{\n OPJ_BYTE * l_current_data = 00;\n OPJ_UINT32 l_mco_size;\n opj_tcp_t * l_tcp = 00;\n opj_simple_mcc_decorrelation_data_t * l_mcc_record;\n OPJ_UINT32 i;\n\n /* preconditions */\n assert(p_j2k != 00);\n assert(p_manager != 00);\n assert(p_stream != 00);\n\n l_tcp =&(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]);\n\t\n l_mco_size = 5 + l_tcp->m_nb_mcc_records;\n if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) {\n\n OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc(p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size);\n if (! new_header_tile_data) {\n opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data);\n p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL;\n p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0;\n opj_event_msg(p_manager, EVT_ERROR, \"Not enough memory to write MCO marker\\n\");\n return OPJ_FALSE;\n }\n p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data;\n p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size;\n }\n l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data;\n\n\n opj_write_bytes(l_current_data,J2K_MS_MCO,2); /* MCO */\n l_current_data += 2;\n\n opj_write_bytes(l_current_data,l_mco_size-2,2); /* Lmco */\n l_current_data += 2;\n\n opj_write_bytes(l_current_data,l_tcp->m_nb_mcc_records,1); /* Nmco : only one tranform stage*/\n ++l_current_data;\n\n l_mcc_record = l_tcp->m_mcc_records;\n for (i=0;im_nb_mcc_records;++i) {\n opj_write_bytes(l_current_data,l_mcc_record->m_index,1);/* Imco -> use the mcc indicated by 1*/\n ++l_current_data;\n ++l_mcc_record;\n }\n\n if (opj_stream_write_data(p_stream,p_j2k->m_specific_param.m_encoder.m_header_tile_data,l_mco_size,p_manager) != l_mco_size) {\n return OPJ_FALSE;\n }\n\n return OPJ_TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "opj_j2k_write_mco", "_file_name": "src/lib/openjp2/j2k.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n int swap, uint32_t namesz, uint32_t descsz,\n size_t noff, size_t doff, int *flags, size_t size, int clazz)\n{\n#ifdef ELFCORE\n\tint os_style = -1;\n\t/*\n\t * Sigh. The 2.0.36 kernel in Debian 2.1, at\n\t * least, doesn't correctly implement name\n\t * sections, in core dumps, as specified by\n\t * the \"Program Linking\" section of \"UNIX(R) System\n\t * V Release 4 Programmer's Guide: ANSI C and\n\t * Programming Support Tools\", because my copy\n\t * clearly says \"The first 'namesz' bytes in 'name'\n\t * contain a *null-terminated* [emphasis mine]\n\t * character representation of the entry's owner\n\t * or originator\", but the 2.0.36 kernel code\n\t * doesn't include the terminating null in the\n\t * name....\n\t */\n\tif ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) ||\n\t (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) {\n\t\tos_style = OS_STYLE_SVR4;\n\t} \n\n\tif ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) {\n\t\tos_style = OS_STYLE_FREEBSD;\n\t}\n\n\tif ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11)\n\t == 0)) {\n\t\tos_style = OS_STYLE_NETBSD;\n\t}\n\n\tif (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {\n\t\tif (file_printf(ms, \", %s-style\", os_style_names[os_style])\n\t\t == -1)\n\t\t\treturn 1;\n\t\t*flags |= FLAGS_DID_CORE_STYLE;\n\t\t*flags |= os_style;\n\t}\n\n\tswitch (os_style) {\n\tcase OS_STYLE_NETBSD:\n\t\tif (type == NT_NETBSD_CORE_PROCINFO) {\n\t\t\tchar sbuf[512];\n\t\t\tstruct NetBSD_elfcore_procinfo pi;\n\t\t\tmemset(&pi, 0, sizeof(pi));\n\t\t\tmemcpy(&pi, nbuf + doff, descsz);\n\n\t\t\tif (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \"\n\t\t\t \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\",\n\t\t\t file_printable(sbuf, sizeof(sbuf),\n\t\t\t CAST(char *, pi.cpi_name)),\n\t\t\t elf_getu32(swap, (uint32_t)pi.cpi_pid),\n\t\t\t elf_getu32(swap, pi.cpi_euid),\n\t\t\t elf_getu32(swap, pi.cpi_egid),\n\t\t\t elf_getu32(swap, pi.cpi_nlwps),\n\t\t\t elf_getu32(swap, (uint32_t)pi.cpi_siglwp),\n\t\t\t elf_getu32(swap, pi.cpi_signo),\n\t\t\t elf_getu32(swap, pi.cpi_sigcode)) == -1)\n\t\t\t\treturn 1;\n\n\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\treturn 1;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {\n\t\t\tsize_t i, j;\n\t\t\tunsigned char c;\n\t\t\t/*\n\t\t\t * Extract the program name. We assume\n\t\t\t * it to be 16 characters (that's what it\n\t\t\t * is in SunOS 5.x and Linux).\n\t\t\t *\n\t\t\t * Unfortunately, it's at a different offset\n\t\t\t * in various OSes, so try multiple offsets.\n\t\t\t * If the characters aren't all printable,\n\t\t\t * reject it.\n\t\t\t */\n\t\t\tfor (i = 0; i < NOFFSETS; i++) {\n\t\t\t\tunsigned char *cname, *cp;\n\t\t\t\tsize_t reloffset = prpsoffsets(i);\n\t\t\t\tsize_t noffset = doff + reloffset;\n\t\t\t\tsize_t k;\n\t\t\t\tfor (j = 0; j < 16; j++, noffset++,\n\t\t\t\t reloffset++) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the buffer; if\n\t\t\t\t\t * we are, just give up.\n\t\t\t\t\t */\n\t\t\t\t\tif (noffset >= size)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the contents;\n\t\t\t\t\t * if we are, this obviously\n\t\t\t\t\t * isn't the right offset.\n\t\t\t\t\t */\n\t\t\t\t\tif (reloffset >= descsz)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\tc = nbuf[noffset];\n\t\t\t\t\tif (c == '\\0') {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A '\\0' at the\n\t\t\t\t\t\t * beginning is\n\t\t\t\t\t\t * obviously wrong.\n\t\t\t\t\t\t * Any other '\\0'\n\t\t\t\t\t\t * means we're done.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * A nonprintable\n\t\t\t\t\t\t * character is also\n\t\t\t\t\t\t * wrong.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (!isprint(c) || isquote(c))\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Well, that worked.\n\t\t\t\t */\n\n\t\t\t\t/*\n\t\t\t\t * Try next offsets, in case this match is\n\t\t\t\t * in the middle of a string.\n\t\t\t\t */\n\t\t\t\tfor (k = i + 1 ; k < NOFFSETS; k++) {\n\t\t\t\t\tsize_t no;\n\t\t\t\t\tint adjust = 1;\n\t\t\t\t\tif (prpsoffsets(k) >= prpsoffsets(i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor (no = doff + prpsoffsets(k);\n\t\t\t\t\t no < doff + prpsoffsets(i); no++)\n\t\t\t\t\t\tadjust = adjust\n\t\t\t\t\t\t && isprint(nbuf[no]);\n\t\t\t\t\tif (adjust)\n\t\t\t\t\t\ti = k;\n\t\t\t\t}\n\n\t\t\t\tcname = (unsigned char *)\n\t\t\t\t &nbuf[doff + prpsoffsets(i)];\n\t\t\t\tfor (cp = cname; *cp && isprint(*cp); cp++)\n\t\t\t\t\tcontinue;\n\t\t\t\t/*\n\t\t\t\t * Linux apparently appends a space at the end\n\t\t\t\t * of the command line: remove it.\n\t\t\t\t */\n\t\t\t\twhile (cp > cname && isspace(cp[-1]))\n\t\t\t\t\tcp--;\n\t\t\t\tif (file_printf(ms, \", from '%.*s'\",\n\t\t\t\t (int)(cp - cname), cname) == -1)\n\t\t\t\t\treturn 1;\n\t\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\t\treturn 1;\n\n\t\t\ttryanother:\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n#endif\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[4087, 4135]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[4087, 4135]]}, "_func_name": "do_core_note", "_file_name": "src/readelf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void hid_input_field(struct hid_device *hid, struct hid_field *field,\n\t\t\t __u8 *data, int interrupt)\n{\n\tunsigned n;\n\tunsigned count = field->report_count;\n\tunsigned offset = field->report_offset;\n\tunsigned size = field->report_size;\n\t__s32 min = field->logical_minimum;\n\t__s32 max = field->logical_maximum;\n\t__s32 *value;\n\n\tvalue = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);\n\tif (!value)\n\t\treturn;\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tvalue[n] = min < 0 ?\n\t\t\tsnto32(hid_field_extract(hid, data, offset + n * size,\n\t\t\t size), size) :\n\t\t\thid_field_extract(hid, data, offset + n * size, size);\n\n\t\t/* Ignore report if ErrorRollOver */\n\t\tif (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&\n\t\t value[n] >= min && value[n] <= max &&\n\t\t field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)\n\t\t\tgoto exit;\n\t}\n\n\tfor (n = 0; n < count; n++) {\n\n\t\tif (HID_MAIN_ITEM_VARIABLE & field->flags) {\n\t\t\thid_process_event(hid, field, &field->usage[n], value[n], interrupt);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (field->value[n] >= min && field->value[n] <= max\n\t\t\t&& field->usage[field->value[n] - min].hid\n\t\t\t&& search(value, field->value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);\n\n\t\tif (value[n] >= min && value[n] <= max\n\t\t\t&& field->usage[value[n] - min].hid\n\t\t\t&& search(field->value, value[n], count))\n\t\t\t\thid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);\n\t}\n\n\tmemcpy(field->value, value, count * sizeof(__s32));\nexit:\n\tkfree(value);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[740, 803]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[740, 803]]}, "_func_name": "hid_input_field", "_file_name": "drivers/hid/hid-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('//save', methods=['POST'])\ndef save_page_edit(page_name):\n # grab the new content from the user\n content = request.form.get('content')\n # check if 'page_name' exists in the database\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n result = query.namedresult()\n # if it doesn't exist, create a new page in the database\n if len(result) < 1:\n db.insert(\n 'page', {\n 'page_name': page_name\n }\n )\n else:\n pass\n # now that we're certain that the page exists in the database, we again grab the query\n # and insert new content in the database\n query = db.query(\"select id from page where page_name = '%s'\" % page_name)\n page_id = query.namedresult()[0].id\n db.insert(\n 'page_content', {\n 'page_id': page_id,\n 'content': content,\n 'timestamp': time.strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n }\n )\n return redirect(\"/%s\" % page_name)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "save_page_edit", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification)\n{\n\tint ret;\n\tstruct fd f;\n\tstruct sock *sock;\n\tstruct inode *inode;\n\tstruct mqueue_inode_info *info;\n\tstruct sk_buff *nc;\n\n\taudit_mq_notify(mqdes, notification);\n\n\tnc = NULL;\n\tsock = NULL;\n\tif (notification != NULL) {\n\t\tif (unlikely(notification->sigev_notify != SIGEV_NONE &&\n\t\t\t notification->sigev_notify != SIGEV_SIGNAL &&\n\t\t\t notification->sigev_notify != SIGEV_THREAD))\n\t\t\treturn -EINVAL;\n\t\tif (notification->sigev_notify == SIGEV_SIGNAL &&\n\t\t\t!valid_signal(notification->sigev_signo)) {\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (notification->sigev_notify == SIGEV_THREAD) {\n\t\t\tlong timeo;\n\n\t\t\t/* create the notify skb */\n\t\t\tnc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);\n\t\t\tif (!nc) {\n\t\t\t\tret = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (copy_from_user(nc->data,\n\t\t\t\t\tnotification->sigev_value.sival_ptr,\n\t\t\t\t\tNOTIFY_COOKIE_LEN)) {\n\t\t\t\tret = -EFAULT;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\t/* TODO: add a header? */\n\t\t\tskb_put(nc, NOTIFY_COOKIE_LEN);\n\t\t\t/* and attach it to the socket */\nretry:\n\t\t\tf = fdget(notification->sigev_signo);\n\t\t\tif (!f.file) {\n\t\t\t\tret = -EBADF;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsock = netlink_getsockbyfilp(f.file);\n\t\t\tfdput(f);\n\t\t\tif (IS_ERR(sock)) {\n\t\t\t\tret = PTR_ERR(sock);\n\t\t\t\tsock = NULL;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\ttimeo = MAX_SCHEDULE_TIMEOUT;\n\t\t\tret = netlink_attachskb(sock, nc, &timeo, NULL);\n\t\t\tif (ret == 1) {\n\t\t\t\tsock = NULL;\n\t\t\t\tgoto retry;\n\t\t\t}\n\t\t\tif (ret) {\n\t\t\t\tsock = NULL;\n\t\t\t\tnc = NULL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t}\n\n\tf = fdget(mqdes);\n\tif (!f.file) {\n\t\tret = -EBADF;\n\t\tgoto out;\n\t}\n\n\tinode = file_inode(f.file);\n\tif (unlikely(f.file->f_op != &mqueue_file_operations)) {\n\t\tret = -EBADF;\n\t\tgoto out_fput;\n\t}\n\tinfo = MQUEUE_I(inode);\n\n\tret = 0;\n\tspin_lock(&info->lock);\n\tif (notification == NULL) {\n\t\tif (info->notify_owner == task_tgid(current)) {\n\t\t\tremove_notification(info);\n\t\t\tinode->i_atime = inode->i_ctime = current_time(inode);\n\t\t}\n\t} else if (info->notify_owner != NULL) {\n\t\tret = -EBUSY;\n\t} else {\n\t\tswitch (notification->sigev_notify) {\n\t\tcase SIGEV_NONE:\n\t\t\tinfo->notify.sigev_notify = SIGEV_NONE;\n\t\t\tbreak;\n\t\tcase SIGEV_THREAD:\n\t\t\tinfo->notify_sock = sock;\n\t\t\tinfo->notify_cookie = nc;\n\t\t\tsock = NULL;\n\t\t\tnc = NULL;\n\t\t\tinfo->notify.sigev_notify = SIGEV_THREAD;\n\t\t\tbreak;\n\t\tcase SIGEV_SIGNAL:\n\t\t\tinfo->notify.sigev_signo = notification->sigev_signo;\n\t\t\tinfo->notify.sigev_value = notification->sigev_value;\n\t\t\tinfo->notify.sigev_notify = SIGEV_SIGNAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tinfo->notify_owner = get_pid(task_tgid(current));\n\t\tinfo->notify_user_ns = get_user_ns(current_user_ns());\n\t\tinode->i_atime = inode->i_ctime = current_time(inode);\n\t}\n\tspin_unlock(&info->lock);\nout_fput:\n\tfdput(f);\nout:\n\tif (sock)\n\t\tnetlink_detachskb(sock, nc);\n\telse if (nc)\n\t\tdev_kfree_skb(nc);\n\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "do_mq_notify", "_file_name": "ipc/mqueue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def create_cf_base():\n url = 'http://codeforces.com/problemset/'\n r = requests.get(url)\n max_page = 0\n soup = BeautifulSoup(r.text, \"lxml\")\n base = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\cf.db\")\n conn = base.cursor()\n conn.execute(\"create table problems (problem INTEGER, diff CHAR)\")\n for i in available_tags:\n conn.execute(\"create table \" + i + \" (problems INTEGER, diff CHAR)\")\n\n for link in soup.find_all(attrs={\"class\" : \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[3]))\n\n a = 0\n b = 0\n f = False\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/problemset/' + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n old = ''\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5 and old != s[3] + s[4]:\n a = s[3]\n b = s[4]\n old = s[3] + s[4]\n if not f:\n f = True\n last_update = old\n conn.execute(\"insert into problems values (?, ?)\", (a, b))\n if len(s) == 4 and s[3] in available_tags:\n conn.execute(\"insert into \" + s[3] + \" values (?, ?)\", (a, b))\n\n base.commit()\n base.close()\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"create table users (chat_id INTEGER, username STRING, last_update STRING, last_problem STRING, state INTEGER)\")\n conn.execute(\"create table last_update_problemset (problem STRING)\")\n conn.execute(\"insert into last_update_problemset values (?)\", (last_update, ))\n settings.commit()\n settings.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[360, 437], [1385, 1468]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[360, 437], [1385, 1468]]}, "_func_name": "create_cf_base", "_file_name": "bases/createcfbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def verify_rno(self, rno):\n query = \"SELECT COUNT(rno) FROM rides WHERE rno = {rno}\".format(rno = rno)\n self.cursor.execute(query)\n result = self.cursor.fetchone()\n if (int(result[0]) > 0):\n return True \n else:\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[31, 149]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[31, 149]]}, "_func_name": "verify_rno", "_file_name": "book_rides/book_rides.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def verify_email(self, member):\n self.cursor.execute(\"SELECT COUNT(email) FROM members WHERE email = ':email'\", {'email':member})\n result = self.cursor.fetchone()\n if (int(result[0]) > 0):\n return True \n else:\n return False", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "verify_email", "_file_name": "book_rides/book_rides.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,\n\t\t\tstruct rq_map_data *map_data,\n\t\t\tconst struct iov_iter *iter, gfp_t gfp_mask)\n{\n\tbool copy = false;\n\tunsigned long align = q->dma_pad_mask | queue_dma_alignment(q);\n\tstruct bio *bio = NULL;\n\tstruct iov_iter i;\n\tint ret;\n\n\tif (map_data)\n\t\tcopy = true;\n\telse if (iov_iter_alignment(iter) & align)\n\t\tcopy = true;\n\telse if (queue_virt_boundary(q))\n\t\tcopy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);\n\n\ti = *iter;\n\tdo {\n\t\tret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);\n\t\tif (ret)\n\t\t\tgoto unmap_rq;\n\t\tif (!bio)\n\t\t\tbio = rq->bio;\n\t} while (iov_iter_count(&i));\n\n\tif (!bio_flagged(bio, BIO_USER_MAPPED))\n\t\trq->cmd_flags |= REQ_COPY_USER;\n\treturn 0;\n\nunmap_rq:\n\t__blk_rq_unmap_user(bio);\n\trq->bio = NULL;\n\treturn -EINVAL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[293, 308]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[293, 308]]}, "_func_name": "blk_rq_map_user_iov", "_file_name": "block/blk-map.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def closeGame(ID):\n\tdb.execute(\"UPDATE games set Running = 'No' WHERE ID = %i\" % ID)\n\tdatabase.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[19, 85]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[19, 85]]}, "_func_name": "closeGame", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _modify_3par_iscsi_host(self, hostname, iscsi_iqn):\n # when using -add, you can not send the persona or domain options\n self.common._cli_run('createhost -iscsi -add %s %s'\n % (hostname, iscsi_iqn), None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[134, 253]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[134, 253]]}, "_func_name": "_modify_3par_iscsi_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int blk_init_allocated_queue(struct request_queue *q)\n{\n\tWARN_ON_ONCE(q->mq_ops);\n\n\tq->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);\n\tif (!q->fq)\n\t\treturn -ENOMEM;\n\n\tif (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))\n\t\tgoto out_free_flush_queue;\n\n\tif (blk_init_rl(&q->root_rl, q, GFP_KERNEL))\n\t\tgoto out_exit_flush_rq;\n\n\tINIT_WORK(&q->timeout_work, blk_timeout_work);\n\tq->queue_flags\t\t|= QUEUE_FLAG_DEFAULT;\n\n\t/*\n\t * This also sets hw/phys segments, boundary and size\n\t */\n\tblk_queue_make_request(q, blk_queue_bio);\n\n\tq->sg_reserved_size = INT_MAX;\n\n\tif (elevator_init(q))\n\t\tgoto out_exit_flush_rq;\n\treturn 0;\n\nout_exit_flush_rq:\n\tif (q->exit_rq_fn)\n\t\tq->exit_rq_fn(q, q->fq->flush_rq);\nout_free_flush_queue:\n\tblk_free_flush_queue(q->fq);\n\treturn -ENOMEM;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[768, 785]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[768, 785]]}, "_func_name": "blk_init_allocated_queue", "_file_name": "block/blk-core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n int\n y;\n\n MagickBooleanType\n monochrome;\n\n QuantumInfo\n *quantum_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n i;\n\n size_t\n count,\n length;\n\n unsigned char\n *pixels;\n\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n\n#define CHUNK 16384\n\n int\n flush,\n level;\n\n unsigned char\n *compressed_pixels;\n\n z_stream\n stream;\n\n compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,\n sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (next_image->compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) CHUNK;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) CHUNK-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1009, 1062]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1009, 1062]]}, "_func_name": "WritePSDChannel", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_sub(name):\n karma = karma_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if karma is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES('{}',-1,0)\n '''.format(name))\n db.commit()\n logger.debug('Inserted into karmadb -1 karma for {}'.format(name))\n db.close()\n return -1\n\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n else:\n karma = karma - 1\n try:\n cursor.execute('''\n UPDATE people SET karma = {0} WHERE name = '{1}'\n '''.format(karma, name))\n db.commit()\n logger.debug('Inserted into karmadb -1 karma for {}'.format(name))\n db.close()\n return karma\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[162, 267], [615, 721]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[162, 267], [615, 721]]}, "_func_name": "karma_sub", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def GameNewPlayed(Played, ID):\n\tdb.execute(\"UPDATE games set GamesPlayed = %i WHERE ID = %i\" % (Played, ID))\n\tdatabase.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[31, 109]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[31, 109]]}, "_func_name": "GameNewPlayed", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _create_vdisk(self, name, size, units, opts):\n \"\"\"Create a new vdisk.\"\"\"\n\n LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)\n\n model_update = None\n autoex = '-autoexpand' if opts['autoexpand'] else ''\n easytier = '-easytier on' if opts['easytier'] else '-easytier off'\n\n # Set space-efficient options\n if opts['rsize'] == -1:\n ssh_cmd_se_opt = ''\n else:\n ssh_cmd_se_opt = (\n '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %\n {'rsize': opts['rsize'],\n 'autoex': autoex,\n 'warn': opts['warning']})\n if opts['compression']:\n ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'\n else:\n ssh_cmd_se_opt = ssh_cmd_se_opt + (\n ' -grainsize %d' % opts['grainsize'])\n\n ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '\n '-iogrp 0 -size %(size)s -unit '\n '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'\n % {'name': name,\n 'mdiskgrp': self.configuration.storwize_svc_volpool_name,\n 'size': size, 'unit': units, 'easytier': easytier,\n 'ssh_cmd_se_opt': ssh_cmd_se_opt})\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), '_create_vdisk',\n ssh_cmd, out, err)\n\n # Ensure that the output is as expected\n match_obj = re.search('Virtual Disk, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('_create_vdisk %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': name, 'out': str(out), 'err': str(err)})\n\n LOG.debug(_('leave: _create_vdisk: volume %s ') % name)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[181, 317], [388, 420], [465, 654], [690, 755], [773, 883], [884, 1311]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[181, 317], [388, 420], [465, 654], [690, 755], [773, 883], [884, 1311]]}, "_func_name": "_create_vdisk", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_monthly_ranks_for_scene(db, scene, tag):\n\n sql = \"SELECT date, rank FROM ranks WHERE scene='{}' AND player='{}'\".format(scene, tag)\n res = db.exec(sql)\n\n res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]\n\n # Build up a dict of {date: rank}\n ranks = {}\n for r in res:\n ranks[r[0]] = r[1]\n\n return ranks", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[50, 143]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[50, 143]]}, "_func_name": "get_monthly_ranks_for_scene", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self,data):\n connection = self.connect()\n try:\n # The following is a flaw\n query = \"INSERT INTO crimes(description) VALUES (%s);\"\n with connection.cursor() as cursor:\n cursor.execute(query, data)\n connection.commit()\n finally:\n connection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,\n MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)\n{\n char\n postscript_file[MaxTextExtent];\n\n const MagicInfo\n *magic_info;\n\n FILE\n *ps_file;\n\n ImageInfo\n *clone_info;\n\n Image\n *image2;\n\n unsigned char\n magick[2*MaxTextExtent];\n\n\n if ((clone_info=CloneImageInfo(image_info)) == NULL)\n return(image);\n clone_info->blob=(void *) NULL;\n clone_info->length=0;\n\n /* Obtain temporary file */\n (void) AcquireUniqueFilename(postscript_file);\n ps_file=fopen_utf8(postscript_file,\"wb\");\n if (ps_file == (FILE *) NULL)\n goto FINISH;\n\n /* Copy postscript to temporary file */\n (void) SeekBlob(image,PS_Offset,SEEK_SET);\n (void) ReadBlob(image, 2*MaxTextExtent, magick);\n\n (void) SeekBlob(image,PS_Offset,SEEK_SET);\n while(PS_Size-- > 0)\n {\n (void) fputc(ReadBlobByte(image),ps_file);\n }\n (void) fclose(ps_file);\n\n /* Detect file format - Check magic.mgk configuration file. */\n magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);\n if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;\n /* printf(\"Detected:%s \\n\",magic_info->name); */\n if(exception->severity != UndefinedException) goto FINISH_UNL;\n if(magic_info->name == (char *) NULL) goto FINISH_UNL;\n\n (void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);\n\n /* Read nested image */\n /*FormatString(clone_info->filename,\"%s:%s\",magic_info->name,postscript_file);*/\n FormatLocaleString(clone_info->filename,MaxTextExtent,\"%s\",postscript_file);\n image2=ReadImage(clone_info,exception);\n\n if (!image2)\n goto FINISH_UNL;\n\n /*\n Replace current image with new image while copying base image\n attributes.\n */\n (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);\n (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);\n (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);\n image2->depth=image->depth;\n DestroyBlob(image2);\n image2->blob=ReferenceBlob(image->blob);\n\n if ((image->rows == 0) || (image->columns == 0))\n DeleteImageFromList(&image);\n\n AppendImageToList(&image,image2);\n\n FINISH_UNL:\n (void) RelinquishUniqueFileResource(postscript_file);\n FINISH:\n DestroyImageInfo(clone_info);\n return(image);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1318, 1396]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1318, 1396]]}, "_func_name": "ExtractPostscript", "_file_name": "coders/wpg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) {\n if(!isWritable() || srcLength == 0 || srcChars == NULL) {\n return *this;\n }\n\n // Perform all remaining operations relative to srcChars + srcStart.\n // From this point forward, do not use srcStart.\n srcChars += srcStart;\n\n if(srcLength < 0) {\n // get the srcLength if necessary\n if((srcLength = u_strlen(srcChars)) == 0) {\n return *this;\n }\n }\n\n int32_t oldLength = length();\n int32_t newLength = oldLength + srcLength;\n\n // Check for append onto ourself\n const UChar* oldArray = getArrayStart();\n if (isBufferWritable() &&\n oldArray < srcChars + srcLength &&\n srcChars < oldArray + oldLength) {\n // Copy into a new UnicodeString and start over\n UnicodeString copy(srcChars, srcLength);\n if (copy.isBogus()) {\n setToBogus();\n return *this;\n }\n return doAppend(copy.getArrayStart(), 0, srcLength);\n }\n\n // optimize append() onto a large-enough, owned string\n if((newLength <= getCapacity() && isBufferWritable()) ||\n cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) {\n UChar *newArray = getArrayStart();\n // Do not copy characters when\n // UChar *buffer=str.getAppendBuffer(...);\n // is followed by\n // str.append(buffer, length);\n // or\n // str.appendString(buffer, length)\n // or similar.\n if(srcChars != newArray + oldLength) {\n us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength);\n }\n setLength(newLength);\n }\n return *this;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[487, 532]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[487, 532]]}, "_func_name": "UnicodeString::doAppend", "_file_name": "icu4c/source/common/unistr.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "wiki_handle_http_request(HttpRequest *req)\n{\n HttpResponse *res = http_response_new(req);\n char *page = http_request_get_path_info(req); \n char *command = http_request_get_query_string(req); \n char *wikitext = \"\";\n\n util_dehttpize(page); \t/* remove any encoding on the requested\n\t\t\t\t page name. */\n\n if (!strcmp(page, \"/\"))\n {\n if (access(\"WikiHome\", R_OK) != 0)\n\twiki_redirect(res, \"/WikiHome?create\");\n page = \"/WikiHome\";\n }\n\n if (!strcmp(page, \"/styles.css\"))\n {\n /* Return CSS page */\n http_response_set_content_type(res, \"text/css\");\n http_response_printf(res, \"%s\", CssData);\n http_response_send(res);\n exit(0);\n }\n\n if (!strcmp(page, \"/favicon.ico\"))\n {\n /* Return favicon */\n http_response_set_content_type(res, \"image/ico\");\n http_response_set_data(res, FaviconData, FaviconDataLen);\n http_response_send(res);\n exit(0);\n }\n\n\n page = page + 1; \t\t/* skip slash */\n\n if (!strncmp(page, \"api/\", 4))\n {\n char *p;\n\n page += 4; \n for (p=page; *p != '\\0'; p++)\n\tif (*p=='?') { *p ='\\0'; break; }\n \n wiki_handle_rest_call(req, res, page); \n exit(0);\n }\n\n /* A little safety. issue a malformed request for any paths,\n * There shouldn't need to be any..\n */\n if (!page_name_is_good(page))\n {\n http_response_set_status(res, 404, \"Not Found\");\n http_response_printf(res, \"404 Not Found\\n\");\n http_response_send(res);\n exit(0);\n }\n\n if (!strcmp(page, \"Changes\"))\n {\n wiki_show_changes_page(res);\n }\n else if (!strcmp(page, \"ChangesRss\"))\n {\n wiki_show_changes_page_rss(res);\n }\n else if (!strcmp(page, \"Search\"))\n {\n wiki_show_search_results_page(res, http_request_param_get(req, \"expr\"));\n }\n else if (!strcmp(page, \"Create\"))\n {\n if ( (wikitext = http_request_param_get(req, \"title\")) != NULL)\n\t{\n\t /* create page and redirect */\n\t wiki_redirect(res, http_request_param_get(req, \"title\"));\n\t}\n else\n\t{\n\t /* show create page form */\n\t wiki_show_create_page(res);\n\t}\n }\n else\n {\n /* TODO: dont blindly write wikitext data to disk */\n if ( (wikitext = http_request_param_get(req, \"wikitext\")) != NULL)\n\t{\n\t file_write(page, wikitext);\t \n\t}\n\n if (access(page, R_OK) == 0) \t/* page exists */\n\t{\n\t wikitext = file_read(page);\n\t \n\t if (!strcmp(command, \"edit\"))\n\t {\n\t /* print edit page */\n\t wiki_show_edit_page(res, wikitext, page);\n\t }\n\t else\n\t {\n\t wiki_show_page(res, wikitext, page);\n\t }\n\t}\n else\n\t{\n\t if (!strcmp(command, \"create\"))\n\t {\n\t wiki_show_edit_page(res, NULL, page);\n\t }\n\t else\n\t {\n\t char buf[1024];\n\t snprintf(buf, 1024, \"%s?create\", page);\n\t wiki_redirect(res, buf);\n\t }\n\t}\n }\n\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "wiki_handle_http_request", "_file_name": "src/wiki.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int get_task_ioprio(struct task_struct *p)\n{\n\tint ret;\n\n\tret = security_task_getioprio(p);\n\tif (ret)\n\t\tgoto out;\n\tret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM);\n\tif (p->io_context)\n\t\tret = p->io_context->ioprio;\nout:\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[178, 198]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[178, 198]]}, "_func_name": "get_task_ioprio", "_file_name": "block/ioprio.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_iscsi_ip_addrs(self):\n generator = self._port_conf_generator('svcinfo lsportip')\n header = next(generator, None)\n if not header:\n return\n\n for port_data in generator:\n try:\n port_node_id = port_data['node_id']\n port_ipv4 = port_data['IP_address']\n port_ipv6 = port_data['IP_address_6']\n state = port_data['state']\n except KeyError:\n self._handle_keyerror('lsportip', header)\n\n if port_node_id in self._storage_nodes and (\n state == 'configured' or state == 'online'):\n node = self._storage_nodes[port_node_id]\n if len(port_ipv4):\n node['ipv4'].append(port_ipv4)\n if len(port_ipv6):\n node['ipv6'].append(port_ipv6)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[35, 101]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[35, 101]]}, "_func_name": "_get_iscsi_ip_addrs", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def updateKey(client):\n\t\"\"\"Updates the contents of a key that already exists in our system.\n\tReturns an error if the specified key doesn't exist for the specified user.\n\t\"\"\"\n\tglobal NOT_FOUND\n\tglobal CREATED\n\n\tvalidateClient(client)\n\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateNewKeyData(token_data)\n\n\t# Use 'w' flag to replace existing key file with the new key data\n\tif os.path.isfile('keys/%s/%s.key' % (client, token_data['name'])):\n\t\twith open('keys/%s/%s.key' % (client, token_data['name']), 'w') as f:\n\t\t\tf.write(token_data['key'])\n\telse:\n\t\traise FoxlockError(NOT_FOUND, \"Key '%s' not found\" % token_data['name'])\n\n\treturn 'Key successfully updated', CREATED", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[233, 234]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[233, 234]]}, "_func_name": "updateKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "TfLiteStatus Subgraph::Invoke() {\n if (!consistent_) {\n ReportError(\"Invoke called on model that is not consistent.\");\n return kTfLiteError;\n }\n\n TfLiteStatus status = kTfLiteOk;\n if (state_ == kStateUninvokable) {\n ReportError(\"Invoke called on model that is not ready.\");\n return kTfLiteError;\n } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {\n ReportError(\"Non-persistent memory is not available.\");\n return kTfLiteError;\n }\n\n // This is only needed for UseNNAPI(true);\n if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) {\n TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate()));\n // only need to modify the graph once upon the first invocation.\n applied_nnapi_delegate_ = true;\n }\n\n // Invocations are always done in node order.\n // Note that calling Invoke repeatedly will cause the original memory plan to\n // be reused, unless either ResizeInputTensor() or AllocateTensors() has been\n // called.\n for (int execution_plan_index = 0;\n execution_plan_index < execution_plan_.size(); execution_plan_index++) {\n if (execution_plan_index == next_execution_plan_index_to_prepare_) {\n TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());\n TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >=\n execution_plan_index);\n }\n int node_index = execution_plan_[execution_plan_index];\n TfLiteNode& node = nodes_and_registration_[node_index].first;\n const TfLiteRegistration& registration =\n nodes_and_registration_[node_index].second;\n\n const char* op_name = nullptr;\n if (profiler_) op_name = GetTFLiteOpName(registration);\n TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index);\n\n // TODO(ycling): This is an extra loop through inputs to check if the data\n // need to be copied from Delegate buffer to raw memory, which is often not\n // needed. We may want to cache this in prepare to know if this needs to be\n // done for a node or not.\n for (int i = 0; i < node.inputs->size; ++i) {\n int tensor_index = node.inputs->data[i];\n if (tensor_index == kTfLiteOptionalTensor) {\n continue;\n }\n TfLiteTensor* tensor = &tensors_[tensor_index];\n if (tensor->delegate && tensor->delegate != node.delegate &&\n tensor->data_is_stale) {\n TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index));\n }\n if (tensor->data.raw == nullptr && tensor->bytes > 0) {\n if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {\n // In general, having a tensor here with no buffer will be an error.\n // However, for the reshape operator, the second input tensor is only\n // used for the shape, not for the data. Thus, null buffer is ok.\n continue;\n } else {\n // In all other cases, we need to return an error as otherwise we will\n // trigger a null pointer dereference (likely).\n ReportError(\"Input tensor %d lacks data\", tensor_index);\n return kTfLiteError;\n }\n }\n }\n\n if (check_cancelled_func_ != nullptr &&\n check_cancelled_func_(cancellation_data_)) {\n ReportError(\"Client requested cancel during Invoke()\");\n return kTfLiteError;\n }\n\n EnsureTensorsVectorCapacity();\n tensor_resized_since_op_invoke_ = false;\n if (OpInvoke(registration, &node) != kTfLiteOk) {\n return ReportOpError(&context_, node, registration, node_index,\n \"failed to invoke\");\n }\n\n // Force execution prep for downstream ops if the latest op triggered the\n // resize of a dynamic tensor.\n if (tensor_resized_since_op_invoke_ &&\n HasDynamicTensor(context_, node.outputs)) {\n next_execution_plan_index_to_prepare_ = execution_plan_index + 1;\n\n // This happens when an intermediate dynamic tensor is resized.\n // We don't have to prepare all the ops, but we need to recompute\n // the allocation plan.\n if (next_execution_plan_index_to_plan_allocation_ >\n next_execution_plan_index_to_prepare_) {\n next_execution_plan_index_to_plan_allocation_ =\n next_execution_plan_index_to_prepare_;\n if (memory_planner_) {\n TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter(\n next_execution_plan_index_to_plan_allocation_ - 1));\n }\n }\n }\n }\n\n return status;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tflite::Subgraph::Invoke", "_file_name": "tensorflow/lite/core/subgraph.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def handle_file(u: Profile, headline: str, category: str, text: str, file):\n m: Media = Media()\n upload_base_path: str = 'uploads/' + str(date.today().year)\n high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace(\" \", \"_\"))\n if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):\n os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)\n with open(high_res_file_name, 'wb+') as destination:\n for chunk in file.chunks():\n destination.write(chunk)\n # TODO crop image\n original = Image.open(high_res_file_name)\n width, height = original.size\n diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))\n width /= diameter\n height /= diameter\n width *= IMAGE_SCALE\n height *= IMAGE_SCALE\n cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)\n cropped.save(low_res_file_name)\n m.text = escape(text)\n m.cachedText = compile_markdown(escape(text))\n m.category = escape(category)\n m.highResFile = \"/\" + high_res_file_name\n m.lowResFile = \"/\" + low_res_file_name\n m.headline = escape(headline)\n m.save()\n mu: MediaUpload = MediaUpload()\n mu.UID = u\n mu.MID = m\n mu.save()\n logging.info(\"Uploaded file '\" + str(file.name) + \"' and cropped it. The resulting PK is \" + str(m.pk))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle_file", "_file_name": "c3shop/frontpage/management/mediatools/media_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def initHeader(self):\n \"\"\"Initialize the IP header according to the IP format definition.\n\n \"\"\"\n\n # Ethernet header\n\n # Retrieve remote MAC address\n dstMacAddr = arpreq.arpreq(self.remoteIP)\n if dstMacAddr is not None:\n dstMacAddr = dstMacAddr.replace(':', '')\n dstMacAddr = binascii.unhexlify(dstMacAddr)\n else:\n # Force ARP resolution\n p = subprocess.Popen([\"/bin/ping\", \"-c1\", self.remoteIP])\n p.wait()\n time.sleep(0.1)\n\n dstMacAddr = arpreq.arpreq(self.remoteIP)\n if dstMacAddr is not None:\n dstMacAddr = dstMacAddr.replace(':', '')\n dstMacAddr = binascii.unhexlify(dstMacAddr)\n else:\n raise Exception(\"Cannot resolve IP address to a MAC address for IP: '{}'\".format(self.remoteIP))\n\n # Retrieve local MAC address\n srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]\n\n eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))\n eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))\n eth_type = Field(name='eth.type', domain=Raw(b\"\\x08\\x00\"))\n\n\n # IP header\n\n ip_ver = Field(\n name='ip.version', domain=BitArray(\n value=bitarray('0100'))) # IP Version 4\n ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))\n ip_tos = Field(\n name='ip.tos',\n domain=Data(\n dataType=BitArray(nbBits=8),\n originalValue=bitarray('00000000'),\n svas=SVAS.PERSISTENT))\n ip_tot_len = Field(\n name='ip.len', domain=BitArray(bitarray('0000000000000000')))\n ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))\n ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT))\n ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT))\n ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT))\n ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED))\n ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000')))\n ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))\n ip_daddr = Field(\n name='ip.dst', domain=IPv4(self.remoteIP))\n ip_payload = Field(name='ip.payload', domain=Raw())\n\n ip_ihl.domain = Size([ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id, ip_flags,\n ip_frag_off,\n ip_ttl, ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32))\n ip_tot_len.domain = Size([ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr,\n ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8))\n ip_checksum.domain = InternetChecksum(fields=[ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))\n \n self.header = Symbol(name='Ethernet layer', fields=[eth_dst,\n eth_src,\n eth_type,\n ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr,\n ip_payload])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "initHeader", "_file_name": "src/netzob/Simulator/Channels/RawEthernetClient.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def handle_message(self, ch, method, properties, body):\n \"\"\"\n this is a pika.basic_consumer callback\n handles client inputs, runs appropriate workflows and views\n\n Args:\n ch: amqp channel\n method: amqp method\n properties:\n body: message body\n \"\"\"\n input = {}\n try:\n self.sessid = method.routing_key\n\n input = json_decode(body)\n data = input['data']\n\n # since this comes as \"path\" we dont know if it's view or workflow yet\n #TODO: just a workaround till we modify ui to\n if 'path' in data:\n if data['path'] in settings.VIEW_URLS:\n data['view'] = data['path']\n else:\n data['wf'] = data['path']\n session = Session(self.sessid)\n\n headers = {'remote_ip': input['_zops_remote_ip']}\n\n if 'wf' in data:\n output = self._handle_workflow(session, data, headers)\n elif 'job' in data:\n\n self._handle_job(session, data, headers)\n return\n else:\n output = self._handle_view(session, data, headers)\n\n except HTTPError as e:\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), \"code\": e.code}\n log.exception(\"Http error occurred\")\n except:\n self.current = Current(session=session, input=data)\n self.current.headers = headers\n import sys\n if hasattr(sys, '_called_from_test'):\n raise\n err = traceback.format_exc()\n output = {'error': self._prepare_error_msg(err), \"code\": 500}\n log.exception(\"Worker error occurred with messsage body:\\n%s\" % body)\n if 'callbackID' in input:\n output['callbackID'] = input['callbackID']\n log.info(\"OUTPUT for %s: %s\" % (self.sessid, output))\n output['reply_timestamp'] = time()\n self.send_output(output)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[867, 929]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[867, 929]]}, "_func_name": "handle_message", "_file_name": "zengine/wf_daemon.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def shame_add(name):\n shame = shame_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if shame is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES('{}',0,1)\n '''.format(name))\n db.commit()\n logger.debug('Inserted into karmadb 1 shame for {}'.format(name))\n db.close()\n return 1\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n\n else:\n shame = shame + 1\n try:\n cursor.execute('''\n UPDATE people SET shame = {0} WHERE name = '{1}'\n '''.format(shame, name))\n db.commit()\n logger.debug('Inserted into karmadb {} shame for {}'.format(\n shame, name))\n db.close()\n return shame\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[162, 266], [612, 718]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[162, 266], [612, 718]]}, "_func_name": "shame_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _get_degree_2(user_id, cnx):\n \"\"\"Get all users of degree 2 follow that are not currently followed.\n Example:\n this user (follows) user B (follows) user B\n AND user (does NOT follow) user B\n means that user B will be in the list\n Args:\n user_id (int): id of user\n cnx: DB connection\n Returns:\n list: list of user_ids\n \"\"\"\n sql = 'WITH tmp_suggest (followed_id) AS ' \\\n '(' \\\n 'SELECT b.followed_id AS followed_id ' \\\n 'FROM ' \\\n 'tbl_follow a INNER JOIN tbl_follow b ' \\\n 'ON a.followed_id = b.follower_id ' \\\n 'WHERE a.follower_id = %s ' \\\n 'AND b.followed_id NOT IN ' \\\n '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \\\n 'AND b.followed_id != %s ' \\\n ') ' \\\n 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \\\n 'GROUP BY followed_id ' \\\n 'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)\n with cnx.cursor() as cursor:\n cursor.execute(sql)\n res = cursor.fetchall()\n return list(map(lambda x: x[0], res))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[912, 973]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[912, 973]]}, "_func_name": "_get_degree_2", "_file_name": "server/ygoons/modules/user/follow_suggest.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "struct sk_buff *skb_segment(struct sk_buff *head_skb,\n\t\t\t netdev_features_t features)\n{\n\tstruct sk_buff *segs = NULL;\n\tstruct sk_buff *tail = NULL;\n\tstruct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;\n\tskb_frag_t *frag = skb_shinfo(head_skb)->frags;\n\tunsigned int mss = skb_shinfo(head_skb)->gso_size;\n\tunsigned int doffset = head_skb->data - skb_mac_header(head_skb);\n\tstruct sk_buff *frag_skb = head_skb;\n\tunsigned int offset = doffset;\n\tunsigned int tnl_hlen = skb_tnl_header_len(head_skb);\n\tunsigned int headroom;\n\tunsigned int len;\n\t__be16 proto;\n\tbool csum;\n\tint sg = !!(features & NETIF_F_SG);\n\tint nfrags = skb_shinfo(head_skb)->nr_frags;\n\tint err = -ENOMEM;\n\tint i = 0;\n\tint pos;\n\n\tproto = skb_network_protocol(head_skb);\n\tif (unlikely(!proto))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tcsum = !!can_checksum_protocol(features, proto);\n\t__skb_push(head_skb, doffset);\n\theadroom = skb_headroom(head_skb);\n\tpos = skb_headlen(head_skb);\n\n\tdo {\n\t\tstruct sk_buff *nskb;\n\t\tskb_frag_t *nskb_frag;\n\t\tint hsize;\n\t\tint size;\n\n\t\tlen = head_skb->len - offset;\n\t\tif (len > mss)\n\t\t\tlen = mss;\n\n\t\thsize = skb_headlen(head_skb) - offset;\n\t\tif (hsize < 0)\n\t\t\thsize = 0;\n\t\tif (hsize > len || !sg)\n\t\t\thsize = len;\n\n\t\tif (!hsize && i >= nfrags && skb_headlen(list_skb) &&\n\t\t (skb_headlen(list_skb) == len || sg)) {\n\t\t\tBUG_ON(skb_headlen(list_skb) > len);\n\n\t\t\ti = 0;\n\t\t\tnfrags = skb_shinfo(list_skb)->nr_frags;\n\t\t\tfrag = skb_shinfo(list_skb)->frags;\n\t\t\tfrag_skb = list_skb;\n\t\t\tpos += skb_headlen(list_skb);\n\n\t\t\twhile (pos < offset + len) {\n\t\t\t\tBUG_ON(i >= nfrags);\n\n\t\t\t\tsize = skb_frag_size(frag);\n\t\t\t\tif (pos + size > offset + len)\n\t\t\t\t\tbreak;\n\n\t\t\t\ti++;\n\t\t\t\tpos += size;\n\t\t\t\tfrag++;\n\t\t\t}\n\n\t\t\tnskb = skb_clone(list_skb, GFP_ATOMIC);\n\t\t\tlist_skb = list_skb->next;\n\n\t\t\tif (unlikely(!nskb))\n\t\t\t\tgoto err;\n\n\t\t\tif (unlikely(pskb_trim(nskb, len))) {\n\t\t\t\tkfree_skb(nskb);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\thsize = skb_end_offset(nskb);\n\t\t\tif (skb_cow_head(nskb, doffset + headroom)) {\n\t\t\t\tkfree_skb(nskb);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tnskb->truesize += skb_end_offset(nskb) - hsize;\n\t\t\tskb_release_head_state(nskb);\n\t\t\t__skb_push(nskb, doffset);\n\t\t} else {\n\t\t\tnskb = __alloc_skb(hsize + doffset + headroom,\n\t\t\t\t\t GFP_ATOMIC, skb_alloc_rx_flag(head_skb),\n\t\t\t\t\t NUMA_NO_NODE);\n\n\t\t\tif (unlikely(!nskb))\n\t\t\t\tgoto err;\n\n\t\t\tskb_reserve(nskb, headroom);\n\t\t\t__skb_put(nskb, doffset);\n\t\t}\n\n\t\tif (segs)\n\t\t\ttail->next = nskb;\n\t\telse\n\t\t\tsegs = nskb;\n\t\ttail = nskb;\n\n\t\t__copy_skb_header(nskb, head_skb);\n\t\tnskb->mac_len = head_skb->mac_len;\n\n\t\tskb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);\n\n\t\tskb_copy_from_linear_data_offset(head_skb, -tnl_hlen,\n\t\t\t\t\t\t nskb->data - tnl_hlen,\n\t\t\t\t\t\t doffset + tnl_hlen);\n\n\t\tif (nskb->len == len + doffset)\n\t\t\tgoto perform_csum_check;\n\n\t\tif (!sg) {\n\t\t\tnskb->ip_summed = CHECKSUM_NONE;\n\t\t\tnskb->csum = skb_copy_and_csum_bits(head_skb, offset,\n\t\t\t\t\t\t\t skb_put(nskb, len),\n\t\t\t\t\t\t\t len, 0);\n\t\t\tcontinue;\n\t\t}\n\n\t\tnskb_frag = skb_shinfo(nskb)->frags;\n\n\t\tskb_copy_from_linear_data_offset(head_skb, offset,\n\t\t\t\t\t\t skb_put(nskb, hsize), hsize);\n\n\t\tskb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &\n\t\t\tSKBTX_SHARED_FRAG;\n\n\t\twhile (pos < offset + len) {\n\t\t\tif (i >= nfrags) {\n\t\t\t\tBUG_ON(skb_headlen(list_skb));\n\n\t\t\t\ti = 0;\n\t\t\t\tnfrags = skb_shinfo(list_skb)->nr_frags;\n\t\t\t\tfrag = skb_shinfo(list_skb)->frags;\n\t\t\t\tfrag_skb = list_skb;\n\n\t\t\t\tBUG_ON(!nfrags);\n\n\t\t\t\tlist_skb = list_skb->next;\n\t\t\t}\n\n\t\t\tif (unlikely(skb_shinfo(nskb)->nr_frags >=\n\t\t\t\t MAX_SKB_FRAGS)) {\n\t\t\t\tnet_warn_ratelimited(\n\t\t\t\t\t\"skb_segment: too many frags: %u %u\\n\",\n\t\t\t\t\tpos, mss);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tif (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))\n\t\t\t\tgoto err;\n\n\t\t\t*nskb_frag = *frag;\n\t\t\t__skb_frag_ref(nskb_frag);\n\t\t\tsize = skb_frag_size(nskb_frag);\n\n\t\t\tif (pos < offset) {\n\t\t\t\tnskb_frag->page_offset += offset - pos;\n\t\t\t\tskb_frag_size_sub(nskb_frag, offset - pos);\n\t\t\t}\n\n\t\t\tskb_shinfo(nskb)->nr_frags++;\n\n\t\t\tif (pos + size <= offset + len) {\n\t\t\t\ti++;\n\t\t\t\tfrag++;\n\t\t\t\tpos += size;\n\t\t\t} else {\n\t\t\t\tskb_frag_size_sub(nskb_frag, pos + size - (offset + len));\n\t\t\t\tgoto skip_fraglist;\n\t\t\t}\n\n\t\t\tnskb_frag++;\n\t\t}\n\nskip_fraglist:\n\t\tnskb->data_len = len - hsize;\n\t\tnskb->len += nskb->data_len;\n\t\tnskb->truesize += nskb->data_len;\n\nperform_csum_check:\n\t\tif (!csum) {\n\t\t\tnskb->csum = skb_checksum(nskb, doffset,\n\t\t\t\t\t\t nskb->len - doffset, 0);\n\t\t\tnskb->ip_summed = CHECKSUM_NONE;\n\t\t}\n\t} while ((offset += len) < head_skb->len);\n\n\treturn segs;\n\nerr:\n\tkfree_skb_list(segs);\n\treturn ERR_PTR(err);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "skb_segment", "_file_name": "net/core/skbuff.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def history_data(start_time, offset=None):\n \"\"\"Return history data.\n\n Arguments:\n start_time: select history starting from this timestamp.\n offset: number of items to skip\n \"\"\"\n # history atimes are stored as ints, ensure start_time is not a float\n start_time = int(start_time)\n hist = objreg.get('web-history')\n if offset is not None:\n entries = hist.entries_before(start_time, limit=1000, offset=offset)\n else:\n # end is 24hrs earlier than start\n end_time = start_time - 24*60*60\n entries = hist.entries_between(end_time, start_time)\n\n return [{\"url\": e.url, \"title\": e.title or e.url, \"time\": e.atime}\n for e in entries]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[603, 703]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[603, 703]]}, "_func_name": "history_data", "_file_name": "qutebrowser/browser/qutescheme.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)\n{\n struct lys_restr *result;\n int i;\n\n if (!size) {\n return NULL;\n }\n\n result = calloc(size, sizeof *result);\n LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);\n\n for (i = 0; i < size; i++) {\n result[i].ext_size = old[i].ext_size;\n lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);\n result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);\n result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);\n result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);\n result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);\n }\n\n return result;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[336, 508]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[336, 508]]}, "_func_name": "lys_restr_dup", "_file_name": "src/tree_schema.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n{\n\tint i;\n\trdpBitmapCache* bitmapCache;\n\tbitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));\n\n\tif (!bitmapCache)\n\t\treturn NULL;\n\n\tbitmapCache->settings = settings;\n\tbitmapCache->update = ((freerdp*)settings->instance)->update;\n\tbitmapCache->context = bitmapCache->update->context;\n\tbitmapCache->cells =\n\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n\n\tif (!bitmapCache->cells)\n\t\tgoto fail;\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n\n\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t{\n\t\tbitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;\n\t\t/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */\n\t\tbitmapCache->cells[i].entries =\n\t\t (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));\n\n\t\tif (!bitmapCache->cells[i].entries)\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapCache;\nfail:\n\n\tif (bitmapCache->cells)\n\t{\n\t\tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n\t\t\tfree(bitmapCache->cells[i].entries);\n\t}\n\n\tfree(bitmapCache);\n\treturn NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "bitmap_cache_new", "_file_name": "libfreerdp/cache/bitmap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_add(name):\n karma = karma_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if karma is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES(%(name)s,1,0)\n ''', name)\n db.commit()\n logger.debug('Inserted into karmadb 1 karma for {}'.format(name))\n return 1\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n else:\n karma = karma + 1\n try:\n cursor.execute('''\n UPDATE people SET karma = %(karma)s WHERE name = %(name)s\n ''', (karma, name))\n db.commit()\n logger.debug('Inserted into karmadb {} karma for {}'.format(\n karma,\n name,\n ))\n return karma\n\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n db.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "karma_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @classmethod\n def simple_search(cls, query, using=None, index=None):\n es_search = cls.search(using=using, index=index)\n es_query = cls.get_es_query(query=query)\n highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]\n\n es_search = es_search.query(es_query).highlight(*highlighted_fields)\n return es_search", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[259, 260]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[259, 260]]}, "_func_name": "simple_search", "_file_name": "readthedocs/search/documents.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)\n{\n char obj_txt[128];\n\n int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);\n BIO_write(bio, obj_txt, len);\n BIO_write(bio, \"\\n\", 1);\n\n return 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[81, 205]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[81, 205]]}, "_func_name": "TS_OBJ_print_bio", "_file_name": "crypto/ts/ts_lib.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,\n const unsigned char *end )\n{\n int ret = 0;\n size_t n;\n\n if( ssl->conf->f_psk == NULL &&\n ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||\n ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"got no pre-shared key\" ) );\n return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );\n }\n\n /*\n * Receive client pre-shared key identity name\n */\n if( end - *p < 2 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n n = ( (*p)[0] << 8 ) | (*p)[1];\n *p += 2;\n\n if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"bad client key exchange message\" ) );\n return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );\n }\n\n if( ssl->conf->f_psk != NULL )\n {\n if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n else\n {\n /* Identity is not a big secret since clients send it in the clear,\n * but treat it carefully anyway, just in case */\n if( n != ssl->conf->psk_identity_len ||\n mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )\n {\n ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;\n }\n }\n\n if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )\n {\n MBEDTLS_SSL_DEBUG_BUF( 3, \"Unknown PSK identity\", *p, n );\n mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,\n MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );\n return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );\n }\n\n *p += n;\n\n return( 0 );\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ssl_parse_client_psk_identity", "_file_name": "library/ssl_srv.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _update_volume_stats(self):\n \"\"\"Retrieve stats info from volume group.\"\"\"\n\n LOG.debug(_(\"Updating volume stats\"))\n data = {}\n\n data['vendor_name'] = 'IBM'\n data['driver_version'] = '1.1'\n data['storage_protocol'] = list(self._enabled_protocols)\n\n data['total_capacity_gb'] = 0 # To be overwritten\n data['free_capacity_gb'] = 0 # To be overwritten\n data['reserved_percentage'] = 0\n data['QoS_support'] = False\n\n pool = self.configuration.storwize_svc_volpool_name\n #Get storage system name\n ssh_cmd = 'svcinfo lssystem -delim !'\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes or not attributes['name']:\n exception_message = (_('_update_volume_stats: '\n 'Could not get system name'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n backend_name = self.configuration.safe_get('volume_backend_name')\n if not backend_name:\n backend_name = '%s_%s' % (attributes['name'], pool)\n data['volume_backend_name'] = backend_name\n\n ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n LOG.error(_('Could not get pool data from the storage'))\n exception_message = (_('_update_volume_stats: '\n 'Could not get storage pool data'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n data['total_capacity_gb'] = (float(attributes['capacity']) /\n (1024 ** 3))\n data['free_capacity_gb'] = (float(attributes['free_capacity']) /\n (1024 ** 3))\n data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']\n data['compression_support'] = self._compression_enabled\n\n self._stats = data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1179, 1244]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1179, 1244]]}, "_func_name": "_update_volume_stats", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)\n{\n\tint r;\n\n\tstatic const char resp[] =\n\t\t\"\"\n\t\t\"%d\"\n\t\t\"\";\n\n\tchar body[512];\n\tint bodylen;\n\tstruct NameValueParserData data;\n\tchar * int_ip, * int_port, * rem_host, * rem_port, * protocol;\n\tint opt=0;\n\t/*int proto=0;*/\n\tunsigned short iport, rport;\n\n\tif (GETFLAG(IPV6FCFWDISABLEDMASK))\n\t{\n\t\tSoapError(h, 702, \"FirewallDisabled\");\n\t\treturn;\n\t}\n\n\tParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);\n\tint_ip = GetValueFromNameValueList(&data, \"InternalClient\");\n\tint_port = GetValueFromNameValueList(&data, \"InternalPort\");\n\trem_host = GetValueFromNameValueList(&data, \"RemoteHost\");\n\trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n\tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n\n\trport = (unsigned short)atoi(rem_port);\n\tiport = (unsigned short)atoi(int_port);\n\t/*proto = atoi(protocol);*/\n\n\tsyslog(LOG_INFO, \"%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s\", action, int_ip, iport,rem_host, rport, protocol);\n\n\t/* TODO */\n\tr = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/\n\n\tswitch(r)\n\t{\n\t\tcase 1:\t/* success */\n\t\t\tbodylen = snprintf(body, sizeof(body), resp,\n\t\t\t action, ns/*\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\"*/,\n\t\t\t opt, action);\n\t\t\tBuildSendAndCloseSoapResp(h, body, bodylen);\n\t\t\tbreak;\n\t\tcase -5:\t/* Protocol not supported */\n\t\t\tSoapError(h, 705, \"ProtocolNotSupported\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSoapError(h, 501, \"ActionFailed\");\n\t}\n\tClearNameValueList(&data);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[903, 944]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[903, 944]]}, "_func_name": "GetOutboundPinholeTimeout", "_file_name": "miniupnpd/upnpsoap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def pascal_case(value: str) -> str:\n return stringcase.pascalcase(_sanitize(value))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "pascal_case", "_file_name": "openapi_python_client/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int hi3660_stub_clk_probe(struct platform_device *pdev)\n{\n\tstruct device *dev = &pdev->dev;\n\tstruct resource *res;\n\tunsigned int i;\n\tint ret;\n\n\t/* Use mailbox client without blocking */\n\tstub_clk_chan.cl.dev = dev;\n\tstub_clk_chan.cl.tx_done = NULL;\n\tstub_clk_chan.cl.tx_block = false;\n\tstub_clk_chan.cl.knows_txdone = false;\n\n\t/* Allocate mailbox channel */\n\tstub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);\n\tif (IS_ERR(stub_clk_chan.mbox))\n\t\treturn PTR_ERR(stub_clk_chan.mbox);\n\n\tres = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tfreq_reg = devm_ioremap(dev, res->start, resource_size(res));\n\tif (!freq_reg)\n\t\treturn -ENOMEM;\n\n\tfreq_reg += HI3660_STUB_CLOCK_DATA;\n\n\tfor (i = 0; i < HI3660_CLK_STUB_NUM; i++) {\n\t\tret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,\n\t\t\t\t\t hi3660_stub_clks);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[558, 621]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[558, 621]]}, "_func_name": "hi3660_stub_clk_probe", "_file_name": "drivers/clk/hisilicon/clk-hi3660-stub.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _run_ssh(self, cmd_list, check_exit_code=True, attempts=1):\n utils.check_ssh_injection(cmd_list)\n command = ' '. join(cmd_list)\n\n if not self.sshpool:\n password = self.configuration.san_password\n privatekey = self.configuration.san_private_key\n min_size = self.configuration.ssh_min_pool_conn\n max_size = self.configuration.ssh_max_pool_conn\n self.sshpool = utils.SSHPool(self.configuration.san_ip,\n self.configuration.san_ssh_port,\n self.configuration.ssh_conn_timeout,\n self.configuration.san_login,\n password=password,\n privatekey=privatekey,\n min_size=min_size,\n max_size=max_size)\n last_exception = None\n try:\n total_attempts = attempts\n with self.sshpool.item() as ssh:\n while attempts > 0:\n attempts -= 1\n try:\n return utils.ssh_execute(\n ssh,\n command,\n check_exit_code=check_exit_code)\n except Exception as e:\n LOG.error(e)\n last_exception = e\n greenthread.sleep(random.randint(20, 500) / 100.0)\n try:\n raise exception.ProcessExecutionError(\n exit_code=last_exception.exit_code,\n stdout=last_exception.stdout,\n stderr=last_exception.stderr,\n cmd=last_exception.cmd)\n except AttributeError:\n raise exception.ProcessExecutionError(\n exit_code=-1,\n stdout=\"\",\n stderr=\"Error running SSH command\",\n cmd=command)\n\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error running SSH command: %s\") % command)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_run_ssh", "_file_name": "cinder/volume/drivers/san/san.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/delete_video/')\ndef delete_video(filename):\n\tif 'username' in session:\n\t\t#os.remove(\"static/videos/{}\".format(filename))\n\t\tprint(session['username'], file=sys.stdout)\n\t\tdata=users.query.filter_by(Username=session['username']).first()\n\t\tvideo=Video.query.filter_by(UserID=data.UserID,Name=filename).first()\n\t\tif video != None:\n\t\t\tos.remove(\"static/videos/{}\".format(filename))\n\t\t\tdb.session.delete(video)\n\t\t\tdb.session.commit()\n\t\telse:\n\t\t\treturn \"Don't delete other people's videos!\"\n\t\treturn redirect(url_for('upload'))\n\treturn \"test\"", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[349, 399]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[349, 399]]}, "_func_name": "delete_video", "_file_name": "Trialwebsite/app/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_ports(self):\n # First get the active FC ports\n out = self._cli_run('showport', None)\n\n # strip out header\n # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,\n # Protocol,Label,Partner,FailoverState\n out = out[1:len(out) - 2]\n\n ports = {'FC': [], 'iSCSI': {}}\n for line in out:\n tmp = line.split(',')\n\n if tmp:\n if tmp[1] == 'target' and tmp[2] == 'ready':\n if tmp[6] == 'FC':\n ports['FC'].append(tmp[4])\n\n # now get the active iSCSI ports\n out = self._cli_run('showport -iscsi', None)\n\n # strip out header\n # N:S:P,State,IPAddr,Netmask,Gateway,\n # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port\n out = out[1:len(out) - 2]\n for line in out:\n tmp = line.split(',')\n\n if tmp and len(tmp) > 2:\n if tmp[1] == 'ready':\n ports['iSCSI'][tmp[2]] = {}\n\n # now get the nsp and iqn\n result = self._cli_run('showport -iscsiname', None)\n if result:\n # first line is header\n # nsp, ip,iqn\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 2:\n if info[1] in ports['iSCSI']:\n nsp = info[0]\n ip_addr = info[1]\n iqn = info[2]\n ports['iSCSI'][ip_addr] = {'nsp': nsp,\n 'iqn': iqn\n }\n\n LOG.debug(\"PORTS = %s\" % pprint.pformat(ports))\n return ports", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[65, 111], [603, 656], [1031, 1091]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[65, 111], [603, 656], [1031, 1091]]}, "_func_name": "get_ports", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_institutions(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the institution table.\n \"\"\"\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_institutions = get_all_old_institutions(conn, sqlite)\n\n # Check if the institution table is allready filled and this is not the first checkup\n institution_table_is_filled = len(old_institutions) > 10\n\n for old_institution in old_institutions:\n if institution_table_is_filled and old_institution not in current_institutions:\n message = \"Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen.\" % old_institution\n send_message(message)\n\n for current_institution in current_institutions:\n if current_institution == \" \" or '\"' in current_institution:\n continue\n if current_institution not in old_institutions:\n message = \"The institution %s is new in Solr.\" % current_institution\n if institution_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO institution (institution) VALUES ('%s')\" % current_institution\n sqlite.execute(sql)\n conn.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1155, 1249]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1155, 1249]]}, "_func_name": "update_institutions", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def delete_resultSet(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = \"DELETE FROM %s WHERE identifier = $1;\" % (self.table)\n self._query(query, sid)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_resultSet", "_file_name": "cheshire3/sql/resultSetStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void dd_save_text(struct dump_dir *dd, const char *name, const char *data)\n{\n if (!dd->locked)\n error_msg_and_die(\"dump_dir is not opened\"); /* bug */\n\n char *full_path = concat_path_file(dd->dd_dirname, name);\n save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);\n free(full_path);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[162, 224]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[162, 224]]}, "_func_name": "dd_save_text", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void usb_sg_cancel(struct usb_sg_request *io)\n{\n\tunsigned long flags;\n\tint i, retval;\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tif (io->status) {\n\t\tspin_unlock_irqrestore(&io->lock, flags);\n\t\treturn;\n\t}\n\t/* shut everything down */\n\tio->status = -ECONNRESET;\n\tspin_unlock_irqrestore(&io->lock, flags);\n\n\tfor (i = io->entries - 1; i >= 0; --i) {\n\t\tusb_block_urb(io->urbs[i]);\n\n\t\tretval = usb_unlink_urb(io->urbs[i]);\n\t\tif (retval != -EINPROGRESS\n\t\t && retval != -ENODEV\n\t\t && retval != -EBUSY\n\t\t && retval != -EIDRM)\n\t\t\tdev_warn(&io->dev->dev, \"%s, unlink --> %d\\n\",\n\t\t\t\t __func__, retval);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[125, 144]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[125, 144]]}, "_func_name": "usb_sg_cancel", "_file_name": "drivers/usb/core/message.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit/', methods=['GET', 'POST'])\ndef edit(msg_id):\n m = None\n if request.method == 'GET':\n sql = \"SELECT * FROM message where msg_id = %d;\" % (msg_id)\n cursor.execute(sql)\n m = cursor.fetchone()\n return render_template('message/edit.html', m=m, msg_id=msg_id)\n\n if request.method == 'POST':\n content = request.form['content']\n sql = \"UPDATE message SET content = '%s' where msg_id = '%d';\" \\\n % (content, msg_id)\n cursor.execute(sql)\n conn.commit()\n flash('Edit Success!')\n return redirect(url_for('show_entries'))\n\n return render_template('message/edit.html', m=m, msg_id=msg_id)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[121, 217], [395, 528]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[121, 217], [395, 528]]}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/message.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _formatCredentials(self, data, name):\n \"\"\"\n Credentials are of the form\n RCLONE_CONFIG_CURRENT_TYPE=s3\n ^ ^ ^ ^\n [mandatory ][name ][key][value]\n \"\"\"\n\n prefix = \"RCLONE_CONFIG_{}\".format(name.upper())\n\n credentials = ''\n credentials += \"{}_TYPE='{}' \".format(prefix, data.type)\n\n def _addCredential(credentials, env_key, data_key):\n value = getattr(data, data_key, None)\n if value is not None:\n credentials += \"{}='{}' \".format(env_key, value)\n return credentials\n\n\n if data.type == 's3':\n credentials = _addCredential(credentials,\n '{}_REGION'.format(prefix),\n 's3_region'\n )\n credentials = _addCredential(credentials,\n '{}_ACCESS_KEY_ID'.format(prefix),\n 's3_access_key_id'\n )\n credentials = _addCredential(credentials,\n '{}_SECRET_ACCESS_KEY'.format(prefix),\n 's3_secret_access_key'\n )\n\n credentials = _addCredential(credentials,\n '{}_ENDPOINT'.format(prefix),\n 's3_endpoint'\n )\n credentials = _addCredential(credentials,\n '{}_V2_AUTH'.format(prefix),\n 's3_v2_auth'\n )\n\n elif data.type == 'azureblob':\n credentials = _addCredential(credentials,\n '{}_ACCOUNT'.format(prefix),\n 'azure_account'\n )\n credentials = _addCredential(credentials,\n '{}_KEY'.format(prefix),\n 'azure_key'\n )\n\n elif data.type == 'swift':\n credentials = _addCredential(credentials,\n '{}_USER'.format(prefix),\n 'swift_user'\n )\n credentials = _addCredential(credentials,\n '{}_KEY'.format(prefix),\n 'swift_key'\n )\n credentials = _addCredential(credentials,\n '{}_AUTH'.format(prefix),\n 'swift_auth'\n )\n credentials = _addCredential(credentials,\n '{}_TENANT'.format(prefix),\n 'swift_tenant'\n )\n\n elif data.type == 'google cloud storage':\n credentials = _addCredential(credentials,\n '{}_CLIENT_ID'.format(prefix),\n 'gcp_client_id'\n )\n credentials = _addCredential(credentials,\n '{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix),\n 'gcp_service_account_credentials'\n )\n credentials = _addCredential(credentials,\n '{}_PROJECT_NUMBER'.format(prefix),\n 'gcp_project_number'\n )\n credentials = _addCredential(credentials,\n '{}_OBJECT_ACL'.format(prefix),\n 'gcp_object_acl'\n )\n credentials = _addCredential(credentials,\n '{}_BUCKET_ACL'.format(prefix),\n 'gcp_bucket_acl'\n )\n\n else:\n logging.error(\"Connection type unknown: {}\".format(data.type))\n\n return credentials", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[283, 373], [518, 583]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[283, 373], [518, 583]]}, "_func_name": "_formatCredentials", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,\n const int whence,void *user_data)\n{\n PhotoshopProfile\n *profile;\n\n profile=(PhotoshopProfile *) user_data;\n switch (whence)\n {\n case SEEK_SET:\n default:\n {\n if (offset < 0)\n return(-1);\n profile->offset=offset;\n break;\n }\n case SEEK_CUR:\n {\n if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) ||\n ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset))))\n {\n errno=EOVERFLOW;\n return(-1);\n }\n if ((profile->offset+offset) < 0)\n return(-1);\n profile->offset+=offset;\n break;\n }\n case SEEK_END:\n {\n if (((MagickOffsetType) profile->length+offset) < 0)\n return(-1);\n profile->offset=profile->length+offset;\n break;\n }\n }\n\n return(profile->offset);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TIFFSeekCustomStream", "_file_name": "coders/tiff.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tconst char *section_name = \"\";\n\tconst char *link_section_name = \"\";\n\tchar *end = NULL;\n\tElf_(Shdr) *link_shdr = NULL;\n\tut8 dfs[sizeof (Elf_(Verdef))] = {0};\n\tSdb *sdb;\n\tint cnt, i;\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn false;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {\n\t\treturn false;\n\t}\n\tElf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));\n\tif (!defs) {\n\t\treturn false;\n\t}\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!defs) {\n\t\tbprintf (\"Warning: Cannot allocate memory (Check Elf_(Verdef))\\n\");\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tend = (char *)defs + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {\n\t\tSdb *sdb_verdef = sdb_new0 ();\n\t\tchar *vstart = ((char*)defs) + i;\n\t\tchar key[32] = {0};\n\t\tElf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;\n\t\tElf_(Verdaux) aux = {0};\n\t\tint j = 0;\n\t\tint isum = 0;\n\n\t\tr_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));\n\t\tverdef->vd_version = READ16 (dfs, j)\n\t\tverdef->vd_flags = READ16 (dfs, j)\n\t\tverdef->vd_ndx = READ16 (dfs, j)\n\t\tverdef->vd_cnt = READ16 (dfs, j)\n\t\tverdef->vd_hash = READ32 (dfs, j)\n\t\tverdef->vd_aux = READ32 (dfs, j)\n\t\tverdef->vd_next = READ32 (dfs, j)\n\t\tint vdaux = verdef->vd_aux;\n\t\tif (vdaux < 1) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tvstart += vdaux;\n\t\tif (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tj = 0;\n\t\taux.vda_name = READ32 (vstart, j)\n\t\taux.vda_next = READ32 (vstart, j)\n\n\t\tisum = i + verdef->vd_aux;\n\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tsdb_num_set (sdb_verdef, \"idx\", i, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_version\", verdef->vd_version, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_ndx\", verdef->vd_ndx, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_cnt\", verdef->vd_cnt, 0);\n\t\tsdb_set (sdb_verdef, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\tsdb_set (sdb_verdef, \"flags\", get_ver_flags (verdef->vd_flags), 0);\n\n\t\tfor (j = 1; j < verdef->vd_cnt; ++j) {\n\t\t\tint k;\n\t\t\tSdb *sdb_parent = sdb_new0 ();\n\t\t\tisum += aux.vda_next;\n\t\t\tvstart += aux.vda_next;\n\t\t\tif (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tk = 0;\n\t\t\taux.vda_name = READ32 (vstart, k)\n\t\t\taux.vda_next = READ32 (vstart, k)\n\t\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_parent, \"idx\", isum, 0);\n\t\t\tsdb_num_set (sdb_parent, \"parent\", j, 0);\n\t\t\tsdb_set (sdb_parent, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\t\tsnprintf (key, sizeof (key), \"parent%d\", j - 1);\n\t\t\tsdb_ns_set (sdb_verdef, key, sdb_parent);\n\t\t}\n\n\t\tsnprintf (key, sizeof (key), \"verdef%d\", cnt);\n\t\tsdb_ns_set (sdb, key, sdb_verdef);\n\t\tif (!verdef->vd_next) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tif ((st32)verdef->vd_next < 1) {\n\t\t\teprintf (\"Warning: Invalid vd_next in the ELF version\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += verdef->vd_next;\n\t}\n\tfree (defs);\n\treturn sdb;\nout_error:\n\tfree (defs);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1241, 1331], [1972, 2035], [2782, 2845]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1241, 1331], [1972, 2035], [2782, 2845]]}, "_func_name": "store_versioninfo_gnu_verdef", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_chap_secret_for_host(self, host_name):\n \"\"\"Return the CHAP secret for the given host.\"\"\"\n\n LOG.debug(_('enter: _get_chap_secret_for_host: host name %s')\n % host_name)\n\n ssh_cmd = 'svcinfo lsiscsiauth -delim !'\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines), '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header, '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n self._assert_ssh_return('iscsi_auth_method' in header,\n '_get_chap_secret_for_host', ssh_cmd, out, err)\n self._assert_ssh_return('iscsi_chap_secret' in header,\n '_get_chap_secret_for_host', ssh_cmd, out, err)\n name_index = header.index('name')\n method_index = header.index('iscsi_auth_method')\n secret_index = header.index('iscsi_chap_secret')\n\n chap_secret = None\n host_found = False\n for line in host_lines:\n info = line.split('!')\n if info[name_index] == host_name:\n host_found = True\n if info[method_index] == 'chap':\n chap_secret = info[secret_index]\n\n self._assert_ssh_return(host_found, '_get_chap_secret_for_host',\n ssh_cmd, out, err)\n\n LOG.debug(_('leave: _get_chap_secret_for_host: host name '\n '%(host_name)s with secret %(chap_secret)s')\n % {'host_name': host_name, 'chap_secret': chap_secret})\n\n return chap_secret", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[212, 261]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[212, 261]]}, "_func_name": "_get_chap_secret_for_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def auto_unlock_tasks(project_id: int):\n \"\"\"Unlock all tasks locked for longer than the auto-unlock delta\"\"\"\n expiry_delta = Task.auto_unlock_delta()\n lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()\n expiry_date = datetime.datetime.utcnow() - expiry_delta\n old_locks_query = '''SELECT t.id\n FROM tasks t, task_history th\n WHERE t.id = th.task_id\n AND t.project_id = th.project_id\n AND t.task_status IN (1,3)\n AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )\n AND th.action_text IS NULL\n AND t.project_id = {0}\n AND th.action_date <= '{1}'\n '''.format(project_id, str(expiry_date))\n\n old_tasks = db.engine.execute(old_locks_query)\n\n if old_tasks.rowcount == 0:\n # no tasks older than the delta found, return without further processing\n return\n\n for old_task in old_tasks:\n task = Task.get(old_task[0], project_id)\n task.auto_unlock_expired_tasks(expiry_date, lock_duration)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[652, 780]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[652, 780]]}, "_func_name": "auto_unlock_tasks", "_file_name": "server/models/postgis/task.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@register.tag\n@basictag(takes_context=True)\ndef screenshotcommentcounts(context, screenshot):\n \"\"\"\n Returns a JSON array of current comments for a screenshot.\n\n Each entry in the array has a dictionary containing the following keys:\n\n =========== ==================================================\n Key Description\n =========== ==================================================\n text The text of the comment\n localdraft True if this is the current user's draft comment\n x The X location of the comment's region\n y The Y location of the comment's region\n w The width of the comment's region\n h The height of the comment's region\n =========== ==================================================\n \"\"\"\n comments = {}\n user = context.get('user', None)\n\n for comment in screenshot.comments.all():\n review = get_object_or_none(comment.review)\n\n if review and (review.public or review.user == user):\n position = '%dx%d+%d+%d' % (comment.w, comment.h, \\\n comment.x, comment.y)\n\n comments.setdefault(position, []).append({\n 'id': comment.id,\n 'text': escape(comment.text),\n 'user': {\n 'username': review.user.username,\n 'name': review.user.get_full_name() or review.user.username,\n },\n 'url': comment.get_review_url(),\n 'localdraft' : review.user == user and \\\n not review.public,\n 'x' : comment.x,\n 'y' : comment.y,\n 'w' : comment.w,\n 'h' : comment.h,\n })\n\n return simplejson.dumps(comments)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "screenshotcommentcounts", "_file_name": "reviewboard/reviews/templatetags/reviewtags.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "set_interface_var(const char *iface,\n\t\t const char *var, const char *name,\n\t\t uint32_t val)\n{\n\tFILE *fp;\n\tchar spath[64+IFNAMSIZ];\t/* XXX: magic constant */\n\tif (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))\n\t\treturn -1;\n\n\t/* No path traversal */\n\tif (strstr(name, \"..\") || strchr(name, '/'))\n\t\treturn -1;\n\n\tif (access(spath, F_OK) != 0)\n\t\treturn -1;\n\n\tfp = fopen(spath, \"w\");\n\tif (!fp) {\n\t\tif (name)\n\t\t\tflog(LOG_ERR, \"failed to set %s (%u) for %s: %s\",\n\t\t\t name, val, iface, strerror(errno));\n\t\treturn -1;\n\t}\n\tfprintf(fp, \"%u\", val);\n\tfclose(fp);\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set_interface_var", "_file_name": "device-linux.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "lexer_process_char_literal (parser_context_t *context_p, /**< context */\n const uint8_t *char_p, /**< characters */\n size_t length, /**< length of string */\n uint8_t literal_type, /**< final literal type */\n bool has_escape) /**< has escape sequences */\n{\n parser_list_iterator_t literal_iterator;\n lexer_literal_t *literal_p;\n uint32_t literal_index = 0;\n\n JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL\n || literal_type == LEXER_STRING_LITERAL);\n\n JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);\n JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);\n\n parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);\n\n while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (literal_p->type == literal_type\n && literal_p->prop.length == length\n && memcmp (literal_p->u.char_p, char_p, length) == 0)\n {\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);\n return;\n }\n\n literal_index++;\n }\n\n JERRY_ASSERT (literal_index == context_p->literal_count);\n\n if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)\n {\n parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);\n }\n\n if (length == 0)\n {\n has_escape = false;\n }\n\n literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);\n literal_p->prop.length = (uint16_t) length;\n literal_p->type = literal_type;\n literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;\n\n if (has_escape)\n {\n literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);\n memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);\n }\n else\n {\n literal_p->u.char_p = char_p;\n }\n\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n context_p->literal_count++;\n} /* lexer_process_char_literal */", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "lexer_process_char_literal", "_file_name": "jerry-core/parser/js/js-lexer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int unimac_mdio_probe(struct platform_device *pdev)\n{\n\tstruct unimac_mdio_pdata *pdata = pdev->dev.platform_data;\n\tstruct unimac_mdio_priv *priv;\n\tstruct device_node *np;\n\tstruct mii_bus *bus;\n\tstruct resource *r;\n\tint ret;\n\n\tnp = pdev->dev.of_node;\n\n\tpriv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);\n\tif (!priv)\n\t\treturn -ENOMEM;\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (!r)\n\t\treturn -EINVAL;\n\n\t/* Just ioremap, as this MDIO block is usually integrated into an\n\t * Ethernet MAC controller register range\n\t */\n\tpriv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));\n\tif (!priv->base) {\n\t\tdev_err(&pdev->dev, \"failed to remap register\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tpriv->mii_bus = mdiobus_alloc();\n\tif (!priv->mii_bus)\n\t\treturn -ENOMEM;\n\n\tbus = priv->mii_bus;\n\tbus->priv = priv;\n\tif (pdata) {\n\t\tbus->name = pdata->bus_name;\n\t\tpriv->wait_func = pdata->wait_func;\n\t\tpriv->wait_func_data = pdata->wait_func_data;\n\t\tbus->phy_mask = ~pdata->phy_mask;\n\t} else {\n\t\tbus->name = \"unimac MII bus\";\n\t\tpriv->wait_func_data = priv;\n\t\tpriv->wait_func = unimac_mdio_poll;\n\t}\n\tbus->parent = &pdev->dev;\n\tbus->read = unimac_mdio_read;\n\tbus->write = unimac_mdio_write;\n\tbus->reset = unimac_mdio_reset;\n\tsnprintf(bus->id, MII_BUS_ID_SIZE, \"%s-%d\", pdev->name, pdev->id);\n\n\tret = of_mdiobus_register(bus, np);\n\tif (ret) {\n\t\tdev_err(&pdev->dev, \"MDIO bus registration failed\\n\");\n\t\tgoto out_mdio_free;\n\t}\n\n\tplatform_set_drvdata(pdev, priv);\n\n\tdev_info(&pdev->dev, \"Broadcom UniMAC MDIO bus at 0x%p\\n\", priv->base);\n\n\treturn 0;\n\nout_mdio_free:\n\tmdiobus_free(bus);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "unimac_mdio_probe", "_file_name": "drivers/net/phy/mdio-bcm-unimac.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "R_API void r_anal_bb_free(RAnalBlock *bb) {\n\tif (!bb) {\n\t\treturn;\n\t}\n\tr_anal_cond_free (bb->cond);\n\tR_FREE (bb->fingerprint);\n\tr_anal_diff_free (bb->diff);\n\tbb->diff = NULL;\n\tR_FREE (bb->op_bytes);\n\tr_anal_switch_op_free (bb->switch_op);\n\tbb->switch_op = NULL;\n\tbb->fingerprint = NULL;\n\tbb->cond = NULL;\n\tR_FREE (bb->label);\n\tR_FREE (bb->op_pos);\n\tR_FREE (bb->parent_reg_arena);\n\tif (bb->prev) {\n\t\tif (bb->prev->jumpbb == bb) {\n\t\t\tbb->prev->jumpbb = NULL;\n\t\t}\n\t\tif (bb->prev->failbb == bb) {\n\t\t\tbb->prev->failbb = NULL;\n\t\t}\n\t\tbb->prev = NULL;\n\t}\n\tif (bb->jumpbb) {\n\t\tbb->jumpbb->prev = NULL;\n\t\tbb->jumpbb = NULL;\n\t}\n\tif (bb->failbb) {\n\t\tbb->failbb->prev = NULL;\n\t\tbb->failbb = NULL;\n\t}\n\tif (bb->next) {\n\t\t// avoid double free\n\t\tbb->next->prev = NULL;\n\t}\n\tR_FREE (bb); // double free\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "r_anal_bb_free", "_file_name": "libr/anal/bb.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _delete_host(self, host_name):\n \"\"\"Delete a host on the storage system.\"\"\"\n\n LOG.debug(_('enter: _delete_host: host %s ') % host_name)\n\n ssh_cmd = 'svctask rmhost %s ' % host_name\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_delete_host', ssh_cmd, out, err)\n\n LOG.debug(_('leave: _delete_host: host %s ') % host_name)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[158, 209]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[158, 209]]}, "_func_name": "_delete_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "async def save(request):\n # TODO csrf\n data = await request.post()\n item = Item(data['src'])\n\n # Update name\n new_src = data.get('new_src')\n if new_src and new_src != data['src']:\n # don't need to worry about html unquote\n shutil.move(item.abspath, settings.STORAGE_DIR + new_src)\n old_backup_abspath = item.backup_abspath\n item = Item(new_src)\n if os.path.isfile(old_backup_abspath):\n shutil.move(old_backup_abspath, item.backup_abspath)\n\n # Update meta\n for field in item.FORM:\n # TODO handle .repeatable (keywords)\n item.meta[field] = [data.get(field, '')]\n\n if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath):\n shutil.copyfile(item.abspath, item.backup_abspath)\n\n # WISHLIST don't write() if nothing changed\n item.meta.write()\n\n return web.Response(\n status=200,\n body=json.dumps(item.get_form_fields()).encode('utf8'),\n content_type='application/json',\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[155, 313]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[155, 313]]}, "_func_name": "save", "_file_name": "gallery/gallery.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost',\n 'iqn.1993-08.org.debian:01:222'])\n in_use_ret = pack('\\r\\nalready used by host fakehost.foo ')\n _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])\n\n show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_invalid_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static const char *parse_string(cJSON *item,const char *str,const char **ep)\n{\n\tconst char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;\n\tif (*str!='\\\"') {*ep=str;return 0;}\t/* not a string! */\n\t\n\twhile (*end_ptr!='\\\"' && *end_ptr && ++len) if (*end_ptr++ == '\\\\') end_ptr++;\t/* Skip escaped quotes. */\n\t\n\tout=(char*)cJSON_malloc(len+1);\t/* This is how long we need for the string, roughly. */\n\tif (!out) return 0;\n\titem->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */\n\titem->type=cJSON_String;\n\t\n\tptr=str+1;ptr2=out;\n\twhile (ptr < end_ptr)\n\t{\n\t\tif (*ptr!='\\\\') *ptr2++=*ptr++;\n\t\telse\n\t\t{\n\t\t\tptr++;\n\t\t\tswitch (*ptr)\n\t\t\t{\n\t\t\t\tcase 'b': *ptr2++='\\b';\tbreak;\n\t\t\t\tcase 'f': *ptr2++='\\f';\tbreak;\n\t\t\t\tcase 'n': *ptr2++='\\n';\tbreak;\n\t\t\t\tcase 'r': *ptr2++='\\r';\tbreak;\n\t\t\t\tcase 't': *ptr2++='\\t';\tbreak;\n\t\t\t\tcase 'u':\t /* transcode utf16 to utf8. */\n\t\t\t\t\tuc=parse_hex4(ptr+1);ptr+=4;\t/* get the unicode char. */\n\t\t\t\t\tif (ptr >= end_ptr) {*ep=str;return 0;}\t/* invalid */\n\t\t\t\t\t\n\t\t\t\t\tif ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;}\t/* check for invalid. */\n\t\t\t\t\t\n\t\t\t\t\tif (uc>=0xD800 && uc<=0xDBFF)\t/* UTF16 surrogate pairs.\t*/\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ptr+6 > end_ptr) {*ep=str;return 0;}\t/* invalid */\n\t\t\t\t\t\tif (ptr[1]!='\\\\' || ptr[2]!='u') {*ep=str;return 0;}\t/* missing second-half of surrogate. */\n\t\t\t\t\t\tuc2=parse_hex4(ptr+3);ptr+=6;\n\t\t\t\t\t\tif (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;}\t/* invalid second-half of surrogate. */\n\t\t\t\t\t\tuc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));\n\t\t\t\t\t}\n\n\t\t\t\t\tlen=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;\n\t\t\t\t\t\n\t\t\t\t\tswitch (len) {\n\t\t\t\t\t\tcase 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 1: *--ptr2 =(uc | firstByteMark[len]);\n\t\t\t\t\t}\n\t\t\t\t\tptr2+=len;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: *ptr2++=*ptr; break;\n\t\t\t}\n\t\t\tptr++;\n\t\t}\n\t}\n\t*ptr2=0;\n\tif (*ptr=='\\\"') ptr++;\n\treturn ptr;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[222, 224]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[222, 224]]}, "_func_name": "parse_string", "_file_name": "cJSON.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('//history')\ndef view_page_history(page_name):\n query = db.query(\"select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = '%s'\" % page_name)\n page_histories = query.namedresult()\n\n return render_template(\n 'page_history.html',\n page_name = page_name,\n page_histories = page_histories\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[69, 239]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[69, 239]]}, "_func_name": "view_page_history", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, path):\n path = self.sanitize_path(path)\n base_paths = self.get_base_paths()\n if hasattr(base_paths, 'split'):\n # String, so go simple\n base_path = base_paths\n else:\n base_path = self.get_first_base(base_paths, path)\n return static_file(path, base_path)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "seagull/routes/app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _delete_3par_host(self, hostname):\n self._cli_run('removehost %s' % hostname, None)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[43, 98]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[43, 98]]}, "_func_name": "_delete_3par_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "acc_ctx_cont(OM_uint32 *minstat,\n\t gss_buffer_t buf,\n\t gss_ctx_id_t *ctx,\n\t gss_buffer_t *responseToken,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 ret, tmpmin;\n\tgss_OID supportedMech;\n\tspnego_gss_ctx_id_t sc;\n\tunsigned int len;\n\tunsigned char *ptr, *bufstart;\n\n\tsc = (spnego_gss_ctx_id_t)*ctx;\n\tret = GSS_S_DEFECTIVE_TOKEN;\n\t*negState = REJECT;\n\t*minstat = 0;\n\tsupportedMech = GSS_C_NO_OID;\n\t*return_token = ERROR_TOKEN_SEND;\n\t*responseToken = *mechListMIC = GSS_C_NO_BUFFER;\n\n\tptr = bufstart = buf->value;\n#define REMAIN (buf->length - (ptr - bufstart))\n\tif (REMAIN > INT_MAX)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\t/*\n\t * Attempt to work with old Sun SPNEGO.\n\t */\n\tif (*ptr == HEADER_ID) {\n\t\tret = g_verify_token_header(gss_mech_spnego,\n\t\t\t\t\t &len, &ptr, 0, REMAIN);\n\t\tif (ret) {\n\t\t\t*minstat = ret;\n\t\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t\t}\n\t}\n\tif (*ptr != (CONTEXT | 0x01)) {\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t}\n\tret = get_negTokenResp(minstat, ptr, REMAIN,\n\t\t\t negState, &supportedMech,\n\t\t\t responseToken, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tif (*responseToken == GSS_C_NO_BUFFER &&\n\t *mechListMIC == GSS_C_NO_BUFFER) {\n\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tsc->firstpass = 0;\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = CONT_TOKEN_SEND;\ncleanup:\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tgeneric_gss_release_oid(&tmpmin, &supportedMech);\n\t}\n\treturn ret;\n#undef REMAIN\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[635, 658]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[635, 658]]}, "_func_name": "acc_ctx_cont", "_file_name": "src/lib/gssapi/spnego/spnego_mech.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def deleteKey(client):\n\t\"\"\"Deletes the specified key.\n\tReturns an error if the key doesn't exist\n\t\"\"\"\n\tglobal BAD_REQUEST\n\tglobal NOT_FOUND\n\n\tvalidateClient(client)\n\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\n\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')\n\n\ttry:\n\t\tos.remove('keys/%s/%s.key' % (client, token_data['key']))\n\texcept FileNotFoundError:\n\t\traise FoxlockError(NOT_FOUND, \"Key '%s' not found\" % token_data['key'])\n\n\treturn \"Key '%s' successfully deleted\" % token_data['key']", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[102, 140], [165, 166], [272, 382]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[102, 140], [165, 166], [272, 382]]}, "_func_name": "deleteKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def tag_to_tag_num(self, tag):\n ''' Returns tag_num given tag. '''\n\n q = \"SELECT rowid FROM tags WHERE tag = ?\"\n self.query(q, tag)\n return self.c.fetchone()[0]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tag_to_tag_num", "_file_name": "modules/query_lastfm.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def candidate_paths_for_url(self, url):\n for root, prefix in self.directories:\n if url.startswith(prefix):\n path = os.path.join(root, url[len(prefix):])\n if os.path.commonprefix((root, path)) == root:\n yield path", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "candidate_paths_for_url", "_file_name": "whitenoise/base.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "choose_volume(struct archive_read *a, struct iso9660 *iso9660)\n{\n\tstruct file_info *file;\n\tint64_t skipsize;\n\tstruct vd *vd;\n\tconst void *block;\n\tchar seenJoliet;\n\n\tvd = &(iso9660->primary);\n\tif (!iso9660->opt_support_joliet)\n\t\tiso9660->seenJoliet = 0;\n\tif (iso9660->seenJoliet &&\n\t\tvd->location > iso9660->joliet.location)\n\t\t/* This condition is unlikely; by way of caution. */\n\t\tvd = &(iso9660->joliet);\n\n\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n\tskipsize = __archive_read_consume(a, skipsize);\n\tif (skipsize < 0)\n\t\treturn ((int)skipsize);\n\tiso9660->current_position = skipsize;\n\n\tblock = __archive_read_ahead(a, vd->size, NULL);\n\tif (block == NULL) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Failed to read full block when scanning \"\n\t\t \"ISO9660 directory list\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\n\t/*\n\t * While reading Root Directory, flag seenJoliet must be zero to\n\t * avoid converting special name 0x00(Current Directory) and\n\t * next byte to UCS2.\n\t */\n\tseenJoliet = iso9660->seenJoliet;/* Save flag. */\n\tiso9660->seenJoliet = 0;\n\tfile = parse_file_info(a, NULL, block);\n\tif (file == NULL)\n\t\treturn (ARCHIVE_FATAL);\n\tiso9660->seenJoliet = seenJoliet;\n\n\t/*\n\t * If the iso image has both RockRidge and Joliet, we preferentially\n\t * use RockRidge Extensions rather than Joliet ones.\n\t */\n\tif (vd == &(iso9660->primary) && iso9660->seenRockridge\n\t && iso9660->seenJoliet)\n\t\tiso9660->seenJoliet = 0;\n\n\tif (vd == &(iso9660->primary) && !iso9660->seenRockridge\n\t && iso9660->seenJoliet) {\n\t\t/* Switch reading data from primary to joliet. */\n\t\tvd = &(iso9660->joliet);\n\t\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n\t\tskipsize -= iso9660->current_position;\n\t\tskipsize = __archive_read_consume(a, skipsize);\n\t\tif (skipsize < 0)\n\t\t\treturn ((int)skipsize);\n\t\tiso9660->current_position += skipsize;\n\n\t\tblock = __archive_read_ahead(a, vd->size, NULL);\n\t\tif (block == NULL) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Failed to read full block when scanning \"\n\t\t\t \"ISO9660 directory list\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tiso9660->seenJoliet = 0;\n\t\tfile = parse_file_info(a, NULL, block);\n\t\tif (file == NULL)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tiso9660->seenJoliet = seenJoliet;\n\t}\n\n\t/* Store the root directory in the pending list. */\n\tif (add_entry(a, iso9660, file) != ARCHIVE_OK)\n\t\treturn (ARCHIVE_FATAL);\n\tif (iso9660->seenRockridge) {\n\t\ta->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;\n\t\ta->archive.archive_format_name =\n\t\t \"ISO9660 with Rockridge extensions\";\n\t}\n\n\treturn (ARCHIVE_OK);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[407, 454], [1599, 1647]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[407, 454], [1599, 1647]]}, "_func_name": "choose_volume", "_file_name": "libarchive/archive_read_support_format_iso9660.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _formatCredentials(self, data, name):\n \"\"\"\n Credentials are of the form\n RCLONE_CONFIG_CURRENT_TYPE=s3\n ^ ^ ^ ^\n [mandatory ][name ][key][value]\n \"\"\"\n\n prefix = \"RCLONE_CONFIG_{}\".format(name.upper())\n\n credentials = {}\n credentials['{}_TYPE'.format(prefix)] = data.type\n\n def _addCredential(credentials, env_key, data_key):\n value = getattr(data, data_key, None)\n if value is not None:\n credentials[env_key] = value\n return credentials\n\n\n if data.type == 's3':\n credentials = _addCredential(credentials,\n '{}_REGION'.format(prefix),\n 's3_region'\n )\n credentials = _addCredential(credentials,\n '{}_ACCESS_KEY_ID'.format(prefix),\n 's3_access_key_id'\n )\n credentials = _addCredential(credentials,\n '{}_SECRET_ACCESS_KEY'.format(prefix),\n 's3_secret_access_key'\n )\n\n credentials = _addCredential(credentials,\n '{}_ENDPOINT'.format(prefix),\n 's3_endpoint'\n )\n credentials = _addCredential(credentials,\n '{}_V2_AUTH'.format(prefix),\n 's3_v2_auth'\n )\n\n elif data.type == 'azureblob':\n credentials = _addCredential(credentials,\n '{}_ACCOUNT'.format(prefix),\n 'azure_account'\n )\n credentials = _addCredential(credentials,\n '{}_KEY'.format(prefix),\n 'azure_key'\n )\n\n elif data.type == 'swift':\n credentials = _addCredential(credentials,\n '{}_USER'.format(prefix),\n 'swift_user'\n )\n credentials = _addCredential(credentials,\n '{}_KEY'.format(prefix),\n 'swift_key'\n )\n credentials = _addCredential(credentials,\n '{}_AUTH'.format(prefix),\n 'swift_auth'\n )\n credentials = _addCredential(credentials,\n '{}_TENANT'.format(prefix),\n 'swift_tenant'\n )\n\n elif data.type == 'google cloud storage':\n credentials = _addCredential(credentials,\n '{}_CLIENT_ID'.format(prefix),\n 'gcp_client_id'\n )\n credentials = _addCredential(credentials,\n '{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix),\n 'gcp_service_account_credentials'\n )\n credentials = _addCredential(credentials,\n '{}_PROJECT_NUMBER'.format(prefix),\n 'gcp_project_number'\n )\n credentials = _addCredential(credentials,\n '{}_OBJECT_ACL'.format(prefix),\n 'gcp_object_acl'\n )\n credentials = _addCredential(credentials,\n '{}_BUCKET_ACL'.format(prefix),\n 'gcp_bucket_acl'\n )\n\n else:\n logging.error(\"Connection type unknown: {}\".format(data.type))\n\n return credentials", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_formatCredentials", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def new_goal():\n \"\"\"\n new goal\n \"\"\"\n\n goals_dir_check()\n\n click.echo(chalk.blue('Input a single-word name of the goal:'))\n goal_name = input().strip()\n\n if goal_name_exists(goal_name):\n click.echo(chalk.red(\n 'A goal with this name already exists. Please type \"yoda goals view\" to see a list of existing goals'))\n else:\n click.echo(chalk.blue('Input description of the goal:'))\n text = input().strip()\n\n click.echo(chalk.blue('Input due date for the goal (YYYY-MM-DD):'))\n deadline = input().strip()\n\n if os.path.isfile(GOALS_CONFIG_FILE_PATH):\n setup_data = dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n append_data_into_file(setup_data, GOALS_CONFIG_FILE_PATH)\n else:\n setup_data = dict(\n entries=[\n dict(\n name=goal_name,\n text=text,\n deadline=deadline,\n status=0\n )\n ]\n )\n input_data(setup_data, GOALS_CONFIG_FILE_PATH)\n\n input_data(dict(entries=[]), get_goal_file_path(goal_name))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[137, 169], [535, 570]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[137, 169], [535, 570]]}, "_func_name": "new_goal", "_file_name": "modules/goals.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void ffs_user_copy_worker(struct work_struct *work)\n{\n\tstruct ffs_io_data *io_data = container_of(work, struct ffs_io_data,\n\t\t\t\t\t\t work);\n\tint ret = io_data->req->status ? io_data->req->status :\n\t\t\t\t\t io_data->req->actual;\n\n\tif (io_data->read && ret > 0) {\n\t\tuse_mm(io_data->mm);\n\t\tret = copy_to_iter(io_data->buf, ret, &io_data->data);\n\t\tif (iov_iter_count(&io_data->data))\n\t\t\tret = -EFAULT;\n\t\tunuse_mm(io_data->mm);\n\t}\n\n\tio_data->kiocb->ki_complete(io_data->kiocb, ret, ret);\n\n\tif (io_data->ffs->ffs_eventfd &&\n\t !(io_data->kiocb->ki_flags & IOCB_EVENTFD))\n\t\teventfd_signal(io_data->ffs->ffs_eventfd, 1);\n\n\tusb_ep_free_request(io_data->ep, io_data->req);\n\n\tio_data->kiocb->private = NULL;\n\tif (io_data->read)\n\t\tkfree(io_data->to_free);\n\tkfree(io_data->buf);\n\tkfree(io_data);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[488, 571], [669, 703]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[488, 571], [669, 703]]}, "_func_name": "ffs_user_copy_worker", "_file_name": "drivers/usb/gadget/function/f_fs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool Scanner::fill(size_t need)\n{\n if (eof) return false;\n\n pop_finished_files();\n\n DASSERT(bot <= tok && tok <= lim);\n size_t free = static_cast(tok - bot);\n size_t copy = static_cast(lim - tok);\n\n if (free >= need) {\n memmove(bot, tok, copy);\n shift_ptrs_and_fpos(-static_cast(free));\n }\n else {\n BSIZE += std::max(BSIZE, need);\n char * buf = new char[BSIZE + YYMAXFILL];\n if (!buf) fatal(\"out of memory\");\n\n memmove(buf, tok, copy);\n shift_ptrs_and_fpos(buf - bot);\n delete [] bot;\n bot = buf;\n\n free = BSIZE - copy;\n }\n\n if (!read(free)) {\n eof = lim;\n memset(lim, 0, YYMAXFILL);\n lim += YYMAXFILL;\n }\n\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[529, 569]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[529, 569]]}, "_func_name": "re2c::Scanner::fill", "_file_name": "src/parse/scanner.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def _call_prepare_fc_map(self, fc_map_id, source, target):\n try:\n out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])\n except exception.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source,\n 'target': target,\n 'out': e.stdout,\n 'err': e.stderr})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_call_prepare_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)\n{\n\tconst char *s = name;\n\n\twhile (1) {\n\t\tconst char *s0 = s;\n\t\tchar *dirname;\n\n\t\t/* Find a directory component, if any. */\n\t\twhile (1) {\n\t\t\tif (*s == 0) {\n\t\t\t\tif (last && s != s0)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\treturn dir;\n\t\t\t}\n\t\t\t/* This is deliberately slash-only. */\n\t\t\tif (*s == '/')\n\t\t\t\tbreak;\n\t\t\ts++;\n\t\t}\n\n\t\tdirname = g_strndup (s0, s - s0);\n\t\twhile (*s == '/')\n\t\t\ts++;\n\n\t\tif (strcmp (dirname, \".\") != 0) {\n\t\t\tGsfInput *subdir =\n\t\t\t\tgsf_infile_child_by_name (GSF_INFILE (dir),\n\t\t\t\t\t\t\t dirname);\n\t\t\tif (subdir) {\n\t\t\t\tdir = GSF_IS_INFILE_TAR (subdir)\n\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n\t\t\t\t\t: dir;\n\t\t\t\t/* Undo the ref. */\n\t\t\t\tg_object_unref (subdir);\n\t\t\t} else\n\t\t\t\tdir = tar_create_dir (dir, dirname);\n\t\t}\n\n\t\tg_free (dirname);\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tar_directory_for_file", "_file_name": "gsf/gsf-infile-tar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow)\n{\n struct ndpi_packet_struct *packet = &flow->packet;\n u_int16_t dport = 0, sport = 0;\n\n NDPI_LOG_DBG(ndpi_struct, \"search ORACLE\\n\");\n\n if(packet->tcp != NULL) {\n sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest);\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n\t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n\t && (packet->payload[1] != 0x00)\n\t && (packet->payload[2] == 0x00)\n\t\t && (packet->payload[3] == 0x00)))) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 &&\n packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 &&\n packet->payload[3] == 0x00 ) {\n NDPI_LOG_INFO(ndpi_struct, \"found oracle\\n\");\n ndpi_int_oracle_add_connection(ndpi_struct, flow);\n }\n } else {\n NDPI_EXCLUDE_PROTO(ndpi_struct, flow);\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[489, 590]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[489, 590]]}, "_func_name": "ndpi_search_oracle", "_file_name": "src/lib/protocols/oracle.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)\n{\n struct ImapMbox mx;\n struct Url url;\n char cachepath[PATH_MAX];\n char mbox[PATH_MAX];\n\n if (path)\n imap_cachepath(idata, path, mbox, sizeof(mbox));\n else\n {\n if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)\n return NULL;\n\n imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));\n FREE(&mx.mbox);\n }\n\n mutt_account_tourl(&idata->conn->account, &url);\n url.path = mbox;\n url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);\n\n return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[413, 464]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[413, 464]]}, "_func_name": "imap_hcache_open", "_file_name": "imap/util.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "xfs_attr_shortform_to_leaf(\n\tstruct xfs_da_args\t*args,\n\tstruct xfs_buf\t\t**leaf_bp)\n{\n\txfs_inode_t *dp;\n\txfs_attr_shortform_t *sf;\n\txfs_attr_sf_entry_t *sfe;\n\txfs_da_args_t nargs;\n\tchar *tmpbuffer;\n\tint error, i, size;\n\txfs_dablk_t blkno;\n\tstruct xfs_buf *bp;\n\txfs_ifork_t *ifp;\n\n\ttrace_xfs_attr_sf_to_leaf(args);\n\n\tdp = args->dp;\n\tifp = dp->i_afp;\n\tsf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;\n\tsize = be16_to_cpu(sf->hdr.totsize);\n\ttmpbuffer = kmem_alloc(size, KM_SLEEP);\n\tASSERT(tmpbuffer != NULL);\n\tmemcpy(tmpbuffer, ifp->if_u1.if_data, size);\n\tsf = (xfs_attr_shortform_t *)tmpbuffer;\n\n\txfs_idata_realloc(dp, -size, XFS_ATTR_FORK);\n\txfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);\n\n\tbp = NULL;\n\terror = xfs_da_grow_inode(args, &blkno);\n\tif (error) {\n\t\t/*\n\t\t * If we hit an IO error middle of the transaction inside\n\t\t * grow_inode(), we may have inconsistent data. Bail out.\n\t\t */\n\t\tif (error == -EIO)\n\t\t\tgoto out;\n\t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n\t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */\n\t\tgoto out;\n\t}\n\n\tASSERT(blkno == 0);\n\terror = xfs_attr3_leaf_create(args, blkno, &bp);\n\tif (error) {\n\t\terror = xfs_da_shrink_inode(args, 0, bp);\n\t\tbp = NULL;\n\t\tif (error)\n\t\t\tgoto out;\n\t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n\t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */\n\t\tgoto out;\n\t}\n\n\tmemset((char *)&nargs, 0, sizeof(nargs));\n\tnargs.dp = dp;\n\tnargs.geo = args->geo;\n\tnargs.firstblock = args->firstblock;\n\tnargs.dfops = args->dfops;\n\tnargs.total = args->total;\n\tnargs.whichfork = XFS_ATTR_FORK;\n\tnargs.trans = args->trans;\n\tnargs.op_flags = XFS_DA_OP_OKNOENT;\n\n\tsfe = &sf->list[0];\n\tfor (i = 0; i < sf->hdr.count; i++) {\n\t\tnargs.name = sfe->nameval;\n\t\tnargs.namelen = sfe->namelen;\n\t\tnargs.value = &sfe->nameval[nargs.namelen];\n\t\tnargs.valuelen = sfe->valuelen;\n\t\tnargs.hashval = xfs_da_hashname(sfe->nameval,\n\t\t\t\t\t\tsfe->namelen);\n\t\tnargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);\n\t\terror = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */\n\t\tASSERT(error == -ENOATTR);\n\t\terror = xfs_attr3_leaf_add(bp, &nargs);\n\t\tASSERT(error != -ENOSPC);\n\t\tif (error)\n\t\t\tgoto out;\n\t\tsfe = XFS_ATTR_SF_NEXTENTRY(sfe);\n\t}\n\terror = 0;\n\t*leaf_bp = bp;\nout:\n\tkmem_free(tmpbuffer);\n\treturn error;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1151, 1221]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1151, 1221]]}, "_func_name": "xfs_attr_shortform_to_leaf", "_file_name": "fs/xfs/libxfs/xfs_attr_leaf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def deleteKey(client):\n\t\"\"\"Deletes the specified key.\n\tReturns an error if the key doesn't exist\n\t\"\"\"\n\tglobal NOT_FOUND\n\n\tvalidateClient(client)\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateKeyName(token_data['key'])\n\n\ttry:\n\t\tos.remove('keys/%s/%s.key' % (client, token_data['key']))\n\texcept FileNotFoundError:\n\t\traise FoxlockError(NOT_FOUND, \"Key '%s' not found\" % token_data['key'])\n\n\treturn \"Key '%s' successfully deleted\" % token_data['key']", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "deleteKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def link_dialog(request):\n # list of wiki pages\n name = request.values.get(\"pagename\", \"\")\n if name:\n from MoinMoin import search\n # XXX error handling!\n searchresult = search.searchPages(request, 't:\"%s\"' % name)\n\n pages = [p.page_name for p in searchresult.hits]\n pages.sort()\n pages[0:0] = [name]\n page_list = '''\n \n \n \n \n \n''' % \"\\n\".join(['' % (wikiutil.escape(page), wikiutil.escape(page))\n for page in pages])\n else:\n page_list = \"\"\n\n # list of interwiki names\n interwiki_list = wikiutil.load_wikimap(request)\n interwiki = interwiki_list.keys()\n interwiki.sort()\n iwpreferred = request.cfg.interwiki_preferred[:]\n if not iwpreferred or iwpreferred and iwpreferred[-1] is not None:\n resultlist = iwpreferred\n for iw in interwiki:\n if not iw in iwpreferred:\n resultlist.append(iw)\n else:\n resultlist = iwpreferred[:-1]\n interwiki = \"\\n\".join(\n ['' % (wikiutil.escape(key), wikiutil.escape(key))\n for key in resultlist])\n\n # wiki url\n url_prefix_static = request.cfg.url_prefix_static\n scriptname = request.script_root + '/'\n action = scriptname\n basepage = wikiutil.escape(request.page.page_name)\n request.write(u'''\n\n\n\n\n\n \n Link Properties\n \n \n \n \n \n \n \n
\n Link Type
\n \n
\n
\n
\n \n \n \n \n
\n
\n \n \n \n \n \n \n \n \n %(page_list)s\n
\n Page Name
\n \n
\n \n
\n
\n
\n
\n
\n \n \n \n \n
\n \n \n \n \n
\n Wiki:PageName
\n :\n \n
\n
\n
\n
\n \n \n \n \n \n \n
\n Protocol
\n \n
 \n URL
\n \n
\n
\n
\n
\n \n\n''' % locals())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[3711, 3789]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3711, 3789]]}, "_func_name": "link_dialog", "_file_name": "MoinMoin/action/fckdialog.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;\n\n\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}\n\n\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}\n\n\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);\n\n\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;\n\n\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;\n\n\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;\n\n\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);\n\n\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);\n\n\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);\n\n\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);\n\n\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}\n\n\tmr->r_trans_private = trans_private;\n\n\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);\n\n\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;\n\n\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}\n\n\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\n\tBUG_ON(found && found != mr);\n\n\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}\n\n\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__rds_rdma_map", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_consumption_data_row(self, ts, energy_used, power_used):\n\n if power_used > 0:\n\n query = '''\n INSERT OR IGNORE INTO Consumption (\n TimeStamp,\n EnergyUsed,\n PowerUsed \n ) VALUES (\n %s,\n %s,\n %s\n );\n ''' % (ts, 0, 0)\n self.c.execute(query)\n\n query = '''\n UPDATE Consumption SET \n EnergyUsed = EnergyUsed + %s,\n PowerUsed = PowerUsed + %s\n WHERE TimeStamp = %s;\n ''' % (energy_used, power_used, ts)\n\n self.c.execute(query)\n\n self.db.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[326, 397], [416, 445], [544, 719]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[326, 397], [416, 445], [544, 719]]}, "_func_name": "add_consumption_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@mod.route('/edit/', methods=['GET', 'POST'])\ndef edit(cmt_id):\n m = None\n if request.method == 'GET':\n sql = \"SELECT * FROM comment where cmt_id = %d;\" % (cmt_id)\n cursor.execute(sql)\n m = cursor.fetchone()\n return render_template('comment/edit.html', m=m, cmt_id=cmt_id)\n\n if request.method == 'POST':\n content = request.form['content']\n sql = \"UPDATE comment SET content = '%s' where cmt_id = '%d';\" \\\n % (content, cmt_id)\n cursor.execute(sql)\n conn.commit()\n sql = \"SELECT msg_id FROM comment where cmt_id = %d;\" % (cmt_id)\n cursor.execute(sql)\n m = cursor.fetchone()\n flash('Edit Success!')\n return redirect(url_for('comment.show', msg_id=m[0]))\n\n return render_template('comment/edit.html', m=m, cmt_id=cmt_id)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[121, 217], [395, 528], [550, 651]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[121, 217], [395, 528], [550, 651]]}, "_func_name": "edit", "_file_name": "flaskr/flaskr/views/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def GameNewPlayed(Played, ID):\n\tdb.execute(\"UPDATE games set GamesPlayed = ? WHERE ID = ?\", Played, ID)\n\tdatabase.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "GameNewPlayed", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int git_delta_apply(\n\tvoid **out,\n\tsize_t *out_len,\n\tconst unsigned char *base,\n\tsize_t base_len,\n\tconst unsigned char *delta,\n\tsize_t delta_len)\n{\n\tconst unsigned char *delta_end = delta + delta_len;\n\tsize_t base_sz, res_sz, alloc_sz;\n\tunsigned char *res_dp;\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\t/*\n\t * Check that the base size matches the data we were given;\n\t * if not we would underflow while accessing data from the\n\t * base object, resulting in data corruption or segfault.\n\t */\n\tif ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tif (hdr_sz(&res_sz, &delta, delta_end) < 0) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tGITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);\n\tres_dp = git__malloc(alloc_sz);\n\tGITERR_CHECK_ALLOC(res_dp);\n\n\tres_dp[res_sz] = '\\0';\n\t*out = res_dp;\n\t*out_len = res_sz;\n\n\twhile (delta < delta_end) {\n\t\tunsigned char cmd = *delta++;\n\t\tif (cmd & 0x80) {\n\t\t\t/* cmd is a copy instruction; copy from the base. */\n\t\t\tsize_t off = 0, len = 0, end;\n\n#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }\n\t\t\tif (cmd & 0x01) ADD_DELTA(off, 0UL);\n\t\t\tif (cmd & 0x02) ADD_DELTA(off, 8UL);\n\t\t\tif (cmd & 0x04) ADD_DELTA(off, 16UL);\n\t\t\tif (cmd & 0x08) ADD_DELTA(off, 24UL);\n\n\t\t\tif (cmd & 0x10) ADD_DELTA(len, 0UL);\n\t\t\tif (cmd & 0x20) ADD_DELTA(len, 8UL);\n\t\t\tif (cmd & 0x40) ADD_DELTA(len, 16UL);\n\t\t\tif (!len) len = 0x10000;\n#undef ADD_DELTA\n\n\t\t\tif (GIT_ADD_SIZET_OVERFLOW(&end, off, len) ||\n\t\t\t base_len < end || res_sz < len)\n\t\t\t\tgoto fail;\n\n\t\t\tmemcpy(res_dp, base + off, len);\n\t\t\tres_dp += len;\n\t\t\tres_sz -= len;\n\n\t\t} else if (cmd) {\n\t\t\t/*\n\t\t\t * cmd is a literal insert instruction; copy from\n\t\t\t * the delta stream itself.\n\t\t\t */\n\t\t\tif (delta_end - delta < cmd || res_sz < cmd)\n\t\t\t\tgoto fail;\n\t\t\tmemcpy(res_dp, delta, cmd);\n\t\t\tdelta += cmd;\n\t\t\tres_dp += cmd;\n\t\t\tres_sz -= cmd;\n\n\t\t} else {\n\t\t\t/* cmd == 0 is reserved for future encodings. */\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tif (delta != delta_end || res_sz)\n\t\tgoto fail;\n\treturn 0;\n\nfail:\n\tgit__free(*out);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tgiterr_set(GITERR_INVALID, \"failed to apply delta\");\n\treturn -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "git_delta_apply", "_file_name": "src/delta.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connect()\n try:\n # The following introduces a deliberate security flaw - SQL Injection\n query = \"INSERT INTO crimes (description) VALUES (%s);\"\n with connection.cursor() as cursor:\n cursor.execute(query, data)\n connection.commit()\n finally:\n connection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_fc_wwpns(self):\n for key in self._storage_nodes:\n node = self._storage_nodes[key]\n ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id']\n raw = self._run_ssh(ssh_cmd)\n resp = CLIResponse(raw, delim='!', with_header=False)\n wwpns = set(node['WWPN'])\n for i, s in resp.select('port_id', 'port_status'):\n if 'unconfigured' != s:\n wwpns.add(i)\n node['WWPN'] = list(wwpns)\n LOG.info(_('WWPN on node %(node)s: %(wwpn)s')\n % {'node': node['id'], 'wwpn': node['WWPN']})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[113, 177]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[113, 177]]}, "_func_name": "_get_fc_wwpns", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def view_grocery_list():\n print(\"grocery== list\")\n groceryListFrame = Frame(self)\n groceryListFrame.rowconfigure(0, weight=1)\n groceryListFrame.columnconfigure(0, weight=1)\n groceryListFrame.rowconfigure(1, weight=3)\n groceryListFrame.columnconfigure(1, weight=3)\n groceryListFrame.pack()\n\n menu.pack_forget()\n groceryButton.pack_forget()\n label.configure(text=\"Grocery List\")\n\n i = 0\n database_file = \"meal_planner.db\"\n item_array = []\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n tableName = \"ingredients_\" + str(weekNumber)\n selection = cursor.execute(\"\"\"SELECT * FROM ?;\"\"\", (tableName, ))\n for result in [selection]:\n for row in result.fetchall():\n print(row)\n for ingredient in row:\n print(ingredient)\n item_array.append(str(ingredient).split())\n i = i +1\n Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=\"w\")\n \n\n j = 0\n for item in item_array:\n print(item)\n\n\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [groceryListFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__init__.view_grocery_list", "_file_name": "mealPlan.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_get_ports(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI),\n ''])\n self.mox.ReplayAll()\n\n ports = self.driver.common.get_ports()\n self.assertEqual(ports['FC'][0], '20210002AC00383D')\n self.assertEqual(ports['iSCSI']['10.10.120.252']['nsp'], '0:8:2')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[273, 308], [380, 424], [562, 610]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[273, 308], [380, 424], [562, 610]]}, "_func_name": "test_get_ports", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,\n struct _7z_folder *f, size_t numFolders)\n{\n\tconst unsigned char *p;\n\tuint64_t *usizes;\n\tsize_t unpack_streams;\n\tint type;\n\tunsigned i;\n\tuint32_t numDigests;\n\n\tmemset(ss, 0, sizeof(*ss));\n\n\tfor (i = 0; i < numFolders; i++)\n\t\tf[i].numUnpackStreams = 1;\n\n\tif ((p = header_bytes(a, 1)) == NULL)\n\t\treturn (-1);\n\ttype = *p;\n\n\tif (type == kNumUnPackStream) {\n\t\tunpack_streams = 0;\n\t\tfor (i = 0; i < numFolders; i++) {\n\t\t\tif (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0)\n\t\t\t\treturn (-1);\n\t\t\tif (UMAX_ENTRY < f[i].numUnpackStreams)\n\t\t\t\treturn (-1);\n\t\t\tunpack_streams += (size_t)f[i].numUnpackStreams;\n\t\t}\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t} else\n\t\tunpack_streams = numFolders;\n\n\tss->unpack_streams = unpack_streams;\n\tif (unpack_streams) {\n\t\tss->unpackSizes = calloc(unpack_streams,\n\t\t sizeof(*ss->unpackSizes));\n\t\tss->digestsDefined = calloc(unpack_streams,\n\t\t sizeof(*ss->digestsDefined));\n\t\tss->digests = calloc(unpack_streams,\n\t\t sizeof(*ss->digests));\n\t\tif (ss->unpackSizes == NULL || ss->digestsDefined == NULL ||\n\t\t ss->digests == NULL)\n\t\t\treturn (-1);\n\t}\n\n\tusizes = ss->unpackSizes;\n\tfor (i = 0; i < numFolders; i++) {\n\t\tunsigned pack;\n\t\tuint64_t sum;\n\n\t\tif (f[i].numUnpackStreams == 0)\n\t\t\tcontinue;\n\n\t\tsum = 0;\n\t\tif (type == kSize) {\n\t\t\tfor (pack = 1; pack < f[i].numUnpackStreams; pack++) {\n\t\t\t\tif (parse_7zip_uint64(a, usizes) < 0)\n\t\t\t\t\treturn (-1);\n\t\t\t\tsum += *usizes++;\n\t\t\t}\n\t\t}\n\t\t*usizes++ = folder_uncompressed_size(&f[i]) - sum;\n\t}\n\n\tif (type == kSize) {\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t}\n\n\tfor (i = 0; i < unpack_streams; i++) {\n\t\tss->digestsDefined[i] = 0;\n\t\tss->digests[i] = 0;\n\t}\n\n\tnumDigests = 0;\n\tfor (i = 0; i < numFolders; i++) {\n\t\tif (f[i].numUnpackStreams != 1 || !f[i].digest_defined)\n\t\t\tnumDigests += (uint32_t)f[i].numUnpackStreams;\n\t}\n\n\tif (type == kCRC) {\n\t\tstruct _7z_digests tmpDigests;\n\t\tunsigned char *digestsDefined = ss->digestsDefined;\n\t\tuint32_t * digests = ss->digests;\n\t\tint di = 0;\n\n\t\tmemset(&tmpDigests, 0, sizeof(tmpDigests));\n\t\tif (read_Digests(a, &(tmpDigests), numDigests) < 0) {\n\t\t\tfree_Digest(&tmpDigests);\n\t\t\treturn (-1);\n\t\t}\n\t\tfor (i = 0; i < numFolders; i++) {\n\t\t\tif (f[i].numUnpackStreams == 1 && f[i].digest_defined) {\n\t\t\t\t*digestsDefined++ = 1;\n\t\t\t\t*digests++ = f[i].digest;\n\t\t\t} else {\n\t\t\t\tunsigned j;\n\n\t\t\t\tfor (j = 0; j < f[i].numUnpackStreams;\n\t\t\t\t j++, di++) {\n\t\t\t\t\t*digestsDefined++ =\n\t\t\t\t\t tmpDigests.defineds[di];\n\t\t\t\t\t*digests++ =\n\t\t\t\t\t tmpDigests.digests[di];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfree_Digest(&tmpDigests);\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t}\n\n\t/*\n\t * Must be kEnd.\n\t */\n\tif (type != kEnd)\n\t\treturn (-1);\n\treturn (0);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[626, 678]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[626, 678]]}, "_func_name": "read_SubStreamsInfo", "_file_name": "libarchive/archive_read_support_format_7zip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)\n{\n Mpeg4DecContext *ctx = s->avctx->priv_data;\n\n int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,\n additional_code_len, sign, mismatch;\n VLC *cur_vlc = &ctx->studio_intra_tab[0];\n uint8_t *const scantable = s->intra_scantable.permutated;\n const uint16_t *quant_matrix;\n uint32_t flc;\n const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));\n const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);\n\n mismatch = 1;\n\n memset(block, 0, 64 * sizeof(int32_t));\n\n if (n < 4) {\n cc = 0;\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);\n quant_matrix = s->intra_matrix;\n } else {\n cc = (n & 1) + 1;\n if (ctx->rgb)\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);\n else\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);\n quant_matrix = s->chroma_intra_matrix;\n }\n\n if (dct_dc_size < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"illegal dct_dc_size vlc\\n\");\n return AVERROR_INVALIDDATA;\n } else if (dct_dc_size == 0) {\n dct_diff = 0;\n } else {\n dct_diff = get_xbits(&s->gb, dct_dc_size);\n\n if (dct_dc_size > 8) {\n if(!check_marker(s->avctx, &s->gb, \"dct_dc_size > 8\"))\n return AVERROR_INVALIDDATA;\n }\n\n }\n\n s->last_dc[cc] += dct_diff;\n\n if (s->mpeg_quant)\n block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);\n else\n block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);\n /* TODO: support mpeg_quant for AC coefficients */\n\n block[0] = av_clip(block[0], min, max);\n mismatch ^= block[0];\n\n /* AC Coefficients */\n while (1) {\n group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);\n\n if (group < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"illegal ac coefficient group vlc\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n additional_code_len = ac_state_tab[group][0];\n cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];\n\n if (group == 0) {\n /* End of Block */\n break;\n } else if (group >= 1 && group <= 6) {\n /* Zero run length (Table B.47) */\n run = 1 << additional_code_len;\n if (additional_code_len)\n run += get_bits(&s->gb, additional_code_len);\n idx += run;\n continue;\n } else if (group >= 7 && group <= 12) {\n /* Zero run length and +/-1 level (Table B.48) */\n code = get_bits(&s->gb, additional_code_len);\n sign = code & 1;\n code >>= 1;\n run = (1 << (additional_code_len - 1)) + code;\n idx += run;\n j = scantable[idx++];\n block[j] = sign ? 1 : -1;\n } else if (group >= 13 && group <= 20) {\n /* Level value (Table B.49) */\n j = scantable[idx++];\n block[j] = get_xbits(&s->gb, additional_code_len);\n } else if (group == 21) {\n /* Escape */\n j = scantable[idx++];\n additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;\n flc = get_bits(&s->gb, additional_code_len);\n if (flc >> (additional_code_len-1))\n block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);\n else\n block[j] = flc;\n }\n block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;\n block[j] = av_clip(block[j], min, max);\n mismatch ^= block[j];\n }\n\n block[63] ^= mismatch & 1;\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2920, 2954]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2920, 2954]]}, "_func_name": "mpeg4_decode_studio_block", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type)\n{\n const char\n *artifact;\n\n ImageInfo\n *image_info;\n\n MagickBooleanType\n status;\n\n QuantizeInfo\n *quantize_info;\n\n assert(image != (Image *) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"...\");\n assert(image->signature == MagickSignature);\n status=MagickTrue;\n image_info=AcquireImageInfo();\n image_info->dither=image->dither;\n artifact=GetImageArtifact(image,\"dither\");\n if (artifact != (const char *) NULL)\n (void) SetImageOption(image_info,\"dither\",artifact);\n switch (type)\n {\n case BilevelType:\n {\n if (SetImageMonochrome(image,&image->exception) == MagickFalse)\n {\n status=TransformImageColorspace(image,GRAYColorspace);\n (void) NormalizeImage(image);\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->number_colors=2;\n quantize_info->colorspace=GRAYColorspace;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n }\n status=AcquireImageColormap(image,2);\n image->matte=MagickFalse;\n break;\n }\n case GrayscaleType:\n {\n if (SetImageGray(image,&image->exception) == MagickFalse)\n status=TransformImageColorspace(image,GRAYColorspace);\n image->matte=MagickFalse;\n break;\n }\n case GrayscaleMatteType:\n {\n if (SetImageGray(image,&image->exception) == MagickFalse)\n status=TransformImageColorspace(image,GRAYColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case PaletteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n {\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->number_colors=256;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n }\n image->matte=MagickFalse;\n break;\n }\n case PaletteBilevelMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n (void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0);\n quantize_info=AcquireQuantizeInfo(image_info);\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n break;\n }\n case PaletteMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n quantize_info=AcquireQuantizeInfo(image_info);\n quantize_info->colorspace=TransparentColorspace;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n break;\n }\n case TrueColorType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n image->matte=MagickFalse;\n break;\n }\n case TrueColorMatteType:\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n status=TransformImageColorspace(image,sRGBColorspace);\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case ColorSeparationType:\n {\n if (image->colorspace != CMYKColorspace)\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace);\n status=TransformImageColorspace(image,CMYKColorspace);\n }\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n image->matte=MagickFalse;\n break;\n }\n case ColorSeparationMatteType:\n {\n if (image->colorspace != CMYKColorspace)\n {\n if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,sRGBColorspace);\n status=TransformImageColorspace(image,CMYKColorspace);\n }\n if (image->storage_class != DirectClass)\n status=SetImageStorageClass(image,DirectClass);\n if (image->matte == MagickFalse)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel);\n break;\n }\n case OptimizeType:\n case UndefinedType:\n break;\n }\n image_info=DestroyImageInfo(image_info);\n if (status == MagickFalse)\n return(MagickFalse);\n image->type=type;\n return(MagickTrue);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "SetImageType", "_file_name": "magick/attribute.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void AllocateDataSet(cmsIT8* it8)\n{\n TABLE* t = GetTable(it8);\n\n if (t -> Data) return; // Already allocated\n\n t-> nSamples = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_FIELDS\"));\n t-> nPatches = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_SETS\"));\n\n if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)\n {\n SynError(it8, \"AllocateDataSet: too much data\");\n }\n else {\n t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));\n if (t->Data == NULL) {\n\n SynError(it8, \"AllocateDataSet: Unable to allocate data array\");\n }\n }\n\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "AllocateDataSet", "_file_name": "src/cmscgats.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n outputs->push_back(Tensor(*context.mutable_output(i)));\n }\n }\n return Status::OK();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[2575, 2637]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2575, 2637]]}, "_func_name": "tensorflow::KernelAndDeviceOp::Run", "_file_name": "tensorflow/core/common_runtime/eager/kernel_and_device.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "int megasas_alloc_cmds(struct megasas_instance *instance)\n{\n\tint i;\n\tint j;\n\tu16 max_cmd;\n\tstruct megasas_cmd *cmd;\n\n\tmax_cmd = instance->max_mfi_cmds;\n\n\t/*\n\t * instance->cmd_list is an array of struct megasas_cmd pointers.\n\t * Allocate the dynamic array first and then allocate individual\n\t * commands.\n\t */\n\tinstance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);\n\n\tif (!instance->cmd_list) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"out of memory\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tmemset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tinstance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),\n\t\t\t\t\t\tGFP_KERNEL);\n\n\t\tif (!instance->cmd_list[i]) {\n\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tkfree(instance->cmd_list[j]);\n\n\t\t\tkfree(instance->cmd_list);\n\t\t\tinstance->cmd_list = NULL;\n\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tcmd = instance->cmd_list[i];\n\t\tmemset(cmd, 0, sizeof(struct megasas_cmd));\n\t\tcmd->index = i;\n\t\tcmd->scmd = NULL;\n\t\tcmd->instance = instance;\n\n\t\tlist_add_tail(&cmd->list, &instance->cmd_pool);\n\t}\n\n\t/*\n\t * Create a frame pool and assign one frame to each cmd\n\t */\n\tif (megasas_create_frame_pool(instance)) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"Error creating frame DMA pool\\n\");\n\t\tmegasas_free_cmds(instance);\n\t\treturn -ENOMEM;\n\t}\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "megasas_alloc_cmds", "_file_name": "drivers/scsi/megaraid/megaraid_sas_base.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)\n{\n Mpeg4DecContext *ctx = s->avctx->priv_data;\n\n int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,\n additional_code_len, sign, mismatch;\n VLC *cur_vlc = &ctx->studio_intra_tab[0];\n uint8_t *const scantable = s->intra_scantable.permutated;\n const uint16_t *quant_matrix;\n uint32_t flc;\n const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));\n const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);\n\n mismatch = 1;\n\n memset(block, 0, 64 * sizeof(int32_t));\n\n if (n < 4) {\n cc = 0;\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);\n quant_matrix = s->intra_matrix;\n } else {\n cc = (n & 1) + 1;\n if (ctx->rgb)\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);\n else\n dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);\n quant_matrix = s->chroma_intra_matrix;\n }\n\n if (dct_dc_size < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"illegal dct_dc_size vlc\\n\");\n return AVERROR_INVALIDDATA;\n } else if (dct_dc_size == 0) {\n dct_diff = 0;\n } else {\n dct_diff = get_xbits(&s->gb, dct_dc_size);\n\n if (dct_dc_size > 8) {\n if(!check_marker(s->avctx, &s->gb, \"dct_dc_size > 8\"))\n return AVERROR_INVALIDDATA;\n }\n\n }\n\n s->last_dc[cc] += dct_diff;\n\n if (s->mpeg_quant)\n block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);\n else\n block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);\n /* TODO: support mpeg_quant for AC coefficients */\n\n block[0] = av_clip(block[0], min, max);\n mismatch ^= block[0];\n\n /* AC Coefficients */\n while (1) {\n group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);\n\n if (group < 0) {\n av_log(s->avctx, AV_LOG_ERROR, \"illegal ac coefficient group vlc\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n additional_code_len = ac_state_tab[group][0];\n cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];\n\n if (group == 0) {\n /* End of Block */\n break;\n } else if (group >= 1 && group <= 6) {\n /* Zero run length (Table B.47) */\n run = 1 << additional_code_len;\n if (additional_code_len)\n run += get_bits(&s->gb, additional_code_len);\n idx += run;\n continue;\n } else if (group >= 7 && group <= 12) {\n /* Zero run length and +/-1 level (Table B.48) */\n code = get_bits(&s->gb, additional_code_len);\n sign = code & 1;\n code >>= 1;\n run = (1 << (additional_code_len - 1)) + code;\n idx += run;\n if (idx > 63)\n return AVERROR_INVALIDDATA;\n j = scantable[idx++];\n block[j] = sign ? 1 : -1;\n } else if (group >= 13 && group <= 20) {\n /* Level value (Table B.49) */\n if (idx > 63)\n return AVERROR_INVALIDDATA;\n j = scantable[idx++];\n block[j] = get_xbits(&s->gb, additional_code_len);\n } else if (group == 21) {\n /* Escape */\n if (idx > 63)\n return AVERROR_INVALIDDATA;\n j = scantable[idx++];\n additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;\n flc = get_bits(&s->gb, additional_code_len);\n if (flc >> (additional_code_len-1))\n block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);\n else\n block[j] = flc;\n }\n block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;\n block[j] = av_clip(block[j], min, max);\n mismatch ^= block[j];\n }\n\n block[63] ^= mismatch & 1;\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mpeg4_decode_studio_block", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def main():\n global word\n print(\"Starting script... press 'ctrl+c' in terminal to turn off\")\n while True:\n if pyperclip.paste() != word and len(pyperclip.paste().split())<5:\n word = pyperclip.paste()\n wordChc=False\n req = requests.get(\"https://api-portal.dictionary.com/dcom/pageData/%s\" % word)\n wordChcURB = False\n reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)\n try: \n data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']\n except TypeError:\n os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n wordChc = True\n except KeyError:\n os.system('notify-send \"Cant find |%s| on dictionary.com!\"' % word)\n wordChc = True\n\n if not wordChc:\n definitions = []\n try:\n for definition in data[:3]:\n definitions.append(cleanhtml(definition['definition']))\n definitions.append(\"------------\")\n os.system('notify-send \"definitions from dictionary.com:[{}\\n{}\"'\\\n .format(word+\"]\\n------------\",'\\n'.join(definitions)))\n except KeyError:\n os.system('notify-send \"no results in dictionary.com\"')\n try: \n dataURB = json.loads(reqURB.text)['list']\n except TypeError:\n os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n wordChcURB = True\n except KeyError:\n os.system('notify-send \"Cant find |%s| on urbandictionary.com!\"' % word)\n wordChcURB = True\n\n if not wordChcURB: \n definitionsURB = []\n for definition in dataURB[:3]:\n definitionsURB.append(definition['definition'])\n definitionsURB.append(\"------------\")\n os.system('notify-send \"definitions from urbandictionary.com:[{}\\n{}\"'\\\n .format(word+\"]\\n------------\",'\\n'.join(definitionsURB)))\n os.system('notify-send \"Thank you for using define.py made by kelj0\"')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[630, 714], [774, 858], [1159, 1322], [1540, 1629], [1692, 1781], [2060, 2223]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[630, 714], [774, 858], [1159, 1322], [1540, 1629], [1692, 1781], [2060, 2223]]}, "_func_name": "main", "_file_name": "SmallProjects/Define/define.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n MessageWriter *input,\n MessageReader *output) {\n int ret;\n\n UntrustedCacheMalloc *untrusted_cache = UntrustedCacheMalloc::Instance();\n\n SgxParams *const sgx_params =\n reinterpret_cast(untrusted_cache->Malloc(sizeof(SgxParams)));\n Cleanup clean_up(\n [sgx_params, untrusted_cache] { untrusted_cache->Free(sgx_params); });\n sgx_params->input_size = 0;\n sgx_params->input = nullptr;\n if (input) {\n sgx_params->input_size = input->MessageSize();\n if (sgx_params->input_size > 0) {\n // Allocate and copy data to |input_buffer|.\n sgx_params->input = untrusted_cache->Malloc(sgx_params->input_size);\n input->Serialize(const_cast(sgx_params->input));\n }\n }\n sgx_params->output_size = 0;\n sgx_params->output = nullptr;\n CHECK_OCALL(\n ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n if (sgx_params->input) {\n untrusted_cache->Free(const_cast(sgx_params->input));\n }\n if (!TrustedPrimitives::IsOutsideEnclave(sgx_params->output,\n sgx_params->output_size)) {\n TrustedPrimitives::BestEffortAbort(\n \"UntrustedCall: sgx_param output should be in untrusted memory\");\n }\n if (sgx_params->output) {\n // For the results obtained in |output_buffer|, copy them to |output|\n // before freeing the buffer.\n output->Deserialize(sgx_params->output, sgx_params->output_size);\n TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n }\n return PrimitiveStatus::OkStatus();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "asylo::primitives::TrustedPrimitives::UntrustedCall", "_file_name": "asylo/platform/primitives/sgx/trusted_sgx.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def initHeader(self):\n \"\"\"Initialize the IP header according to the IP format definition.\n\n \"\"\"\n\n # Ethernet header\n\n # Retrieve remote MAC address\n dstMacAddr = arpreq.arpreq(self.remoteIP)\n if dstMacAddr is not None:\n dstMacAddr = dstMacAddr.replace(':', '')\n dstMacAddr = binascii.unhexlify(dstMacAddr)\n else:\n # Force ARP resolution\n p = subprocess.Popen(\"ping -c1 {}\".format(self.remoteIP), shell=True)\n p.wait()\n time.sleep(0.1)\n\n dstMacAddr = arpreq.arpreq(self.remoteIP)\n if dstMacAddr is not None:\n dstMacAddr = dstMacAddr.replace(':', '')\n dstMacAddr = binascii.unhexlify(dstMacAddr)\n else:\n raise Exception(\"Cannot resolve IP address to a MAC address for IP: '{}'\".format(self.remoteIP))\n\n # Retrieve local MAC address\n srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]\n\n eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))\n eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))\n eth_type = Field(name='eth.type', domain=Raw(b\"\\x08\\x00\"))\n\n\n # IP header\n\n ip_ver = Field(\n name='ip.version', domain=BitArray(\n value=bitarray('0100'))) # IP Version 4\n ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))\n ip_tos = Field(\n name='ip.tos',\n domain=Data(\n dataType=BitArray(nbBits=8),\n originalValue=bitarray('00000000'),\n svas=SVAS.PERSISTENT))\n ip_tot_len = Field(\n name='ip.len', domain=BitArray(bitarray('0000000000000000')))\n ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))\n ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT))\n ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT))\n ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT))\n ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED))\n ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000')))\n ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))\n ip_daddr = Field(\n name='ip.dst', domain=IPv4(self.remoteIP))\n ip_payload = Field(name='ip.payload', domain=Raw())\n\n ip_ihl.domain = Size([ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id, ip_flags,\n ip_frag_off,\n ip_ttl, ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32))\n ip_tot_len.domain = Size([ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr,\n ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8))\n ip_checksum.domain = InternetChecksum(fields=[ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))\n \n self.header = Symbol(name='Ethernet layer', fields=[eth_dst,\n eth_src,\n eth_type,\n ip_ver,\n ip_ihl,\n ip_tos,\n ip_tot_len,\n ip_id,\n ip_flags,\n ip_frag_off,\n ip_ttl,\n ip_proto,\n ip_checksum,\n ip_saddr,\n ip_daddr,\n ip_payload])", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[423, 505]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[423, 505]]}, "_func_name": "initHeader", "_file_name": "src/netzob/Simulator/Channels/RawEthernetClient.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool check_client_passwd(PgSocket *client, const char *passwd)\n{\n\tchar md5[MD5_PASSWD_LEN + 1];\n\tconst char *correct;\n\tPgUser *user = client->auth_user;\n\n\t/* disallow empty passwords */\n\tif (!*passwd || !*user->passwd)\n\t\treturn false;\n\n\tswitch (cf_auth_type) {\n\tcase AUTH_PLAIN:\n\t\treturn strcmp(user->passwd, passwd) == 0;\n\tcase AUTH_CRYPT:\n\t\tcorrect = crypt(user->passwd, (char *)client->tmp_login_salt);\n\t\treturn correct && strcmp(correct, passwd) == 0;\n\tcase AUTH_MD5:\n\t\tif (strlen(passwd) != MD5_PASSWD_LEN)\n\t\t\treturn false;\n\t\tif (!isMD5(user->passwd))\n\t\t\tpg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);\n\t\tpg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);\n\t\treturn strcmp(md5, passwd) == 0;\n\t}\n\treturn false;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[161, 193]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[161, 193]]}, "_func_name": "check_client_passwd", "_file_name": "src/client.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int enc_untrusted_inet_pton(int af, const char *src, void *dst) {\n if (!src || !dst) {\n return 0;\n }\n\n MessageWriter input;\n input.Push(TokLinuxAfFamily(af));\n input.PushByReference(Extent{\n src, std::min(strlen(src) + 1, static_cast(INET6_ADDRSTRLEN))});\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetPtonHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_pton\", 3);\n\n int result = output.next();\n int klinux_errno = output.next();\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return -1;\n }\n\n auto klinux_addr_buffer = output.next();\n size_t max_size = 0;\n if (af == AF_INET) {\n if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }\n max_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_inet_pton: unexpected output size\");\n }\n max_size = sizeof(struct in6_addr);\n }\n memcpy(dst, klinux_addr_buffer.data(),\n std::min(klinux_addr_buffer.size(), max_size));\n return result;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_inet_pton", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " long WebPImage::getHeaderOffset(byte* data, long data_size, byte* header, long header_size)\n {\n if (data_size < header_size) { return -1; }\n long pos = -1;\n for (long i=0; i < data_size - header_size; i++) {\n if (memcmp(header, &data[i], header_size) == 0) {\n pos = i;\n break;\n }\n }\n return pos;\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Exiv2::WebPImage::getHeaderOffset", "_file_name": "src/webpimage.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "CString CWebSock::GetSkinPath(const CString& sSkinName) {\n CString sRet = CZNC::Get().GetZNCPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CZNC::Get().GetCurPath() + \"/webskins/\" + sSkinName;\n\n if (!CFile::IsDir(sRet)) {\n sRet = CString(_SKINDIR_) + \"/\" + sSkinName;\n }\n }\n\n return sRet + \"/\";\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[58, 130], [162, 230], [266, 323]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[58, 130], [162, 230], [266, 323]]}, "_func_name": "CWebSock::GetSkinPath", "_file_name": "src/WebModules.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def poll(self, poll_input):\n username = poll_input.credentials.username\n password = poll_input.credentials.password\n domain = poll_input.credentials.domain\n \n if domain is None:\n opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'\n options = opt_str.format(\n username, password,\n poll_input.server, poll_input.port)\n else:\n opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'\n options = opt_str.format(\n domain.domain, username, password,\n poll_input.server, poll_input.port)\n\n try:\n output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)\n result = RdpPollResult(True)\n return result\n except Exception as e:\n if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):\n result = RdpPollResult(True)\n return result\n print(\"{{{{%s}}}}\" % e.output)\n result = RdpPollResult(False, e)\n return result", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[217, 291], [439, 519]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[217, 291], [439, 519]]}, "_func_name": "poll", "_file_name": "polling/poll_rdp.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _delete_host(self, host_name):\n \"\"\"Delete a host on the storage system.\"\"\"\n\n LOG.debug(_('enter: _delete_host: host %s ') % host_name)\n\n ssh_cmd = ['svctask', 'rmhost', host_name]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_delete_host', ssh_cmd, out, err)\n\n LOG.debug(_('leave: _delete_host: host %s ') % host_name)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_delete_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)\n{\n\tPurpleXfer *xfer = data;\n\tstruct im_connection *ic = purple_ic_by_pa(xfer->account);\n\tstruct prpl_xfer_data *px = xfer->ui_data;\n\tPurpleBuddy *buddy;\n\tconst char *who;\n\n\tbuddy = purple_find_buddy(xfer->account, xfer->who);\n\twho = buddy ? purple_buddy_get_name(buddy) : xfer->who;\n\n\t/* TODO(wilmer): After spreading some more const goodness in BitlBee,\n\t remove the evil cast below. */\n\tpx->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);\n\n\tif (!px->ft) {\n\t\treturn FALSE;\n\t}\n\tpx->ft->data = px;\n\n\tpx->ft->accept = prpl_xfer_accept;\n\tpx->ft->canceled = prpl_xfer_canceled;\n\tpx->ft->free = prpl_xfer_free;\n\tpx->ft->write_request = prpl_xfer_write_request;\n\n\treturn FALSE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "prplcb_xfer_new_send_cb", "_file_name": "protocols/purple/ft.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,\n\t\t\t\t\t\t\t\t\t\topj_cp_t *p_cp,\n\t\t\t\t\t\t\t\t\t\tOPJ_UINT32 p_tile_no)\n{\n\t/* loop */\n\tOPJ_UINT32 pino;\n\tOPJ_UINT32 compno, resno;\n\n\t/* to store w, h, dx and dy fro all components and resolutions */\n\tOPJ_UINT32 * l_tmp_data;\n\tOPJ_UINT32 ** l_tmp_ptr;\n\n\t/* encoding prameters to set */\n\tOPJ_UINT32 l_max_res;\n\tOPJ_UINT32 l_max_prec;\n\tOPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;\n\tOPJ_UINT32 l_dx_min,l_dy_min;\n\tOPJ_UINT32 l_bound;\n\tOPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;\n\tOPJ_UINT32 l_data_stride;\n\n\t/* pointers */\n\topj_pi_iterator_t *l_pi = 00;\n\topj_tcp_t *l_tcp = 00;\n\tconst opj_tccp_t *l_tccp = 00;\n\topj_pi_comp_t *l_current_comp = 00;\n\topj_image_comp_t * l_img_comp = 00;\n\topj_pi_iterator_t * l_current_pi = 00;\n\tOPJ_UINT32 * l_encoding_value_ptr = 00;\n\n\t/* preconditions in debug */\n\tassert(p_cp != 00);\n\tassert(p_image != 00);\n\tassert(p_tile_no < p_cp->tw * p_cp->th);\n\n\t/* initializations */\n\tl_tcp = &p_cp->tcps[p_tile_no];\n\tl_bound = l_tcp->numpocs+1;\n\n\tl_data_stride = 4 * OPJ_J2K_MAXRLVLS;\n\tl_tmp_data = (OPJ_UINT32*)opj_malloc(\n\t\tl_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));\n\tif\n\t\t(! l_tmp_data)\n\t{\n\t\treturn 00;\n\t}\n\tl_tmp_ptr = (OPJ_UINT32**)opj_malloc(\n\t\tp_image->numcomps * sizeof(OPJ_UINT32 *));\n\tif\n\t\t(! l_tmp_ptr)\n\t{\n\t\topj_free(l_tmp_data);\n\t\treturn 00;\n\t}\n\n\t/* memory allocation for pi */\n\tl_pi = opj_pi_create(p_image, p_cp, p_tile_no);\n\tif (!l_pi) {\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\treturn 00;\n\t}\n\n\tl_encoding_value_ptr = l_tmp_data;\n\t/* update pointer array */\n\tfor\n\t\t(compno = 0; compno < p_image->numcomps; ++compno)\n\t{\n\t\tl_tmp_ptr[compno] = l_encoding_value_ptr;\n\t\tl_encoding_value_ptr += l_data_stride;\n\t}\n\t/* get encoding parameters */\n\topj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);\n\n\t/* step calculations */\n\tl_step_p = 1;\n\tl_step_c = l_max_prec * l_step_p;\n\tl_step_r = p_image->numcomps * l_step_c;\n\tl_step_l = l_max_res * l_step_r;\n\n\t/* set values for first packet iterator */\n\tl_current_pi = l_pi;\n\n\t/* memory allocation for include */\n\t/* prevent an integer overflow issue */\n\tl_current_pi->include = 00;\n\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n\t{\n\t\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n\t}\n\n\tif\n\t\t(!l_current_pi->include)\n\t{\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\topj_pi_destroy(l_pi, l_bound);\n\t\treturn 00;\n\t}\n\n\t/* special treatment for the first packet iterator */\n\tl_current_comp = l_current_pi->comps;\n\tl_img_comp = p_image->comps;\n\tl_tccp = l_tcp->tccps;\n\n\tl_current_pi->tx0 = l_tx0;\n\tl_current_pi->ty0 = l_ty0;\n\tl_current_pi->tx1 = l_tx1;\n\tl_current_pi->ty1 = l_ty1;\n\n\t/*l_current_pi->dx = l_img_comp->dx;*/\n\t/*l_current_pi->dy = l_img_comp->dy;*/\n\n\tl_current_pi->step_p = l_step_p;\n\tl_current_pi->step_c = l_step_c;\n\tl_current_pi->step_r = l_step_r;\n\tl_current_pi->step_l = l_step_l;\n\n\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\tfor\n\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t{\n\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\tl_current_comp->dx = l_img_comp->dx;\n\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t/* resolutions have already been initialized */\n\t\tfor\n\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t{\n\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t++l_res;\n\t\t}\n\t\t++l_current_comp;\n\t\t++l_img_comp;\n\t\t++l_tccp;\n\t}\n\t++l_current_pi;\n\n\tfor (pino = 1 ; pinocomps;\n\t\tl_img_comp = p_image->comps;\n\t\tl_tccp = l_tcp->tccps;\n\n\t\tl_current_pi->tx0 = l_tx0;\n\t\tl_current_pi->ty0 = l_ty0;\n\t\tl_current_pi->tx1 = l_tx1;\n\t\tl_current_pi->ty1 = l_ty1;\n\t\t/*l_current_pi->dx = l_dx_min;*/\n\t\t/*l_current_pi->dy = l_dy_min;*/\n\t\tl_current_pi->step_p = l_step_p;\n\t\tl_current_pi->step_c = l_step_c;\n\t\tl_current_pi->step_r = l_step_r;\n\t\tl_current_pi->step_l = l_step_l;\n\n\t\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\t\tfor\n\t\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t\t{\n\t\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\t\tl_current_comp->dx = l_img_comp->dx;\n\t\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t\t/* resolutions have already been initialized */\n\t\t\tfor\n\t\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t\t{\n\t\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t\t++l_res;\n\t\t\t}\n\t\t\t++l_current_comp;\n\t\t\t++l_img_comp;\n\t\t\t++l_tccp;\n\t\t}\n\t\t/* special treatment*/\n\t\tl_current_pi->include = (l_current_pi-1)->include;\n\t\t++l_current_pi;\n\t}\n\topj_free(l_tmp_data);\n\tl_tmp_data = 00;\n\topj_free(l_tmp_ptr);\n\tl_tmp_ptr = 00;\n\tif\n\t\t(l_tcp->POC)\n\t{\n\t\topj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\telse\n\t{\n\t\topj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\treturn l_pi;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "opj_pi_create_decode", "_file_name": "src/lib/openjp2/pi.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n{\n MpegEncContext *s = &ctx->m;\n\n if (get_bits_left(gb) <= 32)\n return 0;\n\n s->partitioned_frame = 0;\n s->interlaced_dct = 0;\n s->decode_mb = mpeg4_decode_studio_mb;\n\n decode_smpte_tc(ctx, gb);\n\n skip_bits(gb, 10); /* temporal_reference */\n skip_bits(gb, 2); /* vop_structure */\n s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */\n if (get_bits1(gb)) { /* vop_coded */\n skip_bits1(gb); /* top_field_first */\n skip_bits1(gb); /* repeat_first_field */\n s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */\n }\n\n if (s->pict_type == AV_PICTURE_TYPE_I) {\n if (get_bits1(gb))\n reset_studio_dc_predictors(s);\n }\n\n if (ctx->shape != BIN_ONLY_SHAPE) {\n s->alternate_scan = get_bits1(gb);\n s->frame_pred_frame_dct = get_bits1(gb);\n s->dct_precision = get_bits(gb, 2);\n s->intra_dc_precision = get_bits(gb, 2);\n s->q_scale_type = get_bits1(gb);\n }\n\n if (s->alternate_scan) {\n ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n } else {\n ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);\n ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);\n }\n\n mpeg4_load_default_matrices(s);\n\n next_start_code_studio(gb);\n extension_and_user_data(s, gb, 4);\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "decode_studio_vop_header", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)\n{\n\tstruct snd_pcm_runtime *runtime;\n\tunsigned long flags;\n\n\tif (PCM_RUNTIME_CHECK(substream))\n\t\treturn;\n\truntime = substream->runtime;\n\n\tsnd_pcm_stream_lock_irqsave(substream, flags);\n\tif (!snd_pcm_running(substream) ||\n\t snd_pcm_update_hw_ptr0(substream, 1) < 0)\n\t\tgoto _end;\n\n#ifdef CONFIG_SND_PCM_TIMER\n\tif (substream->timer_running)\n\t\tsnd_timer_interrupt(substream->timer, 1);\n#endif\n _end:\n\tkill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "snd_pcm_period_elapsed", "_file_name": "sound/core/pcm_lib.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def tcp_forward(self, host_port, device_port):\n \"\"\"Starts tcp forwarding.\n\n Args:\n host_port: Port number to use on the computer.\n device_port: Port number to use on the android device.\n \"\"\"\n self.forward('tcp:%d tcp:%d' % (host_port, device_port))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[238, 302]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[238, 302]]}, "_func_name": "tcp_forward", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int decode_zbuf(AVBPrint *bp, const uint8_t *data,\n const uint8_t *data_end)\n{\n z_stream zstream;\n unsigned char *buf;\n unsigned buf_size;\n int ret;\n\n zstream.zalloc = ff_png_zalloc;\n zstream.zfree = ff_png_zfree;\n zstream.opaque = NULL;\n if (inflateInit(&zstream) != Z_OK)\n return AVERROR_EXTERNAL;\n zstream.next_in = (unsigned char *)data;\n zstream.avail_in = data_end - data;\n av_bprint_init(bp, 0, -1);\n\n while (zstream.avail_in > 0) {\n av_bprint_get_buffer(bp, 1, &buf, &buf_size);\n if (!buf_size) {\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n zstream.next_out = buf;\n zstream.avail_out = buf_size;\n ret = inflate(&zstream, Z_PARTIAL_FLUSH);\n if (ret != Z_OK && ret != Z_STREAM_END) {\n ret = AVERROR_EXTERNAL;\n goto fail;\n }\n bp->len += zstream.next_out - buf;\n if (ret == Z_STREAM_END)\n break;\n }\n inflateEnd(&zstream);\n bp->str[bp->len] = 0;\n return 0;\n\nfail:\n inflateEnd(&zstream);\n av_bprint_finalize(bp, NULL);\n return ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[514, 593]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[514, 593]]}, "_func_name": "decode_zbuf", "_file_name": "libavcodec/pngdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int git_delta_apply(\n\tvoid **out,\n\tsize_t *out_len,\n\tconst unsigned char *base,\n\tsize_t base_len,\n\tconst unsigned char *delta,\n\tsize_t delta_len)\n{\n\tconst unsigned char *delta_end = delta + delta_len;\n\tsize_t base_sz, res_sz, alloc_sz;\n\tunsigned char *res_dp;\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\t/*\n\t * Check that the base size matches the data we were given;\n\t * if not we would underflow while accessing data from the\n\t * base object, resulting in data corruption or segfault.\n\t */\n\tif ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tif (hdr_sz(&res_sz, &delta, delta_end) < 0) {\n\t\tgiterr_set(GITERR_INVALID, \"failed to apply delta: base size does not match given data\");\n\t\treturn -1;\n\t}\n\n\tGITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);\n\tres_dp = git__malloc(alloc_sz);\n\tGITERR_CHECK_ALLOC(res_dp);\n\n\tres_dp[res_sz] = '\\0';\n\t*out = res_dp;\n\t*out_len = res_sz;\n\n\twhile (delta < delta_end) {\n\t\tunsigned char cmd = *delta++;\n\t\tif (cmd & 0x80) {\n\t\t\t/* cmd is a copy instruction; copy from the base. */\n\t\t\tsize_t off = 0, len = 0;\n\n#define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; }\n\t\t\tif (cmd & 0x01) ADD_DELTA(off, 0UL);\n\t\t\tif (cmd & 0x02) ADD_DELTA(off, 8UL);\n\t\t\tif (cmd & 0x04) ADD_DELTA(off, 16UL);\n\t\t\tif (cmd & 0x08) ADD_DELTA(off, 24UL);\n\n\t\t\tif (cmd & 0x10) ADD_DELTA(len, 0UL);\n\t\t\tif (cmd & 0x20) ADD_DELTA(len, 8UL);\n\t\t\tif (cmd & 0x40) ADD_DELTA(len, 16UL);\n\t\t\tif (!len) len = 0x10000;\n#undef ADD_DELTA\n\n\t\t\tif (base_len < off + len || res_sz < len)\n\t\t\t\tgoto fail;\n\t\t\tmemcpy(res_dp, base + off, len);\n\t\t\tres_dp += len;\n\t\t\tres_sz -= len;\n\n\t\t} else if (cmd) {\n\t\t\t/*\n\t\t\t * cmd is a literal insert instruction; copy from\n\t\t\t * the delta stream itself.\n\t\t\t */\n\t\t\tif (delta_end - delta < cmd || res_sz < cmd)\n\t\t\t\tgoto fail;\n\t\t\tmemcpy(res_dp, delta, cmd);\n\t\t\tdelta += cmd;\n\t\t\tres_dp += cmd;\n\t\t\tres_sz -= cmd;\n\n\t\t} else {\n\t\t\t/* cmd == 0 is reserved for future encodings. */\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tif (delta != delta_end || res_sz)\n\t\tgoto fail;\n\treturn 0;\n\nfail:\n\tgit__free(*out);\n\n\t*out = NULL;\n\t*out_len = 0;\n\n\tgiterr_set(GITERR_INVALID, \"failed to apply delta\");\n\treturn -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[1603, 1648]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1603, 1648]]}, "_func_name": "git_delta_apply", "_file_name": "src/delta.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void ip4_datagram_release_cb(struct sock *sk)\n{\n\tconst struct inet_sock *inet = inet_sk(sk);\n\tconst struct ip_options_rcu *inet_opt;\n\t__be32 daddr = inet->inet_daddr;\n\tstruct flowi4 fl4;\n\tstruct rtable *rt;\n\n\tif (! __sk_dst_get(sk) || __sk_dst_check(sk, 0))\n\t\treturn;\n\n\trcu_read_lock();\n\tinet_opt = rcu_dereference(inet->inet_opt);\n\tif (inet_opt && inet_opt->opt.srr)\n\t\tdaddr = inet_opt->opt.faddr;\n\trt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr,\n\t\t\t\t inet->inet_saddr, inet->inet_dport,\n\t\t\t\t inet->inet_sport, sk->sk_protocol,\n\t\t\t\t RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);\n\tif (!IS_ERR(rt))\n\t\t__sk_dst_set(sk, &rt->dst);\n\trcu_read_unlock();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[208, 269], [591, 639]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[208, 269], [591, 639]]}, "_func_name": "ip4_datagram_release_cb", "_file_name": "net/ipv4/datagram.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def test_skip_paths_issue_938(tmpdir):\n base_dir = tmpdir.mkdir('project')\n config_dir = base_dir.mkdir('conf')\n config_dir.join('.isort.cfg').write('[isort]\\n'\n 'line_length = 88\\n'\n 'multi_line_output = 4\\n'\n 'lines_after_imports = 2\\n'\n 'skip_glob =\\n'\n ' migrations/**.py\\n')\n base_dir.join('dont_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")'\n '\\n'\n 'import sys\\n')\n\n migrations_dir = base_dir.mkdir('migrations')\n migrations_dir.join('file_glob_skip.py').write('import os\\n'\n '\\n'\n 'print(\"Hello World\")\\n'\n '\\n'\n 'import sys\\n')\n\n test_run_directory = os.getcwd()\n os.chdir(str(base_dir))\n result = subprocess.run(\n ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n stdout=subprocess.PIPE,\n check=True,\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped' not in result.stdout.lower()\n\n os.chdir(str(base_dir))\n result = subprocess.run(\n ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n stdout=subprocess.PIPE,\n check=True,\n )\n os.chdir(str(test_run_directory))\n\n assert b'skipped 1' in result.stdout.lower()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_skip_paths_issue_938", "_file_name": "test_isort.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_hostvdisk_mappings(self, host_name):\n \"\"\"Return the defined storage mappings for a host.\"\"\"\n\n return_data = {}\n ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]\n out, err = self._run_ssh(ssh_cmd)\n\n mappings = out.strip().split('\\n')\n if len(mappings):\n header = mappings.pop(0)\n for mapping_line in mappings:\n mapping_data = self._get_hdr_dic(header, mapping_line, '!')\n return_data[mapping_data['vdisk_name']] = mapping_data\n\n return return_data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_hostvdisk_mappings", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def store_metadata(self, session, key, mType, value):\n if (self.idNormalizer is not None):\n id = self.idNormalizer.process_string(session, id)\n elif type(id) == unicode:\n id = id.encode('utf-8')\n else:\n id = str(id)\n self._openContainer(session)\n query = (\"UPDATE %s SET %s = $1 WHERE identifier = $2;\" %\n (self.table, mType)\n )\n args = (value, id)\n try:\n self._query(query, *args)\n except:\n return None\n return value", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "store_metadata", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def change_pass(self, new_pass, logged_user):\n update_sql = \"\"\"\n UPDATE Clients\n SET password = '{}'\n WHERE client_id = '{}'\n \"\"\".format(new_pass, logged_user.get_client_id())\n\n cursor = self.__conn.cursor()\n\n cursor.execute(update_sql)\n self.__conn.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[102, 227]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[102, 227]]}, "_func_name": "change_pass", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "repodata_schema2id(Repodata *data, Id *schema, int create)\n{\n int h, len, i;\n Id *sp, cid;\n Id *schematahash;\n\n if (!*schema)\n return 0;\t/* XXX: allow empty schema? */\n if ((schematahash = data->schematahash) == 0)\n {\n data->schematahash = schematahash = solv_calloc(256, sizeof(Id));\n for (i = 1; i < data->nschemata; i++)\n\t{\n\t for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)\n\t h = h * 7 + *sp++;\n\t h &= 255;\n\t schematahash[h] = i;\n\t}\n data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);\n }\n\n for (sp = schema, len = 0, h = 0; *sp; len++)\n h = h * 7 + *sp++;\n h &= 255;\n len++;\n\n cid = schematahash[h];\n if (cid)\n {\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n if ((data->schemata[cid] + len <= data->schemadatalen) &&\n\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */\n if (!create)\n return 0;\n data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);\n data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);\n /* add schema */\n memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));\n data->schemata[data->nschemata] = data->schemadatalen;\n data->schemadatalen += len;\n schematahash[h] = data->nschemata;\n#if 0\nfprintf(stderr, \"schema2id: new schema\\n\");\n#endif\n return data->nschemata++;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "repodata_schema2id", "_file_name": "src/repodata.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _inject_net_into_fs(net, fs, execute=None):\n \"\"\"Inject /etc/network/interfaces into the filesystem rooted at fs.\n\n net is the contents of /etc/network/interfaces.\n \"\"\"\n netdir = _join_and_check_path_within_fs(fs, 'etc', 'network')\n utils.execute('mkdir', '-p', netdir, run_as_root=True)\n utils.execute('chown', 'root:root', netdir, run_as_root=True)\n utils.execute('chmod', 755, netdir, run_as_root=True)\n\n netfile = os.path.join('etc', 'network', 'interfaces')\n _inject_file_into_fs(fs, netfile, net)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_inject_net_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int rom_copy(uint8_t *dest, hwaddr addr, size_t size)\n{\n hwaddr end = addr + size;\n uint8_t *s, *d = dest;\n size_t l = 0;\n Rom *rom;\n\n QTAILQ_FOREACH(rom, &roms, next) {\n if (rom->fw_file) {\n continue;\n }\n if (rom->mr) {\n continue;\n }\n if (rom->addr + rom->romsize < addr) {\n continue;\n }\n if (rom->addr > end) {\n break;\n }\n\n d = dest + (rom->addr - addr);\n s = rom->data;\n l = rom->datasize;\n\n if ((d + l) > (dest + size)) {\n l = dest - d;\n }\n\n if (l > 0) {\n memcpy(d, s, l);\n }\n\n if (rom->romsize > rom->datasize) {\n /* If datasize is less than romsize, it means that we didn't\n * allocate all the ROM because the trailing data are only zeros.\n */\n\n d += l;\n l = rom->romsize - rom->datasize;\n\n if ((d + l) > (dest + size)) {\n /* Rom size doesn't fit in the destination area. Adjust to avoid\n * overflow.\n */\n l = dest - d;\n }\n\n if (l > 0) {\n memset(d, 0x0, l);\n }\n }\n }\n\n return (d + l) - dest;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[379, 410]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[379, 410]]}, "_func_name": "rom_copy", "_file_name": "hw/core/loader.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,\n\t\t\t\tvoid __user *buffer, size_t *lenp,\n\t\t\t\tloff_t *ppos)\n{\n\tint ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);\n\n\tif (ret || !write)\n\t\treturn ret;\n\n\tif (sysctl_perf_cpu_time_max_percent == 100 ||\n\t sysctl_perf_cpu_time_max_percent == 0) {\n\t\tprintk(KERN_WARNING\n\t\t \"perf: Dynamic interrupt throttling disabled, can hang your system!\\n\");\n\t\tWRITE_ONCE(perf_sample_allowed_ns, 0);\n\t} else {\n\t\tupdate_perf_cpu_limits();\n\t}\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "perf_cpu_time_max_percent_handler", "_file_name": "kernel/events/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@endpoints.route(\"/placings\")\ndef placings():\n if db == None:\n init()\n\n tag = request.args.get('tag', default='christmas mike')\n\n # Get all the urls that this player has participated in\n sql = \"SELECT * FROM placings WHERE player = '{}'\".format(tag)\n results = list(db.exec(sql))\n results.sort(key=lambda x: int(x[2]))\n\n return json.dumps(results)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[202, 269]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[202, 269]]}, "_func_name": "placings", "_file_name": "endpoints.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def canonicalize(self):\n \"\"\"::\n\n path = path.canonicalize()\n\n Canonicalize path by resolving ``.`` and ``..``, in addition ``...`` will be\n treated as ``.`` to protect from path traversal attacks.\n\n # \"/foo/baz\"\n Pyjo.Path.new('/foo/./bar/../baz').canonicalize()\n\n # \"/../baz\"\n Pyjo.Path.new('/foo/../bar/../../baz').canonicalize()\n\n # \"/foo/bar\"\n Pyjo.Path.new('/foo/.../bar').canonicalize()\n \"\"\"\n parts = self.parts\n i = 0\n while i < len(parts):\n if parts[i] == '' or parts[i] == '.' or parts[i] == '...':\n parts.pop(i)\n elif i < 1 or parts[i] != '..' or parts[i - 1] == '..':\n i += 1\n else:\n i -= 1\n parts.pop(i)\n parts.pop(i)\n\n if not parts:\n self.trailing_slash = False\n\n return self", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "canonicalize", "_file_name": "Pyjo/Path.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "tcpmss_mangle_packet(struct sk_buff *skb,\n\t\t const struct xt_action_param *par,\n\t\t unsigned int family,\n\t\t unsigned int tcphoff,\n\t\t unsigned int minlen)\n{\n\tconst struct xt_tcpmss_info *info = par->targinfo;\n\tstruct tcphdr *tcph;\n\tint len, tcp_hdrlen;\n\tunsigned int i;\n\t__be16 oldval;\n\tu16 newmss;\n\tu8 *opt;\n\n\t/* This is a fragment, no TCP header is available */\n\tif (par->fragoff != 0)\n\t\treturn 0;\n\n\tif (!skb_make_writable(skb, skb->len))\n\t\treturn -1;\n\n\tlen = skb->len - tcphoff;\n\tif (len < (int)sizeof(struct tcphdr))\n\t\treturn -1;\n\n\ttcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);\n\ttcp_hdrlen = tcph->doff * 4;\n\n\tif (len < tcp_hdrlen || tcp_hdrlen < sizeof(struct tcphdr))\n\t\treturn -1;\n\n\tif (info->mss == XT_TCPMSS_CLAMP_PMTU) {\n\t\tstruct net *net = xt_net(par);\n\t\tunsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family);\n\t\tunsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu);\n\n\t\tif (min_mtu <= minlen) {\n\t\t\tnet_err_ratelimited(\"unknown or invalid path-MTU (%u)\\n\",\n\t\t\t\t\t min_mtu);\n\t\t\treturn -1;\n\t\t}\n\t\tnewmss = min_mtu - minlen;\n\t} else\n\t\tnewmss = info->mss;\n\n\topt = (u_int8_t *)tcph;\n\tfor (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) {\n\t\tif (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) {\n\t\t\tu_int16_t oldmss;\n\n\t\t\toldmss = (opt[i+2] << 8) | opt[i+3];\n\n\t\t\t/* Never increase MSS, even when setting it, as\n\t\t\t * doing so results in problems for hosts that rely\n\t\t\t * on MSS being set correctly.\n\t\t\t */\n\t\t\tif (oldmss <= newmss)\n\t\t\t\treturn 0;\n\n\t\t\topt[i+2] = (newmss & 0xff00) >> 8;\n\t\t\topt[i+3] = newmss & 0x00ff;\n\n\t\t\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t\t\t htons(oldmss), htons(newmss),\n\t\t\t\t\t\t false);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/* There is data after the header so the option can't be added\n\t * without moving it, and doing so may make the SYN packet\n\t * itself too large. Accept the packet unmodified instead.\n\t */\n\tif (len > tcp_hdrlen)\n\t\treturn 0;\n\n\t/* tcph->doff has 4 bits, do not wrap it to 0 */\n\tif (tcp_hdrlen >= 15 * 4)\n\t\treturn 0;\n\n\t/*\n\t * MSS Option not found ?! add it..\n\t */\n\tif (skb_tailroom(skb) < TCPOLEN_MSS) {\n\t\tif (pskb_expand_head(skb, 0,\n\t\t\t\t TCPOLEN_MSS - skb_tailroom(skb),\n\t\t\t\t GFP_ATOMIC))\n\t\t\treturn -1;\n\t\ttcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);\n\t}\n\n\tskb_put(skb, TCPOLEN_MSS);\n\n\t/*\n\t * IPv4: RFC 1122 states \"If an MSS option is not received at\n\t * connection setup, TCP MUST assume a default send MSS of 536\".\n\t * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum\n\t * length IPv6 header of 60, ergo the default MSS value is 1220\n\t * Since no MSS was provided, we must use the default values\n\t */\n\tif (xt_family(par) == NFPROTO_IPV4)\n\t\tnewmss = min(newmss, (u16)536);\n\telse\n\t\tnewmss = min(newmss, (u16)1220);\n\n\topt = (u_int8_t *)tcph + sizeof(struct tcphdr);\n\tmemmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr));\n\n\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t htons(len), htons(len + TCPOLEN_MSS), true);\n\topt[0] = TCPOPT_MSS;\n\topt[1] = TCPOLEN_MSS;\n\topt[2] = (newmss & 0xff00) >> 8;\n\topt[3] = newmss & 0x00ff;\n\n\tinet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false);\n\n\toldval = ((__be16 *)tcph)[6];\n\ttcph->doff += TCPOLEN_MSS/4;\n\tinet_proto_csum_replace2(&tcph->check, skb,\n\t\t\t\t oldval, ((__be16 *)tcph)[6], false);\n\treturn TCPOLEN_MSS;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tcpmss_mangle_packet", "_file_name": "net/netfilter/xt_TCPMSS.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def on_message( self, profile_id, profile_name, level, message, timeout ):\n if 1 == level:\n cmd = \"notify-send \"\n if timeout > 0:\n cmd = cmd + \" -t %s\" % (1000 * timeout)\n\n title = \"Back In Time (%s) : %s\" % (self.user, profile_name)\n message = message.replace(\"\\n\", ' ')\n message = message.replace(\"\\r\", '')\n\n cmd = cmd + \" \\\"%s\\\" \\\"%s\\\"\" % (title, message)\n print(cmd)\n os.system(cmd)\n return", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[102, 135], [163, 219], [391, 501]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[102, 135], [163, 219], [391, 501]]}, "_func_name": "on_message", "_file_name": "qt4/plugins/notifyplugin.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n /*\n rfbLog(\"rfbProcessFileTransferReadBuffer(%dlen)\\n\", length);\n */\n if (length>0) {\n buffer=malloc((uint64_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[177, 249], [269, 312]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[177, 249], [269, 312]]}, "_func_name": "rfbProcessFileTransferReadBuffer", "_file_name": "libvncserver/rfbserver.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def deletePost(self,postid):\n sqlText=\"delete from post where post.postid=%d\"%(postid)\n result=sql.deleteDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[33, 98]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[33, 98]]}, "_func_name": "deletePost", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def writeToDb(self, url):\n try:\n self.cursor.execute(\"INSERT INTO queue (url, visited) VALUES ('{}', '0');\".format(url))\n self.db.commit()\n except Exception as e:\n print(e)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[43, 143]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[43, 143]]}, "_func_name": "writeToDb", "_file_name": "beta/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg,\n\tvoid *buf, int peekonly)\n{\n\tstruct tmComResBusInfo *bus = &dev->bus;\n\tu32 bytes_to_read, write_distance, curr_grp, curr_gwp,\n\t\tnew_grp, buf_size, space_rem;\n\tstruct tmComResInfo msg_tmp;\n\tint ret = SAA_ERR_BAD_PARAMETER;\n\n\tsaa7164_bus_verify(dev);\n\n\tif (msg == NULL)\n\t\treturn ret;\n\n\tif (msg->size > dev->bus.m_wMaxReqSize) {\n\t\tprintk(KERN_ERR \"%s() Exceeded dev->bus.m_wMaxReqSize\\n\",\n\t\t\t__func__);\n\t\treturn ret;\n\t}\n\n\tif ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) {\n\t\tprintk(KERN_ERR\n\t\t\t\"%s() Missing msg buf, size should be %d bytes\\n\",\n\t\t\t__func__, msg->size);\n\t\treturn ret;\n\t}\n\n\tmutex_lock(&bus->lock);\n\n\t/* Peek the bus to see if a msg exists, if it's not what we're expecting\n\t * then return cleanly else read the message from the bus.\n\t */\n\tcurr_gwp = saa7164_readl(bus->m_dwGetWritePos);\n\tcurr_grp = saa7164_readl(bus->m_dwGetReadPos);\n\n\tif (curr_gwp == curr_grp) {\n\t\tret = SAA_ERR_EMPTY;\n\t\tgoto out;\n\t}\n\n\tbytes_to_read = sizeof(*msg);\n\n\t/* Calculate write distance to current read position */\n\twrite_distance = 0;\n\tif (curr_gwp >= curr_grp)\n\t\t/* Write doesn't wrap around the ring */\n\t\twrite_distance = curr_gwp - curr_grp;\n\telse\n\t\t/* Write wraps around the ring */\n\t\twrite_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;\n\n\tif (bytes_to_read > write_distance) {\n\t\tprintk(KERN_ERR \"%s() No message/response found\\n\", __func__);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Calculate the new read position */\n\tnew_grp = curr_grp + bytes_to_read;\n\tif (new_grp > bus->m_dwSizeGetRing) {\n\n\t\t/* Ring wraps */\n\t\tnew_grp -= bus->m_dwSizeGetRing;\n\t\tspace_rem = bus->m_dwSizeGetRing - curr_grp;\n\n\t\tmemcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem);\n\t\tmemcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing,\n\t\t\tbytes_to_read - space_rem);\n\n\t} else {\n\t\t/* No wrapping */\n\t\tmemcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read);\n\t}\n\t/* Convert from little endian to CPU */\n\tmsg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size);\n\tmsg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command);\n\tmsg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector);\n\n\t/* No need to update the read positions, because this was a peek */\n\t/* If the caller specifically want to peek, return */\n\tif (peekonly) {\n\t\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n\t\tgoto peekout;\n\t}\n\n\t/* Check if the command/response matches what is expected */\n\tif ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) ||\n\t\t(msg_tmp.controlselector != msg->controlselector) ||\n\t\t(msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) {\n\n\t\tprintk(KERN_ERR \"%s() Unexpected msg miss-match\\n\", __func__);\n\t\tsaa7164_bus_dumpmsg(dev, msg, buf);\n\t\tsaa7164_bus_dumpmsg(dev, &msg_tmp, NULL);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Get the actual command and response from the bus */\n\tbuf_size = msg->size;\n\n\tbytes_to_read = sizeof(*msg) + msg->size;\n\t/* Calculate write distance to current read position */\n\twrite_distance = 0;\n\tif (curr_gwp >= curr_grp)\n\t\t/* Write doesn't wrap around the ring */\n\t\twrite_distance = curr_gwp - curr_grp;\n\telse\n\t\t/* Write wraps around the ring */\n\t\twrite_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;\n\n\tif (bytes_to_read > write_distance) {\n\t\tprintk(KERN_ERR \"%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\\n\",\n\t\t __func__);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Calculate the new read position */\n\tnew_grp = curr_grp + bytes_to_read;\n\tif (new_grp > bus->m_dwSizeGetRing) {\n\n\t\t/* Ring wraps */\n\t\tnew_grp -= bus->m_dwSizeGetRing;\n\t\tspace_rem = bus->m_dwSizeGetRing - curr_grp;\n\n\t\tif (space_rem < sizeof(*msg)) {\n\t\t\t/* msg wraps around the ring */\n\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);\n\t\t\tmemcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,\n\t\t\t\tsizeof(*msg) - space_rem);\n\t\t\tif (buf)\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) -\n\t\t\t\t\tspace_rem, buf_size);\n\n\t\t} else if (space_rem == sizeof(*msg)) {\n\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n\t\t\tif (buf)\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing, buf_size);\n\t\t} else {\n\t\t\t/* Additional data wraps around the ring */\n\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n\t\t\tif (buf) {\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + curr_grp +\n\t\t\t\t\tsizeof(*msg), space_rem - sizeof(*msg));\n\t\t\t\tmemcpy_fromio(buf + space_rem - sizeof(*msg),\n\t\t\t\t\tbus->m_pdwGetRing, bytes_to_read -\n\t\t\t\t\tspace_rem);\n\t\t\t}\n\n\t\t}\n\n\t} else {\n\t\t/* No wrapping */\n\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n\t\tif (buf)\n\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg),\n\t\t\t\tbuf_size);\n\t}\n\t/* Convert from little endian to CPU */\n\tmsg->size = le16_to_cpu((__force __le16)msg->size);\n\tmsg->command = le32_to_cpu((__force __le32)msg->command);\n\tmsg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);\n\n\t/* Update the read positions, adjusting the ring */\n\tsaa7164_writel(bus->m_dwGetReadPos, new_grp);\n\npeekout:\n\tret = SAA_OK;\nout:\n\tmutex_unlock(&bus->lock);\n\tsaa7164_bus_verify(dev);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2348, 2387], [3732, 3921], [4061, 4128], [4251, 4318], [4580, 4646], [4739, 4970]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2348, 2387], [3732, 3921], [4061, 4128], [4251, 4318], [4580, 4646], [4739, 4970]]}, "_func_name": "saa7164_bus_get", "_file_name": "drivers/media/pci/saa7164/saa7164-bus.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def markTokenUsedExternal(token, optStr=\"\"):\n conn, c = connectDB()\n req = \"UPDATE {} SET \\\"options_selected\\\"='{}' WHERE token='{}'\".format(CFG(\"tokens_table_name\"), \\\n optStr, token)\n c.execute(req)\n closeDB(conn)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[71, 229]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[71, 229]]}, "_func_name": "markTokenUsedExternal", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int string_scan_range(RList *list, RBinFile *bf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (from >= to) {\n\t\teprintf (\"Invalid range to find strings 0x%llx .. 0x%llx\\n\", from, to);\n\t\treturn -1;\n\t}\n\tint len = to - from;\n\tut8 *buf = calloc (len, 1);\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\tr_buf_read_at (bf->buf, from, buf, len);\n\t// may oobread\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle - from, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc - from;\n\t\t\tif ((to - needle) > 5 + rc) {\n\t\t\t\tbool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t/* Eat a whole C string */\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle - from, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Invalid sequence detected */\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r) && r != '\\\\') {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t/* Print the escape code */\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\033\\\\\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 93) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \"\n\t\t\t\t\t \" \\\\\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t// string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t/* \\0 marks the end of C-strings */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t// reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tRBinString *bs = R_NEW0 (RBinString);\n\t\t\tif (!bs) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->type = str_type;\n\t\t\tbs->length = runes;\n\t\t\tbs->size = needle - str_start;\n\t\t\tbs->ordinal = count++;\n\t\t\t// TODO: move into adjust_offset\n\t\t\tswitch (str_type) {\n\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\tif (str_start -from> 1) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 2 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 2; // \\xff\\xfe\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\tif (str_start -from> 3) {\n\t\t\t\t\tconst ut8 *p = buf + str_start - 4 - from;\n\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\tstr_start -= 4; // \\xff\\xfe\\x00\\x00\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbs->paddr = bs->vaddr = str_start;\n\t\t\tbs->string = r_str_ndup ((const char *)tmp, i);\n\t\t\tif (list) {\n\t\t\t\tr_list_append (list, bs);\n\t\t\t} else {\n\t\t\t\tprint_string (bs, bf);\n\t\t\t\tr_bin_string_free (bs);\n\t\t\t}\n\t\t}\n\t}\n\tfree (buf);\n\treturn count;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "string_scan_range", "_file_name": "libr/bin/file.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n{\n\tBYTE* newBitMask;\n\n\tif (Stream_GetRemainingLength(s) < 8)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */\n\tStream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */\n\tStream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */\n\n\tif ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))\n\t{\n\t\tWLog_ERR(TAG, \"invalid bpp value %\" PRIu32 \"\", iconInfo->bpp);\n\t\treturn FALSE;\n\t}\n\n\tStream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */\n\n\t/* cbColorTable is only present when bpp is 1, 4 or 8 */\n\tswitch (iconInfo->bpp)\n\t{\n\t\tcase 1:\n\t\tcase 4:\n\t\tcase 8:\n\t\t\tif (Stream_GetRemainingLength(s) < 2)\n\t\t\t\treturn FALSE;\n\n\t\t\tStream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\ticonInfo->cbColorTable = 0;\n\t\t\tbreak;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 4)\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */\n\tStream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */\n\n\t/* bitsMask */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsMask);\n\t\ticonInfo->bitsMask = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsMask = newBitMask;\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n\t\treturn FALSE;\n\tStream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);\n\n\t/* colorTable */\n\tif (iconInfo->colorTable == NULL)\n\t{\n\t\tif (iconInfo->cbColorTable)\n\t\t{\n\t\t\ticonInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);\n\n\t\t\tif (!iconInfo->colorTable)\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\telse if (iconInfo->cbColorTable)\n\t{\n\t\tBYTE* new_tab;\n\t\tnew_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);\n\n\t\tif (!new_tab)\n\t\t{\n\t\t\tfree(iconInfo->colorTable);\n\t\t\ticonInfo->colorTable = NULL;\n\t\t\treturn FALSE;\n\t\t}\n\n\t\ticonInfo->colorTable = new_tab;\n\t}\n\telse\n\t{\n\t\tfree(iconInfo->colorTable);\n\t\ticonInfo->colorTable = NULL;\n\t}\n\n\tif (iconInfo->colorTable)\n\t{\n\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n\t\t\treturn FALSE;\n\t\tStream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);\n\t}\n\n\t/* bitsColor */\n\tnewBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);\n\n\tif (!newBitMask)\n\t{\n\t\tfree(iconInfo->bitsColor);\n\t\ticonInfo->bitsColor = NULL;\n\t\treturn FALSE;\n\t}\n\n\ticonInfo->bitsColor = newBitMask;\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n\t\treturn FALSE;\n\tStream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);\n\treturn TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_read_icon_info", "_file_name": "libfreerdp/core/window.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "bool Scanner::fill(size_t need)\n{\n if (eof) return false;\n\n pop_finished_files();\n\n DASSERT(bot <= tok && tok <= lim);\n size_t free = static_cast(tok - bot);\n size_t copy = static_cast(lim - tok);\n\n if (free >= need) {\n memmove(bot, tok, copy);\n shift_ptrs_and_fpos(-static_cast(free));\n }\n else {\n BSIZE += std::max(BSIZE, need);\n char * buf = new char[BSIZE + YYMAXFILL];\n if (!buf) fatal(\"out of memory\");\n\n memmove(buf, tok, copy);\n shift_ptrs_and_fpos(buf - tok);\n delete [] bot;\n bot = buf;\n\n free = BSIZE - copy;\n }\n\n DASSERT(lim + free <= bot + BSIZE);\n if (!read(free)) {\n eof = lim;\n memset(lim, 0, YYMAXFILL);\n lim += YYMAXFILL;\n }\n\n return true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "re2c::Scanner::fill", "_file_name": "src/parse/scanner.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/movies/search', methods=['GET', 'POST'])\ndef search_films():\n form = SearchForm()\n if not form.validate_on_submit():\n return render_template('search.html', title='Search for films', form=form)\n search_terms = form.data['term'].split(' ')\n search_string = ' & '.join(search_terms)\n cur.execute(f\"SELECT * FROM film where fulltext @@ to_tsquery('{search_string}')\")\n res = cur.fetchall()\n return render_template('search_results.html', title='Home', res=len(res))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[312, 399]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[312, 399]]}, "_func_name": "search_films", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def nav_path(request):\n \"\"\"Return current path as list of items with \"name\" and \"href\" members\n\n The href members are view_directory links for directories and view_log\n links for files, but are set to None when the link would point to\n the current view\"\"\"\n\n if not request.repos:\n return []\n\n is_dir = request.pathtype == vclib.DIR\n\n # add root item\n items = []\n root_item = _item(name=request.server.escape(request.repos.name), href=None)\n if request.path_parts or request.view_func is not view_directory:\n root_item.href = request.get_url(view_func=view_directory,\n where='', pathtype=vclib.DIR,\n params={}, escape=1)\n items.append(root_item)\n\n # add path part items\n path_parts = []\n for part in request.path_parts:\n path_parts.append(part)\n is_last = len(path_parts) == len(request.path_parts)\n\n item = _item(name=request.server.escape(part), href=None)\n\n if not is_last or (is_dir and request.view_func is not view_directory):\n item.href = request.get_url(view_func=view_directory,\n where=_path_join(path_parts),\n pathtype=vclib.DIR,\n params={}, escape=1)\n elif not is_dir and request.view_func is not view_log:\n item.href = request.get_url(view_func=view_log,\n where=_path_join(path_parts),\n pathtype=vclib.FILE,\n params={}, escape=1)\n items.append(item)\n\n return items", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "nav_path", "_file_name": "lib/viewvc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_exe_section *sects, uint16_t scount, uint32_t pe, int desc) {\n uint8_t *structs = wwsect + 0x2a1, *compd, *ccur, *unpd, *ucur, bc;\n uint32_t src, srcend, szd, bt, bits;\n int error=0, i;\n\n cli_dbgmsg(\"in wwunpack\\n\");\n while (1) {\n if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, structs, 17)) {\n cli_dbgmsg(\"WWPack: Array of structs out of section\\n\");\n break;\n }\n src = sects[scount].rva - cli_readint32(structs); /* src delta / dst delta - not used / dwords / end of src */\n structs+=8;\n szd = cli_readint32(structs) * 4;\n structs+=4;\n srcend = cli_readint32(structs);\n structs+=4;\n\n unpd = ucur = exe+src+srcend+4-szd;\n if (!szd || !CLI_ISCONTAINED(exe, exesz, unpd, szd)) {\n cli_dbgmsg(\"WWPack: Compressed data out of file\\n\");\n break;\n }\n cli_dbgmsg(\"WWP: src: %x, szd: %x, srcend: %x - %x\\n\", src, szd, srcend, srcend+4-szd);\n if (!(compd = cli_malloc(szd))) {\n cli_dbgmsg(\"WWPack: Unable to allocate memory for compd\\n\");\n break;\n }\n memcpy(compd, unpd, szd);\n memset(unpd, -1, szd); /*FIXME*/\n ccur=compd;\n \n RESEED;\n while(!error) {\n uint32_t backbytes, backsize;\n uint8_t saved;\n\n BIT;\n if (!bits) { /* BYTE copy */\n\tif(ccur-compd>=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1))\n\t error=1;\n\telse\n\t *ucur++=*ccur++;\n\tcontinue;\n }\n\n BITS(2);\n if(bits==3) { /* WORD backcopy */\n\tuint8_t shifted, subbed = 31;\n\tBITS(2);\n\tshifted = bits + 5;\n\tif(bits>=2) {\n\t shifted++;\n\t subbed += 0x80;\n\t}\n\tbackbytes = (1< exesz || pe+7 > exesz || pe+0x28 > exesz ||\n\t\tpe+0x50 > exesz || pe+0x14 > exesz) \n\treturn CL_EFORMAT;\n exe[pe+6]=(uint8_t)scount;\n exe[pe+7]=(uint8_t)(scount>>8);\n if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295, 4) ||\n !CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295+sects[scount].rva, 4) ||\n !CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295+sects[scount].rva+0x299, 4)) {\n cli_dbgmsg(\"WWPack: unpack memory address out of bounds.\\n\");\n return CL_EFORMAT;\n }\n cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299);\n cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz);\n\n structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18];\n for(i=0 ; iname) > buf_len, LOGBUF(bits[i]->name), -1);\n sprintf(buf + strlen(buf), \" %s\", bits[i]->name);\n } else {\n LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);\n strcpy(buf, bits[i]->name);\n }\n }\n break;\n\n case LY_TYPE_IDENT:\n module_name = (const char *)data1;\n /* identity must always have a prefix */\n if (!strchr(*value, ':')) {\n sprintf(buf, \"%s:%s\", module_name, *value);\n } else {\n strcpy(buf, *value);\n }\n break;\n\n case LY_TYPE_INST:\n exp = lyxp_parse_expr(ctx, *value);\n LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1);\n\n module_name = NULL;\n count = 0;\n for (i = 0; (unsigned)i < exp->used; ++i) {\n cur_expr = &exp->expr[exp->expr_pos[i]];\n\n /* copy WS */\n if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) {\n if (count + (cur_expr - end) > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(end);\n return -1;\n }\n strncpy(&buf[count], end, cur_expr - end);\n count += cur_expr - end;\n }\n\n if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) {\n /* get the module name with \":\" */\n ++end;\n j = end - cur_expr;\n\n if (!module_name || strncmp(cur_expr, module_name, j)) {\n /* print module name with colon, it does not equal to the parent one */\n if (count + j > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(cur_expr);\n return -1;\n }\n strncpy(&buf[count], cur_expr, j);\n count += j;\n }\n module_name = cur_expr;\n\n /* copy the rest */\n if (count + (exp->tok_len[i] - j) > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(end);\n return -1;\n }\n strncpy(&buf[count], end, exp->tok_len[i] - j);\n count += exp->tok_len[i] - j;\n } else {\n if (count + exp->tok_len[i] > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(&exp->expr[exp->expr_pos[i]]);\n return -1;\n }\n strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]);\n count += exp->tok_len[i];\n }\n }\n if (count > buf_len) {\n LOGINT(ctx);\n lyxp_expr_free(exp);\n return -1;\n }\n buf[count] = '\\0';\n\n lyxp_expr_free(exp);\n break;\n\n case LY_TYPE_DEC64:\n num = *((int64_t *)data1);\n c = *((uint8_t *)data2);\n if (num) {\n count = sprintf(buf, \"%\"PRId64\" \", num);\n if ( (num > 0 && (count - 1) <= c)\n || (count - 2) <= c ) {\n /* we have 0. value, print the value with the leading zeros\n * (one for 0. and also keep the correct with of num according\n * to fraction-digits value)\n * for (num<0) - extra character for '-' sign */\n count = sprintf(buf, \"%0*\"PRId64\" \", (num > 0) ? (c + 1) : (c + 2), num);\n }\n for (i = c, j = 1; i > 0 ; i--) {\n if (j && i > 1 && buf[count - 2] == '0') {\n /* we have trailing zero to skip */\n buf[count - 1] = '\\0';\n } else {\n j = 0;\n buf[count - 1] = buf[count - 2];\n }\n count--;\n }\n buf[count - 1] = '.';\n } else {\n /* zero */\n sprintf(buf, \"0.0\");\n }\n break;\n\n case LY_TYPE_INT8:\n case LY_TYPE_INT16:\n case LY_TYPE_INT32:\n case LY_TYPE_INT64:\n num = *((int64_t *)data1);\n sprintf(buf, \"%\"PRId64, num);\n break;\n\n case LY_TYPE_UINT8:\n case LY_TYPE_UINT16:\n case LY_TYPE_UINT32:\n case LY_TYPE_UINT64:\n unum = *((uint64_t *)data1);\n sprintf(buf, \"%\"PRIu64, unum);\n break;\n\n default:\n /* should not be even called - just do nothing */\n return 0;\n }\n\n if (strcmp(buf, *value)) {\n lydict_remove(ctx, *value);\n *value = lydict_insert(ctx, buf, 0);\n return 1;\n }\n\n return 0;\n\n#undef LOGBUF\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1335, 1391]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1335, 1391]]}, "_func_name": "make_canonical", "_file_name": "src/parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static ssize_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate)\n{\n Image\n *mask;\n\n MagickOffsetType\n rows_offset;\n\n size_t\n channels,\n count,\n length,\n offset_length;\n\n unsigned char\n *compact_pixels;\n\n count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(image);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if (next_image->storage_class != PseudoClass)\n {\n if (IsGrayImage(next_image,&next_image->exception) == MagickFalse)\n channels=next_image->colorspace == CMYKColorspace ? 4 : 3;\n if (next_image->matte != MagickFalse)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if (next_image->storage_class == PseudoClass)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsGrayImage(next_image,&next_image->exception) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateImage(next_image,MagickFalse);\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n\n if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->matte != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateImage(next_image,MagickFalse);\n if (separate != MagickFalse)\n {\n const char\n *property;\n\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n &image->exception);\n if (mask != (Image *) NULL)\n {\n if (mask->compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[490, 540]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[490, 540]]}, "_func_name": "WritePSDChannels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def makeJudge(judge):\n\tdb.execute(\"UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE\", judge) \n\tdatabase.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "makeJudge", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "String StringUtil::Implode(const Variant& items, const String& delim,\n const bool checkIsContainer /* = true */) {\n if (checkIsContainer && !isContainer(items)) {\n throw_param_is_not_container();\n }\n int size = getContainerSize(items);\n if (size == 0) return empty_string();\n\n req::vector sitems;\n sitems.reserve(size);\n size_t len = 0;\n size_t lenDelim = delim.size();\n for (ArrayIter iter(items); iter; ++iter) {\n sitems.emplace_back(iter.second().toString());\n len += sitems.back().size() + lenDelim;\n }\n len -= lenDelim; // always one delimiter less than count of items\n assert(sitems.size() == size);\n\n String s = String(len, ReserveString);\n char *buffer = s.mutableData();\n const char *sdelim = delim.data();\n char *p = buffer;\n String &init_str = sitems[0];\n int init_len = init_str.size();\n memcpy(p, init_str.data(), init_len);\n p += init_len;\n for (int i = 1; i < size; i++) {\n String &item = sitems[i];\n memcpy(p, sdelim, lenDelim);\n p += lenDelim;\n int lenItem = item.size();\n memcpy(p, item.data(), lenItem);\n p += lenItem;\n }\n assert(p - buffer == len);\n s.setSize(len);\n return s;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::StringUtil::Implode", "_file_name": "hphp/runtime/base/string-util.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def terminate_connection(self, volume, connector, **kwargs):\n \"\"\"Cleanup after an iSCSI connection has been terminated.\n\n When we clean up a terminated connection between a given connector\n and volume, we:\n 1. Translate the given connector to a host name\n 2. Remove the volume-to-host mapping if it exists\n 3. Delete the host if it has no more mappings (hosts are created\n automatically by this driver when mappings are created)\n \"\"\"\n LOG.debug(_('enter: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})\n\n vol_name = volume['name']\n host_name = self._get_host_from_connector(connector)\n # Verify that _get_host_from_connector returned the host.\n # This should always succeed as we terminate an existing connection.\n self._driver_assert(\n host_name is not None,\n _('_get_host_from_connector failed to return the host name '\n 'for connector'))\n\n # Check if vdisk-host mapping exists, remove if it does\n mapping_data = self._get_hostvdisk_mappings(host_name)\n if vol_name in mapping_data:\n ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,\n vol_name]\n out, err = self._run_ssh(ssh_cmd)\n # Verify CLI behaviour - no output is returned from\n # rmvdiskhostmap\n self._assert_ssh_return(len(out.strip()) == 0,\n 'terminate_connection', ssh_cmd, out, err)\n del mapping_data[vol_name]\n else:\n LOG.error(_('terminate_connection: No mapping of volume '\n '%(vol_name)s to host %(host_name)s found') %\n {'vol_name': vol_name, 'host_name': host_name})\n\n # If this host has no more mappings, delete it\n if not mapping_data:\n self._delete_host(host_name)\n\n LOG.debug(_('leave: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "terminate_connection", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_error_days(cur, error_percent):\n \"\"\"Fetches the days in which requests led to errors.\n\n Fetches the days in which the specified percentage\n of requests led to errors.\n\n Args:\n cur(obj): The cursor to execute the query.\n error_percent(int): The percentage of requests that led to errors.\n\n Return:\n True if success, False otherwise.\n \"\"\"\n query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),\n round((log_errors.errors * 100\n / log_requests.total::numeric), 2) as percent\n FROM log_errors, log_requests\n WHERE log_errors.date = log_requests.date AND\n log_errors.errors * 100\n / log_requests.total::numeric > {}\n ORDER BY log_errors.date'''.format(error_percent)\n rows = get_data(cur, query)\n\n # Write data to txt file.\n if rows is not None:\n file = open(\"error_report.txt\", \"w\")\n for row in rows:\n file.write(\"{} - {}% errors \\n\".format(row[0], row[1]))\n file.close()\n\n return True\n else:\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[684, 793]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[684, 793]]}, "_func_name": "get_error_days", "_file_name": "news_data_analysis.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def respond_error(self, context, exception):\n context.respond_server_error()\n stack = traceback.format_exc()\n return \"\"\"\n \n \n\n \n\n \n
\n

\n Server error\n

\n
\n%s\n                
\n \n \n \"\"\" % stack", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[871, 890]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[871, 890]]}, "_func_name": "respond_error", "_file_name": "ajenti/routing.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ares_parse_a_reply(const unsigned char *abuf, int alen,\n\t\t struct hostent **host)\n{\n unsigned int qdcount, ancount;\n int status, i, rr_type, rr_class, rr_len, naddrs;\n long int len;\n int naliases;\n const unsigned char *aptr;\n char *hostname, *rr_name, *rr_data, **aliases;\n struct in_addr *addrs;\n struct hostent *hostent;\n\n /* Set *host to NULL for all failure cases. */\n *host = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT(abuf);\n ancount = DNS_HEADER_ANCOUNT(abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name(aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n free(hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Allocate addresses and aliases; ancount gives an upper bound for both. */\n addrs = malloc(ancount * sizeof(struct in_addr));\n if (!addrs)\n {\n free(hostname);\n return ARES_ENOMEM;\n }\n aliases = malloc((ancount + 1) * sizeof(char *));\n if (!aliases)\n {\n free(hostname);\n free(addrs);\n return ARES_ENOMEM;\n }\n naddrs = 0;\n naliases = 0;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < (int)ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name(aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n\tbreak;\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n\t{\n\t free(rr_name);\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n rr_type = DNS_RR_TYPE(aptr);\n rr_class = DNS_RR_CLASS(aptr);\n rr_len = DNS_RR_LEN(aptr);\n aptr += RRFIXEDSZ;\n if (aptr + rr_len > abuf + alen)\n\t{\n\t free(rr_name);\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n\n if (rr_class == C_IN && rr_type == T_A\n\t && rr_len == sizeof(struct in_addr)\n\t && strcasecmp(rr_name, hostname) == 0)\n\t{\n\t memcpy(&addrs[naddrs], aptr, sizeof(struct in_addr));\n\t naddrs++;\n\t status = ARES_SUCCESS;\n\t}\n\n if (rr_class == C_IN && rr_type == T_CNAME)\n\t{\n\t /* Record the RR name as an alias. */\n\t aliases[naliases] = rr_name;\n\t naliases++;\n\n\t /* Decode the RR data and replace the hostname with it. */\n\t status = ares_expand_name(aptr, abuf, alen, &rr_data, &len);\n\t if (status != ARES_SUCCESS)\n\t break;\n\t free(hostname);\n\t hostname = rr_data;\n\t}\n else\n\tfree(rr_name);\n\n aptr += rr_len;\n if (aptr > abuf + alen)\n\t{\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n }\n\n if (status == ARES_SUCCESS && naddrs == 0)\n status = ARES_ENODATA;\n if (status == ARES_SUCCESS)\n {\n /* We got our answer. Allocate memory to build the host entry. */\n aliases[naliases] = NULL;\n hostent = malloc(sizeof(struct hostent));\n if (hostent)\n\t{\n\t hostent->h_addr_list = malloc((naddrs + 1) * sizeof(char *));\n\t if (hostent->h_addr_list)\n\t {\n\t /* Fill in the hostent and return successfully. */\n\t hostent->h_name = hostname;\n\t hostent->h_aliases = aliases;\n\t hostent->h_addrtype = AF_INET;\n\t hostent->h_length = sizeof(struct in_addr);\n\t for (i = 0; i < naddrs; i++)\n\t\thostent->h_addr_list[i] = (char *) &addrs[i];\n\t hostent->h_addr_list[naddrs] = NULL;\n\t *host = hostent;\n\t return ARES_SUCCESS;\n\t }\n\t free(hostent);\n\t}\n status = ARES_ENOMEM;\n }\n for (i = 0; i < naliases; i++)\n free(aliases[i]);\n free(aliases);\n free(addrs);\n free(hostname);\n return status;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ares_parse_a_reply", "_file_name": "rutil/dns/ares/ares_parse_a_reply.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def mode_receive(self, request):\n \"\"\"\n This is called by render_POST when the client is telling us\n that it is ready to receive data as soon as it is available.\n This is the basis of a long-polling (comet) mechanism: the\n server will wait to reply until data is available.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = request.args.get('csessid')[0]\n self.last_alive[csessid] = (time.time(), False)\n\n dataentries = self.databuffer.get(csessid, [])\n if dataentries:\n return dataentries.pop(0)\n request.notifyFinish().addErrback(self._responseFailed, csessid, request)\n if csessid in self.requests:\n self.requests[csessid].finish() # Clear any stale request.\n self.requests[csessid] = request\n return server.NOT_DONE_YET", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[389, 438]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[389, 438]]}, "_func_name": "mode_receive", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _cli_run(self, verb, cli_args):\n \"\"\"Runs a CLI command over SSH, without doing any result parsing.\"\"\"\n cli_arg_strings = []\n if cli_args:\n for k, v in cli_args.items():\n if k == '':\n cli_arg_strings.append(\" %s\" % k)\n else:\n cli_arg_strings.append(\" %s=%s\" % (k, v))\n\n cmd = verb + ''.join(cli_arg_strings)\n LOG.debug(\"SSH CMD = %s \" % cmd)\n\n (stdout, stderr) = self._run_ssh(cmd, False)\n\n # we have to strip out the input and exit lines\n tmp = stdout.split(\"\\r\\n\")\n out = tmp[5:len(tmp) - 2]\n return out", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 422]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 422]]}, "_func_name": "_cli_run", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def retrieve_last_video_position(playlist_id, db):\n db.execute(\"SELECT max(position) as position from video WHERE playlist_id={playlist_id};\".format(\n playlist_id=playlist_id))\n row = db.fetchone()\n return row['position']", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[51, 187]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[51, 187]]}, "_func_name": "retrieve_last_video_position", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_3par_host(self, hostname):\n out = self._cli_run(['showhost', '-verbose', hostname])\n LOG.debug(\"OUTPUT = \\n%s\" % (pprint.pformat(out)))\n host = {'id': None, 'name': None,\n 'domain': None,\n 'descriptors': {},\n 'iSCSIPaths': [],\n 'FCPaths': []}\n\n if out:\n err = out[0]\n if err == 'no hosts listed':\n msg = {'code': 'NON_EXISTENT_HOST',\n 'desc': \"HOST '%s' was not found\" % hostname}\n raise hpexceptions.HTTPNotFound(msg)\n\n # start parsing the lines after the header line\n for line in out[1:]:\n if line == '':\n break\n tmp = line.split(',')\n paths = {}\n\n LOG.debug(\"line = %s\" % (pprint.pformat(tmp)))\n host['id'] = tmp[0]\n host['name'] = tmp[1]\n\n portPos = tmp[4]\n LOG.debug(\"portPos = %s\" % (pprint.pformat(portPos)))\n if portPos == '---':\n portPos = None\n else:\n port = portPos.split(':')\n portPos = {'node': int(port[0]), 'slot': int(port[1]),\n 'cardPort': int(port[2])}\n\n paths['portPos'] = portPos\n\n # If FC entry\n if tmp[5] == 'n/a':\n paths['wwn'] = tmp[3]\n host['FCPaths'].append(paths)\n # else iSCSI entry\n else:\n paths['name'] = tmp[3]\n paths['ipAddr'] = tmp[5]\n host['iSCSIPaths'].append(paths)\n\n # find the offset to the description stuff\n offset = 0\n for line in out:\n if line[:15] == '---------- Host':\n break\n else:\n offset += 1\n\n info = out[offset + 2]\n tmp = info.split(':')\n host['domain'] = tmp[1]\n\n info = out[offset + 4]\n tmp = info.split(':')\n host['descriptors']['location'] = tmp[1]\n\n info = out[offset + 5]\n tmp = info.split(':')\n host['descriptors']['ipAddr'] = tmp[1]\n\n info = out[offset + 6]\n tmp = info.split(':')\n host['descriptors']['os'] = tmp[1]\n\n info = out[offset + 7]\n tmp = info.split(':')\n host['descriptors']['model'] = tmp[1]\n\n info = out[offset + 8]\n tmp = info.split(':')\n host['descriptors']['contact'] = tmp[1]\n\n info = out[offset + 9]\n tmp = info.split(':')\n host['descriptors']['comment'] = tmp[1]\n\n return host", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_3par_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_requested_month(self, date):\n data = dict()\n\n month_start, month_end = self.get_epoch_month(date)\n data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}\n month_total = 0\n\n query = '''\n SELECT TimeStamp, SUM(DayYield) AS Power \n FROM MonthData \n WHERE TimeStamp BETWEEN %s AND %s\n GROUP BY TimeStamp\n '''\n\n data['data'] = list()\n for row in self.c.execute(query % (month_start, month_end)):\n data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})\n month_total += row[1]\n\n data['total'] = month_total\n\n query = '''\n SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max \n FROM ( SELECT TimeStamp FROM MonthData GROUP BY TimeStamp );\n '''\n\n self.c.execute(query)\n first_data, last_data = self.c.fetchone()\n\n if first_data: data['hasPrevious'] = (first_data < month_start)\n else: data['hasPrevious'] = False\n if last_data: data['hasNext'] = (last_data > month_end)\n else: data['hasNext'] = False\n\n return data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[419, 465], [543, 612]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[419, 465], [543, 612]]}, "_func_name": "get_requested_month", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static const char *parse_string(cJSON *item,const char *str,const char **ep)\n{\n\tconst char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;\n\tif (*str!='\\\"') {*ep=str;return 0;}\t/* not a string! */\n\n\twhile (*end_ptr!='\\\"' && *end_ptr && ++len)\n\t{\n\t if (*end_ptr++ == '\\\\')\n\t {\n\t\tif (*end_ptr == '\\0')\n\t\t{\n\t\t /* prevent buffer overflow when last input character is a backslash */\n\t\t return 0;\n\t\t}\n\t\tend_ptr++;\t/* Skip escaped quotes. */\n\t }\n\t}\n\n\tout=(char*)cJSON_malloc(len+1);\t/* This is how long we need for the string, roughly. */\n\tif (!out) return 0;\n\titem->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */\n\titem->type=cJSON_String;\n\t\n\tptr=str+1;ptr2=out;\n\twhile (ptr < end_ptr)\n\t{\n\t\tif (*ptr!='\\\\') *ptr2++=*ptr++;\n\t\telse\n\t\t{\n\t\t\tptr++;\n\t\t\tswitch (*ptr)\n\t\t\t{\n\t\t\t\tcase 'b': *ptr2++='\\b';\tbreak;\n\t\t\t\tcase 'f': *ptr2++='\\f';\tbreak;\n\t\t\t\tcase 'n': *ptr2++='\\n';\tbreak;\n\t\t\t\tcase 'r': *ptr2++='\\r';\tbreak;\n\t\t\t\tcase 't': *ptr2++='\\t';\tbreak;\n\t\t\t\tcase 'u':\t /* transcode utf16 to utf8. */\n\t\t\t\t\tuc=parse_hex4(ptr+1);ptr+=4;\t/* get the unicode char. */\n\t\t\t\t\tif (ptr >= end_ptr) {*ep=str;return 0;}\t/* invalid */\n\t\t\t\t\t\n\t\t\t\t\tif ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;}\t/* check for invalid. */\n\t\t\t\t\t\n\t\t\t\t\tif (uc>=0xD800 && uc<=0xDBFF)\t/* UTF16 surrogate pairs.\t*/\n\t\t\t\t\t{\n\t\t\t\t\t\tif (ptr+6 > end_ptr) {*ep=str;return 0;}\t/* invalid */\n\t\t\t\t\t\tif (ptr[1]!='\\\\' || ptr[2]!='u') {*ep=str;return 0;}\t/* missing second-half of surrogate. */\n\t\t\t\t\t\tuc2=parse_hex4(ptr+3);ptr+=6;\n\t\t\t\t\t\tif (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;}\t/* invalid second-half of surrogate. */\n\t\t\t\t\t\tuc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));\n\t\t\t\t\t}\n\n\t\t\t\t\tlen=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;\n\t\t\t\t\t\n\t\t\t\t\tswitch (len) {\n\t\t\t\t\t\tcase 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;\n\t\t\t\t\t\tcase 1: *--ptr2 =(uc | firstByteMark[len]);\n\t\t\t\t\t}\n\t\t\t\t\tptr2+=len;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: *ptr2++=*ptr; break;\n\t\t\t}\n\t\t\tptr++;\n\t\t}\n\t}\n\t*ptr2=0;\n\tif (*ptr=='\\\"') ptr++;\n\treturn ptr;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "parse_string", "_file_name": "cJSON.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int dnxhd_find_frame_end(DNXHDParserContext *dctx,\n const uint8_t *buf, int buf_size)\n{\n ParseContext *pc = &dctx->pc;\n uint64_t state = pc->state64;\n int pic_found = pc->frame_start_found;\n int i = 0;\n\n if (!pic_found) {\n for (i = 0; i < buf_size; i++) {\n state = (state << 8) | buf[i];\n if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {\n i++;\n pic_found = 1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n break;\n }\n }\n }\n\n if (pic_found && !dctx->remaining) {\n if (!buf_size) /* EOF considered as end of frame */\n return 0;\n for (; i < buf_size; i++) {\n dctx->cur_byte++;\n state = (state << 8) | buf[i];\n\n if (dctx->cur_byte == 24) {\n dctx->h = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 26) {\n dctx->w = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 42) {\n int cid = (state >> 32) & 0xFFFFFFFF;\n int remaining;\n\n if (cid <= 0)\n continue;\n\n remaining = avpriv_dnxhd_get_frame_size(cid);\n if (remaining <= 0) {\n remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n if (remaining <= 0)\n continue;\n }\n dctx->remaining = remaining;\n if (buf_size - i + 47 >= dctx->remaining) {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n } else {\n dctx->remaining -= buf_size;\n }\n }\n }\n } else if (pic_found) {\n if (dctx->remaining > buf_size) {\n dctx->remaining -= buf_size;\n } else {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n }\n }\n pc->frame_start_found = pic_found;\n pc->state64 = state;\n return END_NOT_FOUND;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "dnxhd_find_frame_end", "_file_name": "libavcodec/dnxhd_parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,\n uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)\n{\n\tconst cdf_section_header_t *shp;\n\tcdf_section_header_t sh;\n\tconst uint8_t *p, *q, *e;\n\tsize_t i, o4, nelements, j, slen, left;\n\tcdf_property_info_t *inp;\n\n\tif (offs > UINT32_MAX / 4) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\tshp = CAST(const cdf_section_header_t *,\n\t cdf_offset(sst->sst_tab, offs));\n\tif (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)\n\t\tgoto out;\n\tsh.sh_len = CDF_TOLE4(shp->sh_len);\n\tif (sh.sh_len > CDF_SHLEN_LIMIT) {\n\t\terrno = EFTYPE;\n\t\tgoto out;\n\t}\n\n\tif (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)\n\t\tgoto out;\n\n\tsh.sh_properties = CDF_TOLE4(shp->sh_properties);\n\tDPRINTF((\"section len: %u properties %u\\n\", sh.sh_len,\n\t sh.sh_properties));\n\tif (sh.sh_properties > CDF_PROP_LIMIT)\n\t\tgoto out;\n\tinp = cdf_grow_info(info, maxcount, sh.sh_properties);\n\tif (inp == NULL)\n\t\tgoto out;\n\tinp += *count;\n\t*count += sh.sh_properties;\n\tp = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));\n\te = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));\n\tif (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)\n\t\tgoto out;\n\n\tfor (i = 0; i < sh.sh_properties; i++) {\n\t\tif ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)\n\t\t\tgoto out;\n\t\tinp[i].pi_id = CDF_GETUINT32(p, i << 1);\n\t\tleft = CAST(size_t, e - q);\n\t\tif (left < sizeof(uint32_t)) {\n\t\t\tDPRINTF((\"short info (no type)_\\n\"));\n\t\t\tgoto out;\n\t\t}\n\t\tinp[i].pi_type = CDF_GETUINT32(q, 0);\n\t\tDPRINTF((\"%\" SIZE_T_FORMAT \"u) id=%#x type=%#x offs=%#tx,%#x\\n\",\n\t\t i, inp[i].pi_id, inp[i].pi_type, q - p, offs));\n\t\tif (inp[i].pi_type & CDF_VECTOR) {\n\t\t\tif (left < sizeof(uint32_t) * 2) {\n\t\t\t\tDPRINTF((\"missing CDF_VECTOR length\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tnelements = CDF_GETUINT32(q, 1);\n\t\t\tif (nelements == 0) {\n\t\t\t\tDPRINTF((\"CDF_VECTOR with nelements == 0\\n\"));\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tslen = 2;\n\t\t} else {\n\t\t\tnelements = 1;\n\t\t\tslen = 1;\n\t\t}\n\t\to4 = slen * sizeof(uint32_t);\n\t\tif (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))\n\t\t\tgoto unknown;\n\t\tswitch (inp[i].pi_type & CDF_TYPEMASK) {\n\t\tcase CDF_NULL:\n\t\tcase CDF_EMPTY:\n\t\t\tbreak;\n\t\tcase CDF_SIGNED16:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED32:\n\t\tcase CDF_BOOL:\n\t\tcase CDF_UNSIGNED32:\n\t\tcase CDF_FLOAT:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_SIGNED64:\n\t\tcase CDF_UNSIGNED64:\n\t\tcase CDF_DOUBLE:\n\t\tcase CDF_FILETIME:\n\t\t\tif (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tcase CDF_LENGTH32_STRING:\n\t\tcase CDF_LENGTH32_WSTRING:\n\t\t\tif (nelements > 1) {\n\t\t\t\tsize_t nelem = inp - *info;\n\t\t\t\tinp = cdf_grow_info(info, maxcount, nelements);\n\t\t\t\tif (inp == NULL)\n\t\t\t\t\tgoto out;\n\t\t\t\tinp += nelem;\n\t\t\t}\n\t\t\tDPRINTF((\"nelements = %\" SIZE_T_FORMAT \"u\\n\",\n\t\t\t nelements));\n\t\t\tfor (j = 0; j < nelements && i < sh.sh_properties;\n\t\t\t j++, i++)\n\t\t\t{\n\t\t\t\tuint32_t l;\n\n\t\t\t\tif (o4 + sizeof(uint32_t) > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tl = CDF_GETUINT32(q, slen);\n\t\t\t\to4 += sizeof(uint32_t);\n\t\t\t\tif (o4 + l > left)\n\t\t\t\t\tgoto out;\n\n\t\t\t\tinp[i].pi_str.s_len = l;\n\t\t\t\tinp[i].pi_str.s_buf = CAST(const char *,\n\t\t\t\t CAST(const void *, &q[o4]));\n\n\t\t\t\tDPRINTF((\"o=%\" SIZE_T_FORMAT \"u l=%d(%\"\n\t\t\t\t SIZE_T_FORMAT \"u), t=%\" SIZE_T_FORMAT\n\t\t\t\t \"u s=%s\\n\", o4, l, CDF_ROUND(l, sizeof(l)),\n\t\t\t\t left, inp[i].pi_str.s_buf));\n\n\t\t\t\tif (l & 1)\n\t\t\t\t\tl++;\n\n\t\t\t\tslen += l >> 1;\n\t\t\t\to4 = slen * sizeof(uint32_t);\n\t\t\t}\n\t\t\ti--;\n\t\t\tbreak;\n\t\tcase CDF_CLIPBOARD:\n\t\t\tif (inp[i].pi_type & CDF_VECTOR)\n\t\t\t\tgoto unknown;\n\t\t\tbreak;\n\t\tdefault:\n\t\tunknown:\n\t\t\tmemset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));\n\t\t\tDPRINTF((\"Don't know how to deal with %#x\\n\",\n\t\t\t inp[i].pi_type));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\nout:\n\tfree(*info);\n\t*info = NULL;\n\t*count = 0;\n\t*maxcount = 0;\n\terrno = EFTYPE;\n\treturn -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[1899, 1950], [2891, 2965]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1899, 1950], [2891, 2965]]}, "_func_name": "cdf_read_property_info", "_file_name": "src/cdf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@mod.route('/like/', methods=['GET', 'POST'])\ndef like(msg_id):\n if request.method == 'GET':\n user_id = session['logged_id']\n c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n cursor.execute(\"INSERT INTO like_msg(msg_id, user_id,c_time) VALUES(%s,%s,%s);\", (msg_id, user_id, c_time))\n conn.commit()\n return redirect(url_for('show_entries'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "like", "_file_name": "flaskr/flaskr/views/like_msg.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int uas_switch_interface(struct usb_device *udev,\n\t\t\t\tstruct usb_interface *intf)\n{\n\tstruct usb_host_interface *alt;\n\n\talt = uas_find_uas_alt_setting(intf);\n\tif (!alt)\n\t\treturn -ENODEV;\n\n\treturn usb_set_interface(udev, alt->desc.bInterfaceNumber,\n\t\t\talt->desc.bAlternateSetting);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "uas_switch_interface", "_file_name": "drivers/usb/storage/uas.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2)\n{\n const uint16_t buf_len = 511;\n char buf[buf_len + 1];\n struct lys_type_bit **bits = NULL;\n struct lyxp_expr *exp;\n const char *module_name, *cur_expr, *end;\n int i, j, count;\n int64_t num;\n uint64_t unum;\n uint8_t c;\n\n#define LOGBUF(str) LOGERR(ctx, LY_EINVAL, \"Value \\\"%s\\\" is too long.\", str)\n\n switch (type) {\n case LY_TYPE_BITS:\n bits = (struct lys_type_bit **)data1;\n count = *((int *)data2);\n /* in canonical form, the bits are ordered by their position */\n buf[0] = '\\0';\n for (i = 0; i < count; i++) {\n if (!bits[i]) {\n /* bit not set */\n continue;\n }\n if (buf[0]) {\n LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);\n sprintf(buf + strlen(buf), \" %s\", bits[i]->name);\n } else {\n LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1);\n strcpy(buf, bits[i]->name);\n }\n }\n break;\n\n case LY_TYPE_IDENT:\n module_name = (const char *)data1;\n /* identity must always have a prefix */\n if (!strchr(*value, ':')) {\n LY_CHECK_ERR_RETURN(strlen(module_name) + 1 + strlen(*value) > buf_len, LOGBUF(*value), -1);\n sprintf(buf, \"%s:%s\", module_name, *value);\n } else {\n LY_CHECK_ERR_RETURN(strlen(*value) > buf_len, LOGBUF(*value), -1);\n strcpy(buf, *value);\n }\n break;\n\n case LY_TYPE_INST:\n exp = lyxp_parse_expr(ctx, *value);\n LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1);\n\n module_name = NULL;\n count = 0;\n for (i = 0; (unsigned)i < exp->used; ++i) {\n cur_expr = &exp->expr[exp->expr_pos[i]];\n\n /* copy WS */\n if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) {\n if (count + (cur_expr - end) > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(end);\n return -1;\n }\n strncpy(&buf[count], end, cur_expr - end);\n count += cur_expr - end;\n }\n\n if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) {\n /* get the module name with \":\" */\n ++end;\n j = end - cur_expr;\n\n if (!module_name || strncmp(cur_expr, module_name, j)) {\n /* print module name with colon, it does not equal to the parent one */\n if (count + j > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(cur_expr);\n return -1;\n }\n strncpy(&buf[count], cur_expr, j);\n count += j;\n }\n module_name = cur_expr;\n\n /* copy the rest */\n if (count + (exp->tok_len[i] - j) > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(end);\n return -1;\n }\n strncpy(&buf[count], end, exp->tok_len[i] - j);\n count += exp->tok_len[i] - j;\n } else {\n if (count + exp->tok_len[i] > buf_len) {\n lyxp_expr_free(exp);\n LOGBUF(&exp->expr[exp->expr_pos[i]]);\n return -1;\n }\n strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]);\n count += exp->tok_len[i];\n }\n }\n if (count > buf_len) {\n LOGINT(ctx);\n lyxp_expr_free(exp);\n return -1;\n }\n buf[count] = '\\0';\n\n lyxp_expr_free(exp);\n break;\n\n case LY_TYPE_DEC64:\n num = *((int64_t *)data1);\n c = *((uint8_t *)data2);\n if (num) {\n count = sprintf(buf, \"%\"PRId64\" \", num);\n if ( (num > 0 && (count - 1) <= c)\n || (count - 2) <= c ) {\n /* we have 0. value, print the value with the leading zeros\n * (one for 0. and also keep the correct with of num according\n * to fraction-digits value)\n * for (num<0) - extra character for '-' sign */\n count = sprintf(buf, \"%0*\"PRId64\" \", (num > 0) ? (c + 1) : (c + 2), num);\n }\n for (i = c, j = 1; i > 0 ; i--) {\n if (j && i > 1 && buf[count - 2] == '0') {\n /* we have trailing zero to skip */\n buf[count - 1] = '\\0';\n } else {\n j = 0;\n buf[count - 1] = buf[count - 2];\n }\n count--;\n }\n buf[count - 1] = '.';\n } else {\n /* zero */\n sprintf(buf, \"0.0\");\n }\n break;\n\n case LY_TYPE_INT8:\n case LY_TYPE_INT16:\n case LY_TYPE_INT32:\n case LY_TYPE_INT64:\n num = *((int64_t *)data1);\n sprintf(buf, \"%\"PRId64, num);\n break;\n\n case LY_TYPE_UINT8:\n case LY_TYPE_UINT16:\n case LY_TYPE_UINT32:\n case LY_TYPE_UINT64:\n unum = *((uint64_t *)data1);\n sprintf(buf, \"%\"PRIu64, unum);\n break;\n\n default:\n /* should not be even called - just do nothing */\n return 0;\n }\n\n if (strcmp(buf, *value)) {\n lydict_remove(ctx, *value);\n *value = lydict_insert(ctx, buf, 0);\n return 1;\n }\n\n return 0;\n\n#undef LOGBUF\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "make_canonical", "_file_name": "src/parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _cmd_to_dict(self, arg_list):\n no_param_args = [\n 'autodelete',\n 'autoexpand',\n 'bytes',\n 'compressed',\n 'force',\n 'nohdr',\n ]\n one_param_args = [\n 'chapsecret',\n 'cleanrate',\n 'copyrate',\n 'delim',\n 'filtervalue',\n 'grainsize',\n 'hbawwpn',\n 'host',\n 'iogrp',\n 'iscsiname',\n 'mdiskgrp',\n 'name',\n 'rsize',\n 'scsi',\n 'size',\n 'source',\n 'target',\n 'unit',\n 'easytier',\n 'warning',\n 'wwpn',\n ]\n\n # Handle the special case of lsnode which is a two-word command\n # Use the one word version of the command internally\n if arg_list[0] in ('svcinfo', 'svctask'):\n if arg_list[1] == 'lsnode':\n if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! \n ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}\n else:\n ret = {'cmd': 'lsnodecanister'}\n else:\n ret = {'cmd': arg_list[1]}\n arg_list.pop(0)\n else:\n ret = {'cmd': arg_list[0]}\n\n skip = False\n for i in range(1, len(arg_list)):\n if skip:\n skip = False\n continue\n if arg_list[i][0] == '-':\n if arg_list[i][1:] in no_param_args:\n ret[arg_list[i][1:]] = True\n elif arg_list[i][1:] in one_param_args:\n ret[arg_list[i][1:]] = arg_list[i + 1]\n skip = True\n else:\n raise exception.InvalidInput(\n reason=_('unrecognized argument %s') % arg_list[i])\n else:\n ret['obj'] = arg_list[i]\n return ret", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_cmd_to_dict", "_file_name": "cinder/tests/test_storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType load_tile(Image *image,Image *tile_image,\n XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,\n ExceptionInfo *exception)\n{\n ssize_t\n y;\n\n register ssize_t\n x;\n\n register Quantum\n *q;\n\n ssize_t\n count;\n\n unsigned char\n *graydata;\n\n XCFPixelInfo\n *xcfdata,\n *xcfodata;\n\n xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length,\n tile_image->columns*tile_image->rows),sizeof(*xcfdata));\n if (xcfdata == (XCFPixelInfo *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n xcfodata=xcfdata;\n graydata=(unsigned char *) xcfdata; /* used by gray and indexed */\n count=ReadBlob(image,data_length,(unsigned char *) xcfdata);\n if (count != (ssize_t) data_length)\n ThrowBinaryException(CorruptImageError,\"NotEnoughPixelData\",\n image->filename);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n if (inDocInfo->image_type == GIMP_GRAY)\n {\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);\n SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)\n inLayerInfo->alpha),q);\n graydata++;\n q+=GetPixelChannels(tile_image);\n }\n }\n else\n if (inDocInfo->image_type == GIMP_RGB)\n {\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);\n SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);\n SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);\n SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :\n ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);\n xcfdata++;\n q+=GetPixelChannels(tile_image);\n }\n }\n if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)\n break;\n }\n xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);\n return MagickTrue;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "load_tile", "_file_name": "coders/xcf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_vdisk_attributes(self, vdisk_name):\n \"\"\"Return vdisk attributes, or None if vdisk does not exist\n\n Exception is raised if the information from system can not be\n parsed/matched to a single vdisk.\n \"\"\"\n\n ssh_cmd = ['svcinfo', 'lsvdisk', '-bytes', '-delim', '!', vdisk_name]\n return self._execute_command_and_parse_attributes(ssh_cmd)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_vdisk_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tconst char *section_name = \"\";\n\tconst char *link_section_name = \"\";\n\tchar *end = NULL;\n\tElf_(Shdr) *link_shdr = NULL;\n\tut8 dfs[sizeof (Elf_(Verdef))] = {0};\n\tSdb *sdb;\n\tint cnt, i;\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn false;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (shdr->sh_size < 1) {\n\t\treturn false;\n\t}\n\tElf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));\n\tif (!defs) {\n\t\treturn false;\n\t}\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!defs) {\n\t\tbprintf (\"Warning: Cannot allocate memory (Check Elf_(Verdef))\\n\");\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tend = (char *)defs + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {\n\t\tSdb *sdb_verdef = sdb_new0 ();\n\t\tchar *vstart = ((char*)defs) + i;\n\t\tchar key[32] = {0};\n\t\tElf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;\n\t\tElf_(Verdaux) aux = {0};\n\t\tint j = 0;\n\t\tint isum = 0;\n\n\t\tr_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));\n\t\tverdef->vd_version = READ16 (dfs, j)\n\t\tverdef->vd_flags = READ16 (dfs, j)\n\t\tverdef->vd_ndx = READ16 (dfs, j)\n\t\tverdef->vd_cnt = READ16 (dfs, j)\n\t\tverdef->vd_hash = READ32 (dfs, j)\n\t\tverdef->vd_aux = READ32 (dfs, j)\n\t\tverdef->vd_next = READ32 (dfs, j)\n\t\tvstart += verdef->vd_aux;\n\t\tif (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tj = 0;\n\t\taux.vda_name = READ32 (vstart, j)\n\t\taux.vda_next = READ32 (vstart, j)\n\n\t\tisum = i + verdef->vd_aux;\n\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\n\t\tsdb_num_set (sdb_verdef, \"idx\", i, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_version\", verdef->vd_version, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_ndx\", verdef->vd_ndx, 0);\n\t\tsdb_num_set (sdb_verdef, \"vd_cnt\", verdef->vd_cnt, 0);\n\t\tsdb_set (sdb_verdef, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\tsdb_set (sdb_verdef, \"flags\", get_ver_flags (verdef->vd_flags), 0);\n\n\t\tfor (j = 1; j < verdef->vd_cnt; ++j) {\n\t\t\tint k;\n\t\t\tSdb *sdb_parent = sdb_new0 ();\n\t\t\tisum += aux.vda_next;\n\t\t\tvstart += aux.vda_next;\n\t\t\tif (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tk = 0;\n\t\t\taux.vda_name = READ32 (vstart, k)\n\t\t\taux.vda_next = READ32 (vstart, k)\n\t\t\tif (aux.vda_name > bin->dynstr_size) {\n\t\t\t\tsdb_free (sdb_verdef);\n\t\t\t\tsdb_free (sdb_parent);\n\t\t\t\tgoto out_error;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_parent, \"idx\", isum, 0);\n\t\t\tsdb_num_set (sdb_parent, \"parent\", j, 0);\n\t\t\tsdb_set (sdb_parent, \"vda_name\", &bin->dynstr[aux.vda_name], 0);\n\t\t\tsnprintf (key, sizeof (key), \"parent%d\", j - 1);\n\t\t\tsdb_ns_set (sdb_verdef, key, sdb_parent);\n\t\t}\n\n\t\tsnprintf (key, sizeof (key), \"verdef%d\", cnt);\n\t\tsdb_ns_set (sdb, key, sdb_verdef);\n\t\tif (!verdef->vd_next) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tif ((st32)verdef->vd_next < 1) {\n\t\t\teprintf (\"Warning: Invalid vd_next in the ELF version\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += verdef->vd_next;\n\t}\n\tfree (defs);\n\treturn sdb;\nout_error:\n\tfree (defs);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1827, 1855]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1827, 1855]]}, "_func_name": "store_versioninfo_gnu_verdef", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def view_grocery_list():\n print(\"grocery== list\")\n groceryListFrame = Frame(self)\n groceryListFrame.rowconfigure(0, weight=1)\n groceryListFrame.columnconfigure(0, weight=1)\n groceryListFrame.rowconfigure(1, weight=3)\n groceryListFrame.columnconfigure(1, weight=3)\n groceryListFrame.pack()\n\n menu.pack_forget()\n groceryButton.pack_forget()\n label.configure(text=\"Grocery List\")\n\n i = 0\n database_file = \"meal_planner.db\"\n item_array = []\n with sqlite3.connect(database_file) as conn:\n cursor = conn.cursor()\n tableName = \"ingredients_\" + str(weekNumber)\n selection = cursor.execute(\"\"\"SELECT * FROM \"\"\" + tableName)\n for result in [selection]:\n for row in result.fetchall():\n print(row)\n for ingredient in row:\n print(ingredient)\n item_array.append(str(ingredient).split())\n i = i +1\n Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=\"w\")\n \n\n j = 0\n for item in item_array:\n print(item)\n\n\n returnButton = Button(menuFrame, text = \"Return to Menu\", highlightbackground=\"#e7e7e7\", command=lambda: [groceryListFrame.pack_forget(),\n menu.pack(), returnButton.pack_forget(), label.configure(text=\"Meal Planer\"),\n groceryButton.pack(side=RIGHT)])\n returnButton.pack(side=RIGHT)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[745, 822]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[745, 822]]}, "_func_name": "__init__.view_grocery_list", "_file_name": "mealPlan.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpeg_size(unsigned char* data, unsigned int data_size,\n int *width, int *height)\n{\n int i = 0;\n if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&\n data[i+2] == 0xFF && data[i+3] == 0xE0) {\n i += 4;\n if(i + 6 < data_size &&\n data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&\n data[i+5] == 'F' && data[i+6] == 0x00) {\n unsigned short block_length = data[i] * 256 + data[i+1];\n while(i= data_size)\n return -1;\n if(data[i] != 0xFF)\n return -1;\n if(data[i+1] == 0xC0) {\n *height = data[i+5]*256 + data[i+6];\n *width = data[i+7]*256 + data[i+8];\n return 0;\n }\n i+=2;\n if (i + 1 < data_size)\n block_length = data[i] * 256 + data[i+1];\n }\n }\n }\n\n return -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jpeg_size", "_file_name": "pdfgen.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_title_from_youtube_url(url):\n try:\n output = str(subprocess.check_output(['youtube-dl', '--get-title', url, '--no-warnings'],\n stderr=subprocess.STDOUT)).strip()\n except subprocess.CalledProcessError as ex:\n output = str(ex.output).strip()\n except OSError as ex:\n output = 'youtube-dl not found: %s' % ex\n except Exception as ex:\n output = 'Something bad happened: %s' % ex\n return remove_commas_from_string(output)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_title_from_youtube_url", "_file_name": "src/util.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tif (new_str) {\n\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "php_wddx_pop_element", "_file_name": "ext/wddx/wddx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int snd_timer_open(struct snd_timer_instance **ti,\n\t\t char *owner, struct snd_timer_id *tid,\n\t\t unsigned int slave_id)\n{\n\tstruct snd_timer *timer;\n\tstruct snd_timer_instance *timeri = NULL;\n\tstruct device *card_dev_to_put = NULL;\n\tint err;\n\n\tmutex_lock(®ister_mutex);\n\tif (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {\n\t\t/* open a slave instance */\n\t\tif (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||\n\t\t tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {\n\t\t\tpr_debug(\"ALSA: timer: invalid slave class %i\\n\",\n\t\t\t\t tid->dev_sclass);\n\t\t\terr = -EINVAL;\n\t\t\tgoto unlock;\n\t\t}\n\t\ttimeri = snd_timer_instance_new(owner, NULL);\n\t\tif (!timeri) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto unlock;\n\t\t}\n\t\ttimeri->slave_class = tid->dev_sclass;\n\t\ttimeri->slave_id = tid->device;\n\t\ttimeri->flags |= SNDRV_TIMER_IFLG_SLAVE;\n\t\tlist_add_tail(&timeri->open_list, &snd_timer_slave_list);\n\t\terr = snd_timer_check_slave(timeri);\n\t\tif (err < 0) {\n\t\t\tsnd_timer_close_locked(timeri, &card_dev_to_put);\n\t\t\ttimeri = NULL;\n\t\t}\n\t\tgoto unlock;\n\t}\n\n\t/* open a master instance */\n\ttimer = snd_timer_find(tid);\n#ifdef CONFIG_MODULES\n\tif (!timer) {\n\t\tmutex_unlock(®ister_mutex);\n\t\tsnd_timer_request(tid);\n\t\tmutex_lock(®ister_mutex);\n\t\ttimer = snd_timer_find(tid);\n\t}\n#endif\n\tif (!timer) {\n\t\terr = -ENODEV;\n\t\tgoto unlock;\n\t}\n\tif (!list_empty(&timer->open_list_head)) {\n\t\ttimeri = list_entry(timer->open_list_head.next,\n\t\t\t\t struct snd_timer_instance, open_list);\n\t\tif (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {\n\t\t\terr = -EBUSY;\n\t\t\ttimeri = NULL;\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\tif (timer->num_instances >= timer->max_instances) {\n\t\terr = -EBUSY;\n\t\tgoto unlock;\n\t}\n\ttimeri = snd_timer_instance_new(owner, timer);\n\tif (!timeri) {\n\t\terr = -ENOMEM;\n\t\tgoto unlock;\n\t}\n\t/* take a card refcount for safe disconnection */\n\tif (timer->card)\n\t\tget_device(&timer->card->card_dev);\n\ttimeri->slave_class = tid->dev_sclass;\n\ttimeri->slave_id = slave_id;\n\n\tif (list_empty(&timer->open_list_head) && timer->hw.open) {\n\t\terr = timer->hw.open(timer);\n\t\tif (err) {\n\t\t\tkfree(timeri->owner);\n\t\t\tkfree(timeri);\n\t\t\ttimeri = NULL;\n\n\t\t\tif (timer->card)\n\t\t\t\tcard_dev_to_put = &timer->card->card_dev;\n\t\t\tmodule_put(timer->module);\n\t\t\tgoto unlock;\n\t\t}\n\t}\n\n\tlist_add_tail(&timeri->open_list, &timer->open_list_head);\n\ttimer->num_instances++;\n\terr = snd_timer_check_master(timeri);\n\tif (err < 0) {\n\t\tsnd_timer_close_locked(timeri, &card_dev_to_put);\n\t\ttimeri = NULL;\n\t}\n\n unlock:\n\tmutex_unlock(®ister_mutex);\n\t/* put_device() is called after unlock for avoiding deadlock */\n\tif (card_dev_to_put)\n\t\tput_device(card_dev_to_put);\n\t*ti = timeri;\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1334, 1384], [1431, 1518]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1334, 1384], [1431, 1518]]}, "_func_name": "snd_timer_open", "_file_name": "sound/core/timer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "R_API void r_anal_bb_free(RAnalBlock *bb) {\n\tif (!bb) {\n\t\treturn;\n\t}\n\tr_anal_cond_free (bb->cond);\n\tR_FREE (bb->fingerprint);\n\tr_anal_diff_free (bb->diff);\n\tbb->diff = NULL;\n\tR_FREE (bb->op_bytes);\n\tr_anal_switch_op_free (bb->switch_op);\n\tbb->switch_op = NULL;\n\tbb->fingerprint = NULL;\n\tbb->cond = NULL;\n\tR_FREE (bb->label);\n\tR_FREE (bb->op_pos);\n\tR_FREE (bb->parent_reg_arena);\n\tif (bb->prev) {\n\t\tif (bb->prev->jumpbb == bb) {\n\t\t\tbb->prev->jumpbb = NULL;\n\t\t}\n\t\tif (bb->prev->failbb == bb) {\n\t\t\tbb->prev->failbb = NULL;\n\t\t}\n\t\tbb->prev = NULL;\n\t}\n\tif (bb->jumpbb) {\n\t\tbb->jumpbb->prev = NULL;\n\t\tbb->jumpbb = NULL;\n\t}\n\tif (bb->failbb) {\n\t\tbb->failbb->prev = NULL;\n\t\tbb->failbb = NULL;\n\t}\n\tR_FREE (bb);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[686, 700]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[686, 700]]}, "_func_name": "r_anal_bb_free", "_file_name": "libr/anal/bb.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " */\nstatic void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->type == ST_FIELD && ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n\t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n\n\t\t\t\t\t\t/* Clean up class name var entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[966, 1040]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[966, 1040]]}, "_func_name": "php_wddx_pop_element", "_file_name": "ext/wddx/wddx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int main(int argc, char *argv[])\n{\n FILE *iplist = NULL;\n plist_t root_node = NULL;\n char *plist_out = NULL;\n uint32_t size = 0;\n int read_size = 0;\n char *plist_entire = NULL;\n struct stat filestats;\n options_t *options = parse_arguments(argc, argv);\n\n if (!options)\n {\n print_usage(argc, argv);\n return 0;\n }\n\n // read input file\n iplist = fopen(options->in_file, \"rb\");\n if (!iplist) {\n free(options);\n return 1;\n }\n\n stat(options->in_file, &filestats);\n plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));\n read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);\n fclose(iplist);\n\n // convert from binary to xml or vice-versa\n if (memcmp(plist_entire, \"bplist00\", 8) == 0)\n {\n plist_from_bin(plist_entire, read_size, &root_node);\n plist_to_xml(root_node, &plist_out, &size);\n }\n else\n {\n plist_from_xml(plist_entire, read_size, &root_node);\n plist_to_bin(root_node, &plist_out, &size);\n }\n plist_free(root_node);\n free(plist_entire);\n\n if (plist_out)\n {\n if (options->out_file != NULL)\n {\n FILE *oplist = fopen(options->out_file, \"wb\");\n if (!oplist) {\n free(options);\n return 1;\n }\n fwrite(plist_out, size, sizeof(char), oplist);\n fclose(oplist);\n }\n // if no output file specified, write to stdout\n else\n fwrite(plist_out, size, sizeof(char), stdout);\n\n free(plist_out);\n }\n else\n printf(\"ERROR: Failed to convert input file.\\n\");\n\n free(options);\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[533, 609]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[533, 609]]}, "_func_name": "main", "_file_name": "tools/plistutil.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length)\n{\n char *buffer=NULL;\n int n=0;\n\n FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(\"\", cl, NULL);\n\n /*\n We later alloc length+1, which might wrap around on 32-bit systems if length equals\n 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF\n will safely be allocated since this check will never trigger and malloc() can digest length+1\n without problems as length is a uint32_t.\n */\n if(length == SIZE_MAX) {\n\trfbErr(\"rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u\", (unsigned int)length);\n\trfbCloseClient(cl);\n\treturn NULL;\n }\n\n if (length>0) {\n buffer=malloc((size_t)length+1);\n if (buffer!=NULL) {\n if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) {\n if (n != 0)\n rfbLogPerror(\"rfbProcessFileTransferReadBuffer: read\");\n rfbCloseClient(cl);\n /* NOTE: don't forget to free(buffer) if you return early! */\n if (buffer!=NULL) free(buffer);\n return NULL;\n }\n /* Null Terminate */\n buffer[length]=0;\n }\n }\n return buffer;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rfbProcessFileTransferReadBuffer", "_file_name": "libvncserver/rfbserver.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def update_playlist(id, name, db):\n db.execute(\n \"UPDATE playlist SET name='{name}' WHERE id={id};\".format(name=name, id=id))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[35, 135]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[35, 135]]}, "_func_name": "update_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int kvm_ioctl_create_device(struct kvm *kvm,\n\t\t\t\t struct kvm_create_device *cd)\n{\n\tstruct kvm_device_ops *ops = NULL;\n\tstruct kvm_device *dev;\n\tbool test = cd->flags & KVM_CREATE_DEVICE_TEST;\n\tint ret;\n\n\tif (cd->type >= ARRAY_SIZE(kvm_device_ops_table))\n\t\treturn -ENODEV;\n\n\tops = kvm_device_ops_table[cd->type];\n\tif (ops == NULL)\n\t\treturn -ENODEV;\n\n\tif (test)\n\t\treturn 0;\n\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (!dev)\n\t\treturn -ENOMEM;\n\n\tdev->ops = ops;\n\tdev->kvm = kvm;\n\n\tmutex_lock(&kvm->lock);\n\tret = ops->create(dev, cd->type);\n\tif (ret < 0) {\n\t\tmutex_unlock(&kvm->lock);\n\t\tkfree(dev);\n\t\treturn ret;\n\t}\n\tlist_add(&dev->vm_node, &kvm->devices);\n\tmutex_unlock(&kvm->lock);\n\n\tif (ops->init)\n\t\tops->init(dev);\n\n\tret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);\n\tif (ret < 0) {\n\t\tmutex_lock(&kvm->lock);\n\t\tlist_del(&dev->vm_node);\n\t\tmutex_unlock(&kvm->lock);\n\t\tops->destroy(dev);\n\t\treturn ret;\n\t}\n\n\tkvm_get_kvm(kvm);\n\tcd->fd = ret;\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "kvm_ioctl_create_device", "_file_name": "virt/kvm/kvm_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_previous_yields(self, inverter_serial):\n query = '''\n SELECT TimeStamp, EToday, ETotal\n FROM Inverters\n WHERE Serial = '%s'\n ''' % (inverter_serial)\n self.c.execute(query)\n data = self.c.fetchone()\n return data[0], data[1], data[2]", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[142, 205]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[142, 205]]}, "_func_name": "get_previous_yields", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_MSB,op_LSB;\n\tint ret;\n\tif (!data || len < 2) {\n\t\treturn 0;\n\t}\n\tmemset (op, '\\0', sizeof (RAnalOp));\n\top->addr = addr;\n\top->type = R_ANAL_OP_TYPE_UNK;\n\top->jump = op->fail = -1;\n\top->ptr = op->val = -1;\n\n\top->size = 2;\n\n\top_MSB = anal->big_endian? data[0]: data[1];\n\top_LSB = anal->big_endian? data[1]: data[0];\n\tret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "sh_op", "_file_name": "libr/anal/p/anal_sh.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_host_from_connector(self, connector):\n \"\"\"List the hosts defined in the storage.\n\n Return the host name with the given connection info, or None if there\n is no host fitting that information.\n\n \"\"\"\n\n prefix = self._connector_to_hostname_prefix(connector)\n LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)\n\n # Get list of host in the storage\n ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n # If we have FC information, we have a faster lookup option\n hostname = None\n if 'wwpns' in connector:\n hostname = self._find_host_from_wwpn(connector)\n\n # If we don't have a hostname yet, try the long way\n if not hostname:\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines),\n '_get_host_from_connector',\n ssh_cmd, out, err)\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header,\n '_get_host_from_connector',\n ssh_cmd, out, err)\n name_index = header.index('name')\n hosts = map(lambda x: x.split('!')[name_index], host_lines)\n hostname = self._find_host_exhaustive(connector, hosts)\n\n LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)\n\n return hostname", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_host_from_connector", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "Status KernelAndDeviceOp::Run(\n ScopedStepContainer* step_container, const EagerKernelArgs& inputs,\n std::vector* outputs,\n CancellationManager* cancellation_manager,\n const absl::optional& remote_func_params) {\n OpKernelContext::Params params;\n params.device = device_;\n params.frame_iter = FrameAndIter(0, 0);\n params.inputs = inputs.GetTensorValues();\n params.op_kernel = kernel_.get();\n params.resource_manager = device_->resource_manager();\n params.input_alloc_attrs = &input_alloc_attrs_;\n params.output_attr_array = output_alloc_attrs_.data();\n params.function_library = flr_;\n params.slice_reader_cache = &slice_reader_cache_;\n params.rendezvous = rendezvous_;\n OpExecutionState* op_execution_state = nullptr;\n\n CancellationManager default_cancellation_manager;\n if (cancellation_manager) {\n params.cancellation_manager = cancellation_manager;\n } else if (kernel_->is_deferred()) {\n op_execution_state = new OpExecutionState;\n params.cancellation_manager = &op_execution_state->cancellation_manager;\n params.inc_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Ref();\n };\n params.dec_num_deferred_ops_function = [op_execution_state]() {\n op_execution_state->Unref();\n };\n } else {\n params.cancellation_manager = &default_cancellation_manager;\n }\n\n params.log_memory = log_memory_;\n\n params.runner = get_runner();\n\n params.step_container =\n step_container == nullptr ? &step_container_ : step_container;\n auto step_container_cleanup = gtl::MakeCleanup([step_container, this] {\n if (step_container == nullptr) {\n this->step_container_.CleanUp();\n }\n });\n\n params.collective_executor =\n collective_executor_ ? collective_executor_->get() : nullptr;\n\n OpKernelContext context(¶ms);\n\n {\n port::ScopedFlushDenormal flush;\n port::ScopedSetRound round(FE_TONEAREST);\n // 'AnnotatedTraceMe' will trace both scheduling time on host and execution\n // time on device of the OpKernel.\n profiler::AnnotatedTraceMe activity(\n [&] { return kernel_->TraceString(context, /*verbose=*/false); },\n profiler::TraceMeLevel::kInfo);\n device_->Compute(kernel_.get(), &context);\n }\n\n // Clean up execution op_execution_state if deferred ops aren't running.\n if (op_execution_state != nullptr) {\n op_execution_state->Unref();\n }\n\n if (!context.status().ok()) return context.status();\n\n if (outputs != nullptr) {\n outputs->clear();\n for (int i = 0; i < context.num_outputs(); ++i) {\n const auto* output_tensor = context.mutable_output(i);\n if (output_tensor != nullptr) {\n outputs->push_back(Tensor(*output_tensor));\n } else {\n outputs->push_back(Tensor());\n }\n }\n }\n return Status::OK();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tensorflow::KernelAndDeviceOp::Run", "_file_name": "tensorflow/core/common_runtime/eager/kernel_and_device.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " long WebPImage::getHeaderOffset(byte *data, long data_size,\n byte *header, long header_size) {\n long pos = -1;\n for (long i=0; i < data_size - header_size; i++) {\n if (memcmp(header, &data[i], header_size) == 0) {\n pos = i;\n break;\n }\n }\n return pos;\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[0, 134]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 134]]}, "_func_name": "Exiv2::WebPImage::getHeaderOffset", "_file_name": "src/webpimage.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)\n{\n\tstruct tun_struct *tun;\n\tstruct tun_file *tfile = file->private_data;\n\tstruct net_device *dev;\n\tint err;\n\n\tif (tfile->detached)\n\t\treturn -EINVAL;\n\n\tdev = __dev_get_by_name(net, ifr->ifr_name);\n\tif (dev) {\n\t\tif (ifr->ifr_flags & IFF_TUN_EXCL)\n\t\t\treturn -EBUSY;\n\t\tif ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)\n\t\t\ttun = netdev_priv(dev);\n\t\telse\n\t\t\treturn -EINVAL;\n\n\t\tif (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=\n\t\t !!(tun->flags & IFF_MULTI_QUEUE))\n\t\t\treturn -EINVAL;\n\n\t\tif (tun_not_capable(tun))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_open(tun->security);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\terr = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\tif (tun->flags & IFF_MULTI_QUEUE &&\n\t\t (tun->numqueues + tun->numdisabled > 1)) {\n\t\t\t/* One or more queue has already been attached, no need\n\t\t\t * to initialize the device again.\n\t\t\t */\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse {\n\t\tchar *name;\n\t\tunsigned long flags = 0;\n\t\tint queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?\n\t\t\t MAX_TAP_QUEUES : 1;\n\n\t\tif (!ns_capable(net->user_ns, CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\t\terr = security_tun_dev_create();\n\t\tif (err < 0)\n\t\t\treturn err;\n\n\t\t/* Set dev type */\n\t\tif (ifr->ifr_flags & IFF_TUN) {\n\t\t\t/* TUN device */\n\t\t\tflags |= IFF_TUN;\n\t\t\tname = \"tun%d\";\n\t\t} else if (ifr->ifr_flags & IFF_TAP) {\n\t\t\t/* TAP device */\n\t\t\tflags |= IFF_TAP;\n\t\t\tname = \"tap%d\";\n\t\t} else\n\t\t\treturn -EINVAL;\n\n\t\tif (*ifr->ifr_name)\n\t\t\tname = ifr->ifr_name;\n\n\t\tdev = alloc_netdev_mqs(sizeof(struct tun_struct), name,\n\t\t\t\t NET_NAME_UNKNOWN, tun_setup, queues,\n\t\t\t\t queues);\n\n\t\tif (!dev)\n\t\t\treturn -ENOMEM;\n\t\terr = dev_get_valid_name(net, dev, name);\n\t\tif (err)\n\t\t\tgoto err_free_dev;\n\n\t\tdev_net_set(dev, net);\n\t\tdev->rtnl_link_ops = &tun_link_ops;\n\t\tdev->ifindex = tfile->ifindex;\n\t\tdev->sysfs_groups[0] = &tun_attr_group;\n\n\t\ttun = netdev_priv(dev);\n\t\ttun->dev = dev;\n\t\ttun->flags = flags;\n\t\ttun->txflt.count = 0;\n\t\ttun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);\n\n\t\ttun->align = NET_SKB_PAD;\n\t\ttun->filter_attached = false;\n\t\ttun->sndbuf = tfile->socket.sk->sk_sndbuf;\n\t\ttun->rx_batched = 0;\n\n\t\ttun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);\n\t\tif (!tun->pcpu_stats) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto err_free_dev;\n\t\t}\n\n\t\tspin_lock_init(&tun->lock);\n\n\t\terr = security_tun_dev_alloc_security(&tun->security);\n\t\tif (err < 0)\n\t\t\tgoto err_free_stat;\n\n\t\ttun_net_init(dev);\n\t\ttun_flow_init(tun);\n\n\t\tdev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |\n\t\t\t\t TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX;\n\t\tdev->features = dev->hw_features | NETIF_F_LLTX;\n\t\tdev->vlan_features = dev->features &\n\t\t\t\t ~(NETIF_F_HW_VLAN_CTAG_TX |\n\t\t\t\t NETIF_F_HW_VLAN_STAG_TX);\n\n\t\tINIT_LIST_HEAD(&tun->disabled);\n\t\terr = tun_attach(tun, file, false);\n\t\tif (err < 0)\n\t\t\tgoto err_free_flow;\n\n\t\terr = register_netdevice(tun->dev);\n\t\tif (err < 0)\n\t\t\tgoto err_detach;\n\t}\n\n\tnetif_carrier_on(tun->dev);\n\n\ttun_debug(KERN_INFO, tun, \"tun_set_iff\\n\");\n\n\ttun->flags = (tun->flags & ~TUN_FEATURES) |\n\t\t(ifr->ifr_flags & TUN_FEATURES);\n\n\t/* Make sure persistent devices do not get stuck in\n\t * xoff state.\n\t */\n\tif (netif_running(tun->dev))\n\t\tnetif_tx_wake_all_queues(tun->dev);\n\n\tstrcpy(ifr->ifr_name, tun->dev->name);\n\treturn 0;\n\nerr_detach:\n\ttun_detach_all(dev);\n\t/* register_netdevice() already called tun_free_netdev() */\n\tgoto err_free_dev;\n\nerr_free_flow:\n\ttun_flow_uninit(tun);\n\tsecurity_tun_dev_free_security(tun->security);\nerr_free_stat:\n\tfree_percpu(tun->pcpu_stats);\nerr_free_dev:\n\tfree_netdev(dev);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1859, 1870]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1859, 1870]]}, "_func_name": "tun_set_iff", "_file_name": "drivers/net/tun.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "openscript(\n char_u\t*name,\n int\t\tdirectly)\t/* when TRUE execute directly */\n{\n if (curscript + 1 == NSCRIPT)\n {\n\temsg(_(e_nesting));\n\treturn;\n }\n#ifdef FEAT_EVAL\n if (ignore_script)\n\t/* Not reading from script, also don't open one. Warning message? */\n\treturn;\n#endif\n\n if (scriptin[curscript] != NULL)\t/* already reading script */\n\t++curscript;\n\t\t\t\t/* use NameBuff for expanded name */\n expand_env(name, NameBuff, MAXPATHL);\n if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)\n {\n\tsemsg(_(e_notopen), name);\n\tif (curscript)\n\t --curscript;\n\treturn;\n }\n if (save_typebuf() == FAIL)\n\treturn;\n\n /*\n * Execute the commands from the file right now when using \":source!\"\n * after \":global\" or \":argdo\" or in a loop. Also when another command\n * follows. This means the display won't be updated. Don't do this\n * always, \"make test\" would fail.\n */\n if (directly)\n {\n\toparg_T\toa;\n\tint\toldcurscript;\n\tint\tsave_State = State;\n\tint\tsave_restart_edit = restart_edit;\n\tint\tsave_insertmode = p_im;\n\tint\tsave_finish_op = finish_op;\n\tint\tsave_msg_scroll = msg_scroll;\n\n\tState = NORMAL;\n\tmsg_scroll = FALSE;\t/* no msg scrolling in Normal mode */\n\trestart_edit = 0;\t/* don't go to Insert mode */\n\tp_im = FALSE;\t\t/* don't use 'insertmode' */\n\tclear_oparg(&oa);\n\tfinish_op = FALSE;\n\n\toldcurscript = curscript;\n\tdo\n\t{\n\t update_topline_cursor();\t// update cursor position and topline\n\t normal_cmd(&oa, FALSE);\t// execute one command\n\t vpeekc();\t\t\t// check for end of file\n\t}\n\twhile (scriptin[oldcurscript] != NULL);\n\n\tState = save_State;\n\tmsg_scroll = save_msg_scroll;\n\trestart_edit = save_restart_edit;\n\tp_im = save_insertmode;\n\tfinish_op = save_finish_op;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[160, 177]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[160, 177]]}, "_func_name": "openscript", "_file_name": "src/getchar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int dd_exist(const struct dump_dir *dd, const char *path)\n{\n char *full_path = concat_path_file(dd->dd_dirname, path);\n int ret = exist_file_dir(full_path);\n free(full_path);\n return ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[60, 122]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[60, 122]]}, "_func_name": "dd_exist", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def auto_unlock_tasks(project_id: int):\n \"\"\"Unlock all tasks locked for longer than the auto-unlock delta\"\"\"\n expiry_delta = Task.auto_unlock_delta()\n lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()\n expiry_date = datetime.datetime.utcnow() - expiry_delta\n old_locks_query = '''SELECT t.id\n FROM tasks t, task_history th\n WHERE t.id = th.task_id\n AND t.project_id = th.project_id\n AND t.task_status IN (1,3)\n AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )\n AND th.action_text IS NULL\n AND t.project_id = :project_id\n AND th.action_date <= :expiry_date\n '''\n\n old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date))\n\n if old_tasks.rowcount == 0:\n # no tasks older than the delta found, return without further processing\n return\n\n for old_task in old_tasks:\n task = Task.get(old_task[0], project_id)\n task.auto_unlock_expired_tasks(expiry_date, lock_duration)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "auto_unlock_tasks", "_file_name": "server/models/postgis/task.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def set_language(self, lang):\n \"\"\"\n Update language of user in the User object and in the database\n :param lang: string with language tag like \"en-US\"\n :return: None\n \"\"\"\n log.debug('Updating info about user %s language '\n 'in memory & database...', self)\n\n self.language = lang\n\n query = (\"UPDATE users \"\n f\"SET language=%s \"\n f\"WHERE chat_id=%s\")\n\n parameters = self.language, self.chat_id\n try:\n db.add(query, parameters)\n except DatabaseError:\n log.error(\"Can't add new language of %s to the database\", self)\n else:\n log.debug('Language updated.')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set_language", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def getResults(poll_name):\n conn, c = connectDB()\n req = \"SELECT options from {} where name = '{}'\".format(CFG(\"poll_table_name\"), poll_name)\n options_str = queryOne(c, req)\n\n if not options_str:\n raise LookupError(\"Poll '{}' not found in DB\".format(poll_name))\n\n total = 0\n options = options_str.split(\",\")\n results = dict()\n for opt in options:\n count = getOptionCount(c, poll_name, opt)\n total += int(count)\n results.update({opt:count})\n\n conn.close()\n return (results, total)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[53, 148]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[53, 148]]}, "_func_name": "getResults", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n 'fakehost 123456789012345 123456789054321')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[635, 712]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[635, 712]]}, "_func_name": "test_create_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@then(parsers.parse(\"the hostname '{hostname}' should be resolved\"))\ndef resolve_hostname(busybox_pod, host, hostname):\n with host.sudo():\n # test dns resolve\n result = host.run(\n \"kubectl --kubeconfig=/etc/kubernetes/admin.conf \"\n \"exec -ti %s nslookup %s\",\n busybox_pod,\n hostname,\n )\n\n assert result.rc == 0, \"Cannot resolve {}\".format(hostname)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "resolve_hostname", "_file_name": "tests/post/steps/test_dns.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int __init fm10k_init_module(void)\n{\n\tpr_info(\"%s - version %s\\n\", fm10k_driver_string, fm10k_driver_version);\n\tpr_info(\"%s\\n\", fm10k_copyright);\n\n\t/* create driver workqueue */\n\tfm10k_workqueue = alloc_workqueue(\"%s\", WQ_MEM_RECLAIM, 0,\n\t\t\t\t\t fm10k_driver_name);\n\n\tfm10k_dbg_init();\n\n\treturn fm10k_register_pci_driver();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[272, 273]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[272, 273]]}, "_func_name": "fm10k_init_module", "_file_name": "drivers/net/ethernet/intel/fm10k/fm10k_main.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)\n{\n\tPurpleXfer *xfer = data;\n\tstruct im_connection *ic = purple_ic_by_pa(xfer->account);\n\tstruct prpl_xfer_data *px = xfer->ui_data;\n\tPurpleBuddy *buddy;\n\tconst char *who;\n\n\tbuddy = purple_find_buddy(xfer->account, xfer->who);\n\twho = buddy ? purple_buddy_get_name(buddy) : xfer->who;\n\n\t/* TODO(wilmer): After spreading some more const goodness in BitlBee,\n\t remove the evil cast below. */\n\tpx->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);\n\tpx->ft->data = px;\n\n\tpx->ft->accept = prpl_xfer_accept;\n\tpx->ft->canceled = prpl_xfer_canceled;\n\tpx->ft->free = prpl_xfer_free;\n\tpx->ft->write_request = prpl_xfer_write_request;\n\n\treturn FALSE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[556, 576]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[556, 576]]}, "_func_name": "prplcb_xfer_new_send_cb", "_file_name": "protocols/purple/ft.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int mpol_parse_str(char *str, struct mempolicy **mpol)\n{\n\tstruct mempolicy *new = NULL;\n\tunsigned short mode_flags;\n\tnodemask_t nodes;\n\tchar *nodelist = strchr(str, ':');\n\tchar *flags = strchr(str, '=');\n\tint err = 1, mode;\n\n\tif (flags)\n\t\t*flags++ = '\\0';\t/* terminate mode string */\n\n\tif (nodelist) {\n\t\t/* NUL-terminate mode or flags string */\n\t\t*nodelist++ = '\\0';\n\t\tif (nodelist_parse(nodelist, nodes))\n\t\t\tgoto out;\n\t\tif (!nodes_subset(nodes, node_states[N_MEMORY]))\n\t\t\tgoto out;\n\t} else\n\t\tnodes_clear(nodes);\n\n\tmode = match_string(policy_modes, MPOL_MAX, str);\n\tif (mode < 0)\n\t\tgoto out;\n\n\tswitch (mode) {\n\tcase MPOL_PREFERRED:\n\t\t/*\n\t\t * Insist on a nodelist of one node only\n\t\t */\n\t\tif (nodelist) {\n\t\t\tchar *rest = nodelist;\n\t\t\twhile (isdigit(*rest))\n\t\t\t\trest++;\n\t\t\tif (*rest)\n\t\t\t\tgoto out;\n\t\t}\n\t\tbreak;\n\tcase MPOL_INTERLEAVE:\n\t\t/*\n\t\t * Default to online nodes with memory if no nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tnodes = node_states[N_MEMORY];\n\t\tbreak;\n\tcase MPOL_LOCAL:\n\t\t/*\n\t\t * Don't allow a nodelist; mpol_new() checks flags\n\t\t */\n\t\tif (nodelist)\n\t\t\tgoto out;\n\t\tmode = MPOL_PREFERRED;\n\t\tbreak;\n\tcase MPOL_DEFAULT:\n\t\t/*\n\t\t * Insist on a empty nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\terr = 0;\n\t\tgoto out;\n\tcase MPOL_BIND:\n\t\t/*\n\t\t * Insist on a nodelist\n\t\t */\n\t\tif (!nodelist)\n\t\t\tgoto out;\n\t}\n\n\tmode_flags = 0;\n\tif (flags) {\n\t\t/*\n\t\t * Currently, we only support two mutually exclusive\n\t\t * mode flags.\n\t\t */\n\t\tif (!strcmp(flags, \"static\"))\n\t\t\tmode_flags |= MPOL_F_STATIC_NODES;\n\t\telse if (!strcmp(flags, \"relative\"))\n\t\t\tmode_flags |= MPOL_F_RELATIVE_NODES;\n\t\telse\n\t\t\tgoto out;\n\t}\n\n\tnew = mpol_new(mode, mode_flags, &nodes);\n\tif (IS_ERR(new))\n\t\tgoto out;\n\n\t/*\n\t * Save nodes for mpol_to_str() to show the tmpfs mount options\n\t * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.\n\t */\n\tif (mode != MPOL_PREFERRED)\n\t\tnew->v.nodes = nodes;\n\telse if (nodelist)\n\t\tnew->v.preferred_node = first_node(nodes);\n\telse\n\t\tnew->flags |= MPOL_F_LOCAL;\n\n\t/*\n\t * Save nodes for contextualization: this will be used to \"clone\"\n\t * the mempolicy in a specific context [cpuset] at a later time.\n\t */\n\tnew->w.user_nodemask = nodes;\n\n\terr = 0;\n\nout:\n\t/* Restore string for error message */\n\tif (nodelist)\n\t\t*--nodelist = ':';\n\tif (flags)\n\t\t*--flags = '=';\n\tif (!err)\n\t\t*mpol = new;\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[637, 680]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[637, 680]]}, "_func_name": "mpol_parse_str", "_file_name": "mm/mempolicy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int dnxhd_find_frame_end(DNXHDParserContext *dctx,\n const uint8_t *buf, int buf_size)\n{\n ParseContext *pc = &dctx->pc;\n uint64_t state = pc->state64;\n int pic_found = pc->frame_start_found;\n int i = 0;\n\n if (!pic_found) {\n for (i = 0; i < buf_size; i++) {\n state = (state << 8) | buf[i];\n if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {\n i++;\n pic_found = 1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n break;\n }\n }\n }\n\n if (pic_found && !dctx->remaining) {\n if (!buf_size) /* EOF considered as end of frame */\n return 0;\n for (; i < buf_size; i++) {\n dctx->cur_byte++;\n state = (state << 8) | buf[i];\n\n if (dctx->cur_byte == 24) {\n dctx->h = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 26) {\n dctx->w = (state >> 32) & 0xFFFF;\n } else if (dctx->cur_byte == 42) {\n int cid = (state >> 32) & 0xFFFFFFFF;\n\n if (cid <= 0)\n continue;\n\n dctx->remaining = avpriv_dnxhd_get_frame_size(cid);\n if (dctx->remaining <= 0) {\n dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n if (dctx->remaining <= 0)\n return dctx->remaining;\n }\n if (buf_size - i + 47 >= dctx->remaining) {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n } else {\n dctx->remaining -= buf_size;\n }\n }\n }\n } else if (pic_found) {\n if (dctx->remaining > buf_size) {\n dctx->remaining -= buf_size;\n } else {\n int remaining = dctx->remaining;\n\n pc->frame_start_found = 0;\n pc->state64 = -1;\n dctx->cur_byte = 0;\n dctx->remaining = 0;\n return remaining;\n }\n }\n pc->frame_start_found = pic_found;\n pc->state64 = state;\n return END_NOT_FOUND;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1200, 1492]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1200, 1492]]}, "_func_name": "dnxhd_find_frame_end", "_file_name": "libavcodec/dnxhd_parser.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "struct sk_buff *skb_segment(struct sk_buff *head_skb,\n\t\t\t netdev_features_t features)\n{\n\tstruct sk_buff *segs = NULL;\n\tstruct sk_buff *tail = NULL;\n\tstruct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;\n\tskb_frag_t *frag = skb_shinfo(head_skb)->frags;\n\tunsigned int mss = skb_shinfo(head_skb)->gso_size;\n\tunsigned int doffset = head_skb->data - skb_mac_header(head_skb);\n\tunsigned int offset = doffset;\n\tunsigned int tnl_hlen = skb_tnl_header_len(head_skb);\n\tunsigned int headroom;\n\tunsigned int len;\n\t__be16 proto;\n\tbool csum;\n\tint sg = !!(features & NETIF_F_SG);\n\tint nfrags = skb_shinfo(head_skb)->nr_frags;\n\tint err = -ENOMEM;\n\tint i = 0;\n\tint pos;\n\n\tproto = skb_network_protocol(head_skb);\n\tif (unlikely(!proto))\n\t\treturn ERR_PTR(-EINVAL);\n\n\tcsum = !!can_checksum_protocol(features, proto);\n\t__skb_push(head_skb, doffset);\n\theadroom = skb_headroom(head_skb);\n\tpos = skb_headlen(head_skb);\n\n\tdo {\n\t\tstruct sk_buff *nskb;\n\t\tskb_frag_t *nskb_frag;\n\t\tint hsize;\n\t\tint size;\n\n\t\tlen = head_skb->len - offset;\n\t\tif (len > mss)\n\t\t\tlen = mss;\n\n\t\thsize = skb_headlen(head_skb) - offset;\n\t\tif (hsize < 0)\n\t\t\thsize = 0;\n\t\tif (hsize > len || !sg)\n\t\t\thsize = len;\n\n\t\tif (!hsize && i >= nfrags && skb_headlen(list_skb) &&\n\t\t (skb_headlen(list_skb) == len || sg)) {\n\t\t\tBUG_ON(skb_headlen(list_skb) > len);\n\n\t\t\ti = 0;\n\t\t\tnfrags = skb_shinfo(list_skb)->nr_frags;\n\t\t\tfrag = skb_shinfo(list_skb)->frags;\n\t\t\tpos += skb_headlen(list_skb);\n\n\t\t\twhile (pos < offset + len) {\n\t\t\t\tBUG_ON(i >= nfrags);\n\n\t\t\t\tsize = skb_frag_size(frag);\n\t\t\t\tif (pos + size > offset + len)\n\t\t\t\t\tbreak;\n\n\t\t\t\ti++;\n\t\t\t\tpos += size;\n\t\t\t\tfrag++;\n\t\t\t}\n\n\t\t\tnskb = skb_clone(list_skb, GFP_ATOMIC);\n\t\t\tlist_skb = list_skb->next;\n\n\t\t\tif (unlikely(!nskb))\n\t\t\t\tgoto err;\n\n\t\t\tif (unlikely(pskb_trim(nskb, len))) {\n\t\t\t\tkfree_skb(nskb);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\thsize = skb_end_offset(nskb);\n\t\t\tif (skb_cow_head(nskb, doffset + headroom)) {\n\t\t\t\tkfree_skb(nskb);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\tnskb->truesize += skb_end_offset(nskb) - hsize;\n\t\t\tskb_release_head_state(nskb);\n\t\t\t__skb_push(nskb, doffset);\n\t\t} else {\n\t\t\tnskb = __alloc_skb(hsize + doffset + headroom,\n\t\t\t\t\t GFP_ATOMIC, skb_alloc_rx_flag(head_skb),\n\t\t\t\t\t NUMA_NO_NODE);\n\n\t\t\tif (unlikely(!nskb))\n\t\t\t\tgoto err;\n\n\t\t\tskb_reserve(nskb, headroom);\n\t\t\t__skb_put(nskb, doffset);\n\t\t}\n\n\t\tif (segs)\n\t\t\ttail->next = nskb;\n\t\telse\n\t\t\tsegs = nskb;\n\t\ttail = nskb;\n\n\t\t__copy_skb_header(nskb, head_skb);\n\t\tnskb->mac_len = head_skb->mac_len;\n\n\t\tskb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);\n\n\t\tskb_copy_from_linear_data_offset(head_skb, -tnl_hlen,\n\t\t\t\t\t\t nskb->data - tnl_hlen,\n\t\t\t\t\t\t doffset + tnl_hlen);\n\n\t\tif (nskb->len == len + doffset)\n\t\t\tgoto perform_csum_check;\n\n\t\tif (!sg) {\n\t\t\tnskb->ip_summed = CHECKSUM_NONE;\n\t\t\tnskb->csum = skb_copy_and_csum_bits(head_skb, offset,\n\t\t\t\t\t\t\t skb_put(nskb, len),\n\t\t\t\t\t\t\t len, 0);\n\t\t\tcontinue;\n\t\t}\n\n\t\tnskb_frag = skb_shinfo(nskb)->frags;\n\n\t\tskb_copy_from_linear_data_offset(head_skb, offset,\n\t\t\t\t\t\t skb_put(nskb, hsize), hsize);\n\n\t\tskb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &\n\t\t\tSKBTX_SHARED_FRAG;\n\n\t\twhile (pos < offset + len) {\n\t\t\tif (i >= nfrags) {\n\t\t\t\tBUG_ON(skb_headlen(list_skb));\n\n\t\t\t\ti = 0;\n\t\t\t\tnfrags = skb_shinfo(list_skb)->nr_frags;\n\t\t\t\tfrag = skb_shinfo(list_skb)->frags;\n\n\t\t\t\tBUG_ON(!nfrags);\n\n\t\t\t\tlist_skb = list_skb->next;\n\t\t\t}\n\n\t\t\tif (unlikely(skb_shinfo(nskb)->nr_frags >=\n\t\t\t\t MAX_SKB_FRAGS)) {\n\t\t\t\tnet_warn_ratelimited(\n\t\t\t\t\t\"skb_segment: too many frags: %u %u\\n\",\n\t\t\t\t\tpos, mss);\n\t\t\t\tgoto err;\n\t\t\t}\n\n\t\t\t*nskb_frag = *frag;\n\t\t\t__skb_frag_ref(nskb_frag);\n\t\t\tsize = skb_frag_size(nskb_frag);\n\n\t\t\tif (pos < offset) {\n\t\t\t\tnskb_frag->page_offset += offset - pos;\n\t\t\t\tskb_frag_size_sub(nskb_frag, offset - pos);\n\t\t\t}\n\n\t\t\tskb_shinfo(nskb)->nr_frags++;\n\n\t\t\tif (pos + size <= offset + len) {\n\t\t\t\ti++;\n\t\t\t\tfrag++;\n\t\t\t\tpos += size;\n\t\t\t} else {\n\t\t\t\tskb_frag_size_sub(nskb_frag, pos + size - (offset + len));\n\t\t\t\tgoto skip_fraglist;\n\t\t\t}\n\n\t\t\tnskb_frag++;\n\t\t}\n\nskip_fraglist:\n\t\tnskb->data_len = len - hsize;\n\t\tnskb->len += nskb->data_len;\n\t\tnskb->truesize += nskb->data_len;\n\nperform_csum_check:\n\t\tif (!csum) {\n\t\t\tnskb->csum = skb_checksum(nskb, doffset,\n\t\t\t\t\t\t nskb->len - doffset, 0);\n\t\t\tnskb->ip_summed = CHECKSUM_NONE;\n\t\t}\n\t} while ((offset += len) < head_skb->len);\n\n\treturn segs;\n\nerr:\n\tkfree_skb_list(segs);\n\treturn ERR_PTR(err);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[380, 412]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[380, 412]]}, "_func_name": "skb_segment", "_file_name": "net/core/skbuff.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_least_used_nsp(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = 'showvlun -a -showcols Port'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n # in use count 11 12\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])\n self.assertEqual(nsp, '0:2:1')\n\n # in use count 11 10\n nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])\n self.assertEqual(nsp, '1:2:1')\n\n # in use count 0 10\n nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])\n self.assertEqual(nsp, '1:1:1')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[282, 335]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[282, 335]]}, "_func_name": "test_get_least_used_nsp", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,\n struct _7z_folder *f, size_t numFolders)\n{\n\tconst unsigned char *p;\n\tuint64_t *usizes;\n\tsize_t unpack_streams;\n\tint type;\n\tunsigned i;\n\tuint32_t numDigests;\n\n\tmemset(ss, 0, sizeof(*ss));\n\n\tfor (i = 0; i < numFolders; i++)\n\t\tf[i].numUnpackStreams = 1;\n\n\tif ((p = header_bytes(a, 1)) == NULL)\n\t\treturn (-1);\n\ttype = *p;\n\n\tif (type == kNumUnPackStream) {\n\t\tunpack_streams = 0;\n\t\tfor (i = 0; i < numFolders; i++) {\n\t\t\tif (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0)\n\t\t\t\treturn (-1);\n\t\t\tif (UMAX_ENTRY < f[i].numUnpackStreams)\n\t\t\t\treturn (-1);\n\t\t\tif (unpack_streams > SIZE_MAX - UMAX_ENTRY) {\n\t\t\t\treturn (-1);\n\t\t\t}\n\t\t\tunpack_streams += (size_t)f[i].numUnpackStreams;\n\t\t}\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t} else\n\t\tunpack_streams = numFolders;\n\n\tss->unpack_streams = unpack_streams;\n\tif (unpack_streams) {\n\t\tss->unpackSizes = calloc(unpack_streams,\n\t\t sizeof(*ss->unpackSizes));\n\t\tss->digestsDefined = calloc(unpack_streams,\n\t\t sizeof(*ss->digestsDefined));\n\t\tss->digests = calloc(unpack_streams,\n\t\t sizeof(*ss->digests));\n\t\tif (ss->unpackSizes == NULL || ss->digestsDefined == NULL ||\n\t\t ss->digests == NULL)\n\t\t\treturn (-1);\n\t}\n\n\tusizes = ss->unpackSizes;\n\tfor (i = 0; i < numFolders; i++) {\n\t\tunsigned pack;\n\t\tuint64_t sum;\n\n\t\tif (f[i].numUnpackStreams == 0)\n\t\t\tcontinue;\n\n\t\tsum = 0;\n\t\tif (type == kSize) {\n\t\t\tfor (pack = 1; pack < f[i].numUnpackStreams; pack++) {\n\t\t\t\tif (parse_7zip_uint64(a, usizes) < 0)\n\t\t\t\t\treturn (-1);\n\t\t\t\tsum += *usizes++;\n\t\t\t}\n\t\t}\n\t\t*usizes++ = folder_uncompressed_size(&f[i]) - sum;\n\t}\n\n\tif (type == kSize) {\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t}\n\n\tfor (i = 0; i < unpack_streams; i++) {\n\t\tss->digestsDefined[i] = 0;\n\t\tss->digests[i] = 0;\n\t}\n\n\tnumDigests = 0;\n\tfor (i = 0; i < numFolders; i++) {\n\t\tif (f[i].numUnpackStreams != 1 || !f[i].digest_defined)\n\t\t\tnumDigests += (uint32_t)f[i].numUnpackStreams;\n\t}\n\n\tif (type == kCRC) {\n\t\tstruct _7z_digests tmpDigests;\n\t\tunsigned char *digestsDefined = ss->digestsDefined;\n\t\tuint32_t * digests = ss->digests;\n\t\tint di = 0;\n\n\t\tmemset(&tmpDigests, 0, sizeof(tmpDigests));\n\t\tif (read_Digests(a, &(tmpDigests), numDigests) < 0) {\n\t\t\tfree_Digest(&tmpDigests);\n\t\t\treturn (-1);\n\t\t}\n\t\tfor (i = 0; i < numFolders; i++) {\n\t\t\tif (f[i].numUnpackStreams == 1 && f[i].digest_defined) {\n\t\t\t\t*digestsDefined++ = 1;\n\t\t\t\t*digests++ = f[i].digest;\n\t\t\t} else {\n\t\t\t\tunsigned j;\n\n\t\t\t\tfor (j = 0; j < f[i].numUnpackStreams;\n\t\t\t\t j++, di++) {\n\t\t\t\t\t*digestsDefined++ =\n\t\t\t\t\t tmpDigests.defineds[di];\n\t\t\t\t\t*digests++ =\n\t\t\t\t\t tmpDigests.digests[di];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfree_Digest(&tmpDigests);\n\t\tif ((p = header_bytes(a, 1)) == NULL)\n\t\t\treturn (-1);\n\t\ttype = *p;\n\t}\n\n\t/*\n\t * Must be kEnd.\n\t */\n\tif (type != kEnd)\n\t\treturn (-1);\n\treturn (0);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "read_SubStreamsInfo", "_file_name": "libarchive/archive_read_support_format_7zip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @auth.public\n def get(self, build_id):\n try:\n build_id = int(build_id)\n except ValueError:\n self.response.write('invalid build id')\n self.abort(400)\n\n build = model.Build.get_by_id(build_id)\n can_view = build and user.can_view_build_async(build).get_result()\n\n if not can_view:\n if auth.get_current_identity().is_anonymous:\n return self.redirect(self.create_login_url(self.request.url))\n self.response.write('build %d not found' % build_id)\n self.abort(404)\n\n return self.redirect(str(build.url))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "appengine/cr-buildbucket/handlers.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mode_init(self, request):\n \"\"\"\n This is called by render_POST when the client requests an init\n mode operation (at startup)\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = request.args.get('csessid')[0]\n\n remote_addr = request.getClientIP()\n host_string = \"%s (%s:%s)\" % (_SERVERNAME, request.getRequestHostname(), request.getHost().port)\n\n sess = AjaxWebClientSession()\n sess.client = self\n sess.init_session(\"ajax/comet\", remote_addr, self.sessionhandler)\n\n sess.csessid = csessid\n csession = _CLIENT_SESSIONS(session_key=sess.csessid)\n uid = csession and csession.get(\"webclient_authenticated_uid\", False)\n if uid:\n # the client session is already logged in\n sess.uid = uid\n sess.logged_in = True\n\n sess.sessionhandler.connect(sess)\n\n self.last_alive[csessid] = (time.time(), False)\n if not self.keep_alive:\n # the keepalive is not running; start it.\n self.keep_alive = LoopingCall(self._keepalive)\n self.keep_alive.start(_KEEPALIVE, now=False)\n\n return jsonify({'msg': host_string, 'csessid': csessid})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[230, 279]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[230, 279]]}, "_func_name": "mode_init", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def is_safe_url(url, host=None):\n \"\"\"\n Return ``True`` if the url is a safe redirection (i.e. it doesn't point to\n a different host and uses a safe scheme).\n\n Always returns ``False`` on an empty url.\n \"\"\"\n if url is not None:\n url = url.strip()\n if not url:\n return False\n # Chrome treats \\ completely as /\n url = url.replace('\\\\', '/')\n # Chrome considers any URL with more than two slashes to be absolute, but\n # urlparse is not so flexible. Treat any url with three slashes as unsafe.\n if url.startswith('///'):\n return False\n url_info = urlparse(url)\n # Forbid URLs like http:///example.com - with a scheme, but without a hostname.\n # In that URL, example.com is not the hostname but, a path component. However,\n # Chrome will still consider example.com to be the hostname, so we must not\n # allow this syntax.\n if not url_info.netloc and url_info.scheme:\n return False\n # Forbid URLs that start with control characters. Some browsers (like\n # Chrome) ignore quite a few control characters at the start of a\n # URL and might consider the URL as scheme relative.\n if unicodedata.category(url[0])[0] == 'C':\n return False\n return ((not url_info.netloc or url_info.netloc == host) and\n (not url_info.scheme or url_info.scheme in ['http', 'https']))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[308, 1365]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[308, 1365]]}, "_func_name": "is_safe_url", "_file_name": "django/utils/http.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp)\n{\n ExceptionInfo\n *exception;\n\n int\n bit;\n\n ssize_t\n x;\n\n register PixelPacket\n *q;\n\n IndexPacket\n index;\n\n register IndexPacket\n *indexes;\n\n exception=(&image->exception);\n switch (bpp)\n {\n case 1: /* Convert bitmap scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-7); x+=8)\n {\n for (bit=0; bit < 8; bit++)\n {\n index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n p++;\n }\n if ((image->columns % 8) != 0)\n {\n for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)\n {\n index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);\n SetPixelIndex(indexes+x+bit,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n p++;\n }\n if (!SyncAuthenticPixels(image,exception))\n break;\n break;\n }\n case 2: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=4)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p) & 0x3);\n SetPixelIndex(indexes+x+1,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if ((image->columns % 4) != 0)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n if ((image->columns % 4) >= 1)\n\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n if ((image->columns % 4) >= 2)\n\n {\n index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n }\n }\n p++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n break;\n }\n\n case 4: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n indexes=GetAuthenticIndexQueue(image);\n for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n q++;\n index=ConstrainColormapIndex(image,(*p) & 0x0f);\n SetPixelIndex(indexes+x+1,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if ((image->columns % 2) != 0)\n {\n index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n break;\n }\n case 8: /* Convert PseudoColor scanline. */\n {\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL) break;\n indexes=GetAuthenticIndexQueue(image);\n\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n index=ConstrainColormapIndex(image,*p);\n SetPixelIndex(indexes+x,index);\n SetPixelRGBO(q,image->colormap+(ssize_t) index);\n p++;\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n }\n break;\n\n case 24: /* Convert DirectColor scanline. */\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n q++;\n }\n if (!SyncAuthenticPixels(image,exception))\n break;\n break;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "InsertRow", "_file_name": "coders/wpg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def check_and_update_ranks(self, scene):\n # There are 2 cases here:\n # 1) Ranks have never been calculated for this scene before\n # - This means we need to calculate what the ranks were every month of this scenes history\n # - We should only do this if ranks don't already exist for this scene\n # 2) Ranks have been calculated for this scene before\n # - We already have bulk ranks. We should check if it has been more than 1 month since we last\n # calculated ranks. If so, calculate again with the brackets that have come out this month\n\n LOG.info('About to check if ranks need updating for {}'.format(scene))\n # First, do we have any ranks for this scene already?\n sql = 'select count(*) from ranks where scene=\"{scene}\";'\n args = {'scene': scene}\n res = self.db.exec(sql, args)\n count = res[0][0]\n\n n = 5 if (scene == 'pro' or scene == 'pro_wiiu') else constants.TOURNAMENTS_PER_RANK\n if count == 0:\n LOG.info('Detected that we need to bulk update ranks for {}'.format(scene))\n # Alright, we have nothing. Bulk update ranks\n first_month = bracket_utils.get_first_month(self.db, scene)\n last_month = bracket_utils.get_last_month(self.db, scene)\n \n # Iterate through all tournaments going month by month, and calculate ranks\n months = bracket_utils.iter_months(first_month, last_month, include_first=False, include_last=True)\n for month in months:\n urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)\n self.process_ranks(scene, urls, month)\n else:\n\n # Get the date of the last time we calculated ranks\n sql = \"select date from ranks where scene='{scene}' order by date desc limit 1;\"\n args = {'scene': scene}\n res = self.db.exec(sql, args)\n last_rankings_date = res[0][0]\n\n # Check to see if it's been more than 1 month since we last calculated ranks\n more_than_one_month = bracket_utils.has_month_passed(last_rankings_date)\n if more_than_one_month:\n # Get only the last n tournaments, so it doesn't take too long to process\n today = datetime.datetime.today().strftime('%Y-%m-%d')\n msg = 'Detected that we need up update monthly ranks for {}, on {}'.format(scene, today)\n LOG.info(msg)\n\n # We should only ever calculate ranks on the 1st. If today is not the first, log error\n if not today.split('-')[-1] == '1':\n LOG.exc('We are calculating ranks today, {}, but it isnt the first'.format(today))\n\n months = bracket_utils.iter_months(last_rankings_date, today, include_first=False, include_last=True)\n for month in months:\n # Make sure that we actually have matches during this month\n # Say we are trying to calculate ranks for 2018-05-01, the player would need to have matches during 2018-04-01, 2018-04-30\n prev_date = bracket_utils.get_previous_month(month)\n brackets_during_month = bracket_utils.get_tournaments_during_month(self.db, scene, prev_date)\n\n if len(brackets_during_month) > 0:\n tweet('Calculating {} ranks for {}'.format(month, scene))\n urls, _ = bracket_utils.get_n_tournaments_before_date(self.db, scene, month, n)\n self.process_ranks(scene, urls, month)\n\n else:\n LOG.info('It has not yet been 1 month since we calculated ranks for {}. Skipping'.format(scene))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "check_and_update_ranks", "_file_name": "process_data.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " bool handleBackslash(signed char& out) {\n char ch = *p++;\n switch (ch) {\n case 0: return false;\n case '\"': out = ch; return true;\n case '\\\\': out = ch; return true;\n case '/': out = ch; return true;\n case 'b': out = '\\b'; return true;\n case 'f': out = '\\f'; return true;\n case 'n': out = '\\n'; return true;\n case 'r': out = '\\r'; return true;\n case 't': out = '\\t'; return true;\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {\n uint16_t u16cp = 0;\n for (int i = 0; i < 4; i++) {\n auto const hexv = dehexchar(*p++);\n if (hexv < 0) return false; // includes check for end of string\n u16cp <<= 4;\n u16cp |= hexv;\n }\n if (u16cp > 0x7f) {\n return false;\n } else {\n out = u16cp;\n return true;\n }\n }\n }\n default: return false;\n }\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::SimpleParser::handleBackslash", "_file_name": "hphp/runtime/ext/json/JSON_parser.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def canonicalize(self):\n \"\"\"::\n\n path = path.canonicalize()\n\n Canonicalize path. ::\n\n # \"/foo/baz\"\n Pyjo.Path.new('/foo/./bar/../baz').canonicalize()\n\n # \"/../baz\"\n Pyjo.Path.new('/foo/../bar/../../baz').canonicalize()\n \"\"\"\n parts = self.parts\n i = 0\n while i < len(parts):\n if parts[i] == '.' or parts[i] == '':\n parts.pop(i)\n elif i < 1 or parts[i] != '..' or parts[i - 1] == '..':\n i += 1\n else:\n i -= 1\n parts.pop(i)\n parts.pop(i)\n\n if not parts:\n self.trailing_slash = False\n\n return self", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[83, 113]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[83, 113]]}, "_func_name": "canonicalize", "_file_name": "Pyjo/Path.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,\n AVStream *st, char *mime)\n{\n int number_of_streams = avio_rb16(pb);\n int number_of_mdpr;\n int i, ret;\n unsigned size2;\n for (i = 0; i 0) {\n st2 = avformat_new_stream(s, NULL);\n if (!st2) {\n ret = AVERROR(ENOMEM);\n return ret;\n }\n st2->id = st->id + (i<<16);\n st2->codecpar->bit_rate = st->codecpar->bit_rate;\n st2->start_time = st->start_time;\n st2->duration = st->duration;\n st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;\n st2->priv_data = ff_rm_alloc_rmstream();\n if (!st2->priv_data)\n return AVERROR(ENOMEM);\n } else\n st2 = st;\n\n size2 = avio_rb32(pb);\n ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,\n size2, NULL);\n if (ret < 0)\n return ret;\n }\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rm_read_multi", "_file_name": "libavformat/rmdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int snd_seq_device_dev_free(struct snd_device *device)\n{\n\tstruct snd_seq_device *dev = device->device_data;\n\n\tput_device(&dev->dev);\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[116, 140]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[116, 140]]}, "_func_name": "snd_seq_device_dev_free", "_file_name": "sound/core/seq_device.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_workflow(request):\n workflow_id = request.GET.get('workflow')\n \n if workflow_id:\n wid = {}\n if workflow_id.isdigit():\n wid['id'] = workflow_id\n else:\n wid['uuid'] = workflow_id\n doc = Document2.objects.get(type='oozie-workflow2', **wid)\n workflow = Workflow(document=doc)\n else:\n doc = None\n workflow = Workflow()\n workflow.set_workspace(request.user)\n workflow.check_workspace(request.fs, request.user)\n \n workflow_data = workflow.get_data()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n return render('editor/workflow_editor.mako', request, {\n 'layout_json': json.dumps(workflow_data['layout']),\n 'workflow_json': json.dumps(workflow_data['workflow']),\n 'credentials_json': json.dumps(credentials.credentials.keys()),\n 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'subworkflows_json': json.dumps(_get_workflows(request.user)),\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[743, 1005], [1055, 1124]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[743, 1005], [1055, 1124]]}, "_func_name": "edit_workflow", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int changedline (const Proto *p, int oldpc, int newpc) {\n if (p->lineinfo == NULL) /* no debug information? */\n return 0;\n while (oldpc++ < newpc) {\n if (p->lineinfo[oldpc] != 0)\n return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));\n }\n return 0; /* no line changes between positions */\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "changedline", "_file_name": "ldebug.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _delete_3par_host(self, hostname):\n self._cli_run(['removehost', hostname])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_delete_3par_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ipxitf_ioctl(unsigned int cmd, void __user *arg)\n{\n\tint rc = -EINVAL;\n\tstruct ifreq ifr;\n\tint val;\n\n\tswitch (cmd) {\n\tcase SIOCSIFADDR: {\n\t\tstruct sockaddr_ipx *sipx;\n\t\tstruct ipx_interface_definition f;\n\n\t\trc = -EFAULT;\n\t\tif (copy_from_user(&ifr, arg, sizeof(ifr)))\n\t\t\tbreak;\n\t\tsipx = (struct sockaddr_ipx *)&ifr.ifr_addr;\n\t\trc = -EINVAL;\n\t\tif (sipx->sipx_family != AF_IPX)\n\t\t\tbreak;\n\t\tf.ipx_network = sipx->sipx_network;\n\t\tmemcpy(f.ipx_device, ifr.ifr_name,\n\t\t\tsizeof(f.ipx_device));\n\t\tmemcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);\n\t\tf.ipx_dlink_type = sipx->sipx_type;\n\t\tf.ipx_special = sipx->sipx_special;\n\n\t\tif (sipx->sipx_action == IPX_DLTITF)\n\t\t\trc = ipxitf_delete(&f);\n\t\telse\n\t\t\trc = ipxitf_create(&f);\n\t\tbreak;\n\t}\n\tcase SIOCGIFADDR: {\n\t\tstruct sockaddr_ipx *sipx;\n\t\tstruct ipx_interface *ipxif;\n\t\tstruct net_device *dev;\n\n\t\trc = -EFAULT;\n\t\tif (copy_from_user(&ifr, arg, sizeof(ifr)))\n\t\t\tbreak;\n\t\tsipx = (struct sockaddr_ipx *)&ifr.ifr_addr;\n\t\tdev = __dev_get_by_name(&init_net, ifr.ifr_name);\n\t\trc = -ENODEV;\n\t\tif (!dev)\n\t\t\tbreak;\n\t\tipxif = ipxitf_find_using_phys(dev,\n\t\t\t\t\t ipx_map_frame_type(sipx->sipx_type));\n\t\trc = -EADDRNOTAVAIL;\n\t\tif (!ipxif)\n\t\t\tbreak;\n\n\t\tsipx->sipx_family\t= AF_IPX;\n\t\tsipx->sipx_network\t= ipxif->if_netnum;\n\t\tmemcpy(sipx->sipx_node, ipxif->if_node,\n\t\t\tsizeof(sipx->sipx_node));\n\t\trc = 0;\n\t\tif (copy_to_user(arg, &ifr, sizeof(ifr)))\n\t\t\trc = -EFAULT;\n\t\tipxitf_put(ipxif);\n\t\tbreak;\n\t}\n\tcase SIOCAIPXITFCRT:\n\t\trc = -EFAULT;\n\t\tif (get_user(val, (unsigned char __user *) arg))\n\t\t\tbreak;\n\t\trc = 0;\n\t\tipxcfg_auto_create_interfaces = val;\n\t\tbreak;\n\tcase SIOCAIPXPRISLT:\n\t\trc = -EFAULT;\n\t\tif (get_user(val, (unsigned char __user *) arg))\n\t\t\tbreak;\n\t\trc = 0;\n\t\tipxcfg_set_auto_select(val);\n\t\tbreak;\n\t}\n\n\treturn rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ipxitf_ioctl", "_file_name": "net/ipx/af_ipx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes)\n{\n UINT8* ptr;\n int framesize;\n int c, chunks, advance;\n int l, lines;\n int i, j, x = 0, y, ymax;\n\n /* If not even the chunk size is present, we'd better leave */\n\n if (bytes < 4)\n\treturn 0;\n\n /* We don't decode anything unless we have a full chunk in the\n input buffer */\n\n ptr = buf;\n\n framesize = I32(ptr);\n if (framesize < I32(ptr))\n\treturn 0;\n\n /* Make sure this is a frame chunk. The Python driver takes\n case of other chunk types. */\n\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }\n if (I16(ptr+4) != 0xF1FA) {\n\tstate->errcode = IMAGING_CODEC_UNKNOWN;\n\treturn -1;\n }\n\n chunks = I16(ptr+6);\n ptr += 16;\n bytes -= 16;\n\n /* Process subchunks */\n for (c = 0; c < chunks; c++) {\n\tUINT8* data;\n\tif (bytes < 10) {\n\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t return -1;\n\t}\n\tdata = ptr + 6;\n\tswitch (I16(ptr+4)) {\n\tcase 4: case 11:\n\t /* FLI COLOR chunk */\n\t break; /* ignored; handled by Python code */\n\tcase 7:\n\t /* FLI SS2 chunk (word delta) */\n\t lines = I16(data); data += 2;\n\t for (l = y = 0; l < lines && y < state->ysize; l++, y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tint p, packets;\n\t\tpackets = I16(data); data += 2;\n\t\twhile (packets & 0x8000) {\n\t\t /* flag word */\n\t\t if (packets & 0x4000) {\n\t\t\ty += 65536 - packets; /* skip lines */\n\t\t\tif (y >= state->ysize) {\n\t\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t\t return -1;\n\t\t\t}\n\t\t\tbuf = (UINT8*) im->image[y];\n\t\t } else {\n\t\t\t/* store last byte (used if line width is odd) */\n\t\t\tbuf[state->xsize-1] = (UINT8) packets;\n\t\t }\n\t\t packets = I16(data); data += 2;\n\t\t}\n\t\tfor (p = x = 0; p < packets; p++) {\n\t\t x += data[0]; /* pixel skip */\n\t\t if (data[1] >= 128) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i + i > state->xsize)\n\t\t\t break;\n\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t buf[x++] = data[2];\n\t\t\t buf[x++] = data[3];\n\t\t\t}\n\t\t\tdata += 2 + 2;\n\t\t } else {\n\t\t\ti = 2 * (int) data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(buf + x, data + 2, i);\n\t\t\tdata += 2 + i;\n\t\t\tx += i;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (l < lines) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 12:\n\t /* FLI LC chunk (byte delta) */\n\t y = I16(data); ymax = y + I16(data+2); data += 4;\n\t for (; y < ymax && y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tint p, packets = *data++;\n\t\tfor (p = x = 0; p < packets; p++, x += i) {\n\t\t x += data[0]; /* skip pixels */\n\t\t if (data[1] & 0x80) {\n\t\t\ti = 256-data[1]; /* run */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemset(out + x, data[2], i);\n\t\t\tdata += 3;\n\t\t } else {\n\t\t\ti = data[1]; /* chunk */\n\t\t\tif (x + i > state->xsize)\n\t\t\t break;\n\t\t\tmemcpy(out + x, data + 2, i);\n\t\t\tdata += i + 2;\n\t\t }\n\t\t}\n\t\tif (p < packets)\n\t\t break; /* didn't process all packets */\n\t }\n\t if (y < ymax) {\n\t\t/* didn't process all lines */\n\t\tstate->errcode = IMAGING_CODEC_OVERRUN;\n\t\treturn -1;\n\t }\n\t break;\n\tcase 13:\n\t /* FLI BLACK chunk */\n\t for (y = 0; y < state->ysize; y++)\n\t\tmemset(im->image[y], 0, state->xsize);\n\t break;\n\tcase 15:\n\t /* FLI BRUN chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* out = (UINT8*) im->image[y];\n\t\tdata += 1; /* ignore packetcount byte */\n\t\tfor (x = 0; x < state->xsize; x += i) {\n\t\t if (data[0] & 0x80) {\n\t\t\ti = 256 - data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemcpy(out + x, data + 1, i);\n\t\t\tdata += i + 1;\n\t\t } else {\n\t\t\ti = data[0];\n\t\t\tif (x + i > state->xsize)\n\t\t\t break; /* safety first */\n\t\t\tmemset(out + x, data[1], i);\n\t\t\tdata += 2;\n\t\t }\n\t\t}\n\t\tif (x != state->xsize) {\n\t\t /* didn't unpack whole line */\n\t\t state->errcode = IMAGING_CODEC_OVERRUN;\n\t\t return -1;\n\t\t}\n\t }\n\t break;\n\tcase 16:\n\t /* COPY chunk */\n\t for (y = 0; y < state->ysize; y++) {\n\t\tUINT8* buf = (UINT8*) im->image[y];\n\t\tmemcpy(buf, data, state->xsize);\n\t\tdata += state->xsize;\n\t }\n\t break;\n\tcase 18:\n\t /* PSTAMP chunk */\n\t break; /* ignored */\n\tdefault:\n\t /* unknown chunk */\n\t /* printf(\"unknown FLI/FLC chunk: %d\\n\", I16(ptr+4)); */\n\t state->errcode = IMAGING_CODEC_UNKNOWN;\n\t return -1;\n\t}\n\tadvance = I32(ptr);\n\tptr += advance;\n\tbytes -= advance;\n }\n\n return -1; /* end of frame */\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ImagingFliDecode", "_file_name": "src/libImaging/FliDecode.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "PHP_FUNCTION(unserialize)\n{\n\tchar *buf = NULL;\n\tsize_t buf_len;\n\tconst unsigned char *p;\n\tphp_unserialize_data_t var_hash;\n\tzval *options = NULL, *classes = NULL;\n\tHashTable *class_hash = NULL;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS(), \"s|a\", &buf, &buf_len, &options) == FAILURE) {\n\t\tRETURN_FALSE;\n\t}\n\n\tif (buf_len == 0) {\n\t\tRETURN_FALSE;\n\t}\n\n\tp = (const unsigned char*) buf;\n\tPHP_VAR_UNSERIALIZE_INIT(var_hash);\n\tif(options != NULL) {\n\t\tclasses = zend_hash_str_find(Z_ARRVAL_P(options), \"allowed_classes\", sizeof(\"allowed_classes\")-1);\n\t\tif(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {\n\t\t\tALLOC_HASHTABLE(class_hash);\n\t\t\tzend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);\n\t\t}\n\t\tif(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {\n\t\t\tzval *entry;\n\t\t\tzend_string *lcname;\n\n\t\t\tZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {\n\t\t\t\tconvert_to_string_ex(entry);\n\t\t\t\tlcname = zend_string_tolower(Z_STR_P(entry));\n\t\t\t\tzend_hash_add_empty_element(class_hash, lcname);\n\t\t zend_string_release(lcname);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t}\n\t}\n\n\tif (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {\n\t\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\t\tif (class_hash) {\n\t\t\tzend_hash_destroy(class_hash);\n\t\t\tFREE_HASHTABLE(class_hash);\n\t\t}\n\t\tzval_ptr_dtor(return_value);\n\t\tif (!EG(exception)) {\n\t\t\tphp_error_docref(NULL, E_NOTICE, \"Error at offset \" ZEND_LONG_FMT \" of %zd bytes\",\n\t\t\t\t(zend_long)((char*)p - buf), buf_len);\n\t\t}\n\t\tRETURN_FALSE;\n\t}\n\t/* We should keep an reference to return_value to prevent it from being dtor\n\t in case nesting calls to unserialize */\n\tvar_push_dtor(&var_hash, return_value);\n\n\tPHP_VAR_UNSERIALIZE_DESTROY(var_hash);\n\tif (class_hash) {\n\t\tzend_hash_destroy(class_hash);\n\t\tFREE_HASHTABLE(class_hash);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1140, 1226], [1356, 1387], [1563, 1726]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1140, 1226], [1356, 1387], [1563, 1726]]}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/standard/var.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,\n\t\t\t\tvoid __user *buffer, size_t *lenp,\n\t\t\t\tloff_t *ppos)\n{\n\tint ret = proc_dointvec(table, write, buffer, lenp, ppos);\n\n\tif (ret || !write)\n\t\treturn ret;\n\n\tif (sysctl_perf_cpu_time_max_percent == 100 ||\n\t sysctl_perf_cpu_time_max_percent == 0) {\n\t\tprintk(KERN_WARNING\n\t\t \"perf: Dynamic interrupt throttling disabled, can hang your system!\\n\");\n\t\tWRITE_ONCE(perf_sample_allowed_ns, 0);\n\t} else {\n\t\tupdate_perf_cpu_limits();\n\t}\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[133, 193]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[133, 193]]}, "_func_name": "perf_cpu_time_max_percent_handler", "_file_name": "kernel/events/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def on_save(self):\n connection = get_connection()\n cursor = connection.cursor()\n cursor.execute(\n f\"insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values ('{self.ip_address}', '{self.user_agent}', '{self.referrer}', '{self.full_path}', '{self.visit_time}');\")\n connection.commit()\n connection.close()\n return 0", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[122, 328]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[122, 328]]}, "_func_name": "on_save", "_file_name": "experimental/python/buford/model/visitor.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def list_editor_workflows(request): \n workflows = [d.content_object.to_dict() for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n return render('editor/list_editor_workflows.mako', request, {\n 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML)\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "list_editor_workflows", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int nfc_genl_deactivate_target(struct sk_buff *skb,\n\t\t\t\t struct genl_info *info)\n{\n\tstruct nfc_dev *dev;\n\tu32 device_idx, target_idx;\n\tint rc;\n\n\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||\n\t !info->attrs[NFC_ATTR_TARGET_INDEX])\n\t\treturn -EINVAL;\n\n\tdevice_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);\n\n\tdev = nfc_get_device(device_idx);\n\tif (!dev)\n\t\treturn -ENODEV;\n\n\ttarget_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);\n\n\trc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);\n\n\tnfc_put_device(dev);\n\treturn rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "nfc_genl_deactivate_target", "_file_name": "net/nfc/netlink.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum,\n TSK_DADDR_T numblock, int32_t sec_skew)\n{\n TSK_FS_META *fs_meta;\n TSK_FS_FILE *fs_file;\n YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs;\n char ls[12];\n YAFFSFS_PRINT_ADDR print;\n char timeBuf[128];\n YaffsCacheObject * obj = NULL;\n YaffsCacheVersion * version = NULL;\n YaffsHeader * header = NULL;\n\n yaffscache_version_find_by_inode(yfs, inum, &version, &obj);\n\n if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {\n return 1;\n }\n fs_meta = fs_file->meta;\n\n tsk_fprintf(hFile, \"inode: %\" PRIuINUM \"\\n\", inum);\n tsk_fprintf(hFile, \"%sAllocated\\n\",\n (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? \"\" : \"Not \");\n\n if (fs_meta->link)\n tsk_fprintf(hFile, \"symbolic link to: %s\\n\", fs_meta->link);\n\n tsk_fprintf(hFile, \"uid / gid: %\" PRIuUID \" / %\" PRIuGID \"\\n\",\n fs_meta->uid, fs_meta->gid);\n\n tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls));\n tsk_fprintf(hFile, \"mode: %s\\n\", ls);\n\n tsk_fprintf(hFile, \"size: %\" PRIdOFF \"\\n\", fs_meta->size);\n tsk_fprintf(hFile, \"num of links: %d\\n\", fs_meta->nlink);\n\n if(version != NULL){\n yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset);\n if(header != NULL){\n tsk_fprintf(hFile, \"Name: %s\\n\", header->name);\n }\n }\n\n if (sec_skew != 0) {\n tsk_fprintf(hFile, \"\\nAdjusted Inode Times:\\n\");\n fs_meta->mtime -= sec_skew;\n fs_meta->atime -= sec_skew;\n fs_meta->ctime -= sec_skew;\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n fs_meta->mtime += sec_skew;\n fs_meta->atime += sec_skew;\n fs_meta->ctime += sec_skew;\n\n tsk_fprintf(hFile, \"\\nOriginal Inode Times:\\n\");\n }\n else {\n tsk_fprintf(hFile, \"\\nInode Times:\\n\");\n }\n\n tsk_fprintf(hFile, \"Accessed:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->atime, timeBuf));\n tsk_fprintf(hFile, \"File Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->mtime, timeBuf));\n tsk_fprintf(hFile, \"Inode Modified:\\t%s\\n\",\n tsk_fs_time_to_str(fs_meta->ctime, timeBuf));\n\n if(version != NULL){\n tsk_fprintf(hFile, \"\\nHeader Chunk:\\n\");\n tsk_fprintf(hFile, \"%\" PRIuDADDR \"\\n\", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size)));\n }\n\n if (numblock > 0) {\n TSK_OFF_T lower_size = numblock * fs->block_size;\n fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size);\n }\n tsk_fprintf(hFile, \"\\nData Chunks:\\n\");\n\n\n if (flags & TSK_FS_ISTAT_RUNLIST){\n const TSK_FS_ATTR *fs_attr_default =\n tsk_fs_file_attr_get_type(fs_file,\n TSK_FS_ATTR_TYPE_DEFAULT, 0, 0);\n if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) {\n if (tsk_fs_attr_print(fs_attr_default, hFile)) {\n tsk_fprintf(hFile, \"\\nError creating run lists \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n }\n }\n else {\n print.idx = 0;\n print.hFile = hFile;\n\n if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY,\n (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) {\n tsk_fprintf(hFile, \"\\nError reading file: \");\n tsk_error_print(hFile);\n tsk_error_reset();\n }\n else if (print.idx != 0) {\n tsk_fprintf(hFile, \"\\n\");\n }\n }\n\n tsk_fs_file_close(fs_file);\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "yaffsfs_istat", "_file_name": "tsk/fs/yaffs.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "lexer_process_char_literal (parser_context_t *context_p, /**< context */\n const uint8_t *char_p, /**< characters */\n size_t length, /**< length of string */\n uint8_t literal_type, /**< final literal type */\n bool has_escape) /**< has escape sequences */\n{\n parser_list_iterator_t literal_iterator;\n lexer_literal_t *literal_p;\n uint32_t literal_index = 0;\n\n JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL\n || literal_type == LEXER_STRING_LITERAL);\n\n JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);\n JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);\n\n parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);\n\n while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)\n {\n if (literal_p->type == literal_type\n && literal_p->prop.length == length\n && memcmp (literal_p->u.char_p, char_p, length) == 0)\n {\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);\n return;\n }\n\n literal_index++;\n }\n\n JERRY_ASSERT (literal_index == context_p->literal_count);\n\n if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)\n {\n parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);\n }\n\n literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);\n literal_p->prop.length = (uint16_t) length;\n literal_p->type = literal_type;\n literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;\n\n if (has_escape)\n {\n literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);\n memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);\n }\n else\n {\n literal_p->u.char_p = char_p;\n }\n\n context_p->lit_object.literal_p = literal_p;\n context_p->lit_object.index = (uint16_t) literal_index;\n context_p->literal_count++;\n} /* lexer_process_char_literal */", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1556, 1648]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1556, 1648]]}, "_func_name": "lexer_process_char_literal", "_file_name": "jerry-core/parser/js/js-lexer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get(self, user_id):\n \"\"\" Fetch data for user with corresponding user_id \"\"\"\n return database_utilities.execute_query(f\"\"\"select * from users where user_id = %s\"\"\", (user_id, ))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_previous_yields(self, inverter_serial):\n query = '''\n SELECT TimeStamp, EToday, ETotal\n FROM Inverters\n WHERE Serial=?\n '''\n self.c.execute(query, (inverter_serial,))\n data = self.c.fetchone()\n return data[0], data[1], data[2]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_previous_yields", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool check_client_passwd(PgSocket *client, const char *passwd)\n{\n\tchar md5[MD5_PASSWD_LEN + 1];\n\tconst char *correct;\n\tPgUser *user = client->auth_user;\n\n\t/* auth_user may be missing */\n\tif (!user) {\n\t\tslog_error(client, \"Password packet before auth packet?\");\n\t\treturn false;\n\t}\n\n\t/* disallow empty passwords */\n\tif (!*passwd || !*user->passwd)\n\t\treturn false;\n\n\tswitch (cf_auth_type) {\n\tcase AUTH_PLAIN:\n\t\treturn strcmp(user->passwd, passwd) == 0;\n\tcase AUTH_CRYPT:\n\t\tcorrect = crypt(user->passwd, (char *)client->tmp_login_salt);\n\t\treturn correct && strcmp(correct, passwd) == 0;\n\tcase AUTH_MD5:\n\t\tif (strlen(passwd) != MD5_PASSWD_LEN)\n\t\t\treturn false;\n\t\tif (!isMD5(user->passwd))\n\t\t\tpg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);\n\t\tpg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);\n\t\treturn strcmp(md5, passwd) == 0;\n\t}\n\treturn false;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "check_client_passwd", "_file_name": "src/client.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int ipxitf_ioctl(unsigned int cmd, void __user *arg)\n{\n\tint rc = -EINVAL;\n\tstruct ifreq ifr;\n\tint val;\n\n\tswitch (cmd) {\n\tcase SIOCSIFADDR: {\n\t\tstruct sockaddr_ipx *sipx;\n\t\tstruct ipx_interface_definition f;\n\n\t\trc = -EFAULT;\n\t\tif (copy_from_user(&ifr, arg, sizeof(ifr)))\n\t\t\tbreak;\n\t\tsipx = (struct sockaddr_ipx *)&ifr.ifr_addr;\n\t\trc = -EINVAL;\n\t\tif (sipx->sipx_family != AF_IPX)\n\t\t\tbreak;\n\t\tf.ipx_network = sipx->sipx_network;\n\t\tmemcpy(f.ipx_device, ifr.ifr_name,\n\t\t\tsizeof(f.ipx_device));\n\t\tmemcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);\n\t\tf.ipx_dlink_type = sipx->sipx_type;\n\t\tf.ipx_special = sipx->sipx_special;\n\n\t\tif (sipx->sipx_action == IPX_DLTITF)\n\t\t\trc = ipxitf_delete(&f);\n\t\telse\n\t\t\trc = ipxitf_create(&f);\n\t\tbreak;\n\t}\n\tcase SIOCGIFADDR: {\n\t\tstruct sockaddr_ipx *sipx;\n\t\tstruct ipx_interface *ipxif;\n\t\tstruct net_device *dev;\n\n\t\trc = -EFAULT;\n\t\tif (copy_from_user(&ifr, arg, sizeof(ifr)))\n\t\t\tbreak;\n\t\tsipx = (struct sockaddr_ipx *)&ifr.ifr_addr;\n\t\tdev = __dev_get_by_name(&init_net, ifr.ifr_name);\n\t\trc = -ENODEV;\n\t\tif (!dev)\n\t\t\tbreak;\n\t\tipxif = ipxitf_find_using_phys(dev,\n\t\t\t\t\t ipx_map_frame_type(sipx->sipx_type));\n\t\trc = -EADDRNOTAVAIL;\n\t\tif (!ipxif)\n\t\t\tbreak;\n\n\t\tsipx->sipx_family\t= AF_IPX;\n\t\tsipx->sipx_network\t= ipxif->if_netnum;\n\t\tmemcpy(sipx->sipx_node, ipxif->if_node,\n\t\t\tsizeof(sipx->sipx_node));\n\t\trc = -EFAULT;\n\t\tif (copy_to_user(arg, &ifr, sizeof(ifr)))\n\t\t\tbreak;\n\t\tipxitf_put(ipxif);\n\t\trc = 0;\n\t\tbreak;\n\t}\n\tcase SIOCAIPXITFCRT:\n\t\trc = -EFAULT;\n\t\tif (get_user(val, (unsigned char __user *) arg))\n\t\t\tbreak;\n\t\trc = 0;\n\t\tipxcfg_auto_create_interfaces = val;\n\t\tbreak;\n\tcase SIOCAIPXPRISLT:\n\t\trc = -EFAULT;\n\t\tif (get_user(val, (unsigned char __user *) arg))\n\t\t\tbreak;\n\t\trc = 0;\n\t\tipxcfg_set_auto_select(val);\n\t\tbreak;\n\t}\n\n\treturn rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1332, 1348], [1392, 1433]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1332, 1348], [1392, 1433]]}, "_func_name": "ipxitf_ioctl", "_file_name": "net/ipx/af_ipx.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_ask(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute(''' SELECT karma FROM people WHERE name=%(name)s ''',\n (name, ))\n karma = cursor.fetchone()\n if karma is None:\n logger.debug('No karma found for name {}'.format(name))\n db.close()\n return karma\n else:\n karma = karma[0]\n logger.debug('karma of {} found for name {}'.format(karma, name))\n db.close()\n return karma\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "karma_ask", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def retrieve_playlist_by_id(id, db):\n db.execute(\n \"SELECT id, name, video_position from playlist WHERE id=%s;\", (id,))\n row = db.fetchone()\n return row", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "retrieve_playlist_by_id", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_tournaments_during_month(db, scene, date):\n y, m, d = date.split('-')\n ym_date = '{}-{}'.format(y, m)\n sql = \"select url, date from matches where scene='{scene}' and date like '%{date}%' group by url, date order by date\"\n args = {'scene': scene, 'date': ym_date}\n res = db.exec(sql, args)\n urls = [r[0] for r in res]\n return urls", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_tournaments_during_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "http_error_t::make_body (int n, const str &si, const str &aux)\n{\n strbuf b;\n str ldesc;\n const str sdesc = xss_escape (http_status.get_desc (n, &ldesc));\n b << \"\\n\"\n << \" \\n\"\n << \" \" << n << \" \" << sdesc << \"\\n\"\n << \" \\n\"\n << \" \\n\"\n << \"

Error \" << n << \" \" << sdesc << \"



\\n\"\n ;\n if (n == HTTP_NOT_FOUND && aux) {\n b << \"The file \" << xss_escape (aux)\n << \" was not found on this server.

\\n\\n\";\n }\n b << \"
\\n\"\n << \" \" << xss_escape (si) << \"\\n\"\n << \"
\\n\"\n << \" \\n\"\n << \"\\n\"\n ;\n return b;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "http_error_t::make_body", "_file_name": "libahttp/err.C", "lang": "c", "label_confidence": "diff-derived"} {"code": "def top_karma(bot, trigger):\n \"\"\"\n Show karma status for the top n number of IRC users.\n \"\"\"\n try:\n top_limit = int(trigger.group(2).strip())\n except ValueError:\n top_limit = 5\n\n query = \"SELECT slug, value FROM nick_values NATURAL JOIN nicknames \\\n WHERE key = 'karma' ORDER BY value DESC LIMIT %d\"\n karmalist = bot.db.execute(query % top_limit).fetchall()\n for user in karmalist:\n bot.say(\"%s == %s\" % (user[0], user[1]))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[281, 400]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[281, 400]]}, "_func_name": "top_karma", "_file_name": "sopel_modules/karma/karma.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def delete_playlist(id, db):\n db.execute(\"DELETE FROM playlist where id={id};\".format(id=id))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[29, 96]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[29, 96]]}, "_func_name": "delete_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;\n\n MagickOffsetType\n offset;\n\n MagickBooleanType\n status;\n\n channel_image=image;\n mask=(Image *) NULL;\n if (layer_info->channel_info[channel].type < -1)\n {\n const char\n *option;\n /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->channel_info[channel].type != -2) ||\n (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)))\n {\n SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);\n return(MagickTrue);\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n mask->matte=MagickFalse;\n channel_image=mask;\n }\n\n offset=TellBlob(image);\n status=MagickTrue;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,psd_info->channels,\n layer_info->channel_info[channel].type,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;\n\n sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,psd_info,\n layer_info->channel_info[channel].type,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,layer_info->channels,\n layer_info->channel_info[channel].type,compression,\n layer_info->channel_info[channel].size-2,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }\n\n SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n layer_info->mask.image=mask;\n return(status);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1110, 1167]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1110, 1167]]}, "_func_name": "ReadPSDChannel", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def init_settings(self, ipython_app, kernel_manager, contents_manager,\n cluster_manager, session_manager, kernel_spec_manager,\n config_manager,\n log, base_url, default_url, settings_overrides,\n jinja_env_options=None):\n\n _template_path = settings_overrides.get(\n \"template_path\",\n ipython_app.template_file_path,\n )\n if isinstance(_template_path, py3compat.string_types):\n _template_path = (_template_path,)\n template_path = [os.path.expanduser(path) for path in _template_path]\n\n jenv_opt = {\"autoescape\": True}\n jenv_opt.update(jinja_env_options if jinja_env_options else {})\n\n env = Environment(loader=FileSystemLoader(template_path), **jenv_opt)\n \n sys_info = get_sys_info()\n if sys_info['commit_source'] == 'repository':\n # don't cache (rely on 304) when working from master\n version_hash = ''\n else:\n # reset the cache on server restart\n version_hash = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n settings = dict(\n # basics\n log_function=log_request,\n base_url=base_url,\n default_url=default_url,\n template_path=template_path,\n static_path=ipython_app.static_file_path,\n static_handler_class = FileFindHandler,\n static_url_prefix = url_path_join(base_url,'/static/'),\n static_handler_args = {\n # don't cache custom.js\n 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],\n },\n version_hash=version_hash,\n \n # authentication\n cookie_secret=ipython_app.cookie_secret,\n login_url=url_path_join(base_url,'/login'),\n login_handler_class=ipython_app.login_handler_class,\n logout_handler_class=ipython_app.logout_handler_class,\n password=ipython_app.password,\n\n # managers\n kernel_manager=kernel_manager,\n contents_manager=contents_manager,\n cluster_manager=cluster_manager,\n session_manager=session_manager,\n kernel_spec_manager=kernel_spec_manager,\n config_manager=config_manager,\n\n # IPython stuff\n jinja_template_vars=ipython_app.jinja_template_vars,\n nbextensions_path=ipython_app.nbextensions_path,\n websocket_url=ipython_app.websocket_url,\n mathjax_url=ipython_app.mathjax_url,\n config=ipython_app.config,\n jinja2_env=env,\n terminals_available=False, # Set later if terminals are available\n )\n\n # allow custom overrides for the tornado web app.\n settings.update(settings_overrides)\n return settings", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "init_settings", "_file_name": "IPython/html/notebookapp.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, struct kvec *iov, int n_vec)\n{\n\tstruct smb_rqst rqst;\n\tint rc = 0;\n\tstruct smb2_write_req *req = NULL;\n\tstruct smb2_write_rsp *rsp = NULL;\n\tint resp_buftype;\n\tstruct kvec rsp_iov;\n\tint flags = 0;\n\tunsigned int total_len;\n\n\t*nbytes = 0;\n\n\tif (n_vec < 1)\n\t\treturn rc;\n\n\trc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,\n\t\t\t &total_len);\n\tif (rc)\n\t\treturn rc;\n\n\tif (io_parms->tcon->ses->server == NULL)\n\t\treturn -ECONNABORTED;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\treq->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);\n\n\treq->PersistentFileId = io_parms->persistent_fid;\n\treq->VolatileFileId = io_parms->volatile_fid;\n\treq->WriteChannelInfoOffset = 0;\n\treq->WriteChannelInfoLength = 0;\n\treq->Channel = 0;\n\treq->Length = cpu_to_le32(io_parms->length);\n\treq->Offset = cpu_to_le64(io_parms->offset);\n\treq->DataOffset = cpu_to_le16(\n\t\t\t\toffsetof(struct smb2_write_req, Buffer));\n\treq->RemainingBytes = 0;\n\n\ttrace_smb3_write_enter(xid, io_parms->persistent_fid,\n\t\tio_parms->tcon->tid, io_parms->tcon->ses->Suid,\n\t\tio_parms->offset, io_parms->length);\n\n\tiov[0].iov_base = (char *)req;\n\t/* 1 for Buffer */\n\tiov[0].iov_len = total_len - 1;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = n_vec + 1;\n\n\trc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,\n\t\t\t &resp_buftype, flags, &rsp_iov);\n\tcifs_small_buf_release(req);\n\trsp = (struct smb2_write_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\ttrace_smb3_write_err(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length, rc);\n\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);\n\t\tcifs_dbg(VFS, \"Send error in write = %d\\n\", rc);\n\t} else {\n\t\t*nbytes = le32_to_cpu(rsp->DataLength);\n\t\ttrace_smb3_write_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid,\n\t\t\t\t io_parms->tcon->ses->Suid,\n\t\t\t\t io_parms->offset, *nbytes);\n\t}\n\n\tfree_rsp_buf(resp_buftype, rsp);\n\treturn rc;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1475, 1555]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1475, 1555]]}, "_func_name": "SMB2_write", "_file_name": "fs/cifs/smb2pdu.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def install(filename, target):\n '''Run a package's installer script against the given target directory.'''\n print(' Unpacking %s...' % filename)\n os.system('tar xf ' + filename)\n basename = filename.split('.tar')[0]\n print(' Installing %s...' % basename)\n install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target\n os.system('%s/install.sh %s' % (basename, install_opts))\n print(' Cleaning %s...' % basename)\n os.system('rm -rf %s' % basename)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[147, 181], [260, 385], [423, 458]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[147, 181], [260, 385], [423, 458]]}, "_func_name": "install", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_files(self, submit_id, password=None, astree=False):\n \"\"\"\n Returns files from a submitted analysis.\n @param password: The password to unlock container archives with\n @param astree: sflock option; determines the format in which the files are returned\n @return: A tree of files\n \"\"\"\n submit = Database().view_submit(submit_id)\n files, duplicates = [], []\n\n for data in submit.data[\"data\"]:\n if data[\"type\"] == \"file\":\n filename = Storage.get_filename_from_path(data[\"data\"])\n filepath = os.path.join(submit.tmp_path, filename)\n\n unpacked = sflock.unpack(\n filepath=filepath, password=password, duplicates=duplicates\n )\n\n if astree:\n unpacked = unpacked.astree(sanitize=True)\n\n files.append(unpacked)\n elif data[\"type\"] == \"url\":\n files.append({\n \"filename\": data[\"data\"],\n \"filepath\": \"\",\n \"relapath\": \"\",\n \"selected\": True,\n \"size\": 0,\n \"type\": \"url\",\n \"package\": \"ie\",\n \"extrpath\": [],\n \"duplicate\": False,\n \"children\": [],\n \"mime\": \"text/html\",\n \"finger\": {\n \"magic_human\": \"url\",\n \"magic\": \"url\"\n }\n })\n else:\n raise RuntimeError(\n \"Unknown data entry type: %s\" % data[\"type\"]\n )\n\n return files", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_files", "_file_name": "cuckoo/core/submit.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def addKey(client):\n\t\"\"\"Adds a new key with the specified name and contents.\n\tReturns an error if a key with the specified name already exists.\n\t\"\"\"\n\tglobal BAD_REQUEST\n\tglobal CREATED\n\n\tvalidateClient(client)\n\tclient_pub_key = loadClientRSAKey(client)\n\ttoken_data = decodeRequestToken(request.data, client_pub_key)\n\tvalidateNewKeyData(token_data)\n\tvalidateKeyName(token_data['name'])\n\n\t# Use 'x' flag so we can throw an error if a key with this name already exists\n\ttry:\n\t\twith open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f:\n\t\t\tf.write(token_data['key'])\n\texcept FileExistsError:\n\t\traise FoxlockError(BAD_REQUEST, \"Key '%s' already exists\" % token_data['name'])\n\n\treturn 'Key successfully created', CREATED", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "addKey", "_file_name": "impl.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def process_statistics(self, metadata, _):\n args = [metadata.hostname, '-p', metadata.profile, '-g',\n ':'.join([g for g in metadata.groups])]\n for notifier in os.listdir(self.data):\n if ((notifier[-1] == '~') or\n (notifier[:2] == '.#') or\n (notifier[-4:] == '.swp') or\n (notifier in ['SCCS', '.svn', '4913'])):\n continue\n npath = self.data + '/' + notifier\n self.logger.debug(\"Running %s %s\" % (npath, \" \".join(args)))\n async_run(npath, args)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[425, 579]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[425, 579]]}, "_func_name": "process_statistics", "_file_name": "src/lib/Server/Plugins/Trigger.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;\n\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;\n\n\targs = CMSG_DATA(cmsg);\n\n\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}\n\n\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}\n\n\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;\n\n\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));\n\n\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}\n\n\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}\n\n\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);\n\n\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\tkfree(rm->atomic.op_notifier);\n\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[2680, 2712]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2680, 2712]]}, "_func_name": "rds_cmsg_atomic", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;\n\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;\n\n\targs = CMSG_DATA(cmsg);\n\n\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}\n\n\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}\n\n\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;\n\n\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));\n\n\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}\n\n\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}\n\n\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);\n\n\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\trm->atomic.op_active = 0;\n\tkfree(rm->atomic.op_notifier);\n\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rds_cmsg_atomic", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_coordinator(request):\n coordinator_id = request.GET.get('coordinator')\n doc = None\n \n if coordinator_id:\n doc = Document2.objects.get(id=coordinator_id)\n coordinator = Coordinator(document=doc)\n else:\n coordinator = Coordinator()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')]\n\n if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows):\n raise PopupException(_('You don\\'t have access to the workflow of this coordinator.'))\n\n return render('editor/coordinator_editor.mako', request, {\n 'coordinator_json': coordinator.json_for_html(),\n 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit_coordinator", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)\n{\n FILE *f = NULL;\n int w, h, prec;\n int i, numcomps, max;\n OPJ_COLOR_SPACE color_space;\n opj_image_cmptparm_t cmptparm; /* maximum of 1 component */\n opj_image_t * image = NULL;\n int adjustS, ushift, dshift, force8;\n\n char endian1, endian2, sign;\n char signtmp[32];\n\n char temp[32];\n int bigendian;\n opj_image_comp_t *comp = NULL;\n\n numcomps = 1;\n color_space = OPJ_CLRSPC_GRAY;\n\n memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));\n\n max = 0;\n\n f = fopen(filename, \"rb\");\n if (!f) {\n fprintf(stderr, \"Failed to open %s for reading !\\n\", filename);\n return NULL;\n }\n\n fseek(f, 0, SEEK_SET);\n if (fscanf(f, \"PG%[ \\t]%c%c%[ \\t+-]%d%[ \\t]%d%[ \\t]%d\", temp, &endian1,\n &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {\n fclose(f);\n fprintf(stderr,\n \"ERROR: Failed to read the right number of element from the fscanf() function!\\n\");\n return NULL;\n }\n\n i = 0;\n sign = '+';\n while (signtmp[i] != '\\0') {\n if (signtmp[i] == '-') {\n sign = '-';\n }\n i++;\n }\n\n fgetc(f);\n if (endian1 == 'M' && endian2 == 'L') {\n bigendian = 1;\n } else if (endian2 == 'M' && endian1 == 'L') {\n bigendian = 0;\n } else {\n fclose(f);\n fprintf(stderr, \"Bad pgx header, please check input file\\n\");\n return NULL;\n }\n\n /* initialize image component */\n\n cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;\n cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;\n cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +\n 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx\n + 1;\n cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +\n 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy\n + 1;\n\n if (sign == '-') {\n cmptparm.sgnd = 1;\n } else {\n cmptparm.sgnd = 0;\n }\n if (prec < 8) {\n force8 = 1;\n ushift = 8 - prec;\n dshift = prec - ushift;\n if (cmptparm.sgnd) {\n adjustS = (1 << (prec - 1));\n } else {\n adjustS = 0;\n }\n cmptparm.sgnd = 0;\n prec = 8;\n } else {\n ushift = dshift = force8 = adjustS = 0;\n }\n\n cmptparm.prec = (OPJ_UINT32)prec;\n cmptparm.bpp = (OPJ_UINT32)prec;\n cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;\n cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;\n\n /* create the image */\n image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);\n if (!image) {\n fclose(f);\n return NULL;\n }\n /* set image offset and reference grid */\n image->x0 = cmptparm.x0;\n image->y0 = cmptparm.x0;\n image->x1 = cmptparm.w;\n image->y1 = cmptparm.h;\n\n /* set image data */\n\n comp = &image->comps[0];\n\n for (i = 0; i < w * h; i++) {\n int v;\n if (force8) {\n v = readuchar(f) + adjustS;\n v = (v << ushift) + (v >> dshift);\n comp->data[i] = (unsigned char)v;\n\n if (v > max) {\n max = v;\n }\n\n continue;\n }\n if (comp->prec == 8) {\n if (!comp->sgnd) {\n v = readuchar(f);\n } else {\n v = (char) readuchar(f);\n }\n } else if (comp->prec <= 16) {\n if (!comp->sgnd) {\n v = readushort(f, bigendian);\n } else {\n v = (short) readushort(f, bigendian);\n }\n } else {\n if (!comp->sgnd) {\n v = (int)readuint(f, bigendian);\n } else {\n v = (int) readuint(f, bigendian);\n }\n }\n if (v > max) {\n max = v;\n }\n comp->data[i] = v;\n }\n fclose(f);\n comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;\n\n return image;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[745, 821]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[745, 821]]}, "_func_name": "pgxtoimage", "_file_name": "src/bin/jp2/convert.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n int\n y;\n\n MagickBooleanType\n monochrome;\n\n QuantumInfo\n *quantum_info;\n\n register const Quantum\n *p;\n\n register ssize_t\n i;\n\n size_t\n count,\n length;\n\n unsigned char\n *pixels;\n\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n\n#define CHUNK 16384\n\n int\n flush,\n level;\n\n unsigned char\n *compressed_pixels;\n\n z_stream\n stream;\n\n compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,\n sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n ResetMagickMemory(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (next_image->compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (next_image->compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) CHUNK;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) CHUNK-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (next_image->compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WritePSDChannel", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@register.filter\ndef json_dumps(value, indent=None):\n if isinstance(value, QuerySet):\n result = serialize('json', value, indent=indent)\n else:\n result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)\n\n return mark_safe(force_text(result).translate(_safe_js_escapes))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "json_dumps", "_file_name": "djblets/util/templatetags/djblets_js.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "search_make_new(const struct search_state *const state, int n, const char *const base_name) {\n\tconst size_t base_len = strlen(base_name);\n\tchar need_to_append_dot;\n\tstruct search_domain *dom;\n\n\tif (!base_len) return NULL;\n\tneed_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;\n\n\tfor (dom = state->head; dom; dom = dom->next) {\n\t\tif (!n--) {\n\t\t\t/* this is the postfix we want */\n\t\t\t/* the actual postfix string is kept at the end of the structure */\n\t\t\tconst u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);\n\t\t\tconst int postfix_len = dom->len;\n\t\t\tchar *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);\n\t\t\tif (!newname) return NULL;\n\t\t\tmemcpy(newname, base_name, base_len);\n\t\t\tif (need_to_append_dot) newname[base_len] = '.';\n\t\t\tmemcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);\n\t\t\tnewname[base_len + need_to_append_dot + postfix_len] = 0;\n\t\t\treturn newname;\n\t\t}\n\t}\n\n\t/* we ran off the end of the list and still didn't find the requested string */\n\tEVUTIL_ASSERT(0);\n\treturn NULL; /* unreachable; stops warnings in some compilers. */\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "search_make_new", "_file_name": "evdns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int32_t *enc_untrusted_create_wait_queue() {\n MessageWriter input;\n MessageReader output;\n input.Push(sizeof(int32_t));\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_create_wait_queue\",\n 2);\n int32_t *queue = reinterpret_cast(output.next());\n if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_create_wait_queue: queue should be in untrusted memory\");\n }\n int klinux_errno = output.next();\n if (queue == nullptr) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n }\n enc_untrusted_disable_waiting(queue);\n return queue;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_create_wait_queue", "_file_name": "asylo/platform/host_call/trusted/concurrency.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def list(self, keyfilter='/'):\n path = os.path.join(self.namespace, keyfilter)\n if path != '/':\n path = path.rstrip('/')\n try:\n result = self.etcd.read(path, recursive=True)\n except etcd.EtcdKeyNotFound:\n return None\n except etcd.EtcdException as err:\n log_error(\"Error listing %s: [%r]\" % (keyfilter, repr(err)))\n raise CSStoreError('Error occurred while trying to list keys')\n\n value = set()\n for entry in result.get_subtree():\n if entry.key == path:\n continue\n name = entry.key[len(path):]\n if entry.dir and not name.endswith('/'):\n name += '/'\n value.add(name.lstrip('/'))\n return sorted(value)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[35, 90]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[35, 90]]}, "_func_name": "list", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _exec_cmd(self, cmd):\n \"\"\"Executes adb commands in a new shell.\n\n This is specific to executing adb binary because stderr is not a good\n indicator of cmd execution status.\n\n Args:\n cmds: A string that is the adb command to execute.\n\n Returns:\n The output of the adb command run if exit code is 0.\n\n Raises:\n AdbError is raised if the adb command exit code is not 0.\n \"\"\"\n proc = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n (out, err) = proc.communicate()\n ret = proc.returncode\n logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out,\n err, ret)\n if ret == 0:\n return out\n else:\n raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[0, 79], [80, 201], [202, 279], [494, 571], [641, 717], [807, 880]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 79], [80, 201], [202, 279], [494, 571], [641, 717], [807, 880]]}, "_func_name": "_exec_cmd", "_file_name": "mobly/controllers/android_device_lib/adb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mode_input(self, request):\n \"\"\"\n This is called by render_POST when the client\n is sending data to the server.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = request.args.get('csessid')[0]\n\n self.last_alive[csessid] = (time.time(), False)\n sess = self.sessionhandler.sessions_from_csessid(csessid)\n if sess:\n sess = sess[0]\n cmdarray = json.loads(request.args.get('data')[0])\n sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]})\n return '\"\"'", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[217, 266]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[217, 266]]}, "_func_name": "mode_input", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def make_eb_config(application_name, default_region):\n # Capture our current directory\n UTILS_DIR = os.path.dirname(os.path.abspath(__file__))\n # Create the jinja2 environment.\n # Notice the use of trim_blocks, which greatly helps control whitespace.\n j2_env = Environment(loader=FileSystemLoader(UTILS_DIR), autoescape=True)\n return j2_env.get_template('templates/eb/config.yml').render(\n APPLICATION_NAME=application_name,\n DEFAULT_REGION=default_region\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "make_eb_config", "_file_name": "utils/make_eb_config.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)\n{\n\tconst char *s = name;\n\n\twhile (1) {\n\t\tconst char *s0 = s;\n\t\tchar *dirname;\n\n\t\t/* Find a directory component, if any. */\n\t\twhile (1) {\n\t\t\tif (*s == 0) {\n\t\t\t\tif (last && s != s0)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t\treturn dir;\n\t\t\t}\n\t\t\t/* This is deliberately slash-only. */\n\t\t\tif (*s == '/')\n\t\t\t\tbreak;\n\t\t\ts++;\n\t\t}\n\n\t\tdirname = g_strndup (s0, s - s0);\n\t\twhile (*s == '/')\n\t\t\ts++;\n\n\t\tif (strcmp (dirname, \".\") != 0) {\n\t\t\tGsfInput *subdir =\n\t\t\t\tgsf_infile_child_by_name (GSF_INFILE (dir),\n\t\t\t\t\t\t\t dirname);\n\t\t\tif (subdir) {\n\t\t\t\t/* Undo the ref. */\n\t\t\t\tg_object_unref (subdir);\n\t\t\t\tdir = GSF_INFILE_TAR (subdir);\n\t\t\t} else\n\t\t\t\tdir = tar_create_dir (dir, dirname);\n\t\t}\n\n\t\tg_free (dirname);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[616, 680]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[616, 680]]}, "_func_name": "tar_directory_for_file", "_file_name": "gsf/gsf-infile-tar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_NO_HOST_RET), ''])\n\n create_host_cmd = ('createhost -iscsi -add fakehost '\n 'iqn.1993-08.org.debian:01:222')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[638, 760]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[638, 760]]}, "_func_name": "test_create_modify_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)\n{\n\tGC_REFCOUNT(ht) = 1;\n\tGC_TYPE_INFO(ht) = IS_ARRAY;\n\tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n\tht->nTableSize = zend_hash_check_size(nSize);\n\tht->nTableMask = HT_MIN_MASK;\n\tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n\tht->nNumUsed = 0;\n\tht->nNumOfElements = 0;\n\tht->nInternalPointer = HT_INVALID_IDX;\n\tht->nNextFreeElement = 0;\n\tht->pDestructor = pDestructor;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[303, 381]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[303, 381]]}, "_func_name": "_zend_hash_init", "_file_name": "Zend/zend_hash.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)\n{\n QCA::Initializer init;\n QByteArray temp = cipherText;\n\n //do padding ourselves\n if (direction)\n {\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n else\n {\n temp = b64ToByte(temp);\n while ((temp.length() % 8) != 0) temp.append('\\0');\n }\n\n QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;\n QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);\n QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();\n temp2 += cipher.final().toByteArray();\n\n if (!cipher.ok())\n return cipherText;\n\n if (direction)\n temp2 = byteToB64(temp2);\n\n return temp2;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[689, 708]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[689, 708]]}, "_func_name": "Cipher::blowfishECB", "_file_name": "src/core/cipher.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def copy(self, src_data, src_path, dst_data, dst_path, job_id=None):\n credentials = {}\n\n if src_data is None: # Local\n src = src_path\n else:\n credentials.update(self._formatCredentials(src_data, name='src'))\n src = 'src:{}'.format(src_path)\n\n if dst_data is None: # Local\n dst = dst_path\n else:\n credentials.update(self._formatCredentials(dst_data, name='dst'))\n dst = 'dst:{}'.format(dst_path)\n\n command = [\n 'rclone',\n 'copy',\n src,\n dst,\n '--progress',\n '--stats', '2s',\n ]\n\n bash_command = \"{} {}\".format(\n ' '.join(\"{}='{}'\".format(key, value) for key, value in credentials.items()),\n ' '.join(command),\n )\n\n logging.info(sanitize(bash_command))\n\n if job_id is None:\n job_id = self._get_next_job_id()\n else:\n if self._job_id_exists(job_id):\n raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id))\n\n self._stop_events[job_id] = threading.Event()\n\n try:\n self._execute_interactive(command, credentials, job_id)\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))\n\n return job_id", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "copy", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def getCommentsByPostid(self,postid,userid):\n sqlText=\"select (select Count(*) from comment_like where comments.commentid = comment_like.commentid) as like,(select Count(*) from comment_like where comments.commentid = comment_like.commentid and comment_like.userid=%d) as flag,commentid,name,comment from users,comments where users.userid=comments.userid and postid=%d order by date desc;\"%(userid,postid)\n result=sql.queryDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[49, 417]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[49, 417]]}, "_func_name": "getCommentsByPostid", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CopyKeyAliasesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)\n{\n AliasInfo *alias;\n unsigned i, num_key_aliases;\n struct xkb_key_alias *key_aliases;\n\n /*\n * Do some sanity checking on the aliases. We can't do it before\n * because keys and their aliases may be added out-of-order.\n */\n num_key_aliases = 0;\n darray_foreach(alias, info->aliases) {\n /* Check that ->real is a key. */\n if (!XkbKeyByName(keymap, alias->real, false)) {\n log_vrb(info->ctx, 5,\n \"Attempt to alias %s to non-existent key %s; Ignored\\n\",\n KeyNameText(info->ctx, alias->alias),\n KeyNameText(info->ctx, alias->real));\n alias->real = XKB_ATOM_NONE;\n continue;\n }\n\n /* Check that ->alias is not a key. */\n if (XkbKeyByName(keymap, alias->alias, false)) {\n log_vrb(info->ctx, 5,\n \"Attempt to create alias with the name of a real key; \"\n \"Alias \\\"%s = %s\\\" ignored\\n\",\n KeyNameText(info->ctx, alias->alias),\n KeyNameText(info->ctx, alias->real));\n alias->real = XKB_ATOM_NONE;\n continue;\n }\n\n num_key_aliases++;\n }\n\n /* Copy key aliases. */\n key_aliases = NULL;\n if (num_key_aliases > 0) {\n key_aliases = calloc(num_key_aliases, sizeof(*key_aliases));\n if (!key_aliases)\n return false;\n }\n\n i = 0;\n darray_foreach(alias, info->aliases) {\n if (alias->real != XKB_ATOM_NONE) {\n key_aliases[i].alias = alias->alias;\n key_aliases[i].real = alias->real;\n i++;\n }\n }\n\n keymap->num_key_aliases = num_key_aliases;\n keymap->key_aliases = key_aliases;\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1477, 1484]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1477, 1484]]}, "_func_name": "CopyKeyAliasesToKeymap", "_file_name": "src/xkbcomp/keycodes.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str):\n \"\"\"\n This function is used to alter the reservation beeing build inside\n a cookie. This function automatically crafts the required response.\n \"\"\"\n js_string: str = \"\"\n r: GroupReservation = None\n u: Profile = get_current_user(request)\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if \"srid\" in request.GET:\n if not request.GET.get(\"rid\"):\n return HttpResponseRedirect(\"/admin?error=missing%20primary%20reservation%20id\")\n srid: int = int(request.GET[\"srid\"])\n sr: SubReservation = None\n if srid == 0:\n sr = SubReservation()\n else:\n sr = SubReservation.objects.get(id=srid)\n if request.POST.get(\"notes\"):\n sr.notes = escape(request.POST[\"notes\"])\n else:\n sr.notes = \" \"\n sr.primary_reservation = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n sr.save()\n print(request.POST)\n print(sr.notes)\n return HttpResponseRedirect(\"/admin/reservations/edit?rid=\" + str(int(request.GET[\"rid\"])) + \"&srid=\" + str(sr.id))\n if \"rid\" in request.GET:\n # update reservation\n r = GroupReservation.objects.get(id=int(request.GET[\"rid\"]))\n elif u.number_of_allowed_reservations > GroupReservation.objects.all().filter(createdByUser=u).count():\n r = GroupReservation()\n r.createdByUser = u\n r.ready = False\n r.open = True\n r.pickupDate = datetime.datetime.now()\n else:\n return HttpResponseRedirect(\"/admin?error=Too%20Many%20reservations\")\n if request.POST.get(\"notes\"):\n r.notes = escape(request.POST[\"notes\"])\n if request.POST.get(\"contact\"):\n r.responsiblePerson = escape(str(request.POST[\"contact\"]))\n if (r.createdByUser == u or o.rights > 1) and not r.submitted:\n r.save()\n else:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n response: HttpResponseRedirect = HttpResponseRedirect(forward_url + \"?rid=\" + str(r.id))\n return response", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "manipulate_reservation_action", "_file_name": "c3shop/frontpage/management/reservation_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "authDigestNonceLink(digest_nonce_h * nonce)\n{\n assert(nonce != NULL);\n ++nonce->references;\n assert(nonce->references != 0); // no overflows\n debugs(29, 9, \"nonce '\" << nonce << \"' now at '\" << nonce->references << \"'.\");\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "authDigestNonceLink", "_file_name": "src/auth/digest/Config.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def upsert_mapped_projects(user_id: int, project_id: int):\n \"\"\" Adds projects to mapped_projects if it doesn't exist \"\"\"\n sql = \"select * from users where id = {0} and projects_mapped @> '{{{1}}}'\".format(user_id, project_id)\n result = db.engine.execute(sql)\n\n if result.rowcount > 0:\n return # User has previously mapped this project so return\n\n sql = '''update users\n set projects_mapped = array_append(projects_mapped, {0})\n where id = {1}'''.format(project_id, user_id)\n\n db.engine.execute(sql)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[150, 262], [438, 579]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[150, 262], [438, 579]]}, "_func_name": "upsert_mapped_projects", "_file_name": "server/models/postgis/user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(\n ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(\"Shape must be at least rank \", axis_ + 1,\n \" but is rank \", input.shape().dims()));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar()();\n auto max_val = input_max_tensor.scalar()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value,\n range_shape, &input_max_tensor));\n }\n\n if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor f;\n f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor f;\n f(ctx->eigen_device(),\n input.template flat_inner_outer_dims(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims(axis_ - 1));\n }\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "tensorflow::QuantizeAndDequantizeV2Op::Compute", "_file_name": "tensorflow/core/kernels/quantize_and_dequantize_op.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def get_ports(self):\n # First get the active FC ports\n out = self._cli_run(['showport'])\n\n # strip out header\n # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,\n # Protocol,Label,Partner,FailoverState\n out = out[1:len(out) - 2]\n\n ports = {'FC': [], 'iSCSI': {}}\n for line in out:\n tmp = line.split(',')\n\n if tmp:\n if tmp[1] == 'target' and tmp[2] == 'ready':\n if tmp[6] == 'FC':\n ports['FC'].append(tmp[4])\n\n # now get the active iSCSI ports\n out = self._cli_run(['showport', '-iscsi'])\n\n # strip out header\n # N:S:P,State,IPAddr,Netmask,Gateway,\n # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port\n out = out[1:len(out) - 2]\n for line in out:\n tmp = line.split(',')\n\n if tmp and len(tmp) > 2:\n if tmp[1] == 'ready':\n ports['iSCSI'][tmp[2]] = {}\n\n # now get the nsp and iqn\n result = self._cli_run(['showport', '-iscsiname'])\n if result:\n # first line is header\n # nsp, ip,iqn\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 2:\n if info[1] in ports['iSCSI']:\n nsp = info[0]\n ip_addr = info[1]\n iqn = info[2]\n ports['iSCSI'][ip_addr] = {'nsp': nsp,\n 'iqn': iqn\n }\n\n LOG.debug(\"PORTS = %s\" % pprint.pformat(ports))\n return ports", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_ports", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mkdir(self, data, path):\n credentials = self._formatCredentials(data, name='current')\n command = [\n 'rclone',\n 'touch',\n 'current:{}/.keep'.format(path),\n ]\n\n try:\n result = self._execute(command, credentials)\n return {\n 'message': 'Success',\n }\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mkdir", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/top_proxies')\ndef top_proxies():\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT sum(amount) FROM holders\"\n cur.execute(query)\n total = cur.fetchone()\n total_votes = total[0]\n\n query = \"SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as\"\n cur.execute(query)\n results = cur.fetchall()\n #con.close()\n\n proxies = []\n\n for p in range(0, len(results)):\n\n proxy_line = [0] * 5\n\n proxy_id = results[p][0]\n proxy_line[0] = proxy_id\n\n query = \"SELECT account_name, amount FROM holders WHERE account_id='\"+proxy_id+\"' LIMIT 1\"\n cur.execute(query)\n proxy = cur.fetchone()\n\n try:\n proxy_name = proxy[0]\n proxy_amount = proxy[1]\n except:\n proxy_name = \"unknown\"\n proxy_amount = 0\n\n\n proxy_line[1] = proxy_name\n\n query = \"SELECT amount, account_id FROM holders WHERE voting_as='\"+proxy_id+\"'\"\n cur.execute(query)\n results2 = cur.fetchall()\n\n proxy_line[2] = int(proxy_amount)\n\n for p2 in range(0, len(results2)):\n amount = results2[p2][0]\n account_id = results2[p2][1]\n proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes\n proxy_line[3] = proxy_line[3] + 1 # followers\n\n if proxy_line[3] > 2:\n percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))\n proxy_line[4] = percentage\n proxies.append(proxy_line)\n\n con.close()\n\n proxies = sorted(proxies, key=lambda k: int(k[2]))\n r_proxies = proxies[::-1]\n\n return jsonify(filter(None, r_proxies))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[551, 650], [910, 998]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[551, 650], [910, 998]]}, "_func_name": "top_proxies", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jpc_dec_process_siz", "_file_name": "src/libjasper/jpc/jpc_dec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def zmi_page_request(self, *args, **kwargs):\r\n request = self.REQUEST\r\n RESPONSE = request.RESPONSE\r\n SESSION = request.SESSION\r\n self._zmi_page_request()\r\n RESPONSE.setHeader('Expires',DateTime(request['ZMI_TIME']-10000).toZone('GMT+1').rfc822())\r\n RESPONSE.setHeader('Cache-Control', 'no-cache')\r\n RESPONSE.setHeader('Pragma', 'no-cache')\r\n RESPONSE.setHeader('Content-Type', 'text/html;charset=%s'%request['ZMS_CHARSET'])\r\n if not request.get( 'preview'):\r\n request.set( 'preview','preview')\r\n langs = self.getLanguages(request)\r\n if request.get('lang') not in langs:\r\n request.set('lang',langs[0])\r\n if request.get('manage_lang') not in self.getLocale().get_manage_langs():\r\n request.set('manage_lang',self.get_manage_lang())\r\n if not request.get('manage_tabs_message'):\r\n request.set( 'manage_tabs_message',self.getConfProperty('ZMS.manage_tabs_message',''))\r\n # manage_system\r\n if request.form.has_key('zmi-manage-system'):\r\n request.SESSION.set('zmi-manage-system',int(request.get('zmi-manage-system')))\r\n # avoid declarative urls\r\n physical_path = self.getPhysicalPath()\r\n path_to_handle = request['URL0'][len(request['BASE0']):].split('/')\r\n path = path_to_handle[:-1]\r\n if self.getDocumentElement().id in path and len(filter(lambda x:x.find('.')>0 or x.startswith('manage_'),path))==0:\r\n for i in range(len(path)):\r\n if path[:-(i+1)] != physical_path[:-(i+1)]:\r\n path[:-(i+1)] = physical_path[:-(i+1)]\r\n new_path = path+[path_to_handle[-1]]\r\n if path_to_handle != new_path:\r\n request.RESPONSE.redirect('/'.join(new_path))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "zmi_page_request", "_file_name": "ZMSItem.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,\n void *dummy,\n const char *arg)\n{\n const char *endp = ap_strrchr_c(arg, '>');\n const char *limited_methods;\n void *tog = cmd->cmd->cmd_data;\n apr_int64_t limited = 0;\n apr_int64_t old_limited = cmd->limited;\n const char *errmsg;\n\n if (endp == NULL) {\n return unclosed_directive(cmd);\n }\n\n limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg);\n\n if (!limited_methods[0]) {\n return missing_container_arg(cmd);\n }\n\n while (limited_methods[0]) {\n char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);\n int methnum;\n\n /* check for builtin or module registered method number */\n methnum = ap_method_number_of(method);\n\n if (methnum == M_TRACE && !tog) {\n return \"TRACE cannot be controlled by , see TraceEnable\";\n }\n else if (methnum == M_INVALID) {\n /* method has not been registered yet, but resource restriction\n * is always checked before method handling, so register it.\n */\n methnum = ap_method_register(cmd->pool,\n apr_pstrdup(cmd->pool, method));\n }\n\n limited |= (AP_METHOD_BIT << methnum);\n }\n\n /* Killing two features with one function,\n * if (tog == NULL) , else \n */\n limited = tog ? ~limited : limited;\n\n if (!(old_limited & limited)) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive excludes all methods\", NULL);\n }\n else if ((old_limited & limited) == old_limited) {\n return apr_pstrcat(cmd->pool, cmd->cmd->name,\n \"> directive specifies methods already excluded\",\n NULL);\n }\n\n cmd->limited &= limited;\n\n errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);\n\n cmd->limited = old_limited;\n\n return errmsg;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1227, 1279]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1227, 1279]]}, "_func_name": "ap_limit_section", "_file_name": "server/core.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def update_inverter(self, inverter_serial, ts, status, etoday, etotal):\n query = '''\n UPDATE Inverters\n SET \n TimeStamp='%s', \n Status='%s', \n eToday='%s',\n eTotal='%s'\n WHERE Serial='%s';\n ''' % (ts, status, etoday, etotal, inverter_serial)\n self.c.execute(query)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[146, 386]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[146, 386]]}, "_func_name": "update_inverter", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def can_user_pass_that_amount_of_money(self, user_id, money):\n self.cursor.execute(\"SELECT count(id) FROM kickstarter.users where id = %s and money >= %s\", (user_id, money))\n return self.cursor.fetchall()[0][0]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "can_user_pass_that_amount_of_money", "_file_name": "backend/transactions/TransactionConnector.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@frappe.whitelist(allow_guest=True)\ndef send_message(subject=\"Website Query\", message=\"\", sender=\"\", status=\"Open\"):\n\tfrom frappe.www.contact import send_message as website_send_message\n\tlead = customer = None\n\n\twebsite_send_message(subject, message, sender)\n\n\tcustomer = frappe.db.sql(\"\"\"select distinct dl.link_name from `tabDynamic Link` dl\n\t\tleft join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'\n\t\tand c.email_id='{email_id}'\"\"\".format(email_id=sender))\n\n\tif not customer:\n\t\tlead = frappe.db.get_value('Lead', dict(email_id=sender))\n\t\tif not lead:\n\t\t\tnew_lead = frappe.get_doc(dict(\n\t\t\t\tdoctype='Lead',\n\t\t\t\temail_id = sender,\n\t\t\t\tlead_name = sender.split('@')[0].title()\n\t\t\t)).insert(ignore_permissions=True)\n\n\topportunity = frappe.get_doc(dict(\n\t\tdoctype ='Opportunity',\n\t\tenquiry_from = 'Customer' if customer else 'Lead',\n\t\tstatus = 'Open',\n\t\ttitle = subject,\n\t\tcontact_email = sender,\n\t\tto_discuss = message\n\t))\n\n\tif customer:\n\t\topportunity.customer = customer[0][0]\n\telif lead:\n\t\topportunity.lead = lead\n\telse:\n\t\topportunity.lead = new_lead.name\n\n\topportunity.insert(ignore_permissions=True)\n\n\tcomm = frappe.get_doc({\n\t\t\"doctype\":\"Communication\",\n\t\t\"subject\": subject,\n\t\t\"content\": message,\n\t\t\"sender\": sender,\n\t\t\"sent_or_received\": \"Received\",\n\t\t'reference_doctype': 'Opportunity',\n\t\t'reference_name': opportunity.name\n\t})\n\tcomm.insert(ignore_permissions=True)\n\n\treturn \"okay\"", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[424, 482]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[424, 482]]}, "_func_name": "send_message", "_file_name": "erpnext/templates/utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void * CAPSTONE_API cs_winkernel_malloc(size_t size)\n{\n\t// Disallow zero length allocation because they waste pool header space and,\n\t// in many cases, indicate a potential validation issue in the calling code.\n\tNT_ASSERT(size);\n\n\t// FP; a use of NonPagedPool is required for Windows 7 support\n#pragma prefast(suppress : 30030)\t\t// Allocating executable POOL_TYPE memory\n\tCS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(\n\t\t\tNonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG);\n\tif (!block) {\n\t\treturn NULL;\n\t}\n\tblock->size = size;\n\n\treturn block->data;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[451, 530]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[451, 530]]}, "_func_name": "cs_winkernel_malloc", "_file_name": "windows/winkernel_mm.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "AP4_AtomSampleTable::GetSample(AP4_Ordinal index, \n AP4_Sample& sample)\n{\n AP4_Result result;\n\n // check that we have an stsc atom\n if (!m_StscAtom) {\n return AP4_ERROR_INVALID_FORMAT;\n }\n \n // check that we have a chunk offset table\n if (m_StcoAtom == NULL && m_Co64Atom == NULL) {\n return AP4_ERROR_INVALID_FORMAT;\n }\n\n // MP4 uses 1-based indexes internally, so adjust by one\n index++;\n\n // find out in which chunk this sample is located\n AP4_Ordinal chunk, skip, desc;\n result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);\n if (AP4_FAILED(result)) return result;\n \n // check that the result is within bounds\n if (skip > index) return AP4_ERROR_INTERNAL;\n\n // get the atom offset for this chunk\n AP4_UI64 offset;\n if (m_StcoAtom) {\n AP4_UI32 offset_32;\n result = m_StcoAtom->GetChunkOffset(chunk, offset_32);\n offset = offset_32;\n } else {\n result = m_Co64Atom->GetChunkOffset(chunk, offset);\n }\n if (AP4_FAILED(result)) return result;\n \n // compute the additional offset inside the chunk\n for (unsigned int i = index-skip; i < index; i++) {\n AP4_Size size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(i, size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(i, size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n offset += size;\n }\n\n // set the description index\n sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes\n\n // set the dts and cts\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n if (m_SttsAtom) {\n result = m_SttsAtom->GetDts(index, dts, &duration);\n if (AP4_FAILED(result)) return result;\n }\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {\n sample.SetCts(dts);\n } else {\n result = m_CttsAtom->GetCtsOffset(index, cts_offset); \n\t if (AP4_FAILED(result)) return result;\n sample.SetCtsDelta(cts_offset);\n } \n\n // set the size\n AP4_Size sample_size = 0;\n if (m_StszAtom) {\n result = m_StszAtom->GetSampleSize(index, sample_size); \n } else if (m_Stz2Atom) {\n result = m_Stz2Atom->GetSampleSize(index, sample_size); \n } else {\n result = AP4_ERROR_INVALID_FORMAT;\n }\n if (AP4_FAILED(result)) return result;\n sample.SetSize(sample_size);\n\n // set the sync flag\n if (m_StssAtom == NULL) {\n sample.SetSync(true);\n } else {\n sample.SetSync(m_StssAtom->IsSampleSync(index));\n }\n\n // set the offset\n sample.SetOffset(offset);\n\n // set the data stream\n sample.SetDataStream(m_SampleStream);\n\n\n return AP4_SUCCESS;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "AP4_AtomSampleTable::GetSample", "_file_name": "Source/C++/Core/Ap4AtomSampleTable.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "char *enl_ipc_get(const char *msg_data)\n{\n\n\tstatic char *message = NULL;\n\tstatic size_t len = 0;\n\tchar buff[13], *ret_msg = NULL;\n\tregister unsigned char i;\n\tunsigned char blen;\n\n\tif (msg_data == IPC_TIMEOUT) {\n\t\treturn(IPC_TIMEOUT);\n\t}\n\tfor (i = 0; i < 12; i++) {\n\t\tbuff[i] = msg_data[i];\n\t}\n\tbuff[12] = 0;\n\tblen = strlen(buff);\n\tif (message != NULL) {\n\t\tlen += blen;\n\t\tmessage = (char *) erealloc(message, len + 1);\n\t\tstrcat(message, buff);\n\t} else {\n\t\tlen = blen;\n\t\tmessage = (char *) emalloc(len + 1);\n\t\tstrcpy(message, buff);\n\t}\n\tif (blen < 12) {\n\t\tret_msg = message;\n\t\tmessage = NULL;\n\t\tD((\"Received complete reply: \\\"%s\\\"\\n\", ret_msg));\n\t}\n\treturn(ret_msg);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enl_ipc_get", "_file_name": "src/wallpaper.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def isValidAdmToken(adm_token):\n conn, c = connectDB()\n req = \"SELECT * from {} where adm_token=?\".format(CFG(\"admintoken_table_name\"))\n answer = bool(queryOne(c, req, (adm_token,)))\n closeDB(conn)\n return answer", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "isValidAdmToken", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = 'showhost -verbose fakehost'\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n '(\\'OpenStack\\',) '\n 'fakehost iqn.1993-08.org.debian:01:222')\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[631, 814]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[631, 814]]}, "_func_name": "test_create_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void set_fdc(int drive)\n{\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tfdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (fdc != 1 && fdc != 0) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[119, 148]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[119, 148]]}, "_func_name": "set_fdc", "_file_name": "drivers/block/floppy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@hook.command(autohelp=False)\ndef showPoll(pollID, db=None):\n \"\"\"Shows the answers for a given poll.\"\"\"\n if not db_ready: db_init(db)\n if pollID == None:\n poll = db.execute(\"SELECT pollID, question FROM polls WHERE active = 1\")\n if len(poll) == 0:\n reply(\"There's no poll open.\")\n return\n else:\n poll = db.execute(\"SELECT pollID, question FROM polls WHERE pollID = ?\", (pollID,))\n if len(poll) == 0:\n reply(\"No such poll found.\")\n return\n pollID = poll[0][0]\n question = poll[0][1]\n reply(question)\n for (index, answer, votes) in db.execute(\"SELECT 'index', answer, count(voteID) FROM answers LEFT JOIN votes ON votes.answerID = answers.answerID WHERE pollID = ? GROUP BY answers.answerID, 'index', answer ORDER BY 'index' ASC\", (pollID, )):\n reply(\"%s. %s (%s)\" % (index, answer, votes))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "showPoll", "_file_name": "plugins/poll.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int string_rfind(const char *input, int len, const char *s, int s_len,\n int pos, bool case_sensitive) {\n assertx(input);\n assertx(s);\n if (!s_len || pos < -len || pos > len) {\n return -1;\n }\n void *ptr;\n if (case_sensitive) {\n if (pos >= 0) {\n ptr = bstrrstr(input + pos, len - pos, s, s_len);\n } else {\n ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len);\n }\n } else {\n if (pos >= 0) {\n ptr = bstrrcasestr(input + pos, len - pos, s, s_len);\n } else {\n ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len);\n }\n }\n if (ptr != nullptr) {\n return (int)((const char *)ptr - input);\n }\n return -1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "HPHP::string_rfind", "_file_name": "hphp/runtime/base/zend-string.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "@app.route('/top_proxies')\ndef top_proxies():\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT sum(amount) FROM holders\"\n cur.execute(query)\n total = cur.fetchone()\n total_votes = total[0]\n\n query = \"SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as\"\n cur.execute(query)\n results = cur.fetchall()\n #con.close()\n\n proxies = []\n\n for p in range(0, len(results)):\n\n proxy_line = [0] * 5\n\n proxy_id = results[p][0]\n proxy_line[0] = proxy_id\n\n query = \"SELECT account_name, amount FROM holders WHERE account_id=%s LIMIT 1\"\n cur.execute(query, (proxy_id,))\n proxy = cur.fetchone()\n\n try:\n proxy_name = proxy[0]\n proxy_amount = proxy[1]\n except:\n proxy_name = \"unknown\"\n proxy_amount = 0\n\n\n proxy_line[1] = proxy_name\n\n query = \"SELECT amount, account_id FROM holders WHERE voting_as=%s\"\n cur.execute(query, (proxy_id,))\n results2 = cur.fetchall()\n\n proxy_line[2] = int(proxy_amount)\n\n for p2 in range(0, len(results2)):\n amount = results2[p2][0]\n account_id = results2[p2][1]\n proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes\n proxy_line[3] = proxy_line[3] + 1 # followers\n\n if proxy_line[3] > 2:\n percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes))\n proxy_line[4] = percentage\n proxies.append(proxy_line)\n\n con.close()\n\n proxies = sorted(proxies, key=lambda k: int(k[2]))\n r_proxies = proxies[::-1]\n\n return jsonify(filter(None, r_proxies))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "top_proxies", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_post(content):\n \"\"\"Add a post to the 'database' with the current timestamp.\"\"\"\n conn = psycopg2.connect(\"dbname=forum\")\n cursor = conn.cursor()\n cursor.execute(\"insert into posts values ('%s')\" % content)\n conn.commit()\n conn.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[155, 217]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[155, 217]]}, "_func_name": "add_post", "_file_name": "forumdb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get(self, user_id):\n \"\"\" Fetch data for user with corresponding user_id \"\"\"\n return database_utilities.execute_query(f\"\"\"select * from users where user_id = '{user_id}'\"\"\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[91, 194]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[91, 194]]}, "_func_name": "get", "_file_name": "apis/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int read_entry(\n\tgit_index_entry **out,\n\tsize_t *out_size,\n\tgit_index *index,\n\tconst void *buffer,\n\tsize_t buffer_size,\n\tconst char *last)\n{\n\tsize_t path_length, entry_size;\n\tconst char *path_ptr;\n\tstruct entry_short source;\n\tgit_index_entry entry = {{0}};\n\tbool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;\n\tchar *tmp_path = NULL;\n\n\tif (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)\n\t\treturn -1;\n\n\t/* buffer is not guaranteed to be aligned */\n\tmemcpy(&source, buffer, sizeof(struct entry_short));\n\n\tentry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);\n\tentry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);\n\tentry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);\n\tentry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);\n\tentry.dev = ntohl(source.dev);\n\tentry.ino = ntohl(source.ino);\n\tentry.mode = ntohl(source.mode);\n\tentry.uid = ntohl(source.uid);\n\tentry.gid = ntohl(source.gid);\n\tentry.file_size = ntohl(source.file_size);\n\tgit_oid_cpy(&entry.id, &source.oid);\n\tentry.flags = ntohs(source.flags);\n\n\tif (entry.flags & GIT_IDXENTRY_EXTENDED) {\n\t\tuint16_t flags_raw;\n\t\tsize_t flags_offset;\n\n\t\tflags_offset = offsetof(struct entry_long, flags_extended);\n\t\tmemcpy(&flags_raw, (const char *) buffer + flags_offset,\n\t\t\tsizeof(flags_raw));\n\t\tflags_raw = ntohs(flags_raw);\n\n\t\tmemcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_long, path);\n\t} else\n\t\tpath_ptr = (const char *) buffer + offsetof(struct entry_short, path);\n\n\tif (!compressed) {\n\t\tpath_length = entry.flags & GIT_IDXENTRY_NAMEMASK;\n\n\t\t/* if this is a very long string, we must find its\n\t\t * real length without overflowing */\n\t\tif (path_length == 0xFFF) {\n\t\t\tconst char *path_end;\n\n\t\t\tpath_end = memchr(path_ptr, '\\0', buffer_size);\n\t\t\tif (path_end == NULL)\n\t\t\t\treturn -1;\n\n\t\t\tpath_length = path_end - path_ptr;\n\t\t}\n\n\t\tentry_size = index_entry_size(path_length, 0, entry.flags);\n\t\tentry.path = (char *)path_ptr;\n\t} else {\n\t\tsize_t varint_len, last_len, prefix_len, suffix_len, path_len;\n\t\tuintmax_t strip_len;\n\n\t\tstrip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);\n\t\tlast_len = strlen(last);\n\n\t\tif (varint_len == 0 || last_len < strip_len)\n\t\t\treturn index_error_invalid(\"incorrect prefix length\");\n\n\t\tprefix_len = last_len - strip_len;\n\t\tsuffix_len = strlen(path_ptr + varint_len);\n\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);\n\t\tGITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);\n\t\ttmp_path = git__malloc(path_len);\n\t\tGITERR_CHECK_ALLOC(tmp_path);\n\n\t\tmemcpy(tmp_path, last, prefix_len);\n\t\tmemcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);\n\t\tentry_size = index_entry_size(suffix_len, varint_len, entry.flags);\n\t\tentry.path = tmp_path;\n\t}\n\n\tif (entry_size == 0)\n\t\treturn -1;\n\n\tif (INDEX_FOOTER_SIZE + entry_size > buffer_size)\n\t\treturn -1;\n\n\tif (index_entry_dup(out, index, &entry) < 0) {\n\t\tgit__free(tmp_path);\n\t\treturn -1;\n\t}\n\n\tgit__free(tmp_path);\n\t*out_size = entry_size;\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "read_entry", "_file_name": "src/index.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def update_user(username, chat_id, last_update):\n conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\users\\\\\" + username + '.db')\n conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\\\cf.db')\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n cursor = conn.cursor()\n cursor2 = conn2.cursor()\n cursor_settings = settings.cursor()\n cursor_settings.execute(\"select last_problem from users where chat_id = '\" + str(chat_id) + \"'\")\n update_eq = cursor_settings.fetchone()\n cursor_settings.execute(\"select * from last_update_problemset\")\n update_base = cursor_settings.fetchone()\n last_problem = update_base[0]\n if update_eq[0] != update_base[0]:\n cursor2.execute(\"SELECT * FROM problems\")\n x = cursor2.fetchone()\n while x != None:\n cursor.execute(\"select * from result where problem = '\" + str(x[0]) + \"' and diff = '\" + str(x[1]) + \"'\")\n x2 = cursor.fetchone()\n if x2 == None:\n cursor.execute(\"insert into result values (?, ?, ? )\", (x[0], x[1], \"NULL\"))\n last_problem = x\n x = cursor2.fetchone()\n conn2.close()\n settings.close()\n if len(last_problem) == 2:\n last_problem = last_problem[0] + last_problem[1]\n\n url = 'http://codeforces.com/submissions/' + username\n r = requests.get(url)\n max_page = 1\n soup = BeautifulSoup(r.text, \"lxml\")\n\n for link in soup.find_all(attrs={\"class\": \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[4]))\n\n v = False\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')\n soup = BeautifulSoup(r.text, \"lxml\")\n last_try_new = soup.find(attrs={\"class\": \"status-small\"})\n last_try_new = str(last_try_new).split()\n last_try_new = str(last_try_new[2]) + str(last_try_new[3])\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n count = 0\n j = 0\n ver = soup.find_all(attrs={\"class\": \"submissionVerdictWrapper\"})\n last_try = soup.find_all(attrs={\"class\": \"status-small\"})\n for link in soup.find_all('a'):\n last_try_date = str(last_try[j]).split()\n last_try_date = str(last_try_date[2]) + str(last_try_date[3])\n if last_try_date == last_update:\n v = True\n break\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5:\n s2 = str(ver[count]).split()\n s2 = s2[5].split('\\\"')\n count += 1\n j += 1\n cursor.execute(\"select * from result where problem = '\" + s[3] + \"'and diff = '\" + s[4] + \"'\")\n x = cursor.fetchone()\n if s2[1] == 'OK' and x != None:\n cursor.execute(\n \"update result set verdict = '\" + s2[1] + \"' where problem = '\" + s[3] + \"' and diff = '\" +\n s[4] + \"'\")\n if x[2] != 'OK':\n cursor.execute(\n \"update result set verdict = '\" + s2[1] + \"' where problem = '\" + s[3] + \"' and diff = '\" +\n s[4] + \"'\")\n if v:\n break\n\n conn.commit()\n conn.close()\n\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"update users set username = '\" + str(username) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n conn.execute(\"update users set last_update = '\" + str(last_try_new) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n conn.execute(\"update users set last_problem = '\" + str(last_problem) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n\n settings.commit()\n settings.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[426, 527], [862, 980], [2870, 2985], [3079, 3279], [3316, 3516], [3707, 4055]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[426, 527], [862, 980], [2870, 2985], [3079, 3279], [3316, 3516], [3707, 4055]]}, "_func_name": "update_user", "_file_name": "bases/update.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def list(self, keyfilter='/'):\n path = self._absolute_key(keyfilter)\n if path != '/':\n path = path.rstrip('/')\n try:\n result = self.etcd.read(path, recursive=True)\n except etcd.EtcdKeyNotFound:\n return None\n except etcd.EtcdException as err:\n log_error(\"Error listing %s: [%r]\" % (keyfilter, repr(err)))\n raise CSStoreError('Error occurred while trying to list keys')\n\n value = set()\n for entry in result.get_subtree():\n if entry.key == path:\n continue\n name = entry.key[len(path):]\n if entry.dir and not name.endswith('/'):\n name += '/'\n value.add(name.lstrip('/'))\n return sorted(value)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "list", "_file_name": "custodia/store/etcdstore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "header_cache_t *imap_hcache_open(struct ImapData *idata, const char *path)\n{\n struct ImapMbox mx;\n struct Url url;\n char cachepath[PATH_MAX];\n char mbox[PATH_MAX];\n\n if (path)\n imap_cachepath(idata, path, mbox, sizeof(mbox));\n else\n {\n if (!idata->ctx || imap_parse_path(idata->ctx->path, &mx) < 0)\n return NULL;\n\n imap_cachepath(idata, mx.mbox, mbox, sizeof(mbox));\n FREE(&mx.mbox);\n }\n\n if (strstr(mbox, \"/../\") || (strcmp(mbox, \"..\") == 0) || (strncmp(mbox, \"../\", 3) == 0))\n return NULL;\n size_t len = strlen(mbox);\n if ((len > 3) && (strcmp(mbox + len - 3, \"/..\") == 0))\n return NULL;\n\n mutt_account_tourl(&idata->conn->account, &url);\n url.path = mbox;\n url_tostring(&url, cachepath, sizeof(cachepath), U_PATH);\n\n return mutt_hcache_open(HeaderCache, cachepath, imap_hcache_namer);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "imap_hcache_open", "_file_name": "imap/util.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "search_make_new(const struct search_state *const state, int n, const char *const base_name) {\n\tconst size_t base_len = strlen(base_name);\n\tconst char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;\n\tstruct search_domain *dom;\n\n\tfor (dom = state->head; dom; dom = dom->next) {\n\t\tif (!n--) {\n\t\t\t/* this is the postfix we want */\n\t\t\t/* the actual postfix string is kept at the end of the structure */\n\t\t\tconst u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);\n\t\t\tconst int postfix_len = dom->len;\n\t\t\tchar *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);\n\t\t\tif (!newname) return NULL;\n\t\t\tmemcpy(newname, base_name, base_len);\n\t\t\tif (need_to_append_dot) newname[base_len] = '.';\n\t\t\tmemcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);\n\t\t\tnewname[base_len + need_to_append_dot + postfix_len] = 0;\n\t\t\treturn newname;\n\t\t}\n\t}\n\n\t/* we ran off the end of the list and still didn't find the requested string */\n\tEVUTIL_ASSERT(0);\n\treturn NULL; /* unreachable; stops warnings in some compilers. */\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[138, 239]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[138, 239]]}, "_func_name": "search_make_new", "_file_name": "evdns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void ip4_datagram_release_cb(struct sock *sk)\n{\n\tconst struct inet_sock *inet = inet_sk(sk);\n\tconst struct ip_options_rcu *inet_opt;\n\t__be32 daddr = inet->inet_daddr;\n\tstruct dst_entry *dst;\n\tstruct flowi4 fl4;\n\tstruct rtable *rt;\n\n\trcu_read_lock();\n\n\tdst = __sk_dst_get(sk);\n\tif (!dst || !dst->obsolete || dst->ops->check(dst, 0)) {\n\t\trcu_read_unlock();\n\t\treturn;\n\t}\n\tinet_opt = rcu_dereference(inet->inet_opt);\n\tif (inet_opt && inet_opt->opt.srr)\n\t\tdaddr = inet_opt->opt.faddr;\n\trt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr,\n\t\t\t\t inet->inet_saddr, inet->inet_dport,\n\t\t\t\t inet->inet_sport, sk->sk_protocol,\n\t\t\t\t RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);\n\n\tdst = !IS_ERR(rt) ? &rt->dst : NULL;\n\tsk_dst_set(sk, dst);\n\n\trcu_read_unlock();\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ip4_datagram_release_cb", "_file_name": "net/ipv4/datagram.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n const size_t number_coordinates)\n{\n double\n alpha,\n *coefficients,\n weight;\n\n PointInfo\n end,\n point,\n *points;\n\n PrimitiveInfo\n *primitive_info;\n\n register PrimitiveInfo\n *p;\n\n register ssize_t\n i,\n j;\n\n size_t\n control_points,\n quantum;\n\n /*\n Allocate coefficients.\n */\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n quantum=number_coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n for (j=i+1; j < (ssize_t) number_coordinates; j++)\n {\n alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n }\n }\n quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n coefficients=(double *) AcquireQuantumMemory(number_coordinates,\n sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*\n sizeof(*points));\n if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))\n {\n if (points != (PointInfo *) NULL)\n points=(PointInfo *) RelinquishMagickMemory(points);\n if (coefficients != (double *) NULL)\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n control_points=quantum*number_coordinates;\n if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n /*\n Compute bezier points.\n */\n end=primitive_info[number_coordinates-1].point;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);\n weight=0.0;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n p=primitive_info;\n point.x=0.0;\n point.y=0.0;\n alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);\n for (j=0; j < (ssize_t) number_coordinates; j++)\n {\n point.x+=alpha*coefficients[j]*p->point.x;\n point.y+=alpha*coefficients[j]*p->point.y;\n alpha*=weight/(1.0-weight);\n p++;\n }\n points[i]=point;\n weight+=1.0/control_points;\n }\n /*\n Bezier curves are just short segmented polys.\n */\n p=primitive_info;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n if (TracePoint(p,points[i]) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n }\n if (TracePoint(p,end) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n primitive_info->closed_subpath=MagickFalse;\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickTrue);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1342, 1468]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1342, 1468]]}, "_func_name": "TraceBezier", "_file_name": "MagickCore/draw.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def upsert_mapped_projects(user_id: int, project_id: int):\n \"\"\" Adds projects to mapped_projects if it doesn't exist \"\"\"\n sql = \"select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'\"\n result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)\n\n if result.rowcount > 0:\n return # User has previously mapped this project so return\n\n sql = '''update users\n set projects_mapped = array_append(projects_mapped, :project_id)\n where id = :user_id'''\n\n db.engine.execute(text(sql), project_id=project_id, user_id=user_id)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "upsert_mapped_projects", "_file_name": "server/models/postgis/user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_mod_taken_together_with(code):\n '''\n Retrieves the list of modules taken together with the specified\n module code in the same semester.\n\n Returns a table of lists (up to 10 top results). Each list contains\n (specified code, module code of mod taken together, aySem, number of students)\n\n e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students\n taking CS1010 and CS1231 together in AY 16/17 Sem 1.\n '''\n NUM_TOP_RESULTS_TO_RETURN = 10\n\n sql_command = \"SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) \" + \\\n \"FROM studentPlans sp1, studentPlans sp2 \" + \\\n \"WHERE sp1.moduleCode = '\" + code + \"' AND \" + \\\n \"sp2.moduleCode <> sp1.moduleCode AND \" + \\\n \"sp1.studentId = sp2.studentId AND \" + \\\n \"sp1.acadYearAndSem = sp2.acadYearAndSem \" + \\\n \"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem \" + \\\n \"ORDER BY COUNT(*) DESC\"\n\n DB_CURSOR.execute(sql_command)\n\n return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[665, 730]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[665, 730]]}, "_func_name": "get_mod_taken_together_with", "_file_name": "components/model.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "TiledInputFile::rawTileData (int &dx, int &dy,\n\t\t\t int &lx, int &ly,\n const char *&pixelData,\n\t\t\t int &pixelDataSize)\n{\n try\n {\n Lock lock (*_data->_streamData);\n\n if (!isValidTile (dx, dy, lx, ly))\n throw IEX_NAMESPACE::ArgExc (\"Tried to read a tile outside \"\n\t\t\t \"the image file's data window.\");\n\n TileBuffer *tileBuffer = _data->getTileBuffer (0);\n\n //\n // if file is a multipart file, we have to seek to the required tile\n // since we don't know where the file pointer is\n //\n int old_dx=dx;\n int old_dy=dy;\n int old_lx=lx;\n int old_ly=ly;\n if(isMultiPart(version()))\n {\n _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly));\n }\n readNextTileData (_data->_streamData, _data, dx, dy, lx, ly,\n\t\t\t tileBuffer->buffer,\n pixelDataSize);\n if(isMultiPart(version()))\n {\n if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly)\n {\n throw IEX_NAMESPACE::ArgExc (\"rawTileData read the wrong tile\");\n }\n }\n else\n {\n if(!isValidTile (dx, dy, lx, ly) )\n {\n throw IEX_NAMESPACE::IoExc (\"rawTileData read an invalid tile\");\n }\n }\n pixelData = tileBuffer->buffer;\n }\n catch (IEX_NAMESPACE::BaseExc &e)\n {\n REPLACE_EXC (e, \"Error reading pixel data from image \"\n \"file \\\"\" << fileName() << \"\\\". \" << e.what());\n throw;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TiledInputFile::rawTileData", "_file_name": "OpenEXR/IlmImf/ImfTiledInputFile.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def fetch_data(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = (\"SELECT data FROM %s WHERE identifier = '%s';\" %\n (self.table, sid)\n )\n res = self._query(query)\n try:\n data = res.dictresult()[0]['data']\n except IndexError:\n raise ObjectDoesNotExistException(id)\n try:\n ndata = pg.unescape_bytea(data)\n except:\n # insufficient PyGreSQL version\n ndata = data.replace(\"\\\\'\", \"'\")\n\n ndata = ndata.replace('\\\\000\\\\001', nonTextToken)\n ndata = ndata.replace('\\\\012', '\\n')\n return ndata", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[207, 308]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[207, 308]]}, "_func_name": "fetch_data", "_file_name": "cheshire3/sql/postgresStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def delete_playlist(id, db):\n db.execute(\"DELETE FROM playlist where id=%s;\", (id,))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "delete_playlist", "_file_name": "playlist/playlist_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)\n{\n uint32_t w, h;\n uint32_t shift;\n uint32_t leftbyte;\n uint8_t *ss;\n uint8_t *dd;\n uint8_t leftmask, rightmask;\n int early = x >= 0;\n int late;\n uint32_t bytewidth;\n uint32_t syoffset = 0;\n\n if (src == NULL)\n return 0;\n\n /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */\n\n /* Data is packed msb first within a byte, so with bits numbered: 01234567.\n * Second byte is: 89abcdef. So to combine into a run, we use:\n * (s[0]<<8) | s[1] == 0123456789abcdef.\n * To read from src into dst at offset 3, we need to read:\n * read: 0123456789abcdef...\n * write: 0123456798abcdef...\n * In general, to read from src and write into dst at offset x, we need to shift\n * down by (x&7) bits to allow for bit alignment. So shift = x&7.\n * So the 'central' part of our runs will see us doing:\n * *d++ op= ((s[0]<<8)|s[1])>>shift;\n * with special cases on the left and right edges of the run to mask.\n * With the left hand edge, we have to be careful not to 'underread' the start of\n * the src image; this is what the early flag is about. Similarly we have to be\n * careful not to read off the right hand edge; this is what the late flag is for.\n */\n\n /* clip */\n w = src->width;\n h = src->height;\n shift = (x & 7);\n ss = src->data - early;\n\n if (x < 0) {\n if (w < (uint32_t) -x)\n w = 0;\n else\n w += x;\n ss += (-x-1)>>3;\n x = 0;\n }\n if (y < 0) {\n if (h < (uint32_t) -y)\n h = 0;\n else\n h += y;\n syoffset = -y * src->stride;\n y = 0;\n }\n if ((uint32_t)x + w > dst->width)\n {\n if (dst->width < (uint32_t)x)\n w = 0;\n else\n w = dst->width - x;\n }\n if ((uint32_t)y + h > dst->height)\n {\n if (dst->height < (uint32_t)y)\n h = 0;\n else\n h = dst->height - y;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"compositing %dx%d at (%d, %d) after clipping\", w, h, x, y);\n#endif\n\n /* check for zero clipping region */\n if ((w <= 0) || (h <= 0)) {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"zero clipping region\");\n#endif\n return 0;\n }\n\n leftbyte = (uint32_t) x >> 3;\n dd = dst->data + y * dst->stride + leftbyte;\n bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1;\n leftmask = 255>>(x&7);\n rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7));\n if (bytewidth == 1)\n leftmask &= rightmask;\n late = (ss + bytewidth >= src->data + ((src->width+7)>>3));\n ss += syoffset;\n\n switch(op)\n {\n case JBIG2_COMPOSE_OR:\n jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_AND:\n jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_XOR:\n jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_XNOR:\n jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_REPLACE:\n jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n }\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[363, 462]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[363, 462]]}, "_func_name": "jbig2_image_compose", "_file_name": "jbig2_image.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def closeGame(ID):\n\tdb.execute(\"UPDATE games set Running = 'No' WHERE ID = ?\", ID)\n\tdatabase.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "closeGame", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int get_task_ioprio(struct task_struct *p)\n{\n\tint ret;\n\n\tret = security_task_getioprio(p);\n\tif (ret)\n\t\tgoto out;\n\tret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM);\n\ttask_lock(p);\n\tif (p->io_context)\n\t\tret = p->io_context->ioprio;\n\ttask_unlock(p);\nout:\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_task_ioprio", "_file_name": "block/ioprio.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "mrb_class_real(struct RClass* cl)\n{\n if (cl == 0) return NULL;\n while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {\n cl = cl->super;\n if (cl == 0) return NULL;\n }\n return cl;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mrb_class_real", "_file_name": "src/class.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static ExprList *exprListAppendList(\n Parse *pParse, /* Parsing context */\n ExprList *pList, /* List to which to append. Might be NULL */\n ExprList *pAppend, /* List of values to append. Might be NULL */\n int bIntToNull\n){\n if( pAppend ){\n int i;\n int nInit = pList ? pList->nExpr : 0;\n for(i=0; inExpr; i++){\n Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);\n if( bIntToNull && pDup && pDup->op==TK_INTEGER ){\n pDup->op = TK_NULL;\n pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);\n }\n pList = sqlite3ExprListAppend(pParse, pList, pDup);\n if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;\n }\n }\n return pList;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[426, 482]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[426, 482]]}, "_func_name": "exprListAppendList", "_file_name": "src/window.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def user_verify(self):\n eid = self.email\n code = self.password\n if eid.strip() == '':\n return\n if code.strip() == '':\n return\n query = '''select * from usr where email like\\''''+eid+'\\''\n cursor = g.conn.execute(query)\n for row in cursor:\n key = str(row.password)\n if key.strip() == code.strip():\n self.name = str(row.name)\n self.email = eid\n self.id = eid\n self.valid = True\n break", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[180, 248]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[180, 248]]}, "_func_name": "user_verify", "_file_name": "Web-app/User.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def _add_to_db(user):\n \"\"\"\n Adds User object to the database\n :param user: User object with info about user\n :return: None\n \"\"\"\n query = (\"INSERT INTO users (chat_id, first_name, nickname, \"\n \"last_name, language) \"\n f\"VALUES ({user.chat_id}, '{user.first_name}', \"\n f\"'{user.nickname}', '{user.last_name}', '{user.language}')\")\n try:\n db.add(query)\n except DatabaseError:\n log.error(\"Cannot add user to the database\")\n else:\n log.info(f\"User {user} was successfully added to the users db\")", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[296, 441]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[296, 441]]}, "_func_name": "_add_to_db", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def mode_close(self, request):\n \"\"\"\n This is called by render_POST when the client is signalling\n that it is about to be closed.\n\n Args:\n request (Request): Incoming request.\n\n \"\"\"\n csessid = request.args.get('csessid')[0]\n try:\n sess = self.sessionhandler.sessions_from_csessid(csessid)[0]\n sess.sessionhandler.disconnect(sess)\n except IndexError:\n self.client_disconnect(csessid)\n return '\"\"'", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[231, 280]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[231, 280]]}, "_func_name": "mode_close", "_file_name": "evennia/server/portal/webclient_ajax.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,\n MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)\n{\n char\n postscript_file[MaxTextExtent];\n\n const MagicInfo\n *magic_info;\n\n FILE\n *ps_file;\n\n ImageInfo\n *clone_info;\n\n Image\n *image2;\n\n unsigned char\n magick[2*MaxTextExtent];\n\n\n if ((clone_info=CloneImageInfo(image_info)) == NULL)\n return(image);\n clone_info->blob=(void *) NULL;\n clone_info->length=0;\n\n /* Obtain temporary file */\n (void) AcquireUniqueFilename(postscript_file);\n ps_file=fopen_utf8(postscript_file,\"wb\");\n if (ps_file == (FILE *) NULL)\n goto FINISH;\n\n /* Copy postscript to temporary file */\n (void) SeekBlob(image,PS_Offset,SEEK_SET);\n (void) ReadBlob(image, 2*MaxTextExtent, magick);\n\n (void) SeekBlob(image,PS_Offset,SEEK_SET);\n while(PS_Size-- > 0)\n {\n (void) fputc(ReadBlobByte(image),ps_file);\n }\n (void) fclose(ps_file);\n\n /* Detect file format - Check magic.mgk configuration file. */\n magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);\n if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;\n /* printf(\"Detected:%s \\n\",magic_info->name); */\n if(exception->severity != UndefinedException) goto FINISH_UNL;\n if(magic_info->name == (char *) NULL) goto FINISH_UNL;\n\n (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);\n\n /* Read nested image */\n /*FormatString(clone_info->filename,\"%s:%s\",magic_info->name,postscript_file);*/\n FormatLocaleString(clone_info->filename,MaxTextExtent,\"%s\",postscript_file);\n image2=ReadImage(clone_info,exception);\n\n if (!image2)\n goto FINISH_UNL;\n\n /*\n Replace current image with new image while copying base image\n attributes.\n */\n (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);\n (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);\n (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);\n image2->depth=image->depth;\n DestroyBlob(image2);\n image2->blob=ReferenceBlob(image->blob);\n\n if ((image->rows == 0) || (image->columns == 0))\n DeleteImageFromList(&image);\n\n AppendImageToList(&image,image2);\n\n FINISH_UNL:\n (void) RelinquishUniqueFileResource(postscript_file);\n FINISH:\n DestroyImageInfo(clone_info);\n return(image);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ExtractPostscript", "_file_name": "coders/wpg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n const size_t number_coordinates)\n{\n double\n alpha,\n *coefficients,\n weight;\n\n PointInfo\n end,\n point,\n *points;\n\n PrimitiveInfo\n *primitive_info;\n\n register PrimitiveInfo\n *p;\n\n register ssize_t\n i,\n j;\n\n size_t\n control_points,\n quantum;\n\n /*\n Allocate coefficients.\n */\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n quantum=number_coordinates;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n {\n for (j=i+1; j < (ssize_t) number_coordinates; j++)\n {\n alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);\n if (alpha > (double) SSIZE_MAX)\n {\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n if (alpha > (double) quantum)\n quantum=(size_t) alpha;\n }\n }\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n coefficients=(double *) AcquireQuantumMemory(number_coordinates,\n sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*\n sizeof(*points));\n if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))\n {\n if (points != (PointInfo *) NULL)\n points=(PointInfo *) RelinquishMagickMemory(points);\n if (coefficients != (double *) NULL)\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n (void) ThrowMagickException(mvg_info->exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",\"\");\n return(MagickFalse);\n }\n control_points=quantum*number_coordinates;\n if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n /*\n Compute bezier points.\n */\n end=primitive_info[number_coordinates-1].point;\n for (i=0; i < (ssize_t) number_coordinates; i++)\n coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);\n weight=0.0;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n p=primitive_info;\n point.x=0.0;\n point.y=0.0;\n alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);\n for (j=0; j < (ssize_t) number_coordinates; j++)\n {\n point.x+=alpha*coefficients[j]*p->point.x;\n point.y+=alpha*coefficients[j]*p->point.y;\n alpha*=weight/(1.0-weight);\n p++;\n }\n points[i]=point;\n weight+=1.0/control_points;\n }\n /*\n Bezier curves are just short segmented polys.\n */\n p=primitive_info;\n for (i=0; i < (ssize_t) control_points; i++)\n {\n if (TracePoint(p,points[i]) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n }\n if (TracePoint(p,end) == MagickFalse)\n {\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n p+=p->coordinates;\n primitive_info->coordinates=(size_t) (p-primitive_info);\n primitive_info->closed_subpath=MagickFalse;\n for (i=0; i < (ssize_t) primitive_info->coordinates; i++)\n {\n p->primitive=primitive_info->primitive;\n p--;\n }\n points=(PointInfo *) RelinquishMagickMemory(points);\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickTrue);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "TraceBezier", "_file_name": "MagickCore/draw.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def insertData(self,userid,post):\n sqlText=\"insert into post(userid,date,comment) \\\n values(%d,current_timestamp(0),'%s');\"%(userid,post);\n result=sql.insertDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[95, 165]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[95, 165]]}, "_func_name": "insertData", "_file_name": "modules/post.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _call_prepare_fc_map(self, fc_map_id, source, target):\n try:\n out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id)\n except exception.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source,\n 'target': target,\n 'out': e.stdout,\n 'err': e.stderr})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[76, 153]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[76, 153]]}, "_func_name": "_call_prepare_fc_map", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/delete_crawl', methods=['POST'])\n@is_logged_in\ndef delete_crawl():\n\n # Get Form Fields\n cid = request.form['cid']\n\n # Create cursor\n cur = mysql.connection.cursor()\n\n # Get user by username\n result = cur.execute(\"DELETE FROM Crawls WHERE cid = %s\" % cid)\n\n # Commit to DB\n mysql.connection.commit()\n\n # Close connection\n cur.close()\n\n # FIXME check if successfull first, return message\n flash('Crawl successfully removed', 'success')\n\n return redirect(url_for('dashboard'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[238, 310]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[238, 310]]}, "_func_name": "delete_crawl", "_file_name": "bar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data)\n\t{\n\tconst u_char* data_start = data;\n\n\tif ( len <= 0 )\n\t\treturn 0;\n\n\tfor ( ; len > 0; --len, ++data )\n\t\t{\n\t\tif ( offset >= buf_len )\n\t\t\tInitBuffer(buf_len * 2);\n\n\t\tint c = data[0];\n\n#define EMIT_LINE \\\n\t{ \\\n\tbuf[offset] = '\\0'; \\\n\tint seq_len = data + 1 - data_start; \\\n\tseq_delivered_in_lines = seq + seq_len; \\\n\tlast_char = c; \\\n\tForwardStream(offset, buf, IsOrig()); \\\n\toffset = 0; \\\n\treturn seq_len; \\\n\t}\n\n\t\tswitch ( c ) {\n\t\tcase '\\r':\n\t\t\t// Look ahead for '\\n'.\n\t\t\tif ( len > 1 && data[1] == '\\n' )\n\t\t\t\t{\n\t\t\t\t--len; ++data;\n\t\t\t\tlast_char = c;\n\t\t\t\tc = data[0];\n\t\t\t\tEMIT_LINE\n\t\t\t\t}\n\n\t\t\telse if ( CR_LF_as_EOL & CR_as_EOL )\n\t\t\t\tEMIT_LINE\n\n\t\t\telse\n\t\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\n\t\tcase '\\n':\n\t\t\tif ( last_char == '\\r' )\n\t\t\t\t{\n\t\t\t\t// Weird corner-case:\n\t\t\t\t// this can happen if we see a \\r at the end of a packet where crlf is\n\t\t\t\t// set to CR_as_EOL | LF_as_EOL, with the packet causing crlf to be set to\n\t\t\t\t// 0 and the next packet beginning with a \\n. In this case we just swallow\n\t\t\t\t// the character and re-set last_char.\n\t\t\t\tif ( offset == 0 )\n\t\t\t\t\t{\n\t\t\t\t\tlast_char = c;\n\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t--offset; // remove '\\r'\n\t\t\t\tEMIT_LINE\n\t\t\t\t}\n\n\t\t\telse if ( CR_LF_as_EOL & LF_as_EOL )\n\t\t\t\tEMIT_LINE\n\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tif ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) )\n\t\t\t\t\tConn()->Weird(\"line_terminated_with_single_LF\");\n\t\t\t\tbuf[offset++] = c;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase '\\0':\n\t\t\tif ( flag_NULs )\n\t\t\t\tCheckNUL();\n\t\t\telse\n\t\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbuf[offset++] = c;\n\t\t\tbreak;\n\t\t}\n\n\t\tif ( last_char == '\\r' )\n\t\t\tif ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) )\n\t\t\t\tConn()->Weird(\"line_terminated_with_single_CR\");\n\n\t\tlast_char = c;\n\t\t}\n\n\treturn data - data_start;\n\t}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ContentLine_Analyzer::DoDeliverOnce", "_file_name": "src/analyzer/protocol/tcp/ContentLine.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name)\n{\n INITIALIZE_LIBREPORT();\n\n char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER);\n\n if (!type)\n {\n error_msg(_(\"Missing required item: '%s'\"), FILENAME_ANALYZER);\n return NULL;\n }\n\n if (!str_is_correct_filename(type))\n {\n error_msg(_(\"'%s' is not correct file name\"), FILENAME_ANALYZER);\n return NULL;\n }\n\n uid_t uid = (uid_t)-1L;\n char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);\n\n if (uid_str)\n {\n char *endptr;\n errno = 0;\n long val = strtol(uid_str, &endptr, 10);\n\n if (errno != 0 || endptr == uid_str || *endptr != '\\0' || INT_MAX < val)\n {\n error_msg(_(\"uid value is not valid: '%s'\"), uid_str);\n return NULL;\n }\n\n uid = (uid_t)val;\n }\n\n struct timeval tv;\n if (gettimeofday(&tv, NULL) < 0)\n {\n perror_msg(\"gettimeofday()\");\n return NULL;\n }\n\n char *problem_id = xasprintf(\"%s-%s.%ld-%lu\"NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid());\n\n log_info(\"Saving to %s/%s with uid %d\", base_dir_name, problem_id, uid);\n\n struct dump_dir *dd;\n if (base_dir_name)\n dd = try_dd_create(base_dir_name, problem_id, uid);\n else\n {\n /* Try /var/run/abrt */\n dd = try_dd_create(LOCALSTATEDIR\"/run/abrt\", problem_id, uid);\n /* Try $HOME/tmp */\n if (!dd)\n {\n char *home = getenv(\"HOME\");\n if (home && home[0])\n {\n home = concat_path_file(home, \"tmp\");\n /*mkdir(home, 0777); - do we want this? */\n dd = try_dd_create(home, problem_id, uid);\n free(home);\n }\n }\n//TODO: try user's home dir obtained by getpwuid(getuid())?\n /* Try system temporary directory */\n if (!dd)\n dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid);\n }\n\n if (!dd) /* try_dd_create() already emitted the error message */\n goto ret;\n\n GHashTableIter iter;\n char *name;\n struct problem_item *value;\n g_hash_table_iter_init(&iter, problem_data);\n while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))\n {\n if (!str_is_correct_filename(name))\n {\n error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n continue;\n }\n\n if (value->flags & CD_FLAG_BIN)\n {\n char *dest = concat_path_file(dd->dd_dirname, name);\n log_info(\"copying '%s' to '%s'\", value->content, dest);\n off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH);\n if (copied < 0)\n error_msg(\"Can't copy %s to %s\", value->content, dest);\n else\n log_info(\"copied %li bytes\", (unsigned long)copied);\n free(dest);\n\n continue;\n }\n\n dd_save_text(dd, name, value->content);\n }\n\n /* need to create basic files AFTER we save the pd to dump_dir\n * otherwise we can't skip already created files like in case when\n * reporting from anaconda where we can't read /etc/{system,redhat}-release\n * and os_release is taken from anaconda\n */\n dd_create_basic_files(dd, uid, NULL);\n\n problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\\0';\n char* new_path = concat_path_file(base_dir_name, problem_id);\n log_info(\"Renaming from '%s' to '%s'\", dd->dd_dirname, new_path);\n dd_rename(dd, new_path);\n\n ret:\n free(problem_id);\n return dd;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "create_dump_dir_from_problem_data", "_file_name": "src/lib/create_dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)\n{\n Buffer save;\n char *p;\n int spos, epos, rows, c_rows, pos, col = 0;\n Line *l;\n\n copyBuffer(&save, buf);\n gotoLine(buf, a->start.line);\n switch (form->type) {\n case FORM_TEXTAREA:\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n#endif\t\t\t\t/* MENU_SELECT */\n\tspos = a->start.pos;\n\tepos = a->end.pos;\n\tbreak;\n default:\n\tspos = a->start.pos + 1;\n\tepos = a->end.pos - 1;\n }\n switch (form->type) {\n case FORM_INPUT_CHECKBOX:\n case FORM_INPUT_RADIO:\n\tif (buf->currentLine == NULL ||\n\t spos >= buf->currentLine->len || spos < 0)\n\t break;\n\tif (form->checked)\n\t buf->currentLine->lineBuf[spos] = '*';\n\telse\n\t buf->currentLine->lineBuf[spos] = ' ';\n\tbreak;\n case FORM_INPUT_TEXT:\n case FORM_INPUT_FILE:\n case FORM_INPUT_PASSWORD:\n case FORM_TEXTAREA:\n#ifdef MENU_SELECT\n case FORM_SELECT:\n\tif (form->type == FORM_SELECT) {\n\t p = form->label->ptr;\n\t updateSelectOption(form, form->select_option);\n\t}\n\telse\n#endif\t\t\t\t/* MENU_SELECT */\n\t{\n\t if (!form->value)\n\t\tbreak;\n\t p = form->value->ptr;\n\t}\n\tl = buf->currentLine;\n\tif (!l)\n\t break;\n\tif (form->type == FORM_TEXTAREA) {\n\t int n = a->y - buf->currentLine->linenumber;\n\t if (n > 0)\n\t\tfor (; l && n; l = l->prev, n--) ;\n\t else if (n < 0)\n\t\tfor (; l && n; l = l->prev, n++) ;\n\t if (!l)\n\t\tbreak;\n\t}\n\trows = form->rows ? form->rows : 1;\n\tcol = COLPOS(l, a->start.pos);\n\tfor (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {\n\t if (rows > 1) {\n\t\tpos = columnPos(l, col);\n\t\ta = retrieveAnchor(buf->formitem, l->linenumber, pos);\n\t\tif (a == NULL)\n\t\t break;\n\t\tspos = a->start.pos;\n\t\tepos = a->end.pos;\n\t }\n\t if (a->start.line != a->end.line || spos > epos || epos >= l->len ||\n\t\tspos < 0 || epos < 0 || COLPOS(l, epos) < col)\n\t\tbreak;\n\t pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,\n\t\t\t\t rows > 1,\n\t\t\t\t form->type == FORM_INPUT_PASSWORD);\n\t if (pos != epos) {\n\t\tshiftAnchorPosition(buf->href, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->name, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->img, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t\tshiftAnchorPosition(buf->formitem, buf->hmarklist,\n\t\t\t\t a->start.line, spos, pos - epos);\n\t }\n\t}\n\tbreak;\n }\n copyBuffer(buf, &save);\n arrangeLine(buf);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1647, 1668]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1647, 1668]]}, "_func_name": "formUpdateBuffer", "_file_name": "form.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def htmlvalue(self, val):\n return self.block.render_basic(val)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[30, 73]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[30, 73]]}, "_func_name": "htmlvalue", "_file_name": "wagtail/admin/compare.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_sources(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the source table.\n \"\"\"\n current_sources = get_all_current_sources(k10plus, ai)\n old_sources = get_all_old_sources(conn, sqlite)\n\n # Check if the source table is allready filled and this is not the first checkup\n source_table_is_filled = len(old_sources) > 100\n\n for old_source in old_sources:\n if source_table_is_filled and old_source not in current_sources:\n message = \"Die SID %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die SID aus der Datenbank loeschen.\" % old_source\n send_message(message)\n\n for current_source in current_sources:\n if current_source not in old_sources:\n message = \"The source %s is new in Solr.\" % current_source\n if source_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO source (source) VALUES (%s)\" % current_source\n sqlite.execute(sql)\n conn.commit()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[943, 1020]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[943, 1020]]}, "_func_name": "update_sources", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {\n\tRASN1Object *object;\n\tRCMS *container;\n\tif (!buffer || !length) {\n\t\treturn NULL;\n\t}\n\tcontainer = R_NEW0 (RCMS);\n\tif (!container) {\n\t\treturn NULL;\n\t}\n\tobject = r_asn1_create_object (buffer, length);\n\tif (!object || object->list.length != 2 || !object->list.objects ||\n\t\t!object->list.objects[0] || !object->list.objects[1] ||\n\t\tobject->list.objects[1]->list.length != 1) {\n\t\tr_asn1_free_object (object);\n\t\tfree (container);\n\t\treturn NULL;\n\t}\n\tcontainer->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);\n\tr_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);\n\tr_asn1_free_object (object);\n\treturn container;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "r_pkcs7_parse_cms", "_file_name": "libr/util/r_pkcs7.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def insert(key, value):\n connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])\n cur = connection.cursor()\n try:\n cur.execute(\"insert into reply_map values('{}', '{}')\".format(key, value))\n connection.commit()\n except:\n pass", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[214, 297]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[214, 297]]}, "_func_name": "insert", "_file_name": "db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def misc_file_checks(self):\n\n print_header(\"MISC FILE CHECKS\")\n\n #\n # Check for recommended and mandatory files\n #\n\n filenames = (\"manifest.json\", \"LICENSE\", \"README.md\",\n \"scripts/install\", \"scripts/remove\",\n \"scripts/upgrade\",\n \"scripts/backup\", \"scripts/restore\")\n non_mandatory = (\"script/backup\", \"script/restore\")\n\n for filename in filenames:\n if file_exists(self.path + \"/\" + filename):\n continue\n elif filename in non_mandatory:\n print_warning(\"Consider adding a file %s\" % filename)\n else:\n print_error(\"File %s is mandatory\" % filename)\n\n #\n # Deprecated php-fpm.ini thing\n #\n\n if file_exists(self.path + \"/conf/php-fpm.ini\"):\n print_warning(\n \"Using a separate php-fpm.ini file is deprecated. \"\n \"Please merge your php-fpm directives directly in the pool file. \"\n \"(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )\"\n )\n\n #\n # Analyze nginx conf\n # - Deprecated usage of 'add_header' in nginx conf\n # - Spot path traversal issue vulnerability\n #\n\n for filename in os.listdir(self.path + \"/conf\"):\n # Ignore subdirs or filename not containing nginx in the name\n if not os.path.isfile(self.path + \"/conf/\" + filename) or \"nginx\" not in filename:\n continue\n\n #\n # 'add_header' usage\n #\n content = open(self.path + \"/conf/\" + filename).read()\n if \"location\" in content and \"add_header\" in content:\n print_warning(\n \"Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. \"\n \"(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx \"\n \"and https://github.com/openresty/headers-more-nginx-module#more_set_headers )\"\n )\n\n #\n # Path traversal issues\n #\n lines = open(self.path + \"/conf/\" + filename).readlines()\n lines = [line.strip() for line in lines if not line.strip().startswith(\"#\")]\n # Let's find the first location line\n location_line = None\n path_traversal_vulnerable = False\n lines_iter = lines.__iter__()\n for line in lines_iter:\n if line.startswith(\"location\"):\n location_line = line\n break\n # Look at the next lines for an 'alias' directive\n if location_line is not None:\n for line in lines_iter:\n if line.startswith(\"location\"):\n # Entering a new location block ... abort here\n # and assume there's no alias block later...\n break\n if line.startswith(\"alias\"):\n # We should definitely check for path traversal issue\n # Does the location target ends with / ?\n target = location_line.split()[-2]\n if not target.endswith(\"/\"):\n path_traversal_vulnerable = True\n break\n if path_traversal_vulnerable:\n print_warning(\n \"The nginx configuration appears vulnerable to path traversal as explained in \"\n \"https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/\\n\"\n \"To fix it, look at the first lines of the nginx conf of the example app : \"\n \"https://github.com/YunoHost/example_ynh/blob/master/conf/nginx.conf\"\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "misc_file_checks", "_file_name": "package_linter.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void *__ns_get_path(struct path *path, struct ns_common *ns)\n{\n\tstruct vfsmount *mnt = nsfs_mnt;\n\tstruct qstr qname = { .name = \"\", };\n\tstruct dentry *dentry;\n\tstruct inode *inode;\n\tunsigned long d;\n\n\trcu_read_lock();\n\td = atomic_long_read(&ns->stashed);\n\tif (!d)\n\t\tgoto slow;\n\tdentry = (struct dentry *)d;\n\tif (!lockref_get_not_dead(&dentry->d_lockref))\n\t\tgoto slow;\n\trcu_read_unlock();\n\tns->ops->put(ns);\ngot_it:\n\tpath->mnt = mntget(mnt);\n\tpath->dentry = dentry;\n\treturn NULL;\nslow:\n\trcu_read_unlock();\n\tinode = new_inode_pseudo(mnt->mnt_sb);\n\tif (!inode) {\n\t\tns->ops->put(ns);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\tinode->i_ino = ns->inum;\n\tinode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);\n\tinode->i_flags |= S_IMMUTABLE;\n\tinode->i_mode = S_IFREG | S_IRUGO;\n\tinode->i_fop = &ns_file_operations;\n\tinode->i_private = ns;\n\n\tdentry = d_alloc_pseudo(mnt->mnt_sb, &qname);\n\tif (!dentry) {\n\t\tiput(inode);\n\t\treturn ERR_PTR(-ENOMEM);\n\t}\n\td_instantiate(dentry, inode);\n\tdentry->d_flags |= DCACHE_RCUACCESS;\n\tdentry->d_fsdata = (void *)ns->ops;\n\td = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry);\n\tif (d) {\n\t\td_delete(dentry);\t/* make sure ->d_prune() does nothing */\n\t\tdput(dentry);\n\t\tcpu_relax();\n\t\treturn ERR_PTR(-EAGAIN);\n\t}\n\tgoto got_it;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__ns_get_path", "_file_name": "fs/nsfs.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@csrf.csrf_protect\ndef subscribe_for_tags(request):\n \"\"\"process subscription of users by tags\"\"\"\n #todo - use special separator to split tags\n tag_names = request.REQUEST.get('tags','').strip().split()\n pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)\n if request.user.is_authenticated():\n if request.method == 'POST':\n if 'ok' in request.POST:\n request.user.mark_tags(\n pure_tag_names,\n wildcards,\n reason = 'good',\n action = 'add'\n )\n request.user.message_set.create(\n message = _('Your tag subscription was saved, thanks!')\n )\n else:\n message = _(\n 'Tag subscription was canceled (undo).'\n ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n request.user.message_set.create(message = message)\n return HttpResponseRedirect(reverse('index'))\n else:\n data = {'tags': tag_names}\n return render(request, 'subscribe_for_tags.html', data)\n else:\n all_tag_names = pure_tag_names + wildcards\n message = _('Please sign in to subscribe for: %(tags)s') \\\n % {'tags': ', '.join(all_tag_names)}\n request.user.message_set.create(message = message)\n request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)\n return HttpResponseRedirect(url_utils.get_login_url())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[905, 984]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[905, 984]]}, "_func_name": "subscribe_for_tags", "_file_name": "askbot/views/commands.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tdec->numtiles = dec->numhtiles * dec->numvtiles;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno / dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. */\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[1312, 1362]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1312, 1362]]}, "_func_name": "jpc_dec_process_siz", "_file_name": "src/libjasper/jpc/jpc_dec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def karma_add(name):\n karma = karma_ask(name)\n db = db_connect()\n cursor = db.cursor()\n if karma is None:\n try:\n cursor.execute('''\n INSERT INTO people(name,karma,shame) VALUES('{}',1,0)\n '''.format(name))\n db.commit()\n logger.debug('Inserted into karmadb 1 karma for {}'.format(name))\n return 1\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n else:\n karma = karma + 1\n try:\n cursor.execute('''\n UPDATE people SET karma = {0} WHERE name = '{1}'\n '''.format(karma, name))\n db.commit()\n logger.debug('Inserted into karmadb {} karma for {}'.format(\n karma, name))\n return karma\n\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise\n db.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[162, 266], [588, 694]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[162, 266], [588, 694]]}, "_func_name": "karma_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def followFriends(self,userid,friendid):\n sqlText=\"insert into friends values(%s,%s);\"\n params=[friendid,userid]\n result=sql.insertDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "followFriends", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,\n\t\t\t\t\t\t\t\t\t\topj_cp_t *p_cp,\n\t\t\t\t\t\t\t\t\t\tOPJ_UINT32 p_tile_no)\n{\n\t/* loop */\n\tOPJ_UINT32 pino;\n\tOPJ_UINT32 compno, resno;\n\n\t/* to store w, h, dx and dy fro all components and resolutions */\n\tOPJ_UINT32 * l_tmp_data;\n\tOPJ_UINT32 ** l_tmp_ptr;\n\n\t/* encoding prameters to set */\n\tOPJ_UINT32 l_max_res;\n\tOPJ_UINT32 l_max_prec;\n\tOPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;\n\tOPJ_UINT32 l_dx_min,l_dy_min;\n\tOPJ_UINT32 l_bound;\n\tOPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;\n\tOPJ_UINT32 l_data_stride;\n\n\t/* pointers */\n\topj_pi_iterator_t *l_pi = 00;\n\topj_tcp_t *l_tcp = 00;\n\tconst opj_tccp_t *l_tccp = 00;\n\topj_pi_comp_t *l_current_comp = 00;\n\topj_image_comp_t * l_img_comp = 00;\n\topj_pi_iterator_t * l_current_pi = 00;\n\tOPJ_UINT32 * l_encoding_value_ptr = 00;\n\n\t/* preconditions in debug */\n\tassert(p_cp != 00);\n\tassert(p_image != 00);\n\tassert(p_tile_no < p_cp->tw * p_cp->th);\n\n\t/* initializations */\n\tl_tcp = &p_cp->tcps[p_tile_no];\n\tl_bound = l_tcp->numpocs+1;\n\n\tl_data_stride = 4 * OPJ_J2K_MAXRLVLS;\n\tl_tmp_data = (OPJ_UINT32*)opj_malloc(\n\t\tl_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));\n\tif\n\t\t(! l_tmp_data)\n\t{\n\t\treturn 00;\n\t}\n\tl_tmp_ptr = (OPJ_UINT32**)opj_malloc(\n\t\tp_image->numcomps * sizeof(OPJ_UINT32 *));\n\tif\n\t\t(! l_tmp_ptr)\n\t{\n\t\topj_free(l_tmp_data);\n\t\treturn 00;\n\t}\n\n\t/* memory allocation for pi */\n\tl_pi = opj_pi_create(p_image, p_cp, p_tile_no);\n\tif (!l_pi) {\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\treturn 00;\n\t}\n\n\tl_encoding_value_ptr = l_tmp_data;\n\t/* update pointer array */\n\tfor\n\t\t(compno = 0; compno < p_image->numcomps; ++compno)\n\t{\n\t\tl_tmp_ptr[compno] = l_encoding_value_ptr;\n\t\tl_encoding_value_ptr += l_data_stride;\n\t}\n\t/* get encoding parameters */\n\topj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);\n\n\t/* step calculations */\n\tl_step_p = 1;\n\tl_step_c = l_max_prec * l_step_p;\n\tl_step_r = p_image->numcomps * l_step_c;\n\tl_step_l = l_max_res * l_step_r;\n\n\t/* set values for first packet iterator */\n\tl_current_pi = l_pi;\n\n\t/* memory allocation for include */\n\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n\tif\n\t\t(!l_current_pi->include)\n\t{\n\t\topj_free(l_tmp_data);\n\t\topj_free(l_tmp_ptr);\n\t\topj_pi_destroy(l_pi, l_bound);\n\t\treturn 00;\n\t}\n\n\t/* special treatment for the first packet iterator */\n\tl_current_comp = l_current_pi->comps;\n\tl_img_comp = p_image->comps;\n\tl_tccp = l_tcp->tccps;\n\n\tl_current_pi->tx0 = l_tx0;\n\tl_current_pi->ty0 = l_ty0;\n\tl_current_pi->tx1 = l_tx1;\n\tl_current_pi->ty1 = l_ty1;\n\n\t/*l_current_pi->dx = l_img_comp->dx;*/\n\t/*l_current_pi->dy = l_img_comp->dy;*/\n\n\tl_current_pi->step_p = l_step_p;\n\tl_current_pi->step_c = l_step_c;\n\tl_current_pi->step_r = l_step_r;\n\tl_current_pi->step_l = l_step_l;\n\n\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\tfor\n\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t{\n\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\tl_current_comp->dx = l_img_comp->dx;\n\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t/* resolutions have already been initialized */\n\t\tfor\n\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t{\n\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t++l_res;\n\t\t}\n\t\t++l_current_comp;\n\t\t++l_img_comp;\n\t\t++l_tccp;\n\t}\n\t++l_current_pi;\n\n\tfor (pino = 1 ; pinocomps;\n\t\tl_img_comp = p_image->comps;\n\t\tl_tccp = l_tcp->tccps;\n\n\t\tl_current_pi->tx0 = l_tx0;\n\t\tl_current_pi->ty0 = l_ty0;\n\t\tl_current_pi->tx1 = l_tx1;\n\t\tl_current_pi->ty1 = l_ty1;\n\t\t/*l_current_pi->dx = l_dx_min;*/\n\t\t/*l_current_pi->dy = l_dy_min;*/\n\t\tl_current_pi->step_p = l_step_p;\n\t\tl_current_pi->step_c = l_step_c;\n\t\tl_current_pi->step_r = l_step_r;\n\t\tl_current_pi->step_l = l_step_l;\n\n\t\t/* allocation for components and number of components has already been calculated by opj_pi_create */\n\t\tfor\n\t\t\t(compno = 0; compno < l_current_pi->numcomps; ++compno)\n\t\t{\n\t\t\topj_pi_resolution_t *l_res = l_current_comp->resolutions;\n\t\t\tl_encoding_value_ptr = l_tmp_ptr[compno];\n\n\t\t\tl_current_comp->dx = l_img_comp->dx;\n\t\t\tl_current_comp->dy = l_img_comp->dy;\n\t\t\t/* resolutions have already been initialized */\n\t\t\tfor\n\t\t\t\t(resno = 0; resno < l_current_comp->numresolutions; resno++)\n\t\t\t{\n\t\t\t\tl_res->pdx = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pdy = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->pw = *(l_encoding_value_ptr++);\n\t\t\t\tl_res->ph = *(l_encoding_value_ptr++);\n\t\t\t\t++l_res;\n\t\t\t}\n\t\t\t++l_current_comp;\n\t\t\t++l_img_comp;\n\t\t\t++l_tccp;\n\t\t}\n\t\t/* special treatment*/\n\t\tl_current_pi->include = (l_current_pi-1)->include;\n\t\t++l_current_pi;\n\t}\n\topj_free(l_tmp_data);\n\tl_tmp_data = 00;\n\topj_free(l_tmp_ptr);\n\tl_tmp_ptr = 00;\n\tif\n\t\t(l_tcp->POC)\n\t{\n\t\topj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\telse\n\t{\n\t\topj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);\n\t}\n\treturn l_pi;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[2139, 2242]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2139, 2242]]}, "_func_name": "opj_pi_create_decode", "_file_name": "src/lib/openjp2/pi.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void rfbScaledScreenUpdateRect(rfbScreenInfoPtr screen, rfbScreenInfoPtr ptr, int x0, int y0, int w0, int h0)\n{\n int x,y,w,v,z;\n int x1, y1, w1, h1;\n int bitsPerPixel, bytesPerPixel, bytesPerLine, areaX, areaY, area2;\n unsigned char *srcptr, *dstptr;\n\n /* Nothing to do!!! */\n if (screen==ptr) return;\n\n x1 = x0;\n y1 = y0;\n w1 = w0;\n h1 = h0;\n\n rfbScaledCorrection(screen, ptr, &x1, &y1, &w1, &h1, \"rfbScaledScreenUpdateRect\");\n x0 = ScaleX(ptr, screen, x1);\n y0 = ScaleY(ptr, screen, y1);\n w0 = ScaleX(ptr, screen, w1);\n h0 = ScaleY(ptr, screen, h1);\n\n bitsPerPixel = screen->bitsPerPixel;\n bytesPerPixel = bitsPerPixel / 8;\n bytesPerLine = w1 * bytesPerPixel;\n srcptr = (unsigned char *)(screen->frameBuffer +\n (y0 * screen->paddedWidthInBytes + x0 * bytesPerPixel));\n dstptr = (unsigned char *)(ptr->frameBuffer +\n ( y1 * ptr->paddedWidthInBytes + x1 * bytesPerPixel));\n /* The area of the source framebuffer for each destination pixel */\n areaX = ScaleX(ptr,screen,1);\n areaY = ScaleY(ptr,screen,1);\n area2 = areaX*areaY;\n\n\n /* Ensure that we do not go out of bounds */\n if ((x1+w1) > (ptr->width))\n {\n if (x1==0) w1=ptr->width; else x1 = ptr->width - w1;\n }\n if ((y1+h1) > (ptr->height))\n {\n if (y1==0) h1=ptr->height; else y1 = ptr->height - h1;\n }\n /*\n * rfbLog(\"rfbScaledScreenUpdateRect(%dXx%dY-%dWx%dH -> %dXx%dY-%dWx%dH <%dx%d>) {%dWx%dH -> %dWx%dH} 0x%p\\n\",\n * x0, y0, w0, h0, x1, y1, w1, h1, areaX, areaY,\n * screen->width, screen->height, ptr->width, ptr->height, ptr->frameBuffer);\n */\n\n if (screen->serverFormat.trueColour) { /* Blend neighbouring pixels together */\n unsigned char *srcptr2;\n unsigned long pixel_value, red, green, blue;\n unsigned int redShift = screen->serverFormat.redShift;\n unsigned int greenShift = screen->serverFormat.greenShift;\n unsigned int blueShift = screen->serverFormat.blueShift;\n unsigned long redMax = screen->serverFormat.redMax;\n unsigned long greenMax = screen->serverFormat.greenMax;\n unsigned long blueMax = screen->serverFormat.blueMax;\n\n /* for each *destination* pixel... */\n for (y = 0; y < h1; y++) {\n for (x = 0; x < w1; x++) {\n red = green = blue = 0;\n /* Get the totals for rgb from the source grid... */\n for (w = 0; w < areaX; w++) {\n for (v = 0; v < areaY; v++) {\n srcptr2 = &srcptr[(((x * areaX) + w) * bytesPerPixel) +\n (v * screen->paddedWidthInBytes)];\n pixel_value = 0;\n\n\n switch (bytesPerPixel) {\n case 4: pixel_value = *((unsigned int *)srcptr2); break;\n case 2: pixel_value = *((unsigned short *)srcptr2); break;\n case 1: pixel_value = *((unsigned char *)srcptr2); break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n pixel_value += ((unsigned long)srcptr2[z] << (8 * z));\n break;\n }\n /*\n srcptr2 += bytesPerPixel;\n */\n\n red += ((pixel_value >> redShift) & redMax);\n green += ((pixel_value >> greenShift) & greenMax);\n blue += ((pixel_value >> blueShift) & blueMax);\n\n }\n }\n /* We now have a total for all of the colors, find the average! */\n red /= area2;\n green /= area2;\n blue /= area2;\n /* Stuff the new value back into memory */\n pixel_value = ((red & redMax) << redShift) | ((green & greenMax) << greenShift) | ((blue & blueMax) << blueShift);\n\n switch (bytesPerPixel) {\n case 4: *((unsigned int *)dstptr) = (unsigned int) pixel_value; break;\n case 2: *((unsigned short *)dstptr) = (unsigned short) pixel_value; break;\n case 1: *((unsigned char *)dstptr) = (unsigned char) pixel_value; break;\n default:\n /* fixme: endianness problem? */\n for (z = 0; z < bytesPerPixel; z++)\n dstptr[z]=(pixel_value >> (8 * z)) & 0xff;\n break;\n }\n dstptr += bytesPerPixel;\n }\n srcptr += (screen->paddedWidthInBytes * areaY);\n dstptr += (ptr->paddedWidthInBytes - bytesPerLine);\n }\n } else\n { /* Not truecolour, so we can't blend. Just use the top-left pixel instead */\n for (y = y1; y < (y1+h1); y++) {\n for (x = x1; x < (x1+w1); x++)\n memcpy (&ptr->frameBuffer[(y *ptr->paddedWidthInBytes) + (x * bytesPerPixel)],\n &screen->frameBuffer[(y * areaY * screen->paddedWidthInBytes) + (x *areaX * bytesPerPixel)], bytesPerPixel);\n }\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rfbScaledScreenUpdateRect", "_file_name": "libvncserver/scale.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def populate_custom_grains_and_pillar():\n '''\n Populate local salt-minion grains and pillar fields values as specified in\n config file.\n\n For example:\n\n custom_grains_pillar:\n grains:\n - selinux: selinux:enabled\n - release: osrelease\n pillar:\n - ntpserver: network_services:ntpserver\n\n Note that the core grains are already included in hubble grains -- this\n is only necessary for custom grains and pillar data.\n '''\n log.debug('Fetching custom grains and pillar details')\n grains = {}\n salt.modules.config.__opts__ = __opts__\n custom_grains = __salt__['config.get']('custom_grains_pillar:grains', [])\n for grain in custom_grains:\n for key in grain:\n value = __salt__['cmd.run'](['salt-call', 'grains.get', grain[key]]).split('\\n')[1].strip()\n grains[key] = value\n custom_pillar = __salt__['config.get']('custom_grains_pillar:pillar', [])\n for pillar in custom_pillar:\n for key in pillar:\n value = __salt__['cmd.run'](['salt-call', 'pillar.get', pillar[key]]).split('\\n')[1].strip()\n grains[key] = value\n log.debug('Done with fetching custom grains and pillar details')\n return grains", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "populate_custom_grains_and_pillar", "_file_name": "hubblestack/extmods/grains/custom_grains_pillar.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self,data):\n connection = self.connect()\n\n try:\n query = \"INSERT INTO crimes (description) VALUES ('{}');\".format(data)\n with connection.cursor() as cursor:\n cursor.execute(query)\n connection.commit()\n finally:\n connection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[80, 163]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[80, 163]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification)\n{\n\tint ret;\n\tstruct fd f;\n\tstruct sock *sock;\n\tstruct inode *inode;\n\tstruct mqueue_inode_info *info;\n\tstruct sk_buff *nc;\n\n\taudit_mq_notify(mqdes, notification);\n\n\tnc = NULL;\n\tsock = NULL;\n\tif (notification != NULL) {\n\t\tif (unlikely(notification->sigev_notify != SIGEV_NONE &&\n\t\t\t notification->sigev_notify != SIGEV_SIGNAL &&\n\t\t\t notification->sigev_notify != SIGEV_THREAD))\n\t\t\treturn -EINVAL;\n\t\tif (notification->sigev_notify == SIGEV_SIGNAL &&\n\t\t\t!valid_signal(notification->sigev_signo)) {\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (notification->sigev_notify == SIGEV_THREAD) {\n\t\t\tlong timeo;\n\n\t\t\t/* create the notify skb */\n\t\t\tnc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);\n\t\t\tif (!nc) {\n\t\t\t\tret = -ENOMEM;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tif (copy_from_user(nc->data,\n\t\t\t\t\tnotification->sigev_value.sival_ptr,\n\t\t\t\t\tNOTIFY_COOKIE_LEN)) {\n\t\t\t\tret = -EFAULT;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\t/* TODO: add a header? */\n\t\t\tskb_put(nc, NOTIFY_COOKIE_LEN);\n\t\t\t/* and attach it to the socket */\nretry:\n\t\t\tf = fdget(notification->sigev_signo);\n\t\t\tif (!f.file) {\n\t\t\t\tret = -EBADF;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsock = netlink_getsockbyfilp(f.file);\n\t\t\tfdput(f);\n\t\t\tif (IS_ERR(sock)) {\n\t\t\t\tret = PTR_ERR(sock);\n\t\t\t\tsock = NULL;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\ttimeo = MAX_SCHEDULE_TIMEOUT;\n\t\t\tret = netlink_attachskb(sock, nc, &timeo, NULL);\n\t\t\tif (ret == 1)\n\t\t\t\tgoto retry;\n\t\t\tif (ret) {\n\t\t\t\tsock = NULL;\n\t\t\t\tnc = NULL;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t}\n\n\tf = fdget(mqdes);\n\tif (!f.file) {\n\t\tret = -EBADF;\n\t\tgoto out;\n\t}\n\n\tinode = file_inode(f.file);\n\tif (unlikely(f.file->f_op != &mqueue_file_operations)) {\n\t\tret = -EBADF;\n\t\tgoto out_fput;\n\t}\n\tinfo = MQUEUE_I(inode);\n\n\tret = 0;\n\tspin_lock(&info->lock);\n\tif (notification == NULL) {\n\t\tif (info->notify_owner == task_tgid(current)) {\n\t\t\tremove_notification(info);\n\t\t\tinode->i_atime = inode->i_ctime = current_time(inode);\n\t\t}\n\t} else if (info->notify_owner != NULL) {\n\t\tret = -EBUSY;\n\t} else {\n\t\tswitch (notification->sigev_notify) {\n\t\tcase SIGEV_NONE:\n\t\t\tinfo->notify.sigev_notify = SIGEV_NONE;\n\t\t\tbreak;\n\t\tcase SIGEV_THREAD:\n\t\t\tinfo->notify_sock = sock;\n\t\t\tinfo->notify_cookie = nc;\n\t\t\tsock = NULL;\n\t\t\tnc = NULL;\n\t\t\tinfo->notify.sigev_notify = SIGEV_THREAD;\n\t\t\tbreak;\n\t\tcase SIGEV_SIGNAL:\n\t\t\tinfo->notify.sigev_signo = notification->sigev_signo;\n\t\t\tinfo->notify.sigev_value = notification->sigev_value;\n\t\t\tinfo->notify.sigev_notify = SIGEV_SIGNAL;\n\t\t\tbreak;\n\t\t}\n\n\t\tinfo->notify_owner = get_pid(task_tgid(current));\n\t\tinfo->notify_user_ns = get_user_ns(current_user_ns());\n\t\tinode->i_atime = inode->i_ctime = current_time(inode);\n\t}\n\tspin_unlock(&info->lock);\nout_fput:\n\tfdput(f);\nout:\n\tif (sock)\n\t\tnetlink_detachskb(sock, nc);\n\telse if (nc)\n\t\tdev_kfree_skb(nc);\n\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[1368, 1385]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1368, 1385]]}, "_func_name": "do_mq_notify", "_file_name": "ipc/mqueue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void disk_seqf_stop(struct seq_file *seqf, void *v)\n{\n\tstruct class_dev_iter *iter = seqf->private;\n\n\t/* stop is called even after start failed :-( */\n\tif (iter) {\n\t\tclass_dev_iter_exit(iter);\n\t\tkfree(iter);\n\t\tseqf->private = NULL;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "disk_seqf_stop", "_file_name": "block/genhd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int __get_data_block(struct inode *inode, sector_t iblock,\n\t\t\tstruct buffer_head *bh, int create, int flag,\n\t\t\tpgoff_t *next_pgofs)\n{\n\tstruct f2fs_map_blocks map;\n\tint err;\n\n\tmap.m_lblk = iblock;\n\tmap.m_len = bh->b_size >> inode->i_blkbits;\n\tmap.m_next_pgofs = next_pgofs;\n\n\terr = f2fs_map_blocks(inode, &map, create, flag);\n\tif (!err) {\n\t\tmap_bh(bh, inode->i_sb, map.m_pblk);\n\t\tbh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;\n\t\tbh->b_size = map.m_len << inode->i_blkbits;\n\t}\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[447, 493]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[447, 493]]}, "_func_name": "__get_data_block", "_file_name": "fs/f2fs/data.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)\n{\n\tstruct super_block *sb;\n\tint err;\n\tint rc;\n\n\tif (!ext4_handle_valid(handle)) {\n\t\text4_put_nojournal(handle);\n\t\treturn 0;\n\t}\n\n\terr = handle->h_err;\n\tif (!handle->h_transaction) {\n\t\trc = jbd2_journal_stop(handle);\n\t\treturn err ? err : rc;\n\t}\n\n\tsb = handle->h_transaction->t_journal->j_private;\n\trc = jbd2_journal_stop(handle);\n\n\tif (!err)\n\t\terr = rc;\n\tif (err)\n\t\t__ext4_std_error(sb, where, line, err);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__ext4_journal_stop", "_file_name": "fs/ext4/ext4_jbd2.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def repack(host, targets, channel='stable'):\n url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'\n req = requests.get(url)\n req.raise_for_status()\n manifest = toml.loads(req.content)\n if manifest['manifest-version'] != '2':\n print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])\n return\n print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))\n rustc_version, rustc = package(manifest, 'rustc', host)\n if rustc['available']:\n print('rustc %s\\n %s\\n %s' % (rustc_version, rustc['url'], rustc['hash']))\n fetch(rustc['url'])\n cargo_version, cargo = package(manifest, 'cargo', host)\n if cargo['available']:\n print('cargo %s\\n %s\\n %s' % (cargo_version, cargo['url'], cargo['hash']))\n fetch(cargo['url'])\n stds = []\n for target in targets:\n version, info = package(manifest, 'rust-std', target)\n if info['available']:\n print('rust-std %s\\n %s\\n %s' % (version, info['url'], info['hash']))\n fetch(info['url'])\n stds.append(info)\n print('Installing packages...')\n tar_basename = 'rustc-%s-repack' % host\n install_dir = 'rustc'\n os.system('rm -rf %s' % install_dir)\n install(os.path.basename(rustc['url']), install_dir)\n install(os.path.basename(cargo['url']), install_dir)\n for std in stds:\n install(os.path.basename(std['url']), install_dir)\n print('Tarring %s...' % tar_basename)\n os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))\n os.system('rm -rf %s' % install_dir)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1161, 1200], [1424, 1531]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1161, 1200], [1424, 1531]]}, "_func_name": "repack", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _cli_run(self, cmd):\n \"\"\"Runs a CLI command over SSH, without doing any result parsing.\"\"\"\n LOG.debug(\"SSH CMD = %s \" % cmd)\n\n (stdout, stderr) = self._run_ssh(cmd, False)\n\n # we have to strip out the input and exit lines\n tmp = stdout.split(\"\\r\\n\")\n out = tmp[5:len(tmp) - 2]\n return out", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_cli_run", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap,\n const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight,\n UINT32 bpp, UINT32 length, BOOL compressed,\n UINT32 codecId)\n{\n\tUINT32 SrcSize = length;\n\trdpGdi* gdi = context->gdi;\n\tUINT32 size = DstWidth * DstHeight;\n\tbitmap->compressed = FALSE;\n\tbitmap->format = gdi->dstFormat;\n\n\tif ((GetBytesPerPixel(bitmap->format) == 0) ||\n\t (DstWidth == 0) || (DstHeight == 0) || (DstWidth > UINT32_MAX / DstHeight) ||\n\t (size > (UINT32_MAX / GetBytesPerPixel(bitmap->format))))\n\t\treturn FALSE;\n\n\tsize *= GetBytesPerPixel(bitmap->format);\n\tbitmap->length = size;\n\tbitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16);\n\n\tif (!bitmap->data)\n\t\treturn FALSE;\n\n\tif (compressed)\n\t{\n\t\tif (bpp < 32)\n\t\t{\n\t\t\tif (!interleaved_decompress(context->codecs->interleaved,\n\t\t\t pSrcData, SrcSize,\n\t\t\t DstWidth, DstHeight,\n\t\t\t bpp,\n\t\t\t bitmap->data, bitmap->format,\n\t\t\t 0, 0, 0, DstWidth, DstHeight,\n\t\t\t &gdi->palette))\n\t\t\t\treturn FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!planar_decompress(context->codecs->planar, pSrcData, SrcSize,\n\t\t\t DstWidth, DstHeight,\n\t\t\t bitmap->data, bitmap->format, 0, 0, 0,\n\t\t\t DstWidth, DstHeight, TRUE))\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst UINT32 SrcFormat = gdi_get_pixel_format(bpp);\n\t\tconst size_t sbpp = GetBytesPerPixel(SrcFormat);\n\t\tconst size_t dbpp = GetBytesPerPixel(bitmap->format);\n\n\t\tif ((sbpp == 0) || (dbpp == 0))\n\t\t\treturn FALSE;\n\t\telse\n\t\t{\n\t\t\tconst size_t dstSize = SrcSize * dbpp / sbpp;\n\n\t\t\tif (dstSize < bitmap->length)\n\t\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0,\n\t\t DstWidth, DstHeight, pSrcData, SrcFormat,\n\t\t 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL))\n\t\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "gdi_Bitmap_Decompress", "_file_name": "libfreerdp/gdi/graphics.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)\n{\n AC3HeaderInfo *hdr = NULL;\n struct eac3_info *info;\n int num_blocks, ret;\n\n if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))\n return AVERROR(ENOMEM);\n info = track->eac3_priv;\n\n if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {\n /* drop the packets until we see a good one */\n if (!track->entry) {\n av_log(mov, AV_LOG_WARNING, \"Dropping invalid packet from start of the stream\\n\");\n ret = 0;\n } else\n ret = AVERROR_INVALIDDATA;\n goto end;\n }\n\n info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);\n num_blocks = hdr->num_blocks;\n\n if (!info->ec3_done) {\n /* AC-3 substream must be the first one */\n if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n\n /* this should always be the case, given that our AC-3 parser\n * concatenates dependent frames to their independent parent */\n if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {\n /* substream ids must be incremental */\n if (hdr->substreamid > info->num_ind_sub + 1) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n\n if (hdr->substreamid == info->num_ind_sub + 1) {\n //info->num_ind_sub++;\n avpriv_request_sample(mov->fc, \"Multiple independent substreams\");\n ret = AVERROR_PATCHWELCOME;\n goto end;\n } else if (hdr->substreamid < info->num_ind_sub ||\n hdr->substreamid == 0 && info->substream[0].bsid) {\n info->ec3_done = 1;\n goto concatenate;\n }\n } else {\n if (hdr->substreamid != 0) {\n avpriv_request_sample(mov->fc, \"Multiple non EAC3 independent substreams\");\n ret = AVERROR_PATCHWELCOME;\n goto end;\n }\n }\n\n /* fill the info needed for the \"dec3\" atom */\n info->substream[hdr->substreamid].fscod = hdr->sr_code;\n info->substream[hdr->substreamid].bsid = hdr->bitstream_id;\n info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;\n info->substream[hdr->substreamid].acmod = hdr->channel_mode;\n info->substream[hdr->substreamid].lfeon = hdr->lfe_on;\n\n /* Parse dependent substream(s), if any */\n if (pkt->size != hdr->frame_size) {\n int cumul_size = hdr->frame_size;\n int parent = hdr->substreamid;\n\n while (cumul_size != pkt->size) {\n GetBitContext gbc;\n int i;\n ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);\n if (ret < 0)\n goto end;\n if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n info->substream[parent].num_dep_sub++;\n ret /= 8;\n\n /* header is parsed up to lfeon, but custom channel map may be needed */\n init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);\n /* skip bsid */\n skip_bits(&gbc, 5);\n /* skip volume control params */\n for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {\n skip_bits(&gbc, 5); // skip dialog normalization\n if (get_bits1(&gbc)) {\n skip_bits(&gbc, 8); // skip compression gain word\n }\n }\n /* get the dependent stream channel map, if exists */\n if (get_bits1(&gbc))\n info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;\n else\n info->substream[parent].chan_loc |= hdr->channel_mode;\n cumul_size += hdr->frame_size;\n }\n }\n }\n\nconcatenate:\n if (!info->num_blocks && num_blocks == 6) {\n ret = pkt->size;\n goto end;\n }\n else if (info->num_blocks + num_blocks > 6) {\n ret = AVERROR_INVALIDDATA;\n goto end;\n }\n\n if (!info->num_blocks) {\n ret = av_packet_ref(&info->pkt, pkt);\n if (!ret)\n info->num_blocks = num_blocks;\n goto end;\n } else {\n if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)\n goto end;\n memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);\n info->num_blocks += num_blocks;\n info->pkt.duration += pkt->duration;\n if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)\n goto end;\n if (info->num_blocks != 6)\n goto end;\n av_packet_unref(pkt);\n av_packet_move_ref(pkt, &info->pkt);\n info->num_blocks = 0;\n }\n ret = pkt->size;\n\nend:\n av_free(hdr);\n\n return ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle_eac3", "_file_name": "libavformat/movenc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_articles_by_subject(subject):\n with conn.cursor(cursor_factory=DictCursor) as cur:\n query = \"SELECT * FROM articles WHERE subject=%s ORDER BY last_submitted DESC\"\n cur.execute(query, (subject,))\n articles = cur.fetchall()\n return articles", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_articles_by_subject", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self,data):\n connection = self.connect()\n try:\n # The following is a flaw\n query = \"INSERT INTO crimes(description) VALUES ('{}');\".format(data)\n with connection.cursor() as cursor:\n cursor.execute(query)\n connection.commit()\n finally:\n connection.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[117, 199]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[117, 199]]}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer)\n{\n int row = m_listModel->rowCount();\n // Adding Peer to peer list\n m_listModel->insertRow(row);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);\n if (m_resolveCountries) {\n const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country());\n if (!ico.isNull()) {\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole);\n const QString countryName = Net::GeoIPManager::CountryName(peer.country());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole);\n }\n else {\n m_missingFlags.insert(ip);\n }\n }\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole);\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload());\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance());\n QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex()));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\";\")));\n m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(\"\\n\")), Qt::ToolTipRole);\n\n return m_listModel->item(row, PeerListDelegate::IP);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[1441, 1533]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1441, 1533]]}, "_func_name": "PeerListWidget::addPeer", "_file_name": "src/gui/properties/peerlistwidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "sctp_disposition_t sctp_sf_ootb(struct net *net,\n\t\t\t\tconst struct sctp_endpoint *ep,\n\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\tconst sctp_subtype_t type,\n\t\t\t\tvoid *arg,\n\t\t\t\tsctp_cmd_seq_t *commands)\n{\n\tstruct sctp_chunk *chunk = arg;\n\tstruct sk_buff *skb = chunk->skb;\n\tsctp_chunkhdr_t *ch;\n\tsctp_errhdr_t *err;\n\t__u8 *ch_end;\n\tint ootb_shut_ack = 0;\n\tint ootb_cookie_ack = 0;\n\n\tSCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);\n\n\tch = (sctp_chunkhdr_t *) chunk->chunk_hdr;\n\tdo {\n\t\t/* Report violation if the chunk is less then minimal */\n\t\tif (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* Now that we know we at least have a chunk header,\n\t\t * do things that are type appropriate.\n\t\t */\n\t\tif (SCTP_CID_SHUTDOWN_ACK == ch->type)\n\t\t\tootb_shut_ack = 1;\n\n\t\t/* RFC 2960, Section 3.3.7\n\t\t * Moreover, under any circumstances, an endpoint that\n\t\t * receives an ABORT MUST NOT respond to that ABORT by\n\t\t * sending an ABORT of its own.\n\t\t */\n\t\tif (SCTP_CID_ABORT == ch->type)\n\t\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\n\t\t/* RFC 8.4, 7) If the packet contains a \"Stale cookie\" ERROR\n\t\t * or a COOKIE ACK the SCTP Packet should be silently\n\t\t * discarded.\n\t\t */\n\n\t\tif (SCTP_CID_COOKIE_ACK == ch->type)\n\t\t\tootb_cookie_ack = 1;\n\n\t\tif (SCTP_CID_ERROR == ch->type) {\n\t\t\tsctp_walk_errors(err, ch) {\n\t\t\t\tif (SCTP_ERROR_STALE_COOKIE == err->cause) {\n\t\t\t\t\tootb_cookie_ack = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\tch = (sctp_chunkhdr_t *) ch_end;\n\t} while (ch_end < skb_tail_pointer(skb));\n\n\tif (ootb_shut_ack)\n\t\treturn sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);\n\telse if (ootb_cookie_ack)\n\t\treturn sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);\n\telse\n\t\treturn sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1495, 1724]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1495, 1724]]}, "_func_name": "sctp_sf_ootb", "_file_name": "net/sctp/sm_statefuns.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " @unpack\n def test_process_as_form(self, job_number, dcn_key, was_prev_matched,\n was_prev_closed, was_prev_tracked):\n email_obj = {\n 'sender' : \"Alex Roy \",\n 'subject' : \"DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`\",\n 'date' : \"Tue, 7 May 2019 17:34:17 +0000\",\n 'content' : (\n f\"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&\"\n f\"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&\"\n f\"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&\"\n f\"quality=2&cc_email=&link_to_cert={dcn_key}\\r\\n\"\n )\n }\n # set-up new entries in db, if necessary\n fake_dilfo_insert = \"\"\"\n INSERT INTO df_dilfo (job_number, receiver_email, closed)\n VALUES (?, 'alex.roy616@gmail.com', ?)\n \"\"\"\n fake_match_insert = \"\"\"\n INSERT INTO df_matched (job_number, verifier, ground_truth)\n VALUES (?, 'alex.roy616@gmail.com', ?)\n \"\"\"\n with create_connection() as conn:\n if was_prev_closed or was_prev_tracked:\n conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed])\n if was_prev_matched:\n if was_prev_closed:\n conn.cursor().execute(fake_match_insert, [job_number, 1])\n else:\n conn.cursor().execute(fake_match_insert, [job_number, 0])\n with create_connection() as conn:\n df_dilfo_pre = pd.read_sql(\"SELECT * FROM df_dilfo WHERE job_number=?\", conn, params=[job_number])\n df_matched_pre = pd.read_sql(\"SELECT * FROM df_matched WHERE job_number=?\", conn, params=[job_number])\n process_as_form(email_obj)\n # make assertions about db now that reply has been processed\n with create_connection() as conn:\n df_dilfo_post = pd.read_sql(\"SELECT * FROM df_dilfo WHERE job_number=?\", conn, params=[job_number])\n df_matched_post = pd.read_sql(\"SELECT * FROM df_matched WHERE job_number=?\", conn, params=[job_number])\n self.assertEqual(len(df_dilfo_post), 1)\n self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))\n self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))\n self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))\n self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))\n self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_process_as_form", "_file_name": "tests.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/api/uploads//logs')\ndef get_logs(sid):\n if '/' not in sid:\n path = os.path.join(app.config['UPLOAD_FOLDER'], sid)\n if os.path.isfile(os.path.join(path, app.config['LOG_FILE'])):\n return send_from_directory(directory=path,\n filename=app.config['LOG_FILE'])\n else:\n abort(404)\n else:\n abort(403)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[57, 213], [388, 406]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[57, 213], [388, 406]]}, "_func_name": "get_logs", "_file_name": "app/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "cleanup_pathname(struct archive_write_disk *a)\n{\n\tchar *dest, *src;\n\tchar separator = '\\0';\n\n\tdest = src = a->name;\n\tif (*src == '\\0') {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Invalid empty pathname\");\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n#if defined(__CYGWIN__)\n\tcleanup_pathname_win(a);\n#endif\n\t/* Skip leading '/'. */\n\tif (*src == '/')\n\t\tseparator = *src++;\n\n\t/* Scan the pathname one element at a time. */\n\tfor (;;) {\n\t\t/* src points to first char after '/' */\n\t\tif (src[0] == '\\0') {\n\t\t\tbreak;\n\t\t} else if (src[0] == '/') {\n\t\t\t/* Found '//', ignore second one. */\n\t\t\tsrc++;\n\t\t\tcontinue;\n\t\t} else if (src[0] == '.') {\n\t\t\tif (src[1] == '\\0') {\n\t\t\t\t/* Ignore trailing '.' */\n\t\t\t\tbreak;\n\t\t\t} else if (src[1] == '/') {\n\t\t\t\t/* Skip './'. */\n\t\t\t\tsrc += 2;\n\t\t\t\tcontinue;\n\t\t\t} else if (src[1] == '.') {\n\t\t\t\tif (src[2] == '/' || src[2] == '\\0') {\n\t\t\t\t\t/* Conditionally warn about '..' */\n\t\t\t\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {\n\t\t\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t\t\t ARCHIVE_ERRNO_MISC,\n\t\t\t\t\t\t \"Path contains '..'\");\n\t\t\t\t\t\treturn (ARCHIVE_FAILED);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * Note: Under no circumstances do we\n\t\t\t\t * remove '..' elements. In\n\t\t\t\t * particular, restoring\n\t\t\t\t * '/foo/../bar/' should create the\n\t\t\t\t * 'foo' dir as a side-effect.\n\t\t\t\t */\n\t\t\t}\n\t\t}\n\n\t\t/* Copy current element, including leading '/'. */\n\t\tif (separator)\n\t\t\t*dest++ = '/';\n\t\twhile (*src != '\\0' && *src != '/') {\n\t\t\t*dest++ = *src++;\n\t\t}\n\n\t\tif (*src == '\\0')\n\t\t\tbreak;\n\n\t\t/* Skip '/' separator. */\n\t\tseparator = *src++;\n\t}\n\t/*\n\t * We've just copied zero or more path elements, not including the\n\t * final '/'.\n\t */\n\tif (dest == a->name) {\n\t\t/*\n\t\t * Nothing got copied. The path must have been something\n\t\t * like '.' or '/' or './' or '/././././/./'.\n\t\t */\n\t\tif (separator)\n\t\t\t*dest++ = '/';\n\t\telse\n\t\t\t*dest++ = '.';\n\t}\n\t/* Terminate the result. */\n\t*dest = '\\0';\n\treturn (ARCHIVE_OK);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[336, 354]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[336, 354]]}, "_func_name": "cleanup_pathname", "_file_name": "libarchive/archive_write_disk_posix.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)\n{\n AC3HeaderInfo *hdr = NULL;\n struct eac3_info *info;\n int num_blocks, ret;\n\n if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))\n return AVERROR(ENOMEM);\n info = track->eac3_priv;\n\n if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {\n /* drop the packets until we see a good one */\n if (!track->entry) {\n av_log(mov, AV_LOG_WARNING, \"Dropping invalid packet from start of the stream\\n\");\n ret = 0;\n } else\n ret = AVERROR_INVALIDDATA;\n goto end;\n }\n\n info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);\n num_blocks = hdr->num_blocks;\n\n if (!info->ec3_done) {\n /* AC-3 substream must be the first one */\n if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n\n /* this should always be the case, given that our AC-3 parser\n * concatenates dependent frames to their independent parent */\n if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {\n /* substream ids must be incremental */\n if (hdr->substreamid > info->num_ind_sub + 1) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n\n if (hdr->substreamid == info->num_ind_sub + 1) {\n //info->num_ind_sub++;\n avpriv_request_sample(track->par, \"Multiple independent substreams\");\n ret = AVERROR_PATCHWELCOME;\n goto end;\n } else if (hdr->substreamid < info->num_ind_sub ||\n hdr->substreamid == 0 && info->substream[0].bsid) {\n info->ec3_done = 1;\n goto concatenate;\n }\n } else {\n if (hdr->substreamid != 0) {\n avpriv_request_sample(mov->fc, \"Multiple non EAC3 independent substreams\");\n ret = AVERROR_PATCHWELCOME;\n goto end;\n }\n }\n\n /* fill the info needed for the \"dec3\" atom */\n info->substream[hdr->substreamid].fscod = hdr->sr_code;\n info->substream[hdr->substreamid].bsid = hdr->bitstream_id;\n info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;\n info->substream[hdr->substreamid].acmod = hdr->channel_mode;\n info->substream[hdr->substreamid].lfeon = hdr->lfe_on;\n\n /* Parse dependent substream(s), if any */\n if (pkt->size != hdr->frame_size) {\n int cumul_size = hdr->frame_size;\n int parent = hdr->substreamid;\n\n while (cumul_size != pkt->size) {\n GetBitContext gbc;\n int i;\n ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);\n if (ret < 0)\n goto end;\n if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {\n ret = AVERROR(EINVAL);\n goto end;\n }\n info->substream[parent].num_dep_sub++;\n ret /= 8;\n\n /* header is parsed up to lfeon, but custom channel map may be needed */\n init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);\n /* skip bsid */\n skip_bits(&gbc, 5);\n /* skip volume control params */\n for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {\n skip_bits(&gbc, 5); // skip dialog normalization\n if (get_bits1(&gbc)) {\n skip_bits(&gbc, 8); // skip compression gain word\n }\n }\n /* get the dependent stream channel map, if exists */\n if (get_bits1(&gbc))\n info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;\n else\n info->substream[parent].chan_loc |= hdr->channel_mode;\n cumul_size += hdr->frame_size;\n }\n }\n }\n\nconcatenate:\n if (!info->num_blocks && num_blocks == 6) {\n ret = pkt->size;\n goto end;\n }\n else if (info->num_blocks + num_blocks > 6) {\n ret = AVERROR_INVALIDDATA;\n goto end;\n }\n\n if (!info->num_blocks) {\n ret = av_packet_ref(&info->pkt, pkt);\n if (!ret)\n info->num_blocks = num_blocks;\n goto end;\n } else {\n if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)\n goto end;\n memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);\n info->num_blocks += num_blocks;\n info->pkt.duration += pkt->duration;\n if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)\n goto end;\n if (info->num_blocks != 6)\n goto end;\n av_packet_unref(pkt);\n av_packet_move_ref(pkt, &info->pkt);\n info->num_blocks = 0;\n }\n ret = pkt->size;\n\nend:\n av_free(hdr);\n\n return ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1457, 1543]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1457, 1543]]}, "_func_name": "handle_eac3", "_file_name": "libavformat/movenc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _update_volume_stats(self):\n \"\"\"Retrieve stats info from volume group.\"\"\"\n\n LOG.debug(_(\"Updating volume stats\"))\n data = {}\n\n data['vendor_name'] = 'IBM'\n data['driver_version'] = '1.1'\n data['storage_protocol'] = list(self._enabled_protocols)\n\n data['total_capacity_gb'] = 0 # To be overwritten\n data['free_capacity_gb'] = 0 # To be overwritten\n data['reserved_percentage'] = 0\n data['QoS_support'] = False\n\n pool = self.configuration.storwize_svc_volpool_name\n #Get storage system name\n ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes or not attributes['name']:\n exception_message = (_('_update_volume_stats: '\n 'Could not get system name'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n backend_name = self.configuration.safe_get('volume_backend_name')\n if not backend_name:\n backend_name = '%s_%s' % (attributes['name'], pool)\n data['volume_backend_name'] = backend_name\n\n ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n LOG.error(_('Could not get pool data from the storage'))\n exception_message = (_('_update_volume_stats: '\n 'Could not get storage pool data'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n data['total_capacity_gb'] = (float(attributes['capacity']) /\n (1024 ** 3))\n data['free_capacity_gb'] = (float(attributes['free_capacity']) /\n (1024 ** 3))\n data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']\n data['compression_support'] = self._compression_enabled\n\n self._stats = data", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_update_volume_stats", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)\n{\n\tstruct sockaddr_rc *sa = (struct sockaddr_rc *) addr;\n\tstruct sock *sk = sock->sk;\n\tint chan = sa->rc_channel;\n\tint err = 0;\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa->rc_bdaddr);\n\n\tif (!addr || addr->sa_family != AF_BLUETOOTH)\n\t\treturn -EINVAL;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != BT_OPEN) {\n\t\terr = -EBADFD;\n\t\tgoto done;\n\t}\n\n\tif (sk->sk_type != SOCK_STREAM) {\n\t\terr = -EINVAL;\n\t\tgoto done;\n\t}\n\n\twrite_lock(&rfcomm_sk_list.lock);\n\n\tif (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {\n\t\terr = -EADDRINUSE;\n\t} else {\n\t\t/* Save source address */\n\t\tbacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);\n\t\trfcomm_pi(sk)->channel = chan;\n\t\tsk->sk_state = BT_BOUND;\n\t}\n\n\twrite_unlock(&rfcomm_sk_list.lock);\n\ndone:\n\trelease_sock(sk);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[88, 143], [172, 214], [215, 306], [513, 584], [643, 689]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[88, 143], [172, 214], [215, 306], [513, 584], [643, 689]]}, "_func_name": "rfcomm_sock_bind", "_file_name": "net/bluetooth/rfcomm/sock.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void usb_serial_console_disconnect(struct usb_serial *serial)\n{\n\tif (serial->port[0] == usbcons_info.port) {\n\t\tusb_serial_console_exit();\n\t\tusb_serial_put(serial);\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[64, 109]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[64, 109]]}, "_func_name": "usb_serial_console_disconnect", "_file_name": "drivers/usb/serial/console.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n const char **elem_rtrn, const char **field_rtrn,\n ExprDef **index_rtrn)\n{\n switch (expr->expr.op) {\n case EXPR_IDENT:\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);\n *index_rtrn = NULL;\n return true;\n case EXPR_ARRAY_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);\n *index_rtrn = expr->array_ref.entry;\n return true;\n default:\n break;\n }\n log_wsgo(ctx, \"Unexpected operator %d in ResolveLhs\\n\", expr->expr.op);\n return false;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[552, 573]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[552, 573]]}, "_func_name": "ExprResolveLhs", "_file_name": "src/xkbcomp/expr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "long dd_get_item_size(struct dump_dir *dd, const char *name)\n{\n long size = -1;\n char *iname = concat_path_file(dd->dd_dirname, name);\n struct stat statbuf;\n\n if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode))\n size = statbuf.st_size;\n else\n {\n if (errno == ENOENT)\n size = 0;\n else\n perror_msg(\"Can't get size of file '%s'\", iname);\n }\n\n free(iname);\n\n return size;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[63, 83]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[63, 83]]}, "_func_name": "dd_get_item_size", "_file_name": "src/lib/dump_dir.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_create_modify_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])\n\n create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',\n '123456789054321']\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_modify_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_lines(command: List[str]) -> List[str]:\n \"\"\"\n Run a command and return lines of output\n\n :param str command: the command to run\n :returns: list of whitespace-stripped lines output by command\n \"\"\"\n stdout = get_output(command)\n return [line.strip() for line in stdout.splitlines()]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_lines", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int flb_gzip_compress(void *in_data, size_t in_len,\n void **out_data, size_t *out_len)\n{\n int flush;\n int status;\n int footer_start;\n uint8_t *pb;\n size_t out_size;\n void *out_buf;\n z_stream strm;\n mz_ulong crc;\n\n out_size = in_len + 32;\n out_buf = flb_malloc(out_size);\n if (!out_buf) {\n flb_errno();\n flb_error(\"[gzip] could not allocate outgoing buffer\");\n return -1;\n }\n\n /* Initialize streaming buffer context */\n memset(&strm, '\\0', sizeof(strm));\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.next_in = in_data;\n strm.avail_in = in_len;\n strm.total_out = 0;\n\n /* Deflate mode */\n deflateInit2(&strm, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);\n\n /*\n * Miniz don't support GZip format directly, instead we will:\n *\n * - append manual GZip magic bytes\n * - deflate raw content\n * - append manual CRC32 data\n */\n gzip_header(out_buf);\n\n /* Header offset */\n pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;\n\n flush = Z_NO_FLUSH;\n while (1) {\n strm.next_out = pb + strm.total_out;\n strm.avail_out = out_size - (pb - (uint8_t *) out_buf);\n\n if (strm.avail_in == 0) {\n flush = Z_FINISH;\n }\n\n status = deflate(&strm, flush);\n if (status == Z_STREAM_END) {\n break;\n }\n else if (status != Z_OK) {\n deflateEnd(&strm);\n return -1;\n }\n }\n\n if (deflateEnd(&strm) != Z_OK) {\n flb_free(out_buf);\n return -1;\n }\n *out_len = strm.total_out;\n\n /* Construct the gzip checksum (CRC32 footer) */\n footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;\n pb = (uint8_t *) out_buf + footer_start;\n\n crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);\n *pb++ = crc & 0xFF;\n *pb++ = (crc >> 8) & 0xFF;\n *pb++ = (crc >> 16) & 0xFF;\n *pb++ = (crc >> 24) & 0xFF;\n *pb++ = in_len & 0xFF;\n *pb++ = (in_len >> 8) & 0xFF;\n *pb++ = (in_len >> 16) & 0xFF;\n *pb++ = (in_len >> 24) & 0xFF;\n\n /* Set the real buffer size for the caller */\n *out_len += FLB_GZIP_HEADER_OFFSET + 8;\n *out_data = out_buf;\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[258, 286]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[258, 286]]}, "_func_name": "flb_gzip_compress", "_file_name": "src/flb_gzip.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/players//achievements')\ndef achievements_list_player(player_id):\n \"\"\"Lists the progress of achievements for a player.\n\n :param player_id: ID of the player.\n\n :return:\n If successful, this method returns a response body with the following structure::\n\n {\n \"items\": [\n {\n \"achievement_id\": string,\n \"state\": string,\n \"current_steps\": integer,\n \"create_time\": long,\n \"update_time\": long\n }\n ]\n }\n \"\"\"\n with db.connection:\n cursor = db.connection.cursor(db.pymysql.cursors.DictCursor)\n cursor.execute(\"\"\"SELECT\n achievement_id,\n current_steps,\n state,\n UNIX_TIMESTAMP(create_time) as create_time,\n UNIX_TIMESTAMP(update_time) as update_time\n FROM player_achievements\n WHERE player_id = '%s'\"\"\" % player_id)\n\n return flask.jsonify(items=cursor.fetchall())", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1048, 1111]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1048, 1111]]}, "_func_name": "achievements_list_player", "_file_name": "api/achievements.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def take_bug_report(self, test_name, begin_time):\n \"\"\"Takes a bug report on the device and stores it in a file.\n\n Args:\n test_name: Name of the test case that triggered this bug report.\n begin_time: Logline format timestamp taken when the test started.\n \"\"\"\n new_br = True\n try:\n stdout = self.adb.shell('bugreportz -v').decode('utf-8')\n # This check is necessary for builds before N, where adb shell's ret\n # code and stderr are not propagated properly.\n if 'not found' in stdout:\n new_br = False\n except adb.AdbError:\n new_br = False\n br_path = os.path.join(self.log_path, 'BugReports')\n utils.create_dir(br_path)\n base_name = ',%s,%s.txt' % (begin_time, self.serial)\n if new_br:\n base_name = base_name.replace('.txt', '.zip')\n test_name_len = utils.MAX_FILENAME_LEN - len(base_name)\n out_name = test_name[:test_name_len] + base_name\n full_out_path = os.path.join(br_path, out_name.replace(' ', r'\\ '))\n # in case device restarted, wait for adb interface to return\n self.wait_for_boot_completion()\n self.log.info('Taking bugreport for %s.', test_name)\n if new_br:\n out = self.adb.shell('bugreportz').decode('utf-8')\n if not out.startswith('OK'):\n raise DeviceError(self, 'Failed to take bugreport: %s' % out)\n br_out_path = out.split(':')[1].strip()\n self.adb.pull([br_out_path, full_out_path])\n else:\n # shell=True as this command redirects the stdout to a local file\n # using shell redirection.\n self.adb.bugreport(' > %s' % full_out_path, shell=True)\n self.log.info('Bugreport for %s taken at %s.', test_name,\n full_out_path)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "take_bug_report", "_file_name": "mobly/controllers/android_device.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def nav_path(request):\n \"\"\"Return current path as list of items with \"name\" and \"href\" members\n\n The href members are view_directory links for directories and view_log\n links for files, but are set to None when the link would point to\n the current view\"\"\"\n\n if not request.repos:\n return []\n\n is_dir = request.pathtype == vclib.DIR\n\n # add root item\n items = []\n root_item = _item(name=request.server.escape(request.repos.name), href=None)\n if request.path_parts or request.view_func is not view_directory:\n root_item.href = request.get_url(view_func=view_directory,\n where='', pathtype=vclib.DIR,\n params={}, escape=1)\n items.append(root_item)\n\n # add path part items\n path_parts = []\n for part in request.path_parts:\n path_parts.append(part)\n is_last = len(path_parts) == len(request.path_parts)\n\n item = _item(name=part, href=None)\n\n if not is_last or (is_dir and request.view_func is not view_directory):\n item.href = request.get_url(view_func=view_directory,\n where=_path_join(path_parts),\n pathtype=vclib.DIR,\n params={}, escape=1)\n elif not is_dir and request.view_func is not view_log:\n item.href = request.get_url(view_func=view_log,\n where=_path_join(path_parts),\n pathtype=vclib.FILE,\n params={}, escape=1)\n items.append(item)\n\n return items", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[897, 936]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[897, 936]]}, "_func_name": "nav_path", "_file_name": "lib/viewvc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {\n\tOPCODE_DESC *opcode_desc;\n\tut16 ins = (buf[1] << 8) | buf[0];\n\tint fail;\n\tchar *t;\n\n\t// initialize op struct\n\tmemset (op, 0, sizeof (RAnalOp));\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->jump = UT64_MAX;\n\tr_strbuf_init (&op->esil);\n\n\t// process opcode\n\tfor (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {\n\t\tif ((ins & opcode_desc->mask) == opcode_desc->selector) {\n\t\t\tfail = 0;\n\n\t\t\t// copy default cycles/size values\n\t\t\top->cycles = opcode_desc->cycles;\n\t\t\top->size = opcode_desc->size;\n\t\t\top->type = opcode_desc->type;\n\t\t\top->jump = UT64_MAX;\n\t\t\top->fail = UT64_MAX;\n\t\t\t// op->fail = addr + op->size;\n\t\t\top->addr = addr;\n\n\t\t\t// start void esil expression\n\t\t\tr_strbuf_setf (&op->esil, \"\");\n\n\t\t\t// handle opcode\n\t\t\topcode_desc->handler (anal, op, buf, len, &fail, cpu);\n\t\t\tif (fail) {\n\t\t\t\tgoto INVALID_OP;\n\t\t\t}\n\t\t\tif (op->cycles <= 0) {\n\t\t\t\t// eprintf (\"opcode %s @%\"PFMT64x\" returned 0 cycles.\\n\", opcode_desc->name, op->addr);\n\t\t\t\topcode_desc->cycles = 2;\n\t\t\t}\n\t\t\top->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);\n\n\t\t\t// remove trailing coma (COMETE LA COMA)\n\t\t\tt = r_strbuf_get (&op->esil);\n\t\t\tif (t && strlen (t) > 1) {\n\t\t\t\tt += strlen (t) - 1;\n\t\t\t\tif (*t == ',') {\n\t\t\t\t\t*t = '\\0';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn opcode_desc;\n\t\t}\n\t}\n\n\t// ignore reserved opcodes (if they have not been caught by the previous loop)\n\tif ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {\n\t\tgoto INVALID_OP;\n\t}\n\nINVALID_OP:\n\t// An unknown or invalid option has appeared.\n\t// -- Throw pokeball!\n\top->family = R_ANAL_OP_FAMILY_UNKNOWN;\n\top->type = R_ANAL_OP_TYPE_UNK;\n\top->addr = addr;\n\top->fail = UT64_MAX;\n\top->jump = UT64_MAX;\n\top->ptr = UT64_MAX;\n\top->val = UT64_MAX;\n\top->nopcode = 1;\n\top->cycles = 1;\n\top->size = 2;\n\t// launch esil trap (for communicating upper layers about this weird\n\t// and stinky situation\n\tr_strbuf_set (&op->esil, \"1,$\");\n\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[142, 178]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[142, 178]]}, "_func_name": "avr_op_analyze", "_file_name": "libr/anal/p/anal_avr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@app.route('/')\ndef render_page_name(page_name):\n query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n wiki_page = query.namedresult()\n has_content = False\n page_is_taken = False\n if len(wiki_page) < 1:\n content = \"\"\n else:\n page_is_taken = True\n content = wiki_page[0].content\n if len(content) > 0:\n has_content = True\n else:\n pass\n content = markdown.markdown(wiki_linkify(content))\n return render_template(\n 'pageholder.html',\n page_is_taken = page_is_taken,\n page_name = page_name,\n markdown = markdown,\n wiki_linkify = wiki_linkify,\n has_content = has_content,\n content = content\n )", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "render_page_name", "_file_name": "server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _get_flashcopy_mapping_attributes(self, fc_map_id):\n LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s')\n % fc_map_id)\n\n fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-filtervalue',\n 'id=%s' % fc_map_id, '-delim', '!']\n out, err = self._run_ssh(fc_ls_map_cmd)\n if not len(out.strip()):\n return None\n\n # Get list of FlashCopy mappings\n # We expect zero or one line if mapping does not exist,\n # two lines if it does exist, otherwise error\n lines = out.strip().split('\\n')\n self._assert_ssh_return(len(lines) <= 2,\n '_get_flashcopy_mapping_attributes',\n fc_ls_map_cmd, out, err)\n\n if len(lines) == 2:\n attributes = self._get_hdr_dic(lines[0], lines[1], '!')\n else: # 0 or 1 lines\n attributes = None\n\n LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping '\n '%(fc_map_id)s, attributes %(attributes)s') %\n {'fc_map_id': fc_map_id, 'attributes': attributes})\n\n return attributes", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_flashcopy_mapping_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def set_language(self, lang):\n \"\"\"\n Update language of user in the User object and in the database\n :param lang: string with language tag like \"en-US\"\n :return: None\n \"\"\"\n log.debug('Updating info about user %s language '\n 'in memory & database...', self)\n\n self.language = lang\n\n query = (\"UPDATE users \"\n f\"SET language='{self.language}' \"\n f\"WHERE chat_id='{self.chat_id}'\")\n\n try:\n db.add(query)\n except DatabaseError:\n log.error(\"Can't add new language of %s to the database\", self)\n else:\n log.debug('Language updated.')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[383, 487]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[383, 487]]}, "_func_name": "set_language", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def extend_volume(self, volume, new_size):\n LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])\n ret = self._ensure_vdisk_no_fc_mappings(volume['name'],\n allow_snaps=False)\n if not ret:\n exception_message = (_('extend_volume: Extending a volume with '\n 'snapshots is not supported.'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n extend_amt = int(new_size) - volume['size']\n ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),\n '-unit', 'gb', volume['name']])\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from expandvdisksize\n self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',\n ssh_cmd, out, err)\n LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "extend_volume", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)\n{\n\tioapic->rtc_status.pending_eoi = 0;\n\tbitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[105, 167]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[105, 167]]}, "_func_name": "rtc_irq_eoi_tracking_reset", "_file_name": "arch/x86/kvm/ioapic.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)\n{\n\tstruct sctp_association *asoc = sctp_id2assoc(sk, id);\n\tstruct sctp_sock *sp = sctp_sk(sk);\n\tstruct socket *sock;\n\tint err = 0;\n\n\tif (!asoc)\n\t\treturn -EINVAL;\n\n\t/* If there is a thread waiting on more sndbuf space for\n\t * sending on this asoc, it cannot be peeled.\n\t */\n\tif (waitqueue_active(&asoc->wait))\n\t\treturn -EBUSY;\n\n\t/* An association cannot be branched off from an already peeled-off\n\t * socket, nor is this supported for tcp style sockets.\n\t */\n\tif (!sctp_style(sk, UDP))\n\t\treturn -EINVAL;\n\n\t/* Create a new socket. */\n\terr = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);\n\tif (err < 0)\n\t\treturn err;\n\n\tsctp_copy_sock(sock->sk, sk, asoc);\n\n\t/* Make peeled-off sockets more like 1-1 accepted sockets.\n\t * Set the daddr and initialize id to something more random\n\t */\n\tsp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);\n\n\t/* Populate the fields of the newsk from the oldsk and migrate the\n\t * asoc to the newsk.\n\t */\n\tsctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);\n\n\t*sockp = sock;\n\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[209, 221]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[209, 221]]}, "_func_name": "sctp_do_peeloff", "_file_name": "net/sctp/socket.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_least_used_nsp(self, nspss):\n \"\"\"\"Return the nsp that has the fewest active vluns.\"\"\"\n # return only the nsp (node:server:port)\n result = self.common._cli_run('showvlun -a -showcols Port', None)\n\n # count the number of nsps (there is 1 for each active vlun)\n nsp_counts = {}\n for nsp in nspss:\n # initialize counts to zero\n nsp_counts[nsp] = 0\n\n current_least_used_nsp = None\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n nsp = line.strip()\n if nsp in nsp_counts:\n nsp_counts[nsp] = nsp_counts[nsp] + 1\n\n # identify key (nsp) of least used nsp\n current_smallest_count = sys.maxint\n for (nsp, count) in nsp_counts.iteritems():\n if count < current_smallest_count:\n current_least_used_nsp = nsp\n current_smallest_count = count\n\n return current_least_used_nsp", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[155, 229]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[155, 229]]}, "_func_name": "_get_least_used_nsp", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int pure_strcmp(const char * const s1, const char * const s2)\n{\n const size_t s1_len = strlen(s1);\n const size_t s2_len = strlen(s2);\n\n if (s1_len != s2_len) {\n return -1;\n }\n return pure_memcmp(s1, s2, s1_len);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "pure_strcmp", "_file_name": "src/utils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n socklen_t size) {\n if (!src || !dst) {\n errno = EFAULT;\n return nullptr;\n }\n size_t src_size = 0;\n if (af == AF_INET) {\n src_size = sizeof(struct in_addr);\n } else if (af == AF_INET6) {\n src_size = sizeof(struct in6_addr);\n } else {\n errno = EAFNOSUPPORT;\n return nullptr;\n }\n\n MessageWriter input;\n input.Push(TokLinuxAfFamily(af));\n input.PushByReference(Extent{reinterpret_cast(src), src_size});\n input.Push(size);\n MessageReader output;\n\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kInetNtopHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_inet_ntop\", 2);\n\n auto result = output.next();\n int klinux_errno = output.next();\n if (result.empty()) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return nullptr;\n }\n\n memcpy(\n dst, result.data(),\n std::min({static_cast(size), static_cast(result.size()),\n static_cast(INET6_ADDRSTRLEN)}));\n return dst;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_inet_ntop", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)\n{\n\twStream* s;\n\tsize_t length;\n\tNTLM_NEGOTIATE_MESSAGE* message;\n\tmessage = &context->NEGOTIATE_MESSAGE;\n\tZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));\n\ts = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);\n\n\tif (!s)\n\t\treturn SEC_E_INTERNAL_ERROR;\n\n\tif (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->MessageType != MESSAGE_TYPE_NEGOTIATE)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (Stream_GetRemainingLength(s) < 4)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\tStream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */\n\n\tif (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tcontext->NegotiateFlags = message->NegotiateFlags;\n\n\t/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\t/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t{\n\t\tif (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */\n\t\t{\n\t\t\tStream_Free(s, FALSE);\n\t\t\treturn SEC_E_INVALID_TOKEN;\n\t\t}\n\t}\n\n\tlength = Stream_GetPosition(s);\n\tbuffer->cbBuffer = length;\n\n\tif (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INTERNAL_ERROR;\n\t}\n\n\tCopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);\n\tcontext->NegotiateMessage.BufferType = buffer->BufferType;\n#ifdef WITH_DEBUG_NTLM\n\tWLog_DBG(TAG, \"NEGOTIATE_MESSAGE (length = %\" PRIu32 \")\", context->NegotiateMessage.cbBuffer);\n\twinpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,\n\t context->NegotiateMessage.cbBuffer);\n\tntlm_print_negotiate_flags(message->NegotiateFlags);\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t\tntlm_print_version_info(&(message->Version));\n\n#endif\n\tcontext->state = NTLM_STATE_CHALLENGE;\n\tStream_Free(s, FALSE);\n\treturn SEC_I_CONTINUE_NEEDED;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ntlm_read_NegotiateMessage", "_file_name": "winpr/libwinpr/sspi/NTLM/ntlm_message.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n header[MagickPathExtent];\n\n const char\n *property;\n\n MagickBooleanType\n status;\n\n register const Quantum\n *p;\n\n register ssize_t\n i,\n x;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n pixel[4],\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n if (IsRGBColorspace(image->colorspace) == MagickFalse)\n (void) TransformImageColorspace(image,RGBColorspace,exception);\n /*\n Write header.\n */\n (void) ResetMagickMemory(header,' ',MagickPathExtent);\n length=CopyMagickString(header,\"#?RGBE\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n property=GetImageProperty(image,\"comment\",exception);\n if ((property != (const char *) NULL) &&\n (strchr(property,'\\n') == (char *) NULL))\n {\n count=FormatLocaleString(header,MagickPathExtent,\"#%s\\n\",property);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n property=GetImageProperty(image,\"hdr:exposure\",exception);\n if (property != (const char *) NULL)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"EXPOSURE=%g\\n\",\n strtod(property,(char **) NULL));\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n if (image->gamma != 0.0)\n {\n count=FormatLocaleString(header,MagickPathExtent,\"GAMMA=%g\\n\",\n image->gamma);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n }\n count=FormatLocaleString(header,MagickPathExtent,\n \"PRIMARIES=%g %g %g %g %g %g %g %g\\n\",\n image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,\n image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,\n image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,\n image->chromaticity.white_point.x,image->chromaticity.white_point.y);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n length=CopyMagickString(header,\"FORMAT=32-bit_rle_rgbe\\n\\n\",MagickPathExtent);\n (void) WriteBlob(image,length,(unsigned char *) header);\n count=FormatLocaleString(header,MagickPathExtent,\"-Y %.20g +X %.20g\\n\",\n (double) image->rows,(double) image->columns);\n (void) WriteBlob(image,(size_t) count,(unsigned char *) header);\n /*\n Write HDR pixels.\n */\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4*\n sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels));\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixel[0]=2;\n pixel[1]=2;\n pixel[2]=(unsigned char) (image->columns >> 8);\n pixel[3]=(unsigned char) (image->columns & 0xff);\n count=WriteBlob(image,4*sizeof(*pixel),pixel);\n if (count != (ssize_t) (4*sizeof(*pixel)))\n break;\n }\n i=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;\n\n pixel[0]=0;\n pixel[1]=0;\n pixel[2]=0;\n pixel[3]=0;\n gamma=QuantumScale*GetPixelRed(image,p);\n if ((QuantumScale*GetPixelGreen(image,p)) > gamma)\n gamma=QuantumScale*GetPixelGreen(image,p);\n if ((QuantumScale*GetPixelBlue(image,p)) > gamma)\n gamma=QuantumScale*GetPixelBlue(image,p);\n if (gamma > MagickEpsilon)\n {\n int\n exponent;\n\n gamma=frexp(gamma,&exponent)*256.0/gamma;\n pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));\n pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));\n pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));\n pixel[3]=(unsigned char) (exponent+128);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n pixels[x]=pixel[0];\n pixels[x+image->columns]=pixel[1];\n pixels[x+2*image->columns]=pixel[2];\n pixels[x+3*image->columns]=pixel[3];\n }\n else\n {\n pixels[i++]=pixel[0];\n pixels[i++]=pixel[1];\n pixels[i++]=pixel[2];\n pixels[i++]=pixel[3];\n }\n p+=GetPixelChannels(image);\n }\n if ((image->columns >= 8) && (image->columns <= 0x7ffff))\n {\n for (i=0; i < 4; i++)\n length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);\n }\n else\n {\n count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);\n if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))\n break;\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n (void) CloseBlob(image);\n return(MagickTrue);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "WriteHDRImage", "_file_name": "coders/hdr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int run(const CommandLineOptions& options)\n{\n\tIR::Module irModule;\n\n\t// Load the module.\n\tif(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }\n\tif(options.onlyCheck) { return EXIT_SUCCESS; }\n\n\t// Compile the module.\n\tRuntime::Module* module = nullptr;\n\tif(!options.precompiled) { module = Runtime::compileModule(irModule); }\n\telse\n\t{\n\t\tconst UserSection* precompiledObjectSection = nullptr;\n\t\tfor(const UserSection& userSection : irModule.userSections)\n\t\t{\n\t\t\tif(userSection.name == \"wavm.precompiled_object\")\n\t\t\t{\n\t\t\t\tprecompiledObjectSection = &userSection;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(!precompiledObjectSection)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Input file did not contain 'wavm.precompiled_object' section\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmodule = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);\n\t\t}\n\t}\n\n\t// Link the module with the intrinsic modules.\n\tCompartment* compartment = Runtime::createCompartment();\n\tContext* context = Runtime::createContext(compartment);\n\tRootResolver rootResolver(compartment);\n\n\tEmscripten::Instance* emscriptenInstance = nullptr;\n\tif(options.enableEmscripten)\n\t{\n\t\temscriptenInstance = Emscripten::instantiate(compartment, irModule);\n\t\tif(emscriptenInstance)\n\t\t{\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"env\", emscriptenInstance->env);\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"asm2wasm\", emscriptenInstance->asm2wasm);\n\t\t\trootResolver.moduleNameToInstanceMap.set(\"global\", emscriptenInstance->global);\n\t\t}\n\t}\n\n\tif(options.enableThreadTest)\n\t{\n\t\tModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);\n\t\trootResolver.moduleNameToInstanceMap.set(\"threadTest\", threadTestInstance);\n\t}\n\n\tLinkResult linkResult = linkModule(irModule, rootResolver);\n\tif(!linkResult.success)\n\t{\n\t\tLog::printf(Log::error, \"Failed to link module:\\n\");\n\t\tfor(auto& missingImport : linkResult.missingImports)\n\t\t{\n\t\t\tLog::printf(Log::error,\n\t\t\t\t\t\t\"Missing import: module=\\\"%s\\\" export=\\\"%s\\\" type=\\\"%s\\\"\\n\",\n\t\t\t\t\t\tmissingImport.moduleName.c_str(),\n\t\t\t\t\t\tmissingImport.exportName.c_str(),\n\t\t\t\t\t\tasString(missingImport.type).c_str());\n\t\t}\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t// Instantiate the module.\n\tModuleInstance* moduleInstance = instantiateModule(\n\t\tcompartment, module, std::move(linkResult.resolvedImports), options.filename);\n\tif(!moduleInstance) { return EXIT_FAILURE; }\n\n\t// Call the module start function, if it has one.\n\tFunctionInstance* startFunction = getStartFunction(moduleInstance);\n\tif(startFunction) { invokeFunctionChecked(context, startFunction, {}); }\n\n\tif(options.enableEmscripten)\n\t{\n\t\t// Call the Emscripten global initalizers.\n\t\tEmscripten::initializeGlobals(context, irModule, moduleInstance);\n\t}\n\n\t// Look up the function export to call.\n\tFunctionInstance* functionInstance;\n\tif(!options.functionName)\n\t{\n\t\tfunctionInstance = asFunctionNullable(getInstanceExport(moduleInstance, \"main\"));\n\t\tif(!functionInstance)\n\t\t{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, \"_main\")); }\n\t\tif(!functionInstance)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Module does not export main function\\n\");\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfunctionInstance\n\t\t\t= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));\n\t\tif(!functionInstance)\n\t\t{\n\t\t\tLog::printf(Log::error, \"Module does not export '%s'\\n\", options.functionName);\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tFunctionType functionType = getFunctionType(functionInstance);\n\n\t// Set up the arguments for the invoke.\n\tstd::vector invokeArgs;\n\tif(!options.functionName)\n\t{\n\t\tif(functionType.params().size() == 2)\n\t\t{\n\t\t\tif(!emscriptenInstance)\n\t\t\t{\n\t\t\t\tLog::printf(\n\t\t\t\t\tLog::error,\n\t\t\t\t\t\"Module does not declare a default memory object to put arguments in.\\n\");\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::vector argStrings;\n\t\t\t\targStrings.push_back(options.filename);\n\t\t\t\tchar** args = options.args;\n\t\t\t\twhile(*args) { argStrings.push_back(*args++); };\n\n\t\t\t\twavmAssert(emscriptenInstance);\n\t\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n\t\t\t}\n\t\t}\n\t\telse if(functionType.params().size() > 0)\n\t\t{\n\t\t\tLog::printf(Log::error,\n\t\t\t\t\t\t\"WebAssembly function requires %\" PRIu64\n\t\t\t\t\t\t\" argument(s), but only 0 or 2 can be passed!\",\n\t\t\t\t\t\tfunctionType.params().size());\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(U32 i = 0; options.args[i]; ++i)\n\t\t{\n\t\t\tValue value;\n\t\t\tswitch(functionType.params()[i])\n\t\t\t{\n\t\t\tcase ValueType::i32: value = (U32)atoi(options.args[i]); break;\n\t\t\tcase ValueType::i64: value = (U64)atol(options.args[i]); break;\n\t\t\tcase ValueType::f32: value = (F32)atof(options.args[i]); break;\n\t\t\tcase ValueType::f64: value = atof(options.args[i]); break;\n\t\t\tcase ValueType::v128:\n\t\t\tcase ValueType::anyref:\n\t\t\tcase ValueType::anyfunc:\n\t\t\t\tErrors::fatalf(\"Cannot parse command-line argument for %s function parameter\",\n\t\t\t\t\t\t\t asString(functionType.params()[i]));\n\t\t\tdefault: Errors::unreachable();\n\t\t\t}\n\t\t\tinvokeArgs.push_back(value);\n\t\t}\n\t}\n\n\t// Invoke the function.\n\tTiming::Timer executionTimer;\n\tIR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);\n\tTiming::logTimer(\"Invoked function\", executionTimer);\n\n\tif(options.functionName)\n\t{\n\t\tLog::printf(Log::debug,\n\t\t\t\t\t\"%s returned: %s\\n\",\n\t\t\t\t\toptions.functionName,\n\t\t\t\t\tasString(functionResults).c_str());\n\t\treturn EXIT_SUCCESS;\n\t}\n\telse if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)\n\t{\n\t\treturn functionResults[0].i32;\n\t}\n\telse\n\t{\n\t\treturn EXIT_SUCCESS;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "run", "_file_name": "Programs/wavm/wavm.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)\n{\n\tstruct drm_vc4_submit_cl *args = exec->args;\n\tvoid *temp = NULL;\n\tvoid *bin;\n\tint ret = 0;\n\tuint32_t bin_offset = 0;\n\tuint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,\n\t\t\t\t\t 16);\n\tuint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;\n\tuint32_t exec_size = uniforms_offset + args->uniforms_size;\n\tuint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *\n\t\t\t\t\t args->shader_rec_count);\n\tstruct vc4_bo *bo;\n\n\tif (shader_rec_offset < args->bin_cl_size ||\n\t uniforms_offset < shader_rec_offset ||\n\t exec_size < uniforms_offset ||\n\t args->shader_rec_count >= (UINT_MAX /\n\t\t\t\t\t sizeof(struct vc4_shader_state)) ||\n\t temp_size < exec_size) {\n\t\tDRM_ERROR(\"overflow in exec arguments\\n\");\n\t\tgoto fail;\n\t}\n\n\t/* Allocate space where we'll store the copied in user command lists\n\t * and shader records.\n\t *\n\t * We don't just copy directly into the BOs because we need to\n\t * read the contents back for validation, and I think the\n\t * bo->vaddr is uncached access.\n\t */\n\ttemp = drm_malloc_ab(temp_size, 1);\n\tif (!temp) {\n\t\tDRM_ERROR(\"Failed to allocate storage for copying \"\n\t\t\t \"in bin/render CLs.\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\tbin = temp + bin_offset;\n\texec->shader_rec_u = temp + shader_rec_offset;\n\texec->uniforms_u = temp + uniforms_offset;\n\texec->shader_state = temp + exec_size;\n\texec->shader_state_size = args->shader_rec_count;\n\n\tif (copy_from_user(bin,\n\t\t\t (void __user *)(uintptr_t)args->bin_cl,\n\t\t\t args->bin_cl_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tif (copy_from_user(exec->shader_rec_u,\n\t\t\t (void __user *)(uintptr_t)args->shader_rec,\n\t\t\t args->shader_rec_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tif (copy_from_user(exec->uniforms_u,\n\t\t\t (void __user *)(uintptr_t)args->uniforms,\n\t\t\t args->uniforms_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tbo = vc4_bo_create(dev, exec_size, true);\n\tif (IS_ERR(bo)) {\n\t\tDRM_ERROR(\"Couldn't allocate BO for binning\\n\");\n\t\tret = PTR_ERR(bo);\n\t\tgoto fail;\n\t}\n\texec->exec_bo = &bo->base;\n\n\tlist_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,\n\t\t &exec->unref_list);\n\n\texec->ct0ca = exec->exec_bo->paddr + bin_offset;\n\n\texec->bin_u = bin;\n\n\texec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;\n\texec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;\n\texec->shader_rec_size = args->shader_rec_size;\n\n\texec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;\n\texec->uniforms_p = exec->exec_bo->paddr + uniforms_offset;\n\texec->uniforms_size = args->uniforms_size;\n\n\tret = vc4_validate_bin_cl(dev,\n\t\t\t\t exec->exec_bo->vaddr + bin_offset,\n\t\t\t\t bin,\n\t\t\t\t exec);\n\tif (ret)\n\t\tgoto fail;\n\n\tret = vc4_validate_shader_recs(dev, exec);\n\tif (ret)\n\t\tgoto fail;\n\n\t/* Block waiting on any previous rendering into the CS's VBO,\n\t * IB, or textures, so that pixels are actually written by the\n\t * time we try to read them.\n\t */\n\tret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true);\n\nfail:\n\tdrm_free_large(temp);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "vc4_get_bcl", "_file_name": "drivers/gpu/drm/vc4/vc4_gem.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@contextmanager\ndef run_interactive_shell_command(command, **kwargs):\n \"\"\"\n Runs a command in shell and provides stdout, stderr and stdin streams.\n\n This function creates a context manager that sets up the process, returns\n to caller, closes streams and waits for process to exit on leaving.\n\n The process is opened in `universal_newlines` mode.\n\n :param command: The command to run on shell.\n :param kwargs: Additional keyword arguments to pass to `subprocess.Popen`\n that is used to spawn the process (except `shell`,\n `stdout`, `stderr`, `stdin` and `universal_newlines`, a\n `TypeError` is raised then).\n :return: A context manager yielding the process started from the\n command.\n \"\"\"\n process = Popen(command,\n shell=True,\n stdout=PIPE,\n stderr=PIPE,\n stdin=PIPE,\n universal_newlines=True,\n **kwargs)\n try:\n yield process\n finally:\n process.stdout.close()\n process.stderr.close()\n process.stdin.close()\n process.wait()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[154, 304], [490, 686], [799, 860]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[154, 304], [490, 686], [799, 860]]}, "_func_name": "run_interactive_shell_command", "_file_name": "coalib/misc/Shell.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret)\n{\n\tMD5_CTX md5_secret, my_md5;\n\tunsigned char misc[AUTH_VECTOR_LEN];\n\tint i;\n\tint length = strlen(password);\n\tunsigned char hashed[256 + AUTH_PASS_LEN];\t/* can't be longer than this */\n\tunsigned char *vector;\n\tattribute_t *attr;\n\n\tif (length > MAXPASS) {\t\t\t\t/* shorten the password for now */\n\t\tlength = MAXPASS;\n\t}\n\n\tif (length == 0) {\n\t\tlength = AUTH_PASS_LEN;\t\t\t/* 0 maps to 16 */\n\t} if ((length & (AUTH_PASS_LEN - 1)) != 0) {\n\t\tlength += (AUTH_PASS_LEN - 1);\t\t/* round it up */\n\t\tlength &= ~(AUTH_PASS_LEN - 1);\t\t/* chop it off */\n\t}\t\t\t\t\t\t/* 16*N maps to itself */\n\n\tmemset(hashed, 0, length);\n\tmemcpy(hashed, password, strlen(password));\n\n\tattr = find_attribute(request, PW_PASSWORD);\n\n\tif (type == PW_PASSWORD) {\n\t\tvector = request->vector;\n\t} else {\n\t\tvector = attr->data;\t\t\t/* attr CANNOT be NULL here. */\n\t}\n\n\t/* ************************************************************ */\n\t/* encrypt the password */\n\t/* password : e[0] = p[0] ^ MD5(secret + vector) */\n\tMD5Init(&md5_secret);\n\tMD5Update(&md5_secret, (unsigned char *) secret, strlen(secret));\n\tmy_md5 = md5_secret;\t\t\t\t/* so we won't re-do the hash later */\n\tMD5Update(&my_md5, vector, AUTH_VECTOR_LEN);\n\tMD5Final(misc, &my_md5);\t\t\t/* set the final vector */\n\txor(hashed, misc, AUTH_PASS_LEN);\n\n\t/* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */\n\tfor (i = 1; i < (length >> 4); i++) {\n\t\tmy_md5 = md5_secret;\t\t\t/* grab old value of the hash */\n\t\tMD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN);\n\t\tMD5Final(misc, &my_md5);\t\t\t/* set the final vector */\n\t\txor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN);\n\t}\n\n\tif (type == PW_OLD_PASSWORD) {\n\t\tattr = find_attribute(request, PW_OLD_PASSWORD);\n\t}\n\n\tif (!attr) {\n\t\tadd_attribute(request, type, hashed, length);\n\t} else {\n\t\tmemcpy(attr->data, hashed, length); /* overwrite the packet */\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[698, 743]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[698, 743]]}, "_func_name": "add_password", "_file_name": "src/pam_radius_auth.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void luaD_shrinkstack (lua_State *L) {\n int inuse = stackinuse(L);\n int goodsize = inuse + BASIC_STACK_SIZE;\n if (goodsize > LUAI_MAXSTACK)\n goodsize = LUAI_MAXSTACK; /* respect stack limit */\n /* if thread is currently not handling a stack overflow and its\n good size is smaller than current size, shrink its stack */\n if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize)\n luaD_reallocstack(L, goodsize, 0); /* ok if that fails */\n else /* don't change stack */\n condmovestack(L,{},{}); /* (change only for debugging) */\n luaE_shrinkCI(L); /* shrink CI list */\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "luaD_shrinkstack", "_file_name": "ldo.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_iscsi_ip_addrs(self):\n generator = self._port_conf_generator(['svcinfo', 'lsportip'])\n header = next(generator, None)\n if not header:\n return\n\n for port_data in generator:\n try:\n port_node_id = port_data['node_id']\n port_ipv4 = port_data['IP_address']\n port_ipv6 = port_data['IP_address_6']\n state = port_data['state']\n except KeyError:\n self._handle_keyerror('lsportip', header)\n\n if port_node_id in self._storage_nodes and (\n state == 'configured' or state == 'online'):\n node = self._storage_nodes[port_node_id]\n if len(port_ipv4):\n node['ipv4'].append(port_ipv4)\n if len(port_ipv6):\n node['ipv6'].append(port_ipv6)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_iscsi_ip_addrs", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def change_message(self, new_message, logged_user):\n update_sql = \"\"\"\n UPDATE Clients\n SET message = '{}'\n WHERE client_id = '{}'\n \"\"\".format(new_message, logged_user.get_client_id())\n\n cursor = self.__conn.cursor()\n\n cursor.execute(update_sql)\n self.__conn.commit()\n logged_user.set_message(new_message)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[108, 235]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[108, 235]]}, "_func_name": "change_message", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n{\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tlong ret;\n\n\t/* find the key first */\n\tkey_ref = lookup_user_key(keyid, 0, 0);\n\tif (IS_ERR(key_ref)) {\n\t\tret = -ENOKEY;\n\t\tgoto error;\n\t}\n\n\tkey = key_ref_to_ptr(key_ref);\n\n\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tret = -ENOKEY;\n\t\tgoto error2;\n\t}\n\n\t/* see if we can read it directly */\n\tret = key_permission(key_ref, KEY_NEED_READ);\n\tif (ret == 0)\n\t\tgoto can_read_key;\n\tif (ret != -EACCES)\n\t\tgoto error2;\n\n\t/* we can't; see if it's searchable from this process's keyrings\n\t * - we automatically take account of the fact that it may be\n\t * dangling off an instantiation key\n\t */\n\tif (!is_key_possessed(key_ref)) {\n\t\tret = -EACCES;\n\t\tgoto error2;\n\t}\n\n\t/* the key is probably readable - now try to read it */\ncan_read_key:\n\tret = -EOPNOTSUPP;\n\tif (key->type->read) {\n\t\t/* Read the data with the semaphore held (since we might sleep)\n\t\t * to protect against the key being updated or revoked.\n\t\t */\n\t\tdown_read(&key->sem);\n\t\tret = key_validate(key);\n\t\tif (ret == 0)\n\t\t\tret = key->type->read(key, buffer, buflen);\n\t\tup_read(&key->sem);\n\t}\n\nerror2:\n\tkey_put(key);\nerror:\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "keyctl_read_key", "_file_name": "security/keys/keyctl.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void handle_PORT(ctrl_t *ctrl, char *str)\n{\n\tint a, b, c, d, e, f;\n\tchar addr[INET_ADDRSTRLEN];\n\tstruct sockaddr_in sin;\n\n\tif (ctrl->data_sd > 0) {\n\t\tuev_io_stop(&ctrl->data_watcher);\n\t\tclose(ctrl->data_sd);\n\t\tctrl->data_sd = -1;\n\t}\n\n\t/* Convert PORT command's argument to IP address + port */\n\tsscanf(str, \"%d,%d,%d,%d,%d,%d\", &a, &b, &c, &d, &e, &f);\n\tsprintf(addr, \"%d.%d.%d.%d\", a, b, c, d);\n\n\t/* Check IPv4 address using inet_aton(), throw away converted result */\n\tif (!inet_aton(addr, &(sin.sin_addr))) {\n\t\tERR(0, \"Invalid address '%s' given to PORT command\", addr);\n\t\tsend_msg(ctrl->sd, \"500 Illegal PORT command.\\r\\n\");\n\t\treturn;\n\t}\n\n\tstrlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address));\n\tctrl->data_port = e * 256 + f;\n\n\tDBG(\"Client PORT command accepted for %s:%d\", ctrl->data_address, ctrl->data_port);\n\tsend_msg(ctrl->sd, \"200 PORT command successful.\\r\\n\");\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[360, 403]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[360, 403]]}, "_func_name": "handle_PORT", "_file_name": "src/ftpcmd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {\n\t// Skip whitespace\n\twhile (begin && isspace ((ut8)str[*begin])) {\n\t\t++(*begin);\n\t}\n\n\tif (!str[*begin]) { // null byte\n\t\t*end = *begin;\n\t\treturn TT_EOF;\n\t} else if (isalpha ((ut8)str[*begin])) { // word token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) {\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_WORD;\n\t} else if (isdigit ((ut8)str[*begin])) { // number token\n\t\t*end = *begin;\n\t\twhile (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.\n\t\t\t++(*end);\n\t\t}\n\t\treturn TT_NUMBER;\n\t} else { // special character: [, ], +, *, ...\n\t\t*end = *begin + 1;\n\t\treturn TT_SPECIAL;\n\t}\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[247, 305], [401, 461]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[247, 305], [401, 461]]}, "_func_name": "getToken", "_file_name": "libr/asm/p/asm_x86_nz.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,\n enum expr_value_type type, xkb_mod_mask_t *val_rtrn)\n{\n const char *str;\n xkb_mod_index_t ndx;\n const LookupModMaskPriv *arg = priv;\n const struct xkb_mod_set *mods = arg->mods;\n enum mod_type mod_type = arg->mod_type;\n\n if (type != EXPR_TYPE_INT)\n return false;\n\n str = xkb_atom_text(ctx, field);\n\n if (istreq(str, \"all\")) {\n *val_rtrn = MOD_REAL_MASK_ALL;\n return true;\n }\n\n if (istreq(str, \"none\")) {\n *val_rtrn = 0;\n return true;\n }\n\n ndx = XkbModNameToIndex(mods, field, mod_type);\n if (ndx == XKB_MOD_INVALID)\n return false;\n\n *val_rtrn = (1u << ndx);\n return true;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[415, 416]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[415, 416]]}, "_func_name": "LookupModMask", "_file_name": "src/xkbcomp/expr.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "size_t jsuGetFreeStack() {\n#ifdef ARM\n void *frame = __builtin_frame_address(0);\n size_t stackPos = (size_t)((char*)frame);\n size_t stackEnd = (size_t)((char*)&LINKER_END_VAR);\n if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow!\n return stackPos - stackEnd;\n#elif defined(LINUX)\n // On linux, we set STACK_BASE from `main`.\n char ptr; // this is on the stack\n extern void *STACK_BASE;\n uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr);\n return 1000000 - count; // give it 1 megabyte of stack\n#else\n // stack depth seems pretty platform-specific :( Default to a value that disables it\n return 1000000; // no stack depth check on this platform\n#endif\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[499, 556]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[499, 556]]}, "_func_name": "jsuGetFreeStack", "_file_name": "src/jsutils.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@register.filter\ndef json_dumps(value, indent=None):\n if isinstance(value, QuerySet):\n result = serialize('json', value, indent=indent)\n else:\n result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)\n\n return mark_safe(result)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[231, 259]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[231, 259]]}, "_func_name": "json_dumps", "_file_name": "djblets/util/templatetags/djblets_js.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _inject_file_into_fs(fs, path, contents):\n absolute_path = os.path.join(fs, path.lstrip('/'))\n parent_dir = os.path.dirname(absolute_path)\n utils.execute('mkdir', '-p', parent_dir, run_as_root=True)\n utils.execute('tee', absolute_path, process_input=contents,\n run_as_root=True)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[46, 101], [212, 303]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[46, 101], [212, 303]]}, "_func_name": "_inject_file_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def shame_ask(name):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n SELECT shame FROM people WHERE name=%(name)s\n ''', (name, ))\n shame = cursor.fetchone()\n db.close()\n if shame is None:\n logger.debug('No shame found for name {}'.format(name))\n return shame\n else:\n shame = shame[0]\n logger.debug('shame of {} found for name {}'.format(shame, name))\n return shame\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "shame_ask", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def delete_resultSet(self, session, id):\n self._openContainer(session)\n sid = str(id)\n if (self.idNormalizer is not None):\n sid = self.idNormalizer.process_string(session, sid)\n query = \"DELETE FROM %s WHERE identifier = '%s';\" % (self.table, sid)\n self._query(query)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[213, 291]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[213, 291]]}, "_func_name": "delete_resultSet", "_file_name": "cheshire3/sql/resultSetStore.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def build_board(conn, game,size):\n # we'll build the empty board, and then fill in with the move list that\n # we get from the DB.\n board = []\n for i in range(size):\n board.append([\"\"]*size)\n\n\n # search for all moves that have happenend during this game.\n cursor = conn.cursor()\n cursor.execute(\"SELECT x,y,letter FROM moves WHERE gameID = %d;\", (game,))\n\n counts = {\"X\":0, \"O\":0}\n for move in cursor.fetchall():\n (x,y,letter) = move\n\n x = int(x)\n y = int(y)\n assert x >= 0 and x < size\n assert y >= 0 and y < size\n\n assert letter in \"XO\"\n\n assert board[x][y] == \"\"\n board[x][y] = letter\n\n counts[letter] += 1\n\n cursor.close()\n\n assert counts[\"X\"] >= counts[\"O\"]\n assert counts[\"X\"] <= counts[\"O\"]+1\n\n if counts[\"X\"] == counts[\"O\"]:\n nextPlayer = 0\n else:\n nextPlayer = 1\n letter = \"XO\"[nextPlayer]\n\n return (board,nextPlayer,letter)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "build_board", "_file_name": "cgi/common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,\n CodedBitstreamFragment *frag,\n int header)\n{\n AVBufferRef *data_ref;\n uint8_t *data;\n size_t data_size;\n int unit, start, end, marker, next_start, next_marker;\n int err, i, j, length;\n\n if (frag->data_size < 4) {\n // Definitely too short to be meaningful.\n return AVERROR_INVALIDDATA;\n }\n\n for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);\n if (i > 0) {\n av_log(ctx->log_ctx, AV_LOG_WARNING, \"Discarding %d bytes at \"\n \"beginning of image.\\n\", i);\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size && frag->data[i]) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no SOI marker found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n if (marker != JPEG_MARKER_SOI) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: first \"\n \"marker is %02x, should be SOI.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"no image content found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n marker = frag->data[i];\n start = i + 1;\n\n for (unit = 0;; unit++) {\n if (marker == JPEG_MARKER_EOI) {\n break;\n } else if (marker == JPEG_MARKER_SOS) {\n for (i = start; i + 1 < frag->data_size; i++) {\n if (frag->data[i] != 0xff)\n continue;\n end = i;\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n if (frag->data[i] == 0x00)\n continue;\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n break;\n }\n } else {\n i = start;\n if (i + 2 > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n length = AV_RB16(frag->data + i);\n if (i + length > frag->data_size) {\n av_log(ctx->log_ctx, AV_LOG_ERROR, \"Invalid JPEG image: \"\n \"truncated at %02x marker segment.\\n\", marker);\n return AVERROR_INVALIDDATA;\n }\n end = start + length;\n\n i = end;\n if (frag->data[i] != 0xff) {\n next_marker = -1;\n } else {\n for (++i; i + 1 < frag->data_size &&\n frag->data[i] == 0xff; i++);\n if (i + 1 >= frag->data_size) {\n next_marker = -1;\n } else {\n next_marker = frag->data[i];\n next_start = i + 1;\n }\n }\n }\n\n if (marker == JPEG_MARKER_SOS) {\n length = AV_RB16(frag->data + start);\n\n data_ref = NULL;\n data = av_malloc(end - start +\n AV_INPUT_BUFFER_PADDING_SIZE);\n if (!data)\n return AVERROR(ENOMEM);\n\n memcpy(data, frag->data + start, length);\n for (i = start + length, j = length; i < end; i++, j++) {\n if (frag->data[i] == 0xff) {\n while (frag->data[i] == 0xff)\n ++i;\n data[j] = 0xff;\n } else {\n data[j] = frag->data[i];\n }\n }\n data_size = j;\n\n memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);\n\n } else {\n data = frag->data + start;\n data_size = end - start;\n data_ref = frag->data_ref;\n }\n\n err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,\n data, data_size, data_ref);\n if (err < 0)\n return err;\n\n if (next_marker == -1)\n break;\n marker = next_marker;\n start = next_start;\n }\n\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-787", "source": "SVEN-before", "vuln_type": "cwe-787", "token_labels": {"evidence": [[3398, 3427]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3398, 3427]]}, "_func_name": "cbs_jpeg_split_fragment", "_file_name": "libavcodec/cbs_jpeg.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int xc2028_set_config(struct dvb_frontend *fe, void *priv_cfg)\n{\n\tstruct xc2028_data *priv = fe->tuner_priv;\n\tstruct xc2028_ctrl *p = priv_cfg;\n\tint rc = 0;\n\n\ttuner_dbg(\"%s called\\n\", __func__);\n\n\tmutex_lock(&priv->lock);\n\n\t/*\n\t * Copy the config data.\n\t * For the firmware name, keep a local copy of the string,\n\t * in order to avoid troubles during device release.\n\t */\n\tkfree(priv->ctrl.fname);\n\tpriv->ctrl.fname = NULL;\n\tmemcpy(&priv->ctrl, p, sizeof(priv->ctrl));\n\tif (p->fname) {\n\t\tpriv->ctrl.fname = kstrdup(p->fname, GFP_KERNEL);\n\t\tif (priv->ctrl.fname == NULL)\n\t\t\treturn -ENOMEM;\n\t}\n\n\t/*\n\t * If firmware name changed, frees firmware. As free_firmware will\n\t * reset the status to NO_FIRMWARE, this forces a new request_firmware\n\t */\n\tif (!firmware_name[0] && p->fname &&\n\t priv->fname && strcmp(p->fname, priv->fname))\n\t\tfree_firmware(priv);\n\n\tif (priv->ctrl.max_len < 9)\n\t\tpriv->ctrl.max_len = 13;\n\n\tif (priv->state == XC2028_NO_FIRMWARE) {\n\t\tif (!firmware_name[0])\n\t\t\tpriv->fname = priv->ctrl.fname;\n\t\telse\n\t\t\tpriv->fname = firmware_name;\n\n\t\trc = request_firmware_nowait(THIS_MODULE, 1,\n\t\t\t\t\t priv->fname,\n\t\t\t\t\t priv->i2c_props.adap->dev.parent,\n\t\t\t\t\t GFP_KERNEL,\n\t\t\t\t\t fe, load_firmware_cb);\n\t\tif (rc < 0) {\n\t\t\ttuner_err(\"Failed to request firmware %s\\n\",\n\t\t\t\t priv->fname);\n\t\t\tpriv->state = XC2028_NODEV;\n\t\t} else\n\t\t\tpriv->state = XC2028_WAITING_FIRMWARE;\n\t}\n\tmutex_unlock(&priv->lock);\n\n\treturn rc;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "xc2028_set_config", "_file_name": "drivers/media/tuners/tuner-xc2028.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "PHYSICALPATH_FUNC(mod_alias_physical_handler) {\n\tplugin_data *p = p_d;\n\tint uri_len, basedir_len;\n\tchar *uri_ptr;\n\tsize_t k;\n\n\tif (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;\n\n\tmod_alias_patch_connection(srv, con, p);\n\n\t/* not to include the tailing slash */\n\tbasedir_len = buffer_string_length(con->physical.basedir);\n\tif ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;\n\turi_len = buffer_string_length(con->physical.path) - basedir_len;\n\turi_ptr = con->physical.path->ptr + basedir_len;\n\n\tfor (k = 0; k < p->conf.alias->used; k++) {\n\t\tdata_string *ds = (data_string *)p->conf.alias->data[k];\n\t\tint alias_len = buffer_string_length(ds->key);\n\n\t\tif (alias_len > uri_len) continue;\n\t\tif (buffer_is_empty(ds->key)) continue;\n\n\t\tif (0 == (con->conf.force_lowercase_filenames ?\n\t\t\t\t\tstrncasecmp(uri_ptr, ds->key->ptr, alias_len) :\n\t\t\t\t\tstrncmp(uri_ptr, ds->key->ptr, alias_len))) {\n\t\t\t/* matched */\n\n\t\t\tbuffer_copy_buffer(con->physical.basedir, ds->value);\n\t\t\tbuffer_copy_buffer(srv->tmp_buf, ds->value);\n\t\t\tbuffer_append_string(srv->tmp_buf, uri_ptr + alias_len);\n\t\t\tbuffer_copy_buffer(con->physical.path, srv->tmp_buf);\n\n\t\t\treturn HANDLER_GO_ON;\n\t\t}\n\t}\n\n\t/* not found */\n\treturn HANDLER_GO_ON;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[928, 985]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[928, 985]]}, "_func_name": "PHYSICALPATH_FUNC", "_file_name": "src/mod_alias.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getCommentsLike(self,commentid):\n sqlText=\"select userid from comment_like where commentid=%s\"\n params=[commentid]\n result=sql.queryDB(self.conn,sqlText,params)\n return result;", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getCommentsLike", "_file_name": "modules/comment.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def also_add(name, also):\n db = db_connect()\n cursor = db.cursor()\n try:\n cursor.execute('''\n INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s)\n ''', (\n name,\n also,\n ))\n db.commit()\n logger.debug('added to isalso name {} with value {}'.format(\n name, also))\n db.close()\n except Exception as e:\n logger.error('Execution failed with error: {}'.format(e))\n raise", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "also_add", "_file_name": "KarmaBoi/dbopts.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def estimate_size(task_id, taken_dirs, taken_files):\n report = AnalysisController.get_report(task_id)\n report = report[\"analysis\"]\n path = report[\"info\"][\"analysis_path\"]\n\n size_total = 0\n\n for directory in taken_dirs:\n destination = \"%s/%s\" % (path, os.path.basename(directory))\n if os.path.isdir(destination):\n size_total += get_directory_size(destination)\n\n for filename in taken_files:\n destination = \"%s/%s\" % (path, os.path.basename(filename))\n if os.path.isfile(destination):\n size_total += os.path.getsize(destination)\n\n # estimate file size after zipping; 60% compression rate typically\n size_estimated = size_total / 6.5\n\n return {\n \"size\": int(size_estimated),\n \"size_human\": filesizeformat(size_estimated)\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "estimate_size", "_file_name": "cuckoo/web/controllers/analysis/export/export.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void Logger::addMessage(const QString &message, const Log::MsgType &type)\n{\n QWriteLocker locker(&lock);\n\n Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };\n m_messages.push_back(temp);\n\n if (m_messages.size() >= MAX_LOG_MESSAGES)\n m_messages.pop_front();\n\n emit newLogMessage(temp);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[109, 199]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[109, 199]]}, "_func_name": "Logger::addMessage", "_file_name": "src/base/logger.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def _get_active_nsp(self, hostname):\n \"\"\"Return the active nsp, if one exists, for the given host.\"\"\"\n result = self.common._cli_run(['showvlun', '-a', '-host', hostname])\n if result:\n # first line is header\n result = result[1:]\n for line in result:\n info = line.split(\",\")\n if info and len(info) > 4:\n return info[4]", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_active_nsp", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['comments'] = self.object.comment_set.all().order_by('-time')\n context['form'] = self.get_form()\n context['md'] = safe_md(self.object.content)\n\n return context", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_context_data", "_file_name": "app/Index/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def fetch_issue(cursor, id):\n \"\"\"\n Fetch an issue by id along with its tags. Returns None if no issue\n with the specified id exists in the database.\n \"\"\"\n cursor.execute(f\"\"\"\n SELECT\n issue.id,\n issue.title,\n issue.description,\n tag.namespace,\n tag.predicate,\n tag.value\n FROM\n issue LEFT JOIN tag\n ON issue.id = tag.issue_id\n WHERE\n issue.id = {id}\n \"\"\")\n\n issue = None\n for row in cursor:\n if issue is None:\n issue = {\n \"id\": row[\"id\"],\n \"title\": row[\"title\"],\n \"description\": row[\"description\"],\n \"tags\": [],\n }\n # If tag exists in row, add to issue.\n if row[\"value\"]:\n issue[\"tags\"].append({\n \"namespace\": row[\"namespace\"],\n \"predicate\": row[\"predicate\"],\n \"value\": row[\"value\"],\n })\n\n return issue", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[166, 190], [457, 485]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[166, 190], [457, 485]]}, "_func_name": "fetch_issue", "_file_name": "server/server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)\n{\n\trdpGlyph* prevGlyph;\n\n\tif (id > 9)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache id: %\" PRIu32 \"\", id);\n\t\treturn FALSE;\n\t}\n\n\tif (index >= glyphCache->glyphCache[id].number)\n\t{\n\t\tWLog_ERR(TAG, \"invalid glyph cache index: %\" PRIu32 \" in cache id: %\" PRIu32 \"\", index, id);\n\t\treturn FALSE;\n\t}\n\n\tWLog_Print(glyphCache->log, WLOG_DEBUG, \"GlyphCachePut: id: %\" PRIu32 \" index: %\" PRIu32 \"\", id,\n\t index);\n\tprevGlyph = glyphCache->glyphCache[id].entries[index];\n\n\tif (prevGlyph)\n\t\tprevGlyph->Free(glyphCache->context, prevGlyph);\n\n\tglyphCache->glyphCache[id].entries[index] = glyph;\n\treturn TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "glyph_cache_put", "_file_name": "libfreerdp/cache/glyph.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def update_title(self, title = None):\n if (not self.title):\n self.title = title\n\n # This will fall to a sql injection \n sql = \"UPDATE jdk_entries SET title = '\" + self.title + \"'\" + \\\n \"WHERE jdk_entries.id = '\" + self.entry_id + \"';\" \n\n db_execute(sql)\n \n self.update_date_modified()\n\n return None", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[132, 261]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[132, 261]]}, "_func_name": "update_title", "_file_name": "entry.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void youngcollection (lua_State *L, global_State *g) {\n GCObject **psurvival; /* to point to first non-dead survival object */\n lua_assert(g->gcstate == GCSpropagate);\n markold(g, g->survival, g->reallyold);\n markold(g, g->finobj, g->finobjrold);\n atomic(L);\n\n /* sweep nursery and get a pointer to its last live element */\n psurvival = sweepgen(L, g, &g->allgc, g->survival);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->reallyold);\n g->reallyold = g->old;\n g->old = *psurvival; /* 'survival' survivals are old now */\n g->survival = g->allgc; /* all news are survivals */\n\n /* repeat for 'finobj' lists */\n psurvival = sweepgen(L, g, &g->finobj, g->finobjsur);\n /* sweep 'survival' and 'old' */\n sweepgen(L, g, psurvival, g->finobjrold);\n g->finobjrold = g->finobjold;\n g->finobjold = *psurvival; /* 'survival' survivals are old now */\n g->finobjsur = g->finobj; /* all news are survivals */\n\n sweepgen(L, g, &g->tobefnz, NULL);\n\n finishgencycle(L, g);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[178, 219]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[178, 219]]}, "_func_name": "youngcollection", "_file_name": "lgc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def getAllComments(self):\n sqlText=\"select comment from comments where userid=%d order by date;\"\n allposts=sql.queryDB(self.conn,sqlText)\n return allposts;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[30, 108]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[30, 108]]}, "_func_name": "getAllComments", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int mpeg4video_probe(AVProbeData *probe_packet)\n{\n uint32_t temp_buffer = -1;\n int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;\n int i;\n\n for (i = 0; i < probe_packet->buf_size; i++) {\n temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];\n if ((temp_buffer & 0xffffff00) != 0x100)\n continue;\n\n if (temp_buffer == VOP_START_CODE)\n VOP++;\n else if (temp_buffer == VISUAL_OBJECT_START_CODE)\n VISO++;\n else if (temp_buffer < 0x120)\n VO++;\n else if (temp_buffer < 0x130)\n VOL++;\n else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&\n !(0x1B9 < temp_buffer && temp_buffer < 0x1C4))\n res++;\n }\n\n if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)\n return AVPROBE_SCORE_EXTENSION;\n return 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[269, 318]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[269, 318]]}, "_func_name": "mpeg4video_probe", "_file_name": "libavformat/m4vdec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp)\n{\n\tsize_t olen;\n\n\tif (!rdp || !rdp->fips_decrypt)\n\t\treturn FALSE;\n\n\tif (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "security_fips_decrypt", "_file_name": "libfreerdp/core/security.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def terminate_connection(self, volume, connector, **kwargs):\n \"\"\"Cleanup after an iSCSI connection has been terminated.\n\n When we clean up a terminated connection between a given connector\n and volume, we:\n 1. Translate the given connector to a host name\n 2. Remove the volume-to-host mapping if it exists\n 3. Delete the host if it has no more mappings (hosts are created\n automatically by this driver when mappings are created)\n \"\"\"\n LOG.debug(_('enter: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})\n\n vol_name = volume['name']\n host_name = self._get_host_from_connector(connector)\n # Verify that _get_host_from_connector returned the host.\n # This should always succeed as we terminate an existing connection.\n self._driver_assert(\n host_name is not None,\n _('_get_host_from_connector failed to return the host name '\n 'for connector'))\n\n # Check if vdisk-host mapping exists, remove if it does\n mapping_data = self._get_hostvdisk_mappings(host_name)\n if vol_name in mapping_data:\n ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \\\n (host_name, vol_name)\n out, err = self._run_ssh(ssh_cmd)\n # Verify CLI behaviour - no output is returned from\n # rmvdiskhostmap\n self._assert_ssh_return(len(out.strip()) == 0,\n 'terminate_connection', ssh_cmd, out, err)\n del mapping_data[vol_name]\n else:\n LOG.error(_('terminate_connection: No mapping of volume '\n '%(vol_name)s to host %(host_name)s found') %\n {'vol_name': vol_name, 'host_name': host_name})\n\n # If this host has no more mappings, delete it\n if not mapping_data:\n self._delete_host(host_name)\n\n LOG.debug(_('leave: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s') % {'vol': str(volume),\n 'conn': str(connector)})", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1277, 1378]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1277, 1378]]}, "_func_name": "terminate_connection", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def add_input(self, data):\n connection = self.connect()\n try:\n # The following introduces a deliberate security flaw. \n # See section on SQL injection below\n query = \"INSERT INTO crimes (description) VALUES(%s);\"\n with connection.cursor() as cursor:\n cursor.execute(query, data)\n connection.commit()\n finally:\n connection.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_input", "_file_name": "dbhelper.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)\n{\n\tbee_t *bee = ic->bee;\n\tbee_user_t *bu = bee_user_by_handle(bee, ic, handle);\n\n\tif (bee->ui->ft_in_start && bu) {\n\t\treturn bee->ui->ft_in_start(bee, bu, file_name, file_size);\n\t} else {\n\t\treturn NULL;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "imcb_file_send_start", "_file_name": "protocols/bee_ft.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet,\n\t\t\t\t char *buf, u_int8_t client_hash) {\n u_int16_t offset = 22, buf_out_len = 0;\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n offset += 4;\n\n /* -1 for ';' */\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n /* ssh.kex_algorithms [C/S] */\n strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len);\n buf[buf_out_len++] = ';';\n offset += len;\n\n /* ssh.server_host_key_algorithms [None] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n offset += 4 + len;\n\n /* ssh.encryption_algorithms_client_to_server [C] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.encryption_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.mac_algorithms_client_to_server [C] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.mac_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n buf[buf_out_len++] = ';';\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.compression_algorithms_client_to_server [C] */\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.compression_algorithms_server_to_client [S] */\n len = ntohl(*(u_int32_t*)&packet->payload[offset]);\n\n if(!client_hash) {\n offset += 4;\n\n if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))\n goto invalid_payload;\n\n strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);\n buf_out_len += len;\n offset += len;\n } else\n offset += 4 + len;\n\n /* ssh.languages_client_to_server [None] */\n\n /* ssh.languages_server_to_client [None] */\n\n#ifdef SSH_DEBUG\n printf(\"[SSH] %s\\n\", buf);\n#endif\n\n return(buf_out_len);\n\ninvalid_payload:\n\n#ifdef SSH_DEBUG\n printf(\"[SSH] Invalid packet payload\\n\");\n#endif\n\n return(0);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[615, 661]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[615, 661]]}, "_func_name": "concat_hash_string", "_file_name": "src/lib/protocols/ssh.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def retrieve_videos_from_playlist(playlist_id, db):\n db.execute(\"SELECT id, title, thumbnail, position from video WHERE playlist_id=%s ORDER BY position ASC;\", (playlist_id,))\n rows = db.fetchall()\n return rows", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "retrieve_videos_from_playlist", "_file_name": "video/video_repository.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent)\n{\n clear();\n m_torrent = torrent;\n downloaded_pieces->setTorrent(m_torrent);\n pieces_availability->setTorrent(m_torrent);\n if (!m_torrent) return;\n\n // Save path\n updateSavePath(m_torrent);\n // Hash\n hash_lbl->setText(m_torrent->hash());\n PropListModel->model()->clear();\n if (m_torrent->hasMetadata()) {\n // Creation date\n lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate));\n\n label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize()));\n\n // Comment\n comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));\n\n // URL seeds\n loadUrlSeeds();\n\n label_created_by_val->setText(m_torrent->creator());\n\n // List files in torrent\n PropListModel->model()->setupModelData(m_torrent->info());\n filesList->setExpanded(PropListModel->index(0, 0), true);\n\n // Load file priorities\n PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities());\n }\n // Load dynamic data\n loadDynamicData();\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[655, 737], [784, 845]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[655, 737], [784, 845]]}, "_func_name": "PropertiesWidget::loadTorrentInfos", "_file_name": "src/gui/properties/propertieswidget.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def test_create_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost',\n 'iqn.1993-08.org.debian:01:222'])\n _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])\n\n _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n self.assertEqual(host['name'], self.FAKE_HOST)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int main(int argc, char *argv[])\n{\n FILE *iplist = NULL;\n plist_t root_node = NULL;\n char *plist_out = NULL;\n uint32_t size = 0;\n int read_size = 0;\n char *plist_entire = NULL;\n struct stat filestats;\n options_t *options = parse_arguments(argc, argv);\n\n if (!options)\n {\n print_usage(argc, argv);\n return 0;\n }\n\n // read input file\n iplist = fopen(options->in_file, \"rb\");\n if (!iplist) {\n free(options);\n return 1;\n }\n\n stat(options->in_file, &filestats);\n\n if (filestats.st_size < 8) {\n printf(\"ERROR: Input file is too small to contain valid plist data.\\n\");\n return -1;\n }\n\n plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));\n read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);\n fclose(iplist);\n\n // convert from binary to xml or vice-versa\n if (memcmp(plist_entire, \"bplist00\", 8) == 0)\n {\n plist_from_bin(plist_entire, read_size, &root_node);\n plist_to_xml(root_node, &plist_out, &size);\n }\n else\n {\n plist_from_xml(plist_entire, read_size, &root_node);\n plist_to_bin(root_node, &plist_out, &size);\n }\n plist_free(root_node);\n free(plist_entire);\n\n if (plist_out)\n {\n if (options->out_file != NULL)\n {\n FILE *oplist = fopen(options->out_file, \"wb\");\n if (!oplist) {\n free(options);\n return 1;\n }\n fwrite(plist_out, size, sizeof(char), oplist);\n fclose(oplist);\n }\n // if no output file specified, write to stdout\n else\n fwrite(plist_out, size, sizeof(char), stdout);\n\n free(plist_out);\n }\n else\n printf(\"ERROR: Failed to convert input file.\\n\");\n\n free(options);\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "main", "_file_name": "tools/plistutil.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "BYTE *DecompressRTF(variableLength *p, int *size) {\n BYTE *dst; // destination for uncompressed bytes\n BYTE *src;\n unsigned int in;\n unsigned int out;\n variableLength comp_Prebuf;\n ULONG compressedSize, uncompressedSize, magic;\n\n comp_Prebuf.size = strlen(RTF_PREBUF);\n comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);\n ALLOCCHECK_CHAR(comp_Prebuf.data);\n memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);\n\n src = p->data;\n in = 0;\n\n if (p->size < 20) {\n printf(\"File too small\\n\");\n return(NULL);\n }\n compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);\n in += 4;\n uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);\n in += 4;\n magic = SwapDWord((BYTE*)src + in, 4);\n in += 4;\n in += 4;\n\n // check size excluding the size field itself\n if (compressedSize != p->size - 4) {\n printf(\" Size Mismatch: %u != %i\\n\", compressedSize, p->size - 4);\n free(comp_Prebuf.data);\n return NULL;\n }\n\n // process the data\n if (magic == 0x414c454d) {\n // magic number that identifies the stream as a uncompressed stream\n dst = calloc(uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, src + 4, uncompressedSize);\n } else if (magic == 0x75465a4c) {\n // magic number that identifies the stream as a compressed stream\n int flagCount = 0;\n int flags = 0;\n // Prevent overflow on 32 Bit Systems\n if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {\n printf(\"Corrupted file\\n\");\n exit(-1);\n }\n dst = calloc(comp_Prebuf.size + uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);\n out = comp_Prebuf.size;\n while (out < (comp_Prebuf.size + uncompressedSize)) {\n // each flag byte flags 8 literals/references, 1 per bit\n flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;\n if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal\n unsigned int offset = src[in++];\n unsigned int length = src[in++];\n unsigned int end;\n offset = (offset << 4) | (length >> 4); // the offset relative to block start\n length = (length & 0xF) + 2; // the number of bytes to copy\n // the decompression buffer is supposed to wrap around back\n // to the beginning when the end is reached. we save the\n // need for such a buffer by pointing straight into the data\n // buffer, and simulating this behaviour by modifying the\n // pointers appropriately.\n offset = (out / 4096) * 4096 + offset;\n if (offset >= out) // take from previous block\n offset -= 4096;\n // note: can't use System.arraycopy, because the referenced\n // bytes can cross through the current out position.\n end = offset + length;\n while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))\n && (offset < (comp_Prebuf.size + uncompressedSize)))\n dst[out++] = dst[offset++];\n } else { // literal\n if ((out >= (comp_Prebuf.size + uncompressedSize)) ||\n (in >= p->size)) {\n printf(\"Corrupted stream\\n\");\n exit(-1);\n }\n dst[out++] = src[in++];\n }\n }\n // copy it back without the prebuffered data\n src = dst;\n dst = calloc(uncompressedSize, 1);\n ALLOCCHECK_CHAR(dst);\n memcpy(dst, src + comp_Prebuf.size, uncompressedSize);\n free(src);\n *size = uncompressedSize;\n free(comp_Prebuf.data);\n return dst;\n } else { // unknown magic number\n printf(\"Unknown compression type (magic number %x)\\n\", magic);\n }\n free(comp_Prebuf.data);\n return NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1641, 1699]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1641, 1699]]}, "_func_name": "DecompressRTF", "_file_name": "lib/ytnef.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)\n{\n\twStream* s;\n\tsize_t length;\n\tNTLM_NEGOTIATE_MESSAGE* message;\n\tmessage = &context->NEGOTIATE_MESSAGE;\n\tZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));\n\ts = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);\n\n\tif (!s)\n\t\treturn SEC_E_INTERNAL_ERROR;\n\n\tif (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->MessageType != MESSAGE_TYPE_NEGOTIATE)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tStream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */\n\n\tif (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&\n\t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tcontext->NegotiateFlags = message->NegotiateFlags;\n\n\t/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\t/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */\n\n\tif (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t{\n\t\tif (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */\n\t\t{\n\t\t\tStream_Free(s, FALSE);\n\t\t\treturn SEC_E_INVALID_TOKEN;\n\t\t}\n\t}\n\n\tlength = Stream_GetPosition(s);\n\tbuffer->cbBuffer = length;\n\n\tif (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INTERNAL_ERROR;\n\t}\n\n\tCopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);\n\tcontext->NegotiateMessage.BufferType = buffer->BufferType;\n#ifdef WITH_DEBUG_NTLM\n\tWLog_DBG(TAG, \"NEGOTIATE_MESSAGE (length = %\" PRIu32 \")\", context->NegotiateMessage.cbBuffer);\n\twinpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,\n\t context->NegotiateMessage.cbBuffer);\n\tntlm_print_negotiate_flags(message->NegotiateFlags);\n\n\tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n\t\tntlm_print_version_info(&(message->Version));\n\n#endif\n\tcontext->state = NTLM_STATE_CHALLENGE;\n\tStream_Free(s, FALSE);\n\treturn SEC_I_CONTINUE_NEEDED;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[592, 672]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[592, 672]]}, "_func_name": "ntlm_read_NegotiateMessage", "_file_name": "winpr/libwinpr/sspi/NTLM/ntlm_message.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_consumption_data_row(self, ts, energy_used, power_used):\n\n if power_used > 0:\n\n query = '''\n INSERT OR IGNORE INTO Consumption (\n TimeStamp,\n EnergyUsed,\n PowerUsed \n ) VALUES (\n ?,\n ?,\n ?\n );\n '''\n self.c.execute(query, (ts, 0, 0))\n\n query = '''\n UPDATE Consumption SET \n EnergyUsed = EnergyUsed + ?,\n PowerUsed = PowerUsed + ?\n WHERE TimeStamp=?;\n '''\n\n self.c.execute(query, (energy_used, power_used, ts))\n\n self.db.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_consumption_data_row", "_file_name": "util/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):\n \"\"\"Create a 3PAR host.\n\n Create a 3PAR host, if there is already a host on the 3par using\n the same iqn but with a different hostname, return the hostname\n used by 3PAR.\n \"\"\"\n cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \\\n (persona_id, domain, hostname, iscsi_iqn)\n out = self.common._cli_run(cmd, None)\n if out and len(out) > 1:\n return self.common.parse_create_host_error(hostname, out)\n return hostname", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[291, 460]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[291, 460]]}, "_func_name": "_create_3par_iscsi_host", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_iscsi.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def clean_cache(self, limit):\n \"\"\"\n Method that remove several User objects from cache - the least \n active users\n :param limit: number of the users that the method should remove\n from cache\n :return: None\n \"\"\"\n\n log.info('Figuring out the least active users...')\n # Select users that the least active recently\n user_ids = tuple(self.users.keys())\n query = ('SELECT chat_id '\n 'FROM photo_queries_table2 '\n f'WHERE chat_id in {user_ids} '\n 'GROUP BY chat_id '\n 'ORDER BY MAX(time) '\n f'LIMIT {limit}')\n\n try:\n cursor = db.execute_query(query)\n except DatabaseConnectionError:\n log.error(\"Can't figure out the least active users...\")\n return\n\n if not cursor.rowcount:\n log.warning(\"There are no users in the db\")\n return\n\n # Make list out of tuple of tuples that is returned by MySQL\n least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]\n log.info('Removing %d least active users from cache...', limit)\n num_deleted_entries = 0\n for entry in least_active_users:\n log.debug('Deleting %s...', entry)\n deleted_entry = self.users.pop(entry, None)\n if deleted_entry:\n num_deleted_entries += 1\n log.debug(\"%d users were removed from cache.\", num_deleted_entries)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[628, 663]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[628, 663]]}, "_func_name": "clean_cache", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_language(lang):\n try:\n cur.execute(f\"INSERT INTO language (name) VALUES ('{lang}')\")\n except Exception as e:\n pass\n cur.execute(f\"SELECT language_id FROM language where name='{lang}'\")\n lang_id = cur.fetchone()[0]\n if conn.commit():\n return lang_id\n return lang_id", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[33, 103], [143, 216]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[33, 103], [143, 216]]}, "_func_name": "add_language", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _execute_command_and_parse_attributes(self, ssh_cmd):\n \"\"\"Execute command on the Storwize/SVC and parse attributes.\n\n Exception is raised if the information from the system\n can not be obtained.\n\n \"\"\"\n\n LOG.debug(_('enter: _execute_command_and_parse_attributes: '\n ' command %s') % ssh_cmd)\n\n try:\n out, err = self._run_ssh(ssh_cmd)\n except exception.ProcessExecutionError as e:\n # Didn't get details from the storage, return None\n LOG.error(_('CLI Exception output:\\n command: %(cmd)s\\n '\n 'stdout: %(out)s\\n stderr: %(err)s') %\n {'cmd': ssh_cmd,\n 'out': e.stdout,\n 'err': e.stderr})\n return None\n\n self._assert_ssh_return(len(out),\n '_execute_command_and_parse_attributes',\n ssh_cmd, out, err)\n attributes = {}\n for attrib_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attrib_name, foo, attrib_value = attrib_line.partition('!')\n if attrib_name is not None and len(attrib_name.strip()):\n attributes[attrib_name] = attrib_value\n\n LOG.debug(_('leave: _execute_command_and_parse_attributes:\\n'\n 'command: %(cmd)s\\n'\n 'attributes: %(attr)s')\n % {'cmd': ssh_cmd,\n 'attr': str(attributes)})\n\n return attributes", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[307, 353], [1465, 1502]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[307, 353], [1465, 1502]]}, "_func_name": "_execute_command_and_parse_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "mark_context_stack(mrb_state *mrb, struct mrb_context *c)\n{\n size_t i;\n size_t e;\n mrb_value nil;\n\n if (c->stack == NULL) return;\n e = c->stack - c->stbase;\n if (c->ci) e += c->ci->nregs;\n if (c->stbase + e > c->stend) e = c->stend - c->stbase;\n for (i=0; istbase[i];\n\n if (!mrb_immediate_p(v)) {\n mrb_gc_mark(mrb, mrb_basic_ptr(v));\n }\n }\n e = c->stend - c->stbase;\n nil = mrb_nil_value();\n for (; istbase[i] = nil;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mark_context_stack", "_file_name": "src/gc.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def extend_volume(self, volume, new_size):\n volume_name = self._get_3par_vol_name(volume['id'])\n old_size = volume.size\n growth_size = int(new_size) - old_size\n LOG.debug(\"Extending Volume %s from %s to %s, by %s GB.\" %\n (volume_name, old_size, new_size, growth_size))\n try:\n self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.error(_(\"Error extending volume %s\") % volume)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "extend_volume", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int rom_copy(uint8_t *dest, hwaddr addr, size_t size)\n{\n hwaddr end = addr + size;\n uint8_t *s, *d = dest;\n size_t l = 0;\n Rom *rom;\n\n QTAILQ_FOREACH(rom, &roms, next) {\n if (rom->fw_file) {\n continue;\n }\n if (rom->mr) {\n continue;\n }\n if (rom->addr + rom->romsize < addr) {\n continue;\n }\n if (rom->addr > end || rom->addr < addr) {\n break;\n }\n\n d = dest + (rom->addr - addr);\n s = rom->data;\n l = rom->datasize;\n\n if ((d + l) > (dest + size)) {\n l = dest - d;\n }\n\n if (l > 0) {\n memcpy(d, s, l);\n }\n\n if (rom->romsize > rom->datasize) {\n /* If datasize is less than romsize, it means that we didn't\n * allocate all the ROM because the trailing data are only zeros.\n */\n\n d += l;\n l = rom->romsize - rom->datasize;\n\n if ((d + l) > (dest + size)) {\n /* Rom size doesn't fit in the destination area. Adjust to avoid\n * overflow.\n */\n l = dest - d;\n }\n\n if (l > 0) {\n memset(d, 0x0, l);\n }\n }\n }\n\n return (d + l) - dest;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rom_copy", "_file_name": "hw/core/loader.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_queryset(self, **kwargs):\n queryset = Article.objects.order_by('-time')\n for i in queryset:\n i.md = markdown(i.content, extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n\n return queryset", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[118, 323]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[118, 323]]}, "_func_name": "get_queryset", "_file_name": "app/Index/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def update_institutions(conn, sqlite, k10plus, ai):\n \"\"\"\n Update the institution table.\n \"\"\"\n current_institutions = get_all_current_institutions(k10plus, ai)\n old_institutions = get_all_old_institutions(conn, sqlite)\n\n # Check if the institution table is allready filled and this is not the first checkup\n institution_table_is_filled = len(old_institutions) > 10\n\n for old_institution in old_institutions:\n if institution_table_is_filled and old_institution not in current_institutions:\n message = \"Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen.\" % old_institution\n send_message(message)\n\n for current_institution in current_institutions:\n if current_institution == \" \" or '\"' in current_institution:\n continue\n if current_institution not in old_institutions:\n message = \"The institution %s is new in Solr.\" % current_institution\n if institution_table_is_filled:\n send_message(message)\n else:\n logging.info(message)\n sql = \"INSERT INTO institution (institution) VALUES (?)\"\n sqlite.execute(sql, (current_institution,))\n conn.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "update_institutions", "_file_name": "bin/solrcheckup.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int b_unpack (lua_State *L) {\n Header h;\n const char *fmt = luaL_checkstring(L, 1);\n size_t ld;\n const char *data = luaL_checklstring(L, 2, &ld);\n size_t pos = luaL_optinteger(L, 3, 1);\n luaL_argcheck(L, pos > 0, 3, \"offset must be 1 or greater\");\n pos--; /* Lua indexes are 1-based, but here we want 0-based for C\n * pointer math. */\n int n = 0; /* number of results */\n defaultoptions(&h);\n while (*fmt) {\n int opt = *fmt++;\n size_t size = optsize(L, opt, &fmt);\n pos += gettoalign(pos, &h, opt, size);\n luaL_argcheck(L, size <= ld && pos <= ld - size,\n 2, \"data string too short\");\n /* stack space for item + next position */\n luaL_checkstack(L, 2, \"too many results\");\n switch (opt) {\n case 'b': case 'B': case 'h': case 'H':\n case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */\n int issigned = islower(opt);\n lua_Number res = getinteger(data+pos, h.endian, issigned, size);\n lua_pushnumber(L, res); n++;\n break;\n }\n case 'x': {\n break;\n }\n case 'f': {\n float f;\n memcpy(&f, data+pos, size);\n correctbytes((char *)&f, sizeof(f), h.endian);\n lua_pushnumber(L, f); n++;\n break;\n }\n case 'd': {\n double d;\n memcpy(&d, data+pos, size);\n correctbytes((char *)&d, sizeof(d), h.endian);\n lua_pushnumber(L, d); n++;\n break;\n }\n case 'c': {\n if (size == 0) {\n if (n == 0 || !lua_isnumber(L, -1))\n luaL_error(L, \"format 'c0' needs a previous size\");\n size = lua_tonumber(L, -1);\n lua_pop(L, 1); n--;\n luaL_argcheck(L, size <= ld && pos <= ld - size,\n 2, \"data string too short\");\n }\n lua_pushlstring(L, data+pos, size); n++;\n break;\n }\n case 's': {\n const char *e = (const char *)memchr(data+pos, '\\0', ld - pos);\n if (e == NULL)\n luaL_error(L, \"unfinished string in data\");\n size = (e - (data+pos)) + 1;\n lua_pushlstring(L, data+pos, size - 1); n++;\n break;\n }\n default: controloptions(L, opt, &fmt, &h);\n }\n pos += size;\n }\n lua_pushinteger(L, pos + 1); /* next position */\n return n + 1;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "b_unpack", "_file_name": "deps/lua/src/lua_struct.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def misc_file_checks(self):\n\n print_header(\"MISC FILE CHECKS\")\n\n #\n # Check for recommended and mandatory files\n #\n\n filenames = (\"manifest.json\", \"LICENSE\", \"README.md\",\n \"scripts/install\", \"scripts/remove\",\n \"scripts/upgrade\",\n \"scripts/backup\", \"scripts/restore\")\n non_mandatory = (\"script/backup\", \"script/restore\")\n\n for filename in filenames:\n if file_exists(self.path + \"/\" + filename):\n continue\n elif filename in non_mandatory:\n print_warning(\"Consider adding a file %s\" % filename)\n else:\n print_error(\"File %s is mandatory\" % filename)\n\n #\n # Deprecated php-fpm.ini thing\n #\n\n if file_exists(self.path + \"/conf/php-fpm.ini\"):\n print_warning(\n \"Using a separate php-fpm.ini file is deprecated. \"\n \"Please merge your php-fpm directives directly in the pool file. \"\n \"(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )\"\n )\n\n #\n # Deprecated usage of 'add_header' in nginx conf\n #\n\n for filename in os.listdir(self.path + \"/conf\"):\n if not os.path.isfile(self.path + \"/conf/\" + filename):\n continue\n content = open(self.path + \"/conf/\" + filename).read()\n if \"location\" in content and \"add_header\" in content:\n print_warning(\n \"Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. \"\n \"(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx \"\n \"and https://github.com/openresty/headers-more-nginx-module#more_set_headers )\"\n )", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1268, 1336]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1268, 1336]]}, "_func_name": "misc_file_checks", "_file_name": "package_linter.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_articles_by_subject(subject):\n with conn.cursor(cursor_factory=DictCursor) as cur:\n query = \"SELECT * FROM articles WHERE subject='\" + subject + \"' ORDER BY last_submitted DESC\"\n cur.execute(query)\n articles = cur.fetchall()\n return articles", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[94, 196]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[94, 196]]}, "_func_name": "get_articles_by_subject", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "matchCurrentInput(\n\t\tconst InString *input, int pos, const widechar *passInstructions, int passIC) {\n\tint k;\n\tint kk = pos;\n\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n\t\tif (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])\n\t\t\treturn 0;\n\treturn 1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[124, 198]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[124, 198]]}, "_func_name": "matchCurrentInput", "_file_name": "liblouis/lou_translateString.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def addTags(tag_list, listing_id):\n \"\"\"\n Adds a list of tags tag_list for a given listing with listing_id to the database\n \"\"\"\n cur = conn.cursor()\n for x in tag_list:\n sql = \"INSERT INTO {} VALUES {}\".format(listing_tags_table_name, str((listing_id, x)))\n cur.execute(sql)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[183, 302]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[183, 302]]}, "_func_name": "addTags", "_file_name": "backend-api/backend-api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const MagickBooleanType separate,ExceptionInfo *exception)\n{\n size_t\n channels,\n packet_size;\n\n unsigned char\n *compact_pixels;\n\n /*\n Write uncompressed pixels as separate planes.\n */\n channels=1;\n packet_size=next_image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) NULL;\n if (next_image->compression == RLECompression)\n {\n compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels*\n next_image->columns,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n if (IsImageGray(next_image) != MagickFalse)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GrayQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GrayQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n if (next_image->storage_class == PseudoClass)\n {\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,IndexQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n IndexQuantum,MagickTrue,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,0,1);\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (next_image->compression == RLECompression)\n {\n /*\n Packbits compression.\n */\n (void) WriteBlobMSBShort(image,1);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,RedQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,GreenQuantum,exception);\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlueQuantum,exception);\n if (next_image->colorspace == CMYKColorspace)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,BlackQuantum,exception);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WritePackbitsLength(psd_info,image_info,image,next_image,\n compact_pixels,AlphaQuantum,exception);\n }\n (void) SetImageProgress(image,SaveImagesTag,0,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n RedQuantum,MagickTrue,exception);\n (void) SetImageProgress(image,SaveImagesTag,1,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n GreenQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,2,6);\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlueQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,3,6);\n if (next_image->colorspace == CMYKColorspace)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n BlackQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,4,6);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,\n AlphaQuantum,separate,exception);\n (void) SetImageProgress(image,SaveImagesTag,5,6);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n }\n if (next_image->compression == RLECompression)\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n return(MagickTrue);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[494, 632]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[494, 632]]}, "_func_name": "WriteImageChannels", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,\n\t\t\t\t struct srpt_recv_ioctx *recv_ioctx,\n\t\t\t\t struct srpt_send_ioctx *send_ioctx)\n{\n\tstruct srp_tsk_mgmt *srp_tsk;\n\tstruct se_cmd *cmd;\n\tstruct se_session *sess = ch->sess;\n\tuint64_t unpacked_lun;\n\tint tcm_tmr;\n\tint rc;\n\n\tBUG_ON(!send_ioctx);\n\n\tsrp_tsk = recv_ioctx->ioctx.buf;\n\tcmd = &send_ioctx->cmd;\n\n\tpr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\"\n\t\t \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func,\n\t\t srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);\n\n\tsrpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);\n\tsend_ioctx->cmd.tag = srp_tsk->tag;\n\ttcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);\n\tunpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,\n\t\t\t\t sizeof(srp_tsk->lun));\n\trc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,\n\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,\n\t\t\t\tTARGET_SCF_ACK_KREF);\n\tif (rc != 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;\n\t\tgoto fail;\n\t}\n\treturn;\nfail:\n\ttransport_send_check_condition_and_sense(cmd, 0, 0); // XXX:\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "srpt_handle_tsk_mgmt", "_file_name": "drivers/infiniband/ulp/srpt/ib_srpt.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def findNPC(race, classe, sex,level):\n\tc, conn = getConnection()\n\tdate = now()\n\t#select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC;\n\tc.execute(\"select image, avg(legit) as l FROM npc WHERE race='\"+race+\"' AND class='\"+classe+\"' AND sex='\"+sex+\"' GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC;\")\n\tconn.commit()\n\tout = c.fetchmany(5)\n\tconn.close()\n\treturn out", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[221, 391]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[221, 391]]}, "_func_name": "findNPC", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _find_host_from_wwpn(self, connector):\n for wwpn in connector['wwpns']:\n ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n # This WWPN is not in use\n continue\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('remote_wwpn' in header and\n 'name' in header,\n '_find_host_from_wwpn',\n ssh_cmd, out, err)\n rmt_wwpn_idx = header.index('remote_wwpn')\n name_idx = header.index('name')\n\n wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)\n\n if wwpn in wwpns:\n # All the wwpns will be the mapping for the same\n # host from this WWPN-based query. Just pick\n # the name from first line.\n hostname = host_lines[0].split('!')[name_idx]\n return hostname\n\n # Didn't find a host\n return None", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[87, 153]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[87, 153]]}, "_func_name": "_find_host_from_wwpn", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def main():\n global word\n print(\"Starting script... press 'ctrl+c' in terminal to turn off\")\n while True:\n if pyperclip.paste() != word and len(pyperclip.paste().split())<5:\n word = pyperclip.paste()\n wordChc=False\n req = requests.get(\"https://api-portal.dictionary.com/dcom/pageData/%s\" % word)\n wordChcURB = False\n reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)\n try: \n data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']\n except TypeError:\n os.system('notify-send \"Cant find that word on dictionary.com!\"')\n wordChc = True\n except KeyError:\n os.system('notify-send \"Cant find that word on dictionary.com!\"')\n wordChc = True\n\n if not wordChc:\n definitions = []\n try:\n for definition in data[:3]:\n definitions.append(cleanhtml(definition['definition']))\n definitions.append(\"------------\")\n os.system('notify-send \"definitions from dictionary.com:\\n{}\"'.format('\\n'.join(definitions)))\n except KeyError:\n os.system('notify-send \"no results in dictionary.com\"')\n try: \n dataURB = json.loads(reqURB.text)['list']\n except TypeError:\n os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n wordChcURB = True\n except KeyError:\n os.system('notify-send \"Cant find that word on urbandictionary.com!\"' % word)\n wordChcURB = True\n\n if not wordChcURB: \n definitionsURB = []\n for definition in dataURB[:3]:\n definitionsURB.append(definition['definition'])\n definitionsURB.append(\"------------\")\n os.system('notify-send \"definitions from urbandictionary.com:\\n{}\"'.format('\\n'.join(definitionsURB)))\n os.system('notify-send \"Thank you for using define.py made by kelj0\"')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "main", "_file_name": "SmallProjects/Define/define.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap,\n const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight,\n UINT32 bpp, UINT32 length, BOOL compressed,\n UINT32 codecId)\n{\n\tUINT32 SrcSize = length;\n\trdpGdi* gdi = context->gdi;\n\tbitmap->compressed = FALSE;\n\tbitmap->format = gdi->dstFormat;\n\tbitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format);\n\tbitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16);\n\n\tif (!bitmap->data)\n\t\treturn FALSE;\n\n\tif (compressed)\n\t{\n\t\tif (bpp < 32)\n\t\t{\n\t\t\tif (!interleaved_decompress(context->codecs->interleaved,\n\t\t\t pSrcData, SrcSize,\n\t\t\t DstWidth, DstHeight,\n\t\t\t bpp,\n\t\t\t bitmap->data, bitmap->format,\n\t\t\t 0, 0, 0, DstWidth, DstHeight,\n\t\t\t &gdi->palette))\n\t\t\t\treturn FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!planar_decompress(context->codecs->planar, pSrcData, SrcSize,\n\t\t\t DstWidth, DstHeight,\n\t\t\t bitmap->data, bitmap->format, 0, 0, 0,\n\t\t\t DstWidth, DstHeight, TRUE))\n\t\t\t\treturn FALSE;\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst UINT32 SrcFormat = gdi_get_pixel_format(bpp);\n\t\tconst size_t sbpp = GetBytesPerPixel(SrcFormat);\n\t\tconst size_t dbpp = GetBytesPerPixel(bitmap->format);\n\n\t\tif ((sbpp == 0) || (dbpp == 0))\n\t\t\treturn FALSE;\n\t\telse\n\t\t{\n\t\t\tconst size_t dstSize = SrcSize * dbpp / sbpp;\n\n\t\t\tif (dstSize < bitmap->length)\n\t\t\t\treturn FALSE;\n\t\t}\n\n\t\tif (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0,\n\t\t DstWidth, DstHeight, pSrcData, SrcFormat,\n\t\t 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL))\n\t\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[413, 488]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[413, 488]]}, "_func_name": "gdi_Bitmap_Decompress", "_file_name": "libfreerdp/gdi/graphics.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def login(self, username, password):\n select_query = \"\"\"\n SELECT client_id, username, balance, message\n FROM Clients\n WHERE username = '{}' AND password = '{}'\n LIMIT 1\n \"\"\".format(username, password)\n\n cursor = self.__conn.cursor()\n\n cursor.execute(select_query)\n user = cursor.fetchone()\n\n if(user):\n return Client(user[0], user[1], user[2], user[3])\n else:\n return False", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[150, 204], [224, 263]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[150, 204], [224, 263]]}, "_func_name": "login", "_file_name": "Week_9/sql_manager.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void pb_controller::play_file(const std::string& file) {\n\tstd::string cmdline;\n\tstd::string player = cfg->get_configvalue(\"player\");\n\tif (player == \"\")\n\t\treturn;\n\tcmdline.append(player);\n\tcmdline.append(\" '\");\n\tcmdline.append(utils::replace_all(file,\"'\", \"%27\"));\n\tcmdline.append(\"'\");\n\tstfl::reset();\n\tutils::run_interactively(cmdline, \"pb_controller::play_file\");\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "podbeuter::pb_controller::play_file", "_file_name": "src/pb_controller.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def test_initialize_connection(self):\n self.driver._eql_execute = self.mox.\\\n CreateMock(self.driver._eql_execute)\n volume = {'name': self.volume_name}\n self.stubs.Set(self.driver, \"_get_iscsi_properties\",\n self._fake_get_iscsi_properties)\n self.driver._eql_execute('volume', 'select', volume['name'], 'access',\n 'create', 'initiator',\n self.connector['initiator'],\n 'authmethod chap',\n 'username',\n self.configuration.eqlx_chap_login)\n self.mox.ReplayAll()\n iscsi_properties = self.driver.initialize_connection(volume,\n self.connector)\n self.assertEqual(iscsi_properties['data'],\n self._fake_get_iscsi_properties(volume))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[495, 547]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[495, 547]]}, "_func_name": "test_initialize_connection", "_file_name": "cinder/tests/test_eqlx.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)\n{\n\tstruct drm_vc4_submit_cl *args = exec->args;\n\tvoid *temp = NULL;\n\tvoid *bin;\n\tint ret = 0;\n\tuint32_t bin_offset = 0;\n\tuint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,\n\t\t\t\t\t 16);\n\tuint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;\n\tuint32_t exec_size = uniforms_offset + args->uniforms_size;\n\tuint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *\n\t\t\t\t\t args->shader_rec_count);\n\tstruct vc4_bo *bo;\n\n\tif (uniforms_offset < shader_rec_offset ||\n\t exec_size < uniforms_offset ||\n\t args->shader_rec_count >= (UINT_MAX /\n\t\t\t\t\t sizeof(struct vc4_shader_state)) ||\n\t temp_size < exec_size) {\n\t\tDRM_ERROR(\"overflow in exec arguments\\n\");\n\t\tgoto fail;\n\t}\n\n\t/* Allocate space where we'll store the copied in user command lists\n\t * and shader records.\n\t *\n\t * We don't just copy directly into the BOs because we need to\n\t * read the contents back for validation, and I think the\n\t * bo->vaddr is uncached access.\n\t */\n\ttemp = drm_malloc_ab(temp_size, 1);\n\tif (!temp) {\n\t\tDRM_ERROR(\"Failed to allocate storage for copying \"\n\t\t\t \"in bin/render CLs.\\n\");\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\tbin = temp + bin_offset;\n\texec->shader_rec_u = temp + shader_rec_offset;\n\texec->uniforms_u = temp + uniforms_offset;\n\texec->shader_state = temp + exec_size;\n\texec->shader_state_size = args->shader_rec_count;\n\n\tif (copy_from_user(bin,\n\t\t\t (void __user *)(uintptr_t)args->bin_cl,\n\t\t\t args->bin_cl_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tif (copy_from_user(exec->shader_rec_u,\n\t\t\t (void __user *)(uintptr_t)args->shader_rec,\n\t\t\t args->shader_rec_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tif (copy_from_user(exec->uniforms_u,\n\t\t\t (void __user *)(uintptr_t)args->uniforms,\n\t\t\t args->uniforms_size)) {\n\t\tret = -EFAULT;\n\t\tgoto fail;\n\t}\n\n\tbo = vc4_bo_create(dev, exec_size, true);\n\tif (IS_ERR(bo)) {\n\t\tDRM_ERROR(\"Couldn't allocate BO for binning\\n\");\n\t\tret = PTR_ERR(bo);\n\t\tgoto fail;\n\t}\n\texec->exec_bo = &bo->base;\n\n\tlist_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,\n\t\t &exec->unref_list);\n\n\texec->ct0ca = exec->exec_bo->paddr + bin_offset;\n\n\texec->bin_u = bin;\n\n\texec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;\n\texec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;\n\texec->shader_rec_size = args->shader_rec_size;\n\n\texec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;\n\texec->uniforms_p = exec->exec_bo->paddr + uniforms_offset;\n\texec->uniforms_size = args->uniforms_size;\n\n\tret = vc4_validate_bin_cl(dev,\n\t\t\t\t exec->exec_bo->vaddr + bin_offset,\n\t\t\t\t bin,\n\t\t\t\t exec);\n\tif (ret)\n\t\tgoto fail;\n\n\tret = vc4_validate_shader_recs(dev, exec);\n\tif (ret)\n\t\tgoto fail;\n\n\t/* Block waiting on any previous rendering into the CS's VBO,\n\t * IB, or textures, so that pixels are actually written by the\n\t * time we try to read them.\n\t */\n\tret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true);\n\nfail:\n\tdrm_free_large(temp);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[523, 567]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[523, 567]]}, "_func_name": "vc4_get_bcl", "_file_name": "drivers/gpu/drm/vc4/vc4_gem.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)\n{\n\tint r;\n\n\tstatic const char resp[] =\n\t\t\"\"\n\t\t\"%d\"\n\t\t\"\";\n\n\tchar body[512];\n\tint bodylen;\n\tstruct NameValueParserData data;\n\tchar * int_ip, * int_port, * rem_host, * rem_port, * protocol;\n\tint opt=0;\n\t/*int proto=0;*/\n\tunsigned short iport, rport;\n\n\tif (GETFLAG(IPV6FCFWDISABLEDMASK))\n\t{\n\t\tSoapError(h, 702, \"FirewallDisabled\");\n\t\treturn;\n\t}\n\n\tParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);\n\tint_ip = GetValueFromNameValueList(&data, \"InternalClient\");\n\tint_port = GetValueFromNameValueList(&data, \"InternalPort\");\n\trem_host = GetValueFromNameValueList(&data, \"RemoteHost\");\n\trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n\tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n\n\tif (!int_port || !ext_port || !protocol)\n\t{\n\t\tClearNameValueList(&data);\n\t\tSoapError(h, 402, \"Invalid Args\");\n\t\treturn;\n\t}\n\n\trport = (unsigned short)atoi(rem_port);\n\tiport = (unsigned short)atoi(int_port);\n\t/*proto = atoi(protocol);*/\n\n\tsyslog(LOG_INFO, \"%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s\", action, int_ip, iport,rem_host, rport, protocol);\n\n\t/* TODO */\n\tr = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/\n\n\tswitch(r)\n\t{\n\t\tcase 1:\t/* success */\n\t\t\tbodylen = snprintf(body, sizeof(body), resp,\n\t\t\t action, ns/*\"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1\"*/,\n\t\t\t opt, action);\n\t\t\tBuildSendAndCloseSoapResp(h, body, bodylen);\n\t\t\tbreak;\n\t\tcase -5:\t/* Protocol not supported */\n\t\t\tSoapError(h, 705, \"ProtocolNotSupported\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSoapError(h, 501, \"ActionFailed\");\n\t}\n\tClearNameValueList(&data);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "GetOutboundPinholeTimeout", "_file_name": "miniupnpd/upnpsoap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);\n unsigned numEntries = darray_size(append->keysym_list.syms);\n\n darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, numEntries);\n darray_concat(expr->keysym_list.syms, append->keysym_list.syms);\n\n FreeStmt((ParseCommon *) append);\n\n return expr;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ExprAppendMultiKeysymList", "_file_name": "src/xkbcomp/ast-build.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)\n{\n\tstruct grid_cell\t*gc = &ictx->cell.cell;\n\tchar\t\t\t*s = ictx->param_list[i].str, *copy, *ptr, *out;\n\tint\t\t\t p[8];\n\tu_int\t\t\t n;\n\tconst char\t\t*errstr;\n\n\tfor (n = 0; n < nitems(p); n++)\n\t\tp[n] = -1;\n\tn = 0;\n\n\tptr = copy = xstrdup(s);\n\twhile ((out = strsep(&ptr, \":\")) != NULL) {\n\t\tif (*out != '\\0') {\n\t\t\tp[n++] = strtonum(out, 0, INT_MAX, &errstr);\n\t\t\tif (errstr != NULL || n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tn++;\n\t\t\tif (n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tlog_debug(\"%s: %u = %d\", __func__, n - 1, p[n - 1]);\n\t}\n\tfree(copy);\n\n\tif (n == 0)\n\t\treturn;\n\tif (p[0] == 4) {\n\t\tif (n != 2)\n\t\t\treturn;\n\t\tswitch (p[1]) {\n\t\tcase 0:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_2;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_3;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_4;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tgc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;\n\t\t\tgc->attr |= GRID_ATTR_UNDERSCORE_5;\n\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t}\n\tif (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))\n\t\treturn;\n\tswitch (p[1]) {\n\tcase 2:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tif (n == 5)\n\t\t\ti = 2;\n\t\telse\n\t\t\ti = 3;\n\t\tif (n < i + 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],\n\t\t p[i + 2]);\n\t\tbreak;\n\tcase 5:\n\t\tif (n < 3)\n\t\t\tbreak;\n\t\tinput_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);\n\t\tbreak;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "input_csi_dispatch_sgr_colon", "_file_name": "input.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def process_ranks(self, scene, urls, recent_date):\n PLAYER1 = 0\n PLAYER2 = 1\n WINNER = 2\n DATE = 3\n SCENE = 4\n\n # make sure if we already have calculated ranks for these players at this time, we do not do it again\n sql = \"SELECT * FROM ranks WHERE scene = '{scene}' AND date='{date}';\"\n args = {'scene': scene, 'date': recent_date}\n res = self.db.exec(sql, args)\n if len(res) > 0:\n LOG.info('We have already calculated ranks for {} on date {}. SKipping'.format(scene, recent_date))\n return\n\n matches = bracket_utils.get_matches_from_urls(self.db, urls)\n LOG.info('About to start processing ranks for scene {} on {}'.format(scene, recent_date))\n\n # Iterate through each match, and build up our dict\n win_loss_dict = {}\n for match in matches:\n p1 = match[PLAYER1]\n p2 = match[PLAYER2]\n winner = match[WINNER]\n date = match[DATE]\n\n #Add p1 to the dict\n if p1 not in win_loss_dict:\n win_loss_dict[p1] = {}\n\n if p2 not in win_loss_dict[p1]:\n win_loss_dict[p1][p2] = []\n\n # Add an entry to represent this match to p1\n win_loss_dict[p1][p2].append((date, winner == p1))\n\n # add p2 to the dict\n if p2 not in win_loss_dict:\n win_loss_dict[p2] = {}\n\n if p1 not in win_loss_dict[p2]:\n win_loss_dict[p2][p1] = []\n\n win_loss_dict[p2][p1].append((date, winner == p2))\n\n ranks = get_ranks(win_loss_dict)\n\n tag_rank_map = {}\n for i, x in enumerate(ranks):\n points, player = x\n rank = len(ranks) - i\n\n sql = \"INSERT INTO ranks (scene, player, rank, points, date) VALUES ('{scene}', '{player}', '{rank}', '{points}', '{recent_date}');\"\n args = {'scene': scene, 'player': player, 'rank': rank, 'points': points, 'recent_date': recent_date}\n self.db.exec(sql, args)\n\n # Only count this player if this is the scene he/she belongs to\n sql = \"SELECT scene FROM players WHERE tag='{player}';\"\n args = {'player': player}\n res = self.db.exec(sql, args)\n\n if len(res) == 0 or res[0][0] == scene:\n # Also create a list to update the player web\n map = {'rank':rank, 'total_ranked':len(ranks)}\n tag_rank_map[player] = map\n\n player_web.update_ranks(tag_rank_map)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "process_ranks", "_file_name": "process_data.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_roster(self, server_id):\n sql = \"\"\"SELECT username, role\n FROM roles\n WHERE roles.server_id = {0};\n \"\"\".format(server_id)\n self.cur.execute(sql)\n return self.cur.fetchall()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[76, 189]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[76, 189]]}, "_func_name": "get_roster", "_file_name": "db/dbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def init_user(username, chat_id):\n conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\users\\\\\" + username + '.db')\n conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\\\cf.db')\n cursor = conn.cursor()\n cursor2 = conn2.cursor()\n cursor.execute(\"CREATE TABLE result (problem INTEGER, diff STRING, verdict STRING)\")\n cursor2.execute(\"SELECT * FROM problems\")\n x = cursor2.fetchone()\n while x != None:\n cursor.execute(\"insert into result values (?, ?, ? )\", (x[0], x[1], \"NULL\"))\n x = cursor2.fetchone()\n\n url = 'http://codeforces.com/submissions/' + username\n r = requests.get(url)\n max_page = 1\n soup = BeautifulSoup(r.text, \"lxml\")\n\n for link in soup.find_all(attrs={\"class\": \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[4]))\n\n old = \"\"\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')\n soup = BeautifulSoup(r.text, \"lxml\")\n last_try = soup.find(attrs={\"class\":\"status-small\"})\n if not last_try == None:\n last_try = str(last_try).split()\n last_try = str(last_try[2]) + str(last_try[3])\n\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n count = 0\n ver = soup.find_all(attrs={\"class\": \"submissionVerdictWrapper\"})\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5:\n s2 = str(ver[count]).split()\n s2 = s2[5].split('\\\"')\n count += 1\n cursor.execute(\"select * from result where problem = '\" + s[3] + \"'and diff = '\" + s[4] + \"'\")\n x = cursor.fetchone()\n if s2[1] == 'OK' and x != None:\n cursor.execute(\"update result set verdict = '\" + s2[1] + \"' where problem = '\" + s[3] + \"' and diff = '\" + s[4] + \"'\")\n if x != None and x[2] != 'OK':\n cursor.execute(\"update result set verdict = '\" + s2[1] +\"' where problem = '\" + s[3] + \"' and diff = '\" + s[4] + \"'\")\n\n conn.commit()\n conn.close()\n conn2.close()\n\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from last_update_problemset\")\n last_problem = conn.fetchone()\n conn.execute(\"select * from users where chat_id = '\" + str(chat_id) + \"'\")\n x = conn.fetchone()\n if x == None:\n conn.execute(\"insert into users values (?, ?, ?, ?, ?)\", (chat_id, username, str(last_try), str(last_problem[0]), 1))\n else:\n conn.execute(\"update users set username = '\" + str(username) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n conn.execute(\"update users set last_update = '\" + str(last_try) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n conn.execute(\"update users set last_problem = '\" + str(last_problem[0]) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n conn.execute(\"update users set state = '\" + str(1) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n settings.commit()\n settings.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[893, 907], [1799, 1914], [2008, 2151], [2202, 2344], [2398, 2399], [2613, 2692], [2870, 3334]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[893, 907], [1799, 1914], [2008, 2151], [2202, 2344], [2398, 2399], [2613, 2692], [2870, 3334]]}, "_func_name": "init_user", "_file_name": "bases/createuserbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "mrb_obj_clone(mrb_state *mrb, mrb_value self)\n{\n struct RObject *p;\n mrb_value clone;\n\n if (mrb_immediate_p(self)) {\n mrb_raisef(mrb, E_TYPE_ERROR, \"can't clone %S\", self);\n }\n if (mrb_type(self) == MRB_TT_SCLASS) {\n mrb_raise(mrb, E_TYPE_ERROR, \"can't clone singleton class\");\n }\n p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));\n p->c = mrb_singleton_class_clone(mrb, self);\n mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);\n clone = mrb_obj_value(p);\n init_copy(mrb, clone, self);\n p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;\n\n return clone;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mrb_obj_clone", "_file_name": "src/kernel.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "daemon_AuthUserPwd(char *username, char *password, char *errbuf)\n{\n#ifdef _WIN32\n\t/*\n\t * Warning: the user which launches the process must have the\n\t * SE_TCB_NAME right.\n\t * This corresponds to have the \"Act as part of the Operating System\"\n\t * turned on (administrative tools, local security settings, local\n\t * policies, user right assignment)\n\t * However, it seems to me that if you run it as a service, this\n\t * right should be provided by default.\n\t *\n\t * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,\n\t * which merely indicates that the user name or password is\n\t * incorrect, not whether it's the user name or the password\n\t * that's incorrect, so a client that's trying to brute-force\n\t * accounts doesn't know whether it's the user name or the\n\t * password that's incorrect, so it doesn't know whether to\n\t * stop trying to log in with a given user name and move on\n\t * to another user name.\n\t */\n\tHANDLE Token;\n\tif (LogonUser(username, \".\", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"LogonUser() failed\");\n\t\treturn -1;\n\t}\n\n\t// This call should change the current thread to the selected user.\n\t// I didn't test it.\n\tif (ImpersonateLoggedOnUser(Token) == 0)\n\t{\n\t\tpcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,\n\t\t GetLastError(), \"ImpersonateLoggedOnUser() failed\");\n\t\tCloseHandle(Token);\n\t\treturn -1;\n\t}\n\n\tCloseHandle(Token);\n\treturn 0;\n\n#else\n\t/*\n\t * See\n\t *\n\t *\thttp://www.unixpapa.com/incnote/passwd.html\n\t *\n\t * We use the Solaris/Linux shadow password authentication if\n\t * we have getspnam(), otherwise we just do traditional\n\t * authentication, which, on some platforms, might work, even\n\t * with shadow passwords, if we're running as root. Traditional\n\t * authenticaion won't work if we're not running as root, as\n\t * I think these days all UN*Xes either won't return the password\n\t * at all with getpwnam() or will only do so if you're root.\n\t *\n\t * XXX - perhaps what we *should* be using is PAM, if we have\n\t * it. That might hide all the details of username/password\n\t * authentication, whether it's done with a visible-to-root-\n\t * only password database or some other authentication mechanism,\n\t * behind its API.\n\t */\n\tstruct passwd *user;\n\tchar *user_password;\n#ifdef HAVE_GETSPNAM\n\tstruct spwd *usersp;\n#endif\n\n\t// This call is needed to get the uid\n\tif ((user = getpwnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n#ifdef HAVE_GETSPNAM\n\t// This call is needed to get the password; otherwise 'x' is returned\n\tif ((usersp = getspnam(username)) == NULL)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\tuser_password = usersp->sp_pwdp;\n#else\n\t/*\n\t * XXX - what about other platforms?\n\t * The unixpapa.com page claims this Just Works on *BSD if you're\n\t * running as root - it's from 2000, so it doesn't indicate whether\n\t * macOS (which didn't come out until 2001, under the name Mac OS\n\t * X) behaves like the *BSDs or not, and might also work on AIX.\n\t * HP-UX does something else.\n\t *\n\t * Again, hopefully PAM hides all that.\n\t */\n\tuser_password = user->pw_passwd;\n#endif\n\n\tif (strcmp(user_password, (char *) crypt(password, user_password)) != 0)\n\t{\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed: user name or password incorrect\");\n\t\treturn -1;\n\t}\n\n\tif (setuid(user->pw_uid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setuid\");\n\t\treturn -1;\n\t}\n\n/*\tif (setgid(user->pw_gid))\n\t{\n\t\tpcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,\n\t\t errno, \"setgid\");\n\t\treturn -1;\n\t}\n*/\n\treturn 0;\n\n#endif\n\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[3317, 3391]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3317, 3391]]}, "_func_name": "daemon_AuthUserPwd", "_file_name": "rpcapd/daemon.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def verify(self, data):\n credentials = self._formatCredentials(data, name='current')\n command = '{} rclone lsjson current:'.format(credentials)\n\n try:\n result = self._execute(command)\n return {\n 'result': True,\n 'message': 'Success',\n }\n except subprocess.CalledProcessError as e:\n returncode = e.returncode\n return {\n 'result': False,\n 'message': 'Exit status {}'.format(returncode),\n }", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[96, 162]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[96, 162]]}, "_func_name": "verify", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "char *compose_path(ctrl_t *ctrl, char *path)\n{\n\tstruct stat st;\n\tstatic char rpath[PATH_MAX];\n\tchar *name, *ptr;\n\tchar dir[PATH_MAX] = { 0 };\n\n\tstrlcpy(dir, ctrl->cwd, sizeof(dir));\n\tDBG(\"Compose path from cwd: %s, arg: %s\", ctrl->cwd, path ?: \"\");\n\tif (!path || !strlen(path))\n\t\tgoto check;\n\n\tif (path) {\n\t\tif (path[0] != '/') {\n\t\t\tif (dir[strlen(dir) - 1] != '/')\n\t\t\t\tstrlcat(dir, \"/\", sizeof(dir));\n\t\t}\n\t\tstrlcat(dir, path, sizeof(dir));\n\t}\n\ncheck:\n\twhile ((ptr = strstr(dir, \"//\")))\n\t\tmemmove(ptr, &ptr[1], strlen(&ptr[1]) + 1);\n\n\tif (!chrooted) {\n\t\tsize_t len = strlen(home);\n\n\t\tDBG(\"Server path from CWD: %s\", dir);\n\t\tif (len > 0 && home[len - 1] == '/')\n\t\t\tlen--;\n\t\tmemmove(dir + len, dir, strlen(dir) + 1);\n\t\tmemcpy(dir, home, len);\n\t\tDBG(\"Resulting non-chroot path: %s\", dir);\n\t}\n\n\t/*\n\t * Handle directories slightly differently, since dirname() on a\n\t * directory returns the parent directory. So, just squash ..\n\t */\n\tif (!stat(dir, &st) && S_ISDIR(st.st_mode)) {\n\t\tif (!realpath(dir, rpath))\n\t\t\treturn NULL;\n\t} else {\n\t\t/*\n\t\t * Check realpath() of directory containing the file, a\n\t\t * STOR may want to save a new file. Then append the\n\t\t * file and return it.\n\t\t */\n\t\tname = basename(path);\n\t\tptr = dirname(dir);\n\n\t\tmemset(rpath, 0, sizeof(rpath));\n\t\tif (!realpath(ptr, rpath)) {\n\t\t\tINFO(\"Failed realpath(%s): %m\", ptr);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (rpath[1] != 0)\n\t\t\tstrlcat(rpath, \"/\", sizeof(rpath));\n\t\tstrlcat(rpath, name, sizeof(rpath));\n\t}\n\n\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n\t\tDBG(\"Failed non-chroot dir:%s vs home:%s\", dir, home);\n\t\treturn NULL;\n\t}\n\n\treturn rpath;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1460, 1514]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1460, 1514]]}, "_func_name": "compose_path", "_file_name": "src/common.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg,\n\tvoid *buf, int peekonly)\n{\n\tstruct tmComResBusInfo *bus = &dev->bus;\n\tu32 bytes_to_read, write_distance, curr_grp, curr_gwp,\n\t\tnew_grp, buf_size, space_rem;\n\tstruct tmComResInfo msg_tmp;\n\tint ret = SAA_ERR_BAD_PARAMETER;\n\n\tsaa7164_bus_verify(dev);\n\n\tif (msg == NULL)\n\t\treturn ret;\n\n\tif (msg->size > dev->bus.m_wMaxReqSize) {\n\t\tprintk(KERN_ERR \"%s() Exceeded dev->bus.m_wMaxReqSize\\n\",\n\t\t\t__func__);\n\t\treturn ret;\n\t}\n\n\tif ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) {\n\t\tprintk(KERN_ERR\n\t\t\t\"%s() Missing msg buf, size should be %d bytes\\n\",\n\t\t\t__func__, msg->size);\n\t\treturn ret;\n\t}\n\n\tmutex_lock(&bus->lock);\n\n\t/* Peek the bus to see if a msg exists, if it's not what we're expecting\n\t * then return cleanly else read the message from the bus.\n\t */\n\tcurr_gwp = saa7164_readl(bus->m_dwGetWritePos);\n\tcurr_grp = saa7164_readl(bus->m_dwGetReadPos);\n\n\tif (curr_gwp == curr_grp) {\n\t\tret = SAA_ERR_EMPTY;\n\t\tgoto out;\n\t}\n\n\tbytes_to_read = sizeof(*msg);\n\n\t/* Calculate write distance to current read position */\n\twrite_distance = 0;\n\tif (curr_gwp >= curr_grp)\n\t\t/* Write doesn't wrap around the ring */\n\t\twrite_distance = curr_gwp - curr_grp;\n\telse\n\t\t/* Write wraps around the ring */\n\t\twrite_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;\n\n\tif (bytes_to_read > write_distance) {\n\t\tprintk(KERN_ERR \"%s() No message/response found\\n\", __func__);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Calculate the new read position */\n\tnew_grp = curr_grp + bytes_to_read;\n\tif (new_grp > bus->m_dwSizeGetRing) {\n\n\t\t/* Ring wraps */\n\t\tnew_grp -= bus->m_dwSizeGetRing;\n\t\tspace_rem = bus->m_dwSizeGetRing - curr_grp;\n\n\t\tmemcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem);\n\t\tmemcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing,\n\t\t\tbytes_to_read - space_rem);\n\n\t} else {\n\t\t/* No wrapping */\n\t\tmemcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read);\n\t}\n\t/* Convert from little endian to CPU */\n\tmsg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size);\n\tmsg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command);\n\tmsg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector);\n\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n\n\t/* No need to update the read positions, because this was a peek */\n\t/* If the caller specifically want to peek, return */\n\tif (peekonly) {\n\t\tgoto peekout;\n\t}\n\n\t/* Check if the command/response matches what is expected */\n\tif ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) ||\n\t\t(msg_tmp.controlselector != msg->controlselector) ||\n\t\t(msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) {\n\n\t\tprintk(KERN_ERR \"%s() Unexpected msg miss-match\\n\", __func__);\n\t\tsaa7164_bus_dumpmsg(dev, msg, buf);\n\t\tsaa7164_bus_dumpmsg(dev, &msg_tmp, NULL);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Get the actual command and response from the bus */\n\tbuf_size = msg->size;\n\n\tbytes_to_read = sizeof(*msg) + msg->size;\n\t/* Calculate write distance to current read position */\n\twrite_distance = 0;\n\tif (curr_gwp >= curr_grp)\n\t\t/* Write doesn't wrap around the ring */\n\t\twrite_distance = curr_gwp - curr_grp;\n\telse\n\t\t/* Write wraps around the ring */\n\t\twrite_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp;\n\n\tif (bytes_to_read > write_distance) {\n\t\tprintk(KERN_ERR \"%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\\n\",\n\t\t __func__);\n\t\tret = SAA_ERR_INVALID_COMMAND;\n\t\tgoto out;\n\t}\n\n\t/* Calculate the new read position */\n\tnew_grp = curr_grp + bytes_to_read;\n\tif (new_grp > bus->m_dwSizeGetRing) {\n\n\t\t/* Ring wraps */\n\t\tnew_grp -= bus->m_dwSizeGetRing;\n\t\tspace_rem = bus->m_dwSizeGetRing - curr_grp;\n\n\t\tif (space_rem < sizeof(*msg)) {\n\t\t\tif (buf)\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) -\n\t\t\t\t\tspace_rem, buf_size);\n\n\t\t} else if (space_rem == sizeof(*msg)) {\n\t\t\tif (buf)\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing, buf_size);\n\t\t} else {\n\t\t\t/* Additional data wraps around the ring */\n\t\t\tif (buf) {\n\t\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + curr_grp +\n\t\t\t\t\tsizeof(*msg), space_rem - sizeof(*msg));\n\t\t\t\tmemcpy_fromio(buf + space_rem - sizeof(*msg),\n\t\t\t\t\tbus->m_pdwGetRing, bytes_to_read -\n\t\t\t\t\tspace_rem);\n\t\t\t}\n\n\t\t}\n\n\t} else {\n\t\t/* No wrapping */\n\t\tif (buf)\n\t\t\tmemcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg),\n\t\t\t\tbuf_size);\n\t}\n\n\t/* Update the read positions, adjusting the ring */\n\tsaa7164_writel(bus->m_dwGetReadPos, new_grp);\n\npeekout:\n\tret = SAA_OK;\nout:\n\tmutex_unlock(&bus->lock);\n\tsaa7164_bus_verify(dev);\n\treturn ret;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "saa7164_bus_get", "_file_name": "drivers/media/pci/saa7164/saa7164-bus.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,\n\t\t\tstruct rq_map_data *map_data,\n\t\t\tconst struct iov_iter *iter, gfp_t gfp_mask)\n{\n\tbool copy = false;\n\tunsigned long align = q->dma_pad_mask | queue_dma_alignment(q);\n\tstruct bio *bio = NULL;\n\tstruct iov_iter i;\n\tint ret;\n\n\tif (!iter_is_iovec(iter))\n\t\tgoto fail;\n\n\tif (map_data)\n\t\tcopy = true;\n\telse if (iov_iter_alignment(iter) & align)\n\t\tcopy = true;\n\telse if (queue_virt_boundary(q))\n\t\tcopy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);\n\n\ti = *iter;\n\tdo {\n\t\tret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);\n\t\tif (ret)\n\t\t\tgoto unmap_rq;\n\t\tif (!bio)\n\t\t\tbio = rq->bio;\n\t} while (iov_iter_count(&i));\n\n\tif (!bio_flagged(bio, BIO_USER_MAPPED))\n\t\trq->cmd_flags |= REQ_COPY_USER;\n\treturn 0;\n\nunmap_rq:\n\t__blk_rq_unmap_user(bio);\nfail:\n\trq->bio = NULL;\n\treturn -EINVAL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "blk_rq_map_user_iov", "_file_name": "block/blk-map.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_workflow(request):\n workflow_id = request.GET.get('workflow')\n \n if workflow_id:\n wid = {}\n if workflow_id.isdigit():\n wid['id'] = workflow_id\n else:\n wid['uuid'] = workflow_id\n doc = Document2.objects.get(type='oozie-workflow2', **wid)\n workflow = Workflow(document=doc)\n else:\n doc = None\n workflow = Workflow()\n workflow.set_workspace(request.user)\n workflow.check_workspace(request.fs, request.user)\n \n workflow_data = workflow.get_data()\n\n api = get_oozie(request.user)\n credentials = Credentials()\n \n try: \n credentials.fetch(api)\n except Exception, e:\n LOG.error(smart_str(e))\n\n return render('editor/workflow_editor.mako', request, {\n 'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML),\n 'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML),\n 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))\n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit_workflow", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def followFriends(self,userid,friendid):\n sqlText=\"insert into friends values(%d,%d);\"%(friendid,userid)\n result=sql.insertDB(self.conn,sqlText)\n return result;", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[45, 116]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[45, 116]]}, "_func_name": "followFriends", "_file_name": "modules/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def action_save_user(request: HttpRequest, default_forward_url: str = \"/admin/users\"):\n \"\"\"\n This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse\n :param request: the HttpRequest\n :param default_forward_url: The URL to forward to if nothing was specified\n :return: The crafted HttpResponse\n \"\"\"\n forward_url = default_forward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n if not request.user.is_authenticated:\n return HttpResponseForbidden()\n profile = Profile.objects.get(authuser=request.user)\n if profile.rights < 2:\n return HttpResponseForbidden()\n try:\n if request.GET.get(\"user_id\"):\n pid = int(request.GET[\"user_id\"])\n displayname = str(request.POST[\"display_name\"])\n dect = int(request.POST[\"dect\"])\n notes = str(request.POST[\"notes\"])\n pw1 = str(request.POST[\"password\"])\n pw2 = str(request.POST[\"confirm_password\"])\n mail = str(request.POST[\"email\"])\n rights = int(request.POST[\"rights\"])\n user: Profile = Profile.objects.get(pk=pid)\n user.displayName = escape(displayname)\n user.dect = dect\n user.notes = escape(notes)\n user.rights = rights\n user.number_of_allowed_reservations = int(request.POST[\"allowed_reservations\"])\n if request.POST.get(\"active\"):\n user.active = magic.parse_bool(request.POST[\"active\"])\n au: User = user.authuser\n if check_password_conformity(pw1, pw2):\n logging.log(logging.INFO, \"Set password for user: \" + user.displayName)\n au.set_password(pw1)\n else:\n logging.log(logging.INFO, \"Failed to set password for: \" + user.displayName)\n au.email = escape(mail)\n au.save()\n user.save()\n else:\n # assume new user\n username = str(request.POST[\"username\"])\n displayname = str(request.POST[\"display_name\"])\n dect = int(request.POST[\"dect\"])\n notes = str(request.POST[\"notes\"])\n pw1 = str(request.POST[\"password\"])\n pw2 = str(request.POST[\"confirm_password\"])\n mail = str(request.POST[\"email\"])\n rights = int(request.POST[\"rights\"])\n if not check_password_conformity(pw1, pw2):\n recreate_form('password mismatch')\n auth_user: User = User.objects.create_user(username=escape(username), email=escape(mail), password=pw1)\n auth_user.save()\n user: Profile = Profile()\n user.rights = rights\n user.number_of_allowed_reservations = int(request.POST[\"allowed_reservations\"])\n user.displayName = escape(displayname)\n user.authuser = auth_user\n user.dect = dect\n user.notes = escape(notes)\n user.active = True\n user.save()\n pass\n pass\n except Exception as e:\n return HttpResponseBadRequest(str(e))\n return redirect(forward_url)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "action_save_user", "_file_name": "c3shop/frontpage/management/edit_user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void rds_tcp_kill_sock(struct net *net)\n{\n\tstruct rds_tcp_connection *tc, *_tc;\n\tstruct sock *sk;\n\tLIST_HEAD(tmp_list);\n\tstruct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);\n\n\trds_tcp_listen_stop(rtn->rds_tcp_listen_sock);\n\trtn->rds_tcp_listen_sock = NULL;\n\tflush_work(&rtn->rds_tcp_accept_w);\n\tspin_lock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {\n\t\tstruct net *c_net = read_pnet(&tc->conn->c_net);\n\n\t\tif (net != c_net)\n\t\t\tcontinue;\n\t\tlist_move_tail(&tc->t_tcp_node, &tmp_list);\n\t}\n\tspin_unlock_irq(&rds_tcp_conn_lock);\n\tlist_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node) {\n\t\tif (tc->t_sock) {\n\t\t\tsk = tc->t_sock->sk;\n\t\t\tsk->sk_prot->disconnect(sk, 0);\n\t\t\ttcp_done(sk);\n\t\t}\n\t\tif (tc->conn->c_passive)\n\t\t\trds_conn_destroy(tc->conn->c_passive);\n\t\trds_conn_destroy(tc->conn);\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "rds_tcp_kill_sock", "_file_name": "net/rds/tcp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) \n{\n\tVipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );\n\tGifFileType *file = gif->file;\n\tColorMapObject *map = file->Image.ColorMap ?\n\t\tfile->Image.ColorMap : file->SColorMap;\n\n\tGifByteType *extension;\n\n\tif( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {\n\t\tvips_foreign_load_gif_error( gif ); \n\t\treturn( -1 );\n\t}\n\n\t/* Check that the frame looks sane. Perhaps giflib checks\n\t * this for us.\n\t */\n\tif( file->Image.Left < 0 ||\n\t\tfile->Image.Width < 1 ||\n\t\tfile->Image.Width > 10000 ||\n\t\tfile->Image.Left + file->Image.Width > file->SWidth ||\n\t\tfile->Image.Top < 0 ||\n\t\tfile->Image.Height < 1 ||\n\t\tfile->Image.Height > 10000 ||\n\t\tfile->Image.Top + file->Image.Height > file->SHeight ) {\n\t\tvips_error( class->nickname, \"%s\", _( \"bad frame size\" ) ); \n\t\treturn( -1 ); \n\t}\n\n\t/* Test for a non-greyscale colourmap for this frame.\n\t */\n\tif( !gif->has_colour &&\n\t\tmap ) {\n\t\tint i;\n\n\t\tfor( i = 0; i < map->ColorCount; i++ ) \n\t\t\tif( map->Colors[i].Red != map->Colors[i].Green ||\n\t\t\t\tmap->Colors[i].Green != map->Colors[i].Blue ) {\n\t\t\t\tgif->has_colour = TRUE;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t/* Step over compressed image data.\n\t */\n\tdo {\n\t\tif( vips_foreign_load_gif_code_next( gif, &extension ) ) \n\t\t\treturn( -1 );\n\t} while( extension != NULL );\n\n\treturn( 0 );\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[151, 239]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[151, 239]]}, "_func_name": "vips_foreign_load_gif_scan_image", "_file_name": "libvips/foreign/gifload.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static void opj_get_encoding_parameters(const opj_image_t *p_image,\n const opj_cp_t *p_cp,\n OPJ_UINT32 p_tileno,\n OPJ_INT32 * p_tx0,\n OPJ_INT32 * p_tx1,\n OPJ_INT32 * p_ty0,\n OPJ_INT32 * p_ty1,\n OPJ_UINT32 * p_dx_min,\n OPJ_UINT32 * p_dy_min,\n OPJ_UINT32 * p_max_prec,\n OPJ_UINT32 * p_max_res)\n{\n /* loop */\n OPJ_UINT32 compno, resno;\n /* pointers */\n const opj_tcp_t *l_tcp = 00;\n const opj_tccp_t * l_tccp = 00;\n const opj_image_comp_t * l_img_comp = 00;\n\n /* position in x and y of tile */\n OPJ_UINT32 p, q;\n\n /* non-corrected (in regard to image offset) tile offset */\n OPJ_UINT32 l_tx0, l_ty0;\n\n /* preconditions */\n assert(p_cp != 00);\n assert(p_image != 00);\n assert(p_tileno < p_cp->tw * p_cp->th);\n\n /* initializations */\n l_tcp = &p_cp->tcps [p_tileno];\n l_img_comp = p_image->comps;\n l_tccp = l_tcp->tccps;\n\n /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */\n p = p_tileno % p_cp->tw;\n q = p_tileno / p_cp->tw;\n\n /* find extent of tile */\n l_tx0 = p_cp->tx0 + p *\n p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */\n *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);\n *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);\n l_ty0 = p_cp->ty0 + q *\n p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */\n *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);\n *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);\n\n /* max precision is 0 (can only grow) */\n *p_max_prec = 0;\n *p_max_res = 0;\n\n /* take the largest value for dx_min and dy_min */\n *p_dx_min = 0x7fffffff;\n *p_dy_min = 0x7fffffff;\n\n for (compno = 0; compno < p_image->numcomps; ++compno) {\n /* arithmetic variables to calculate */\n OPJ_UINT32 l_level_no;\n OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;\n OPJ_INT32 l_px0, l_py0, l_px1, py1;\n OPJ_UINT32 l_pdx, l_pdy;\n OPJ_UINT32 l_pw, l_ph;\n OPJ_UINT32 l_product;\n OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;\n\n l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);\n l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);\n l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);\n l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);\n\n if (l_tccp->numresolutions > *p_max_res) {\n *p_max_res = l_tccp->numresolutions;\n }\n\n /* use custom size for precincts */\n for (resno = 0; resno < l_tccp->numresolutions; ++resno) {\n OPJ_UINT32 l_dx, l_dy;\n\n /* precinct width and height */\n l_pdx = l_tccp->prcw[resno];\n l_pdy = l_tccp->prch[resno];\n\n l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));\n l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));\n\n /* take the minimum size for dx for each comp and resolution */\n *p_dx_min = opj_uint_min(*p_dx_min, l_dx);\n *p_dy_min = opj_uint_min(*p_dy_min, l_dy);\n\n /* various calculations of extents */\n l_level_no = l_tccp->numresolutions - 1 - resno;\n\n l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);\n l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);\n l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);\n l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);\n\n l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;\n l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;\n l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;\n\n py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;\n\n l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);\n l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);\n\n l_product = l_pw * l_ph;\n\n /* update precision */\n if (l_product > *p_max_prec) {\n *p_max_prec = l_product;\n }\n }\n ++l_img_comp;\n ++l_tccp;\n }\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "opj_get_encoding_parameters", "_file_name": "src/lib/openjp2/pi.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = ['showport']\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = ['showport', '-iscsi']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = ['showport', '-iscsiname']\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n #record\n show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']\n show_vlun_ret = 'no vluns listed\\r\\n'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), ''])\n show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.iscsi_ip_address = '10.10.10.10'\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.252')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_get_iscsi_ip", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(\n output_len, sizeof(uint64_t)) ||\n !asylo::primitives::TrustedPrimitives::IsOutsideEnclave(output,\n *output_len)) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input/output found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ecall_restore", "_file_name": "asylo/platform/primitives/sgx/ecalls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": " def clean_cache(self, limit):\n \"\"\"\n Method that remove several User objects from cache - the least \n active users\n :param limit: number of the users that the method should remove\n from cache\n :return: None\n \"\"\"\n\n log.info('Figuring out the least active users...')\n # Select users that the least active recently\n user_ids = tuple(self.users.keys())\n query = ('SELECT chat_id '\n 'FROM photo_queries_table2 '\n f'WHERE chat_id in {user_ids} '\n 'GROUP BY chat_id '\n 'ORDER BY MAX(time) '\n f'LIMIT %s')\n\n parameters = limit,\n\n try:\n cursor = db.execute_query(query, parameters)\n except DatabaseConnectionError:\n log.error(\"Can't figure out the least active users...\")\n return\n\n if not cursor.rowcount:\n log.warning(\"There are no users in the db\")\n return\n\n # Make list out of tuple of tuples that is returned by MySQL\n least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]\n log.info('Removing %d least active users from cache...', limit)\n num_deleted_entries = 0\n for entry in least_active_users:\n log.debug('Deleting %s...', entry)\n deleted_entry = self.users.pop(entry, None)\n if deleted_entry:\n num_deleted_entries += 1\n log.debug(\"%d users were removed from cache.\", num_deleted_entries)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "clean_cache", "_file_name": "photogpsbot/users.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "ssize_t enc_untrusted_recvfrom(int sockfd, void *buf, size_t len, int flags,\n struct sockaddr *src_addr, socklen_t *addrlen) {\n int klinux_flags = TokLinuxRecvSendFlag(flags);\n if (klinux_flags == 0 && flags != 0) {\n errno = EINVAL;\n return -1;\n }\n\n MessageWriter input;\n input.Push(sockfd);\n input.Push(len);\n input.Push(klinux_flags);\n MessageReader output;\n const auto status = NonSystemCallDispatcher(\n ::asylo::host_call::kRecvFromHandler, &input, &output);\n CheckStatusAndParamCount(status, output, \"enc_untrusted_recvfrom\", 4);\n\n int result = output.next();\n int klinux_errno = output.next();\n // recvfrom() returns -1 on failure, with errno set to indicate the cause\n // of the error.\n if (result == -1) {\n errno = FromkLinuxErrorNumber(klinux_errno);\n return result;\n }\n\n if (result > len) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_recvfrom: result exceeds requested\");\n }\n\n auto buffer_received = output.next();\n memcpy(buf, buffer_received.data(), std::min(len, buffer_received.size()));\n\n // If |src_addr| is not NULL, and the underlying protocol provides the source\n // address, this source address is filled in. When |src_addr| is NULL, nothing\n // is filled in; in this case, |addrlen| is not used, and should also be NULL.\n if (src_addr != nullptr && addrlen != nullptr) {\n auto klinux_sockaddr_buf = output.next();\n const struct klinux_sockaddr *klinux_addr =\n klinux_sockaddr_buf.As();\n FromkLinuxSockAddr(klinux_addr, klinux_sockaddr_buf.size(), src_addr,\n addrlen, TrustedPrimitives::BestEffortAbort);\n }\n\n return result;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "enc_untrusted_recvfrom", "_file_name": "asylo/platform/host_call/trusted/host_calls.cc", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def getGameID(ID):\n\tdb.execute(\"SELECT * FROM games WHERE ID = ?\", ID)\n\tID = db.fetchone()\n\treturn ID", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "getGameID", "_file_name": "plugins/database.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "int shadow_server_start(rdpShadowServer* server)\n{\n\tBOOL ipc;\n\tBOOL status;\n\tWSADATA wsaData;\n\n\tif (!server)\n\t\treturn -1;\n\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)\n\t\treturn -1;\n\n#ifndef _WIN32\n\tsignal(SIGPIPE, SIG_IGN);\n#endif\n\tserver->screen = shadow_screen_new(server);\n\n\tif (!server->screen)\n\t{\n\t\tWLog_ERR(TAG, \"screen_new failed\");\n\t\treturn -1;\n\t}\n\n\tserver->capture = shadow_capture_new(server);\n\n\tif (!server->capture)\n\t{\n\t\tWLog_ERR(TAG, \"capture_new failed\");\n\t\treturn -1;\n\t}\n\n\t/* Bind magic:\n\t *\n\t * emtpy ... bind TCP all\n\t * ... bind local (IPC)\n\t * bind-socket,
... bind TCP to specified interface\n\t */\n\tipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket,\n\t strnlen(bind_address, sizeof(bind_address))) != 0);\n\tif (!ipc)\n\t{\n\t\tsize_t x, count;\n\t\tchar** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count);\n\t\tif (!list || (count <= 1))\n\t\t{\n\t\t\tif (server->ipcSocket == NULL)\n\t\t\t{\n\t\t\t\tif (!open_port(server, NULL))\n\t\t\t\t{\n\t\t\t\t\tfree(list);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tfor (x = 1; x < count; x++)\n\t\t{\n\t\t\tBOOL success = open_port(server, list[x]);\n\t\t\tif (!success)\n\t\t\t{\n\t\t\t\tfree(list);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tfree(list);\n\t}\n\telse\n\t{\n\t\tstatus = server->listener->OpenLocal(server->listener, server->ipcSocket);\n\t\tif (!status)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Problem creating local socket listener. (Port already used or \"\n\t\t\t \"insufficient permissions?)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL)))\n\t{\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "shadow_server_start", "_file_name": "server/shadow/shadow_server.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int __mdiobus_register(struct mii_bus *bus, struct module *owner)\n{\n\tstruct mdio_device *mdiodev;\n\tint i, err;\n\tstruct gpio_desc *gpiod;\n\n\tif (NULL == bus || NULL == bus->name ||\n\t NULL == bus->read || NULL == bus->write)\n\t\treturn -EINVAL;\n\n\tBUG_ON(bus->state != MDIOBUS_ALLOCATED &&\n\t bus->state != MDIOBUS_UNREGISTERED);\n\n\tbus->owner = owner;\n\tbus->dev.parent = bus->parent;\n\tbus->dev.class = &mdio_bus_class;\n\tbus->dev.groups = NULL;\n\tdev_set_name(&bus->dev, \"%s\", bus->id);\n\n\terr = device_register(&bus->dev);\n\tif (err) {\n\t\tpr_err(\"mii_bus %s failed to register\\n\", bus->id);\n\t\treturn -EINVAL;\n\t}\n\n\tmutex_init(&bus->mdio_lock);\n\n\t/* de-assert bus level PHY GPIO reset */\n\tgpiod = devm_gpiod_get_optional(&bus->dev, \"reset\", GPIOD_OUT_LOW);\n\tif (IS_ERR(gpiod)) {\n\t\tdev_err(&bus->dev, \"mii_bus %s couldn't get reset GPIO\\n\",\n\t\t\tbus->id);\n\t\tdevice_del(&bus->dev);\n\t\treturn PTR_ERR(gpiod);\n\t} else\tif (gpiod) {\n\t\tbus->reset_gpiod = gpiod;\n\n\t\tgpiod_set_value_cansleep(gpiod, 1);\n\t\tudelay(bus->reset_delay_us);\n\t\tgpiod_set_value_cansleep(gpiod, 0);\n\t}\n\n\tif (bus->reset)\n\t\tbus->reset(bus);\n\n\tfor (i = 0; i < PHY_MAX_ADDR; i++) {\n\t\tif ((bus->phy_mask & (1 << i)) == 0) {\n\t\t\tstruct phy_device *phydev;\n\n\t\t\tphydev = mdiobus_scan(bus, i);\n\t\t\tif (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) {\n\t\t\t\terr = PTR_ERR(phydev);\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t}\n\t}\n\n\tmdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device);\n\n\tbus->state = MDIOBUS_REGISTERED;\n\tpr_info(\"%s: probed\\n\", bus->name);\n\treturn 0;\n\nerror:\n\twhile (--i >= 0) {\n\t\tmdiodev = bus->mdio_map[i];\n\t\tif (!mdiodev)\n\t\t\tcontinue;\n\n\t\tmdiodev->device_remove(mdiodev);\n\t\tmdiodev->device_free(mdiodev);\n\t}\n\n\t/* Put PHYs in RESET to save power */\n\tif (bus->reset_gpiod)\n\t\tgpiod_set_value_cansleep(bus->reset_gpiod, 1);\n\n\tdevice_del(&bus->dev);\n\treturn err;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "__mdiobus_register", "_file_name": "drivers/net/phy/mdio_bus.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def new_category(category_name):\n try:\n conn = check_heroku_db()\n cur = conn.cursor()\n cur.execute('''INSERT INTO categories (cat_name) VALUES (%s)''', (category_name,))\n conn.commit()\n conn.close()\n\n except psycopg2.DatabaseError as e:\n print('Error %s' % e)\n sys.exit(1)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[103, 194]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[103, 194]]}, "_func_name": "new_category", "_file_name": "db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)\n{\n bool ok;\n XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };\n enum xkb_file_type type;\n struct xkb_context *ctx = keymap->ctx;\n\n /* Collect section files and check for duplicates. */\n for (file = (XkbFile *) file->defs; file;\n file = (XkbFile *) file->common.next) {\n if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||\n file->file_type > LAST_KEYMAP_FILE_TYPE) {\n log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n if (files[file->file_type]) {\n log_err(ctx,\n \"More than one %s section in keymap file; \"\n \"All sections after the first ignored\\n\",\n xkb_file_type_to_string(file->file_type));\n continue;\n }\n\n files[file->file_type] = file;\n }\n\n /*\n * Check that all required section were provided.\n * Report everything before failing.\n */\n ok = true;\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n if (files[type] == NULL) {\n log_err(ctx, \"Required section %s missing from keymap\\n\",\n xkb_file_type_to_string(type));\n ok = false;\n }\n }\n if (!ok)\n return false;\n\n /* Compile sections. */\n for (type = FIRST_KEYMAP_FILE_TYPE;\n type <= LAST_KEYMAP_FILE_TYPE;\n type++) {\n log_dbg(ctx, \"Compiling %s \\\"%s\\\"\\n\",\n xkb_file_type_to_string(type), files[type]->name);\n\n ok = compile_file_fns[type](files[type], keymap, merge);\n if (!ok) {\n log_err(ctx, \"Failed to compile %s\\n\",\n xkb_file_type_to_string(type));\n return false;\n }\n }\n\n return UpdateDerivedKeymapFields(keymap);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[489, 616]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[489, 616]]}, "_func_name": "CompileKeymap", "_file_name": "src/xkbcomp/keymap.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _copy_volume(self, src_name, dest_name, cpg=None, snap_cpg=None,\n tpvv=True):\n # Virtual volume sets are not supported with the -online option\n cmd = ['createvvcopy', '-p', src_name, '-online']\n if snap_cpg:\n cmd.extend(['-snp_cpg', snap_cpg])\n if tpvv:\n cmd.append('-tpvv')\n if cpg:\n cmd.append(cpg)\n cmd.append(dest_name)\n LOG.debug('Creating clone of a volume with %s' % cmd)\n self._cli_run(cmd)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_copy_volume", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@login_manager.user_loader\ndef load_user(s_id):\n email = str(s_id)\n query = 'select * from usr where email like %s'\n cursor = g.conn.execute(query, (email, ))\n user = User()\n for row in cursor:\n user.name = str(row.name)\n user.email = str(row.email)\n break\n return user", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "load_user", "_file_name": "Web-app/Server.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def get_context_data(self, *args, **kwargs):\n data = super().get_context_data(*args, **kwargs)\n\n if self.request.GET.get('back', None) is not None:\n data['back_link'] = self.request.GET['back']\n\n return data", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[107, 223]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[107, 223]]}, "_func_name": "get_context_data", "_file_name": "socialsystem/core/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/lookup_assets')\ndef lookup_assets():\n start = request.args.get('start')\n\n con = psycopg2.connect(**config.POSTGRES)\n cur = con.cursor()\n\n query = \"SELECT aname FROM assets WHERE aname LIKE '\"+start+\"%'\"\n cur.execute(query)\n results = cur.fetchall()\n con.close()\n return jsonify(results)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[159, 228]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[159, 228]]}, "_func_name": "lookup_assets", "_file_name": "api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@app.route('/movies/add', methods=['GET', 'POST'])\ndef add_movie():\n form = MovieForm()\n if not form.validate_on_submit():\n return render_template('new_movie.html', title='Add New Movie', form=form)\n lang_id = add_language(form.data['language'])\n movie = {\n 'title': '',\n 'description': '',\n 'release_year': 0,\n 'rental_duration': 0,\n 'rental_rate': 0.00,\n 'length': 0,\n 'replacement_cost': 0.00\n }\n for k, v in movie.items():\n movie[k] = form.data[k]\n movie['language_id'] = movie.get('language_id', lang_id)\n cur.execute(\n \"\"\"\n INSERT INTO film (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\", [(v, ) for k, v in movie.items()]\n )\n try:\n cur.execute(\"SELECT * FROM film where fulltext @@ to_tsquery(%s)\", (movie['title'], ))\n res = cur.fetchall()\n conn.commit()\n return redirect(url_for('movies'))\n except Exception as e:\n return redirect(url_for('index'))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_movie", "_file_name": "app.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int ng_pkt(git_pkt **out, const char *line, size_t len)\n{\n\tgit_pkt_ng *pkt;\n\tconst char *ptr;\n\tsize_t alloclen;\n\n\tpkt = git__malloc(sizeof(*pkt));\n\tGITERR_CHECK_ALLOC(pkt);\n\n\tpkt->ref = NULL;\n\tpkt->type = GIT_PKT_NG;\n\n\tline += 3; /* skip \"ng \" */\n\tif (!(ptr = strchr(line, ' ')))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->ref = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->ref);\n\n\tmemcpy(pkt->ref, line, len);\n\tpkt->ref[len] = '\\0';\n\n\tline = ptr + 1;\n\tif (!(ptr = strchr(line, '\\n')))\n\t\tgoto out_err;\n\tlen = ptr - line;\n\n\tGITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);\n\tpkt->msg = git__malloc(alloclen);\n\tGITERR_CHECK_ALLOC(pkt->msg);\n\n\tmemcpy(pkt->msg, line, len);\n\tpkt->msg[len] = '\\0';\n\n\t*out = (git_pkt *)pkt;\n\treturn 0;\n\nout_err:\n\tgiterr_set(GITERR_NET, \"invalid packet line\");\n\tgit__free(pkt->ref);\n\tgit__free(pkt);\n\treturn -1;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[254, 287], [505, 539]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[254, 287], [505, 539]]}, "_func_name": "ng_pkt", "_file_name": "src/transports/smart_pkt.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size,\n\t\t\tint cpu_id)\n{\n\tstruct ring_buffer_per_cpu *cpu_buffer;\n\tunsigned long nr_pages;\n\tint cpu, err = 0;\n\n\t/*\n\t * Always succeed at resizing a non-existent buffer:\n\t */\n\tif (!buffer)\n\t\treturn size;\n\n\t/* Make sure the requested buffer exists */\n\tif (cpu_id != RING_BUFFER_ALL_CPUS &&\n\t !cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\treturn size;\n\n\tsize = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\tsize *= BUF_PAGE_SIZE;\n\n\t/* we need a minimum of two pages */\n\tif (size < BUF_PAGE_SIZE * 2)\n\t\tsize = BUF_PAGE_SIZE * 2;\n\n\tnr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n\n\t/*\n\t * Don't succeed if resizing is disabled, as a reader might be\n\t * manipulating the ring buffer and is expecting a sane state while\n\t * this is true.\n\t */\n\tif (atomic_read(&buffer->resize_disabled))\n\t\treturn -EBUSY;\n\n\t/* prevent another thread from changing buffer sizes */\n\tmutex_lock(&buffer->mutex);\n\n\tif (cpu_id == RING_BUFFER_ALL_CPUS) {\n\t\t/* calculate the pages to update */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\n\t\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\t\tcpu_buffer->nr_pages;\n\t\t\t/*\n\t\t\t * nothing more to do for removing pages or no update\n\t\t\t */\n\t\t\tif (cpu_buffer->nr_pages_to_update <= 0)\n\t\t\t\tcontinue;\n\t\t\t/*\n\t\t\t * to add pages, make sure all new pages can be\n\t\t\t * allocated without receiving ENOMEM\n\t\t\t */\n\t\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\t\tif (__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t\t&cpu_buffer->new_pages, cpu)) {\n\t\t\t\t/* not enough memory for new pages */\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out_err;\n\t\t\t}\n\t\t}\n\n\t\tget_online_cpus();\n\t\t/*\n\t\t * Fire off all the required work handlers\n\t\t * We can't schedule on offline CPUs, but it's not necessary\n\t\t * since we can change their buffer sizes without any race.\n\t\t */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\t/* Can't run something on an offline CPU. */\n\t\t\tif (!cpu_online(cpu)) {\n\t\t\t\trb_update_pages(cpu_buffer);\n\t\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t\t} else {\n\t\t\t\tschedule_work_on(cpu,\n\t\t\t\t\t\t&cpu_buffer->update_pages_work);\n\t\t\t}\n\t\t}\n\n\t\t/* wait for all the updates to complete */\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\tif (!cpu_buffer->nr_pages_to_update)\n\t\t\t\tcontinue;\n\n\t\t\tif (cpu_online(cpu))\n\t\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\t}\n\n\t\tput_online_cpus();\n\t} else {\n\t\t/* Make sure this CPU has been intitialized */\n\t\tif (!cpumask_test_cpu(cpu_id, buffer->cpumask))\n\t\t\tgoto out;\n\n\t\tcpu_buffer = buffer->buffers[cpu_id];\n\n\t\tif (nr_pages == cpu_buffer->nr_pages)\n\t\t\tgoto out;\n\n\t\tcpu_buffer->nr_pages_to_update = nr_pages -\n\t\t\t\t\t\tcpu_buffer->nr_pages;\n\n\t\tINIT_LIST_HEAD(&cpu_buffer->new_pages);\n\t\tif (cpu_buffer->nr_pages_to_update > 0 &&\n\t\t\t__rb_allocate_pages(cpu_buffer->nr_pages_to_update,\n\t\t\t\t\t &cpu_buffer->new_pages, cpu_id)) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_err;\n\t\t}\n\n\t\tget_online_cpus();\n\n\t\t/* Can't run something on an offline CPU. */\n\t\tif (!cpu_online(cpu_id))\n\t\t\trb_update_pages(cpu_buffer);\n\t\telse {\n\t\t\tschedule_work_on(cpu_id,\n\t\t\t\t\t &cpu_buffer->update_pages_work);\n\t\t\twait_for_completion(&cpu_buffer->update_done);\n\t\t}\n\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\t\tput_online_cpus();\n\t}\n\n out:\n\t/*\n\t * The ring buffer resize can happen with the ring buffer\n\t * enabled, so that the update disturbs the tracing as little\n\t * as possible. But if the buffer is disabled, we do not need\n\t * to worry about that, and we can take the time to verify\n\t * that the buffer is not corrupt.\n\t */\n\tif (atomic_read(&buffer->record_disabled)) {\n\t\tatomic_inc(&buffer->record_disabled);\n\t\t/*\n\t\t * Even though the buffer was disabled, we must make sure\n\t\t * that it is truly disabled before calling rb_check_pages.\n\t\t * There could have been a race between checking\n\t\t * record_disable and incrementing it.\n\t\t */\n\t\tsynchronize_sched();\n\t\tfor_each_buffer_cpu(buffer, cpu) {\n\t\t\tcpu_buffer = buffer->buffers[cpu];\n\t\t\trb_check_pages(cpu_buffer);\n\t\t}\n\t\tatomic_dec(&buffer->record_disabled);\n\t}\n\n\tmutex_unlock(&buffer->mutex);\n\treturn size;\n\n out_err:\n\tfor_each_buffer_cpu(buffer, cpu) {\n\t\tstruct buffer_page *bpage, *tmp;\n\n\t\tcpu_buffer = buffer->buffers[cpu];\n\t\tcpu_buffer->nr_pages_to_update = 0;\n\n\t\tif (list_empty(&cpu_buffer->new_pages))\n\t\t\tcontinue;\n\n\t\tlist_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages,\n\t\t\t\t\tlist) {\n\t\t\tlist_del_init(&bpage->list);\n\t\t\tfree_buffer_page(bpage);\n\t\t}\n\t}\n\tmutex_unlock(&buffer->mutex);\n\treturn err;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[416, 483], [522, 581], [582, 629]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[416, 483], [522, 581], [582, 629]]}, "_func_name": "ring_buffer_resize", "_file_name": "kernel/trace/ring_buffer.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n FILE\n *file;\n\n Image\n *image,\n *next_image,\n *pwp_image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n register Image\n *p;\n\n register ssize_t\n i;\n\n size_t\n filesize,\n length;\n\n ssize_t\n count;\n\n unsigned char\n magick[MaxTextExtent];\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n pwp_image=AcquireImage(image_info);\n image=pwp_image;\n status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n return((Image *) NULL);\n count=ReadBlob(pwp_image,5,magick);\n if ((count != 5) || (LocaleNCompare((char *) magick,\"SFW95\",5) != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n read_info=CloneImageInfo(image_info);\n (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,\n (void *) NULL);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n unique_file=AcquireUniqueFileResource(read_info->filename);\n for ( ; ; )\n {\n for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))\n {\n for (i=0; i < 17; i++)\n magick[i]=magick[i+1];\n magick[17]=(unsigned char) c;\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) == 0)\n break;\n }\n if (c == EOF)\n break;\n if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) != 0)\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n /*\n Dump SFW image to a temporary file.\n */\n file=(FILE *) NULL;\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\",\n image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n length=fwrite(\"SFW94A\",1,6,file);\n (void) length;\n filesize=65535UL*magick[2]+256L*magick[1]+magick[0];\n for (i=0; i < (ssize_t) filesize; i++)\n {\n c=ReadBlobByte(pwp_image);\n (void) fputc(c,file);\n }\n (void) fclose(file);\n next_image=ReadImage(read_info,exception);\n if (next_image == (Image *) NULL)\n break;\n (void) FormatLocaleString(next_image->filename,MaxTextExtent,\n \"slide_%02ld.sfw\",(long) next_image->scene);\n if (image == (Image *) NULL)\n image=next_image;\n else\n {\n /*\n Link image into image list.\n */\n for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;\n next_image->previous=p;\n next_image->scene=p->scene+1;\n p->next=next_image;\n }\n if (image_info->number_scenes != 0)\n if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),\n GetBlobSize(pwp_image));\n if (status == MagickFalse)\n break;\n }\n if (unique_file != -1)\n (void) close(unique_file);\n (void) RelinquishUniqueFileResource(read_info->filename);\n read_info=DestroyImageInfo(read_info);\n (void) CloseBlob(pwp_image);\n pwp_image=DestroyImage(pwp_image);\n if (EOFBlob(image) != MagickFalse)\n {\n char\n *message;\n\n message=GetExceptionMessage(errno);\n (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,\n \"UnexpectedEndOfFile\",\"`%s': %s\",image->filename,message);\n message=DestroyString(message);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[3575, 3680]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[3575, 3680]]}, "_func_name": "ReadPWPImage", "_file_name": "coders/pwp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;\n\n\t/* sanity checking for parameters. */\n\tif ((int)g->sect <= 0 ||\n\t (int)g->head <= 0 ||\n\t /* check for overflow in max_sector */\n\t (int)(g->sect * g->head) <= 0 ||\n\t /* check for zero in F_SECT_PER_TRACK */\n\t (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;\n\n\t\tif (lock_fdc(drive))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "set_geometry", "_file_name": "drivers/block/floppy.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def init_user(username, chat_id):\n conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\users\\\\\" + username + '.db')\n conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\\\cf.db')\n cursor = conn.cursor()\n cursor2 = conn2.cursor()\n cursor.execute(\"CREATE TABLE result (problem INTEGER, diff STRING, verdict STRING)\")\n cursor2.execute(\"SELECT * FROM problems\")\n x = cursor2.fetchone()\n while x != None:\n cursor.execute(\"insert into result values (?, ?, ? )\", (x[0], x[1], \"NULL\"))\n x = cursor2.fetchone()\n\n url = 'http://codeforces.com/submissions/' + username\n r = requests.get(url)\n max_page = 1\n soup = BeautifulSoup(r.text, \"lxml\")\n\n for link in soup.find_all(attrs={\"class\": \"page-index\"}):\n s = link.find('a')\n s2 = s.get(\"href\").split('/')\n max_page = max(max_page, int(s2[4]))\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')\n soup = BeautifulSoup(r.text, \"lxml\")\n last_try = soup.find(attrs={\"class\":\"status-small\"})\n if not last_try == None:\n last_try = str(last_try).split()\n last_try = str(last_try[2]) + str(last_try[3])\n\n for i in range(1, max_page + 1):\n r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))\n soup = BeautifulSoup(r.text, \"lxml\")\n count = 0\n ver = soup.find_all(attrs={\"class\": \"submissionVerdictWrapper\"})\n for link in soup.find_all('a'):\n s = link.get('href')\n if s != None and s.find('/problemset') != -1:\n s = s.split('/')\n if len(s) == 5:\n s2 = str(ver[count]).split()\n s2 = s2[5].split('\\\"')\n count += 1\n cursor.execute(\"select * from result where problem = ? and diff = ?\", (s[3], s[4]))\n x = cursor.fetchone()\n if s2[1] == 'OK' and x != None:\n cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n if x != None and x[2] != 'OK':\n cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n conn.commit()\n conn.close()\n conn2.close()\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from last_update_problemset\")\n last_problem = conn.fetchone()\n conn.execute(\"select * from users where chat_id = ?\", (str(chat_id),))\n x = conn.fetchone()\n if x == None:\n conn.execute(\"insert into users values (?, ?, ?, ?, ?)\", (chat_id, username, str(last_try), str(last_problem[0]), 1))\n else:\n conn.execute(\"update users set username = ? where chat_id = ?\", (str(username), str(chat_id)))\n conn.execute(\"update users set last_update = ? where chat_id = ?\", (str(last_try), str(chat_id)))\n conn.execute(\"update users set last_problem = ? where chat_id = ?\", (str(last_problem[0]), str(chat_id)))\n conn.execute(\"update users set state = ? where chat_id = ?\", (str(1), str(chat_id)))\n settings.commit()\n settings.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "init_user", "_file_name": "bases/createuserbase.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,\n ExceptionInfo *exception)\n{\n char\n *attribute,\n format[MagickPathExtent],\n name[MagickPathExtent],\n *resource;\n\n const StringInfo\n *profile;\n\n const unsigned char\n *info;\n\n long\n start,\n stop;\n\n MagickBooleanType\n status;\n\n register ssize_t\n i;\n\n size_t\n length;\n\n ssize_t\n count,\n id,\n sub_number;\n\n /*\n There are no newlines in path names, so it's safe as terminator.\n */\n profile=GetImageProfile(image,\"8bim\");\n if (profile == (StringInfo *) NULL)\n return(MagickFalse);\n count=(ssize_t) sscanf(key,\"8BIM:%ld,%ld:%1024[^\\n]\\n%1024[^\\n]\",&start,&stop,\n name,format);\n if ((count != 2) && (count != 3) && (count != 4))\n return(MagickFalse);\n if (count < 4)\n (void) CopyMagickString(format,\"SVG\",MagickPathExtent);\n if (count < 3)\n *name='\\0';\n sub_number=1;\n if (*name == '#')\n sub_number=(ssize_t) StringToLong(&name[1]);\n sub_number=MagickMax(sub_number,1L);\n resource=(char *) NULL;\n status=MagickFalse;\n length=GetStringInfoLength(profile);\n info=GetStringInfoDatum(profile);\n while ((length > 0) && (status == MagickFalse))\n {\n if (ReadPropertyByte(&info,&length) != (unsigned char) '8')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')\n continue;\n if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')\n continue;\n id=(ssize_t) ReadPropertyMSBShort(&info,&length);\n if (id < (ssize_t) start)\n continue;\n if (id > (ssize_t) stop)\n continue;\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n count=(ssize_t) ReadPropertyByte(&info,&length);\n if ((count != 0) && ((size_t) count <= length))\n {\n resource=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n resource=(char *) AcquireQuantumMemory((size_t) count+\n MagickPathExtent,sizeof(*resource));\n if (resource != (char *) NULL)\n {\n for (i=0; i < (ssize_t) count; i++)\n resource[i]=(char) ReadPropertyByte(&info,&length);\n resource[count]='\\0';\n }\n }\n if ((count & 0x01) == 0)\n (void) ReadPropertyByte(&info,&length);\n count=(ssize_t) ReadPropertyMSBLong(&info,&length);\n if ((count < 0) || ((size_t) count > length))\n {\n length=0; \n continue;\n }\n if ((*name != '\\0') && (*name != '#'))\n if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))\n {\n /*\n No name match, scroll forward and try next.\n */\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n if ((*name == '#') && (sub_number != 1))\n {\n /*\n No numbered match, scroll forward and try next.\n */\n sub_number--;\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n continue;\n }\n /*\n We have the resource of interest.\n */\n attribute=(char *) NULL;\n if (~((size_t) count) >= (MagickPathExtent-1))\n attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,\n sizeof(*attribute));\n if (attribute != (char *) NULL)\n {\n (void) CopyMagickMemory(attribute,(char *) info,(size_t) count);\n attribute[count]='\\0';\n info+=count;\n length-=MagickMin(count,(ssize_t) length);\n if ((id <= 1999) || (id >= 2999))\n (void) SetImageProperty((Image *) image,key,(const char *)\n attribute,exception);\n else\n {\n char\n *path;\n\n if (LocaleCompare(format,\"svg\") == 0)\n path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,\n image->columns,image->rows);\n else\n path=TracePSClippath((unsigned char *) attribute,(size_t) count);\n (void) SetImageProperty((Image *) image,key,(const char *) path,\n exception);\n path=DestroyString(path);\n }\n attribute=DestroyString(attribute);\n status=MagickTrue;\n }\n }\n if (resource != (char *) NULL)\n resource=DestroyString(resource);\n return(status);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "Get8BIMProperty", "_file_name": "MagickCore/property.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int changedline (const Proto *p, int oldpc, int newpc) {\n while (oldpc++ < newpc) {\n if (p->lineinfo[oldpc] != 0)\n return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));\n }\n return 0; /* no line changes in the way */\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[206, 252]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[206, 252]]}, "_func_name": "changedline", "_file_name": "ldebug.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);\n unsigned numEntries = darray_size(append->keysym_list.syms);\n\n darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, numEntries);\n darray_concat(expr->keysym_list.syms, append->keysym_list.syms);\n\n FreeStmt((ParseCommon *) &append);\n\n return expr;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-416", "source": "SVEN-before", "vuln_type": "cwe-416", "token_labels": {"evidence": [[377, 416]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[377, 416]]}, "_func_name": "ExprAppendMultiKeysymList", "_file_name": "src/xkbcomp/ast-build.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def insert(key, value):\n connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])\n cur = connection.cursor()\n try:\n cur.execute(\"insert into reply_map values(?, ?)\", (key, value))\n connection.commit()\n except:\n pass", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "insert", "_file_name": "db.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "PHP_FUNCTION(imagegammacorrect)\n{\n\tzval *IM;\n\tgdImagePtr im;\n\tint i;\n\tdouble input, output;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"rdd\", &IM, &input, &output) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif ( input <= 0.0 || output <= 0.0 ) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Gamma values should be positive\");\n\t\tRETURN_FALSE;\n\t}\n\n\tZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, \"Image\", le_gd);\n\n\tif (gdImageTrueColor(im))\t{\n\t\tint x, y, c;\n\n\t\tfor (y = 0; y < gdImageSY(im); y++)\t{\n\t\t\tfor (x = 0; x < gdImageSX(im); x++)\t{\n\t\t\t\tc = gdImageGetPixel(im, x, y);\n\t\t\t\tgdImageSetPixel(im, x, y,\n\t\t\t\t\tgdTrueColorAlpha(\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\t(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5),\n\t\t\t\t\t\tgdTrueColorGetAlpha(c)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tRETURN_TRUE;\n\t}\n\n\tfor (i = 0; i < gdImageColorsTotal(im); i++) {\n\t\tim->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t\tim->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t\tim->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);\n\t}\n\n\tRETURN_TRUE;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "PHP_FUNCTION", "_file_name": "ext/gd/gd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_iscsi_ip_active(self):\n self.flags(lock_path=self.tempdir)\n\n #record set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n #record\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_vlun_cmd = 'showvlun -a -host fakehost'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])\n\n self.mox.ReplayAll()\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.253')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[290, 325], [397, 441], [579, 627], [1105, 1158]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[290, 325], [397, 441], [579, 627], [1105, 1158]]}, "_func_name": "test_get_iscsi_ip_active", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "upnp_redirect(const char * rhost, unsigned short eport,\n const char * iaddr, unsigned short iport,\n const char * protocol, const char * desc,\n unsigned int leaseduration)\n{\n\tint proto, r;\n\tchar iaddr_old[32];\n\tchar rhost_old[32];\n\tunsigned short iport_old;\n\tstruct in_addr address;\n\tunsigned int timestamp;\n\n\tproto = proto_atoi(protocol);\n\tif(inet_aton(iaddr, &address) <= 0) {\n\t\tsyslog(LOG_ERR, \"inet_aton(%s) FAILED\", iaddr);\n\t\treturn -1;\n\t}\n\n\tif(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,\n\t eport, address, iport)) {\n\t\tsyslog(LOG_INFO, \"redirection permission check failed for \"\n\t\t \"%hu->%s:%hu %s\", eport, iaddr, iport, protocol);\n\t\treturn -3;\n\t}\n\n\tif (desc == NULL)\n\t\tdesc = \"\";\t/* assume empty description */\n\n\t/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)\n\t * - 2.2.20.PortMappingDescription :\n\t * Overwriting Previous / Existing Port Mappings:\n\t * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient\n\t * are exactly the same as an existing mapping, the existing mapping values\n\t * for InternalPort, PortMappingDescription, PortMappingEnabled and\n\t * PortMappingLeaseDuration are overwritten.\n\t * Rejecting a New Port Mapping:\n\t * In cases where the RemoteHost, ExternalPort and PortMappingProtocol\n\t * are the same as an existing mapping, but the InternalClient is\n\t * different, the action is rejected with an appropriate error.\n\t * Add or Reject New Port Mapping behavior based on vendor implementation:\n\t * In cases where the ExternalPort, PortMappingProtocol and InternalClient\n\t * are the same, but RemoteHost is different, the vendor can choose to\n\t * support both mappings simultaneously, or reject the second mapping\n\t * with an appropriate error.\n\t *\n\t * - 2.4.16.AddPortMapping\n\t * This action creates a new port mapping or overwrites an existing\n\t * mapping with the same internal client. If the ExternalPort and\n\t * PortMappingProtocol pair is already mapped to another internal client,\n\t * an error is returned.\n\t *\n\t * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)\n\t * Protocol ExternalPort RemoteHost InternalClient Result\n\t * = = ≠ ≠ Failure\n\t * = = ≠ = Failure or success\n\t * (vendor specific)\n\t * = = = ≠ Failure\n\t * = = = = Success (overwrite)\n\t */\n\trhost_old[0] = '\\0';\n\tr = get_redirect_rule(ext_if_name, eport, proto,\n\t iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,\n\t rhost_old, sizeof(rhost_old),\n\t ×tamp, 0, 0);\n\tif(r == 0) {\n\t\tif(strcmp(iaddr, iaddr_old)==0 &&\n\t\t ((rhost == NULL && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, \"*\") == 0) && rhost_old[0]=='\\0') ||\n\t\t (rhost && (strcmp(rhost, rhost_old) == 0)))) {\n\t\t\tsyslog(LOG_INFO, \"updating existing port mapping %hu %s (rhost '%s') => %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\t\tif(iport != iport_old) {\n\t\t\t\tr = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);\n\t\t\t} else {\n\t\t\t\tr = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);\n\t\t\t}\n#ifdef ENABLE_LEASEFILE\n\t\t\tif(r == 0) {\n\t\t\t\tlease_file_remove(eport, proto);\n\t\t\t\tlease_file_add(eport, iaddr, iport, proto, desc, timestamp);\n\t\t\t}\n#endif /* ENABLE_LEASEFILE */\n\t\t\treturn r;\n\t\t} else {\n\t\t\tsyslog(LOG_INFO, \"port %hu %s (rhost '%s') already redirected to %s:%hu\",\n\t\t\t\teport, protocol, rhost_old, iaddr_old, iport_old);\n\t\t\treturn -2;\n\t\t}\n#ifdef CHECK_PORTINUSE\n\t} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {\n\t\tsyslog(LOG_INFO, \"port %hu protocol %s already in use\",\n\t\t eport, protocol);\n\t\treturn -4;\n#endif /* CHECK_PORTINUSE */\n\t} else {\n\t\ttimestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;\n\t\tsyslog(LOG_INFO, \"redirecting port %hu to %s:%hu protocol %s for: %s\",\n\t\t\teport, iaddr, iport, protocol, desc);\n\t\treturn upnp_redirect_internal(rhost, eport, iaddr, iport, proto,\n\t\t desc, timestamp);\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "upnp_redirect", "_file_name": "miniupnpd/upnpredirect.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _get_host_from_connector(self, connector):\n \"\"\"List the hosts defined in the storage.\n\n Return the host name with the given connection info, or None if there\n is no host fitting that information.\n\n \"\"\"\n\n prefix = self._connector_to_hostname_prefix(connector)\n LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)\n\n # Get list of host in the storage\n ssh_cmd = 'svcinfo lshost -delim !'\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n # If we have FC information, we have a faster lookup option\n hostname = None\n if 'wwpns' in connector:\n hostname = self._find_host_from_wwpn(connector)\n\n # If we don't have a hostname yet, try the long way\n if not hostname:\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines),\n '_get_host_from_connector',\n ssh_cmd, out, err)\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header,\n '_get_host_from_connector',\n ssh_cmd, out, err)\n name_index = header.index('name')\n hosts = map(lambda x: x.split('!')[name_index], host_lines)\n hostname = self._find_host_exhaustive(connector, hosts)\n\n LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)\n\n return hostname", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[421, 465]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[421, 465]]}, "_func_name": "_get_host_from_connector", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)\n{\n\tstruct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);\n\tbool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||\n\t\t ipv6_sk_rxinfo(sk);\n\n\tif (prepare && skb_rtable(skb)) {\n\t\t/* skb->cb is overloaded: prior to this point it is IP{6}CB\n\t\t * which has interface index (iif) as the first member of the\n\t\t * underlying inet{6}_skb_parm struct. This code then overlays\n\t\t * PKTINFO_SKB_CB and in_pktinfo also has iif as the first\n\t\t * element so the iif is picked up from the prior IPCB. If iif\n\t\t * is the loopback interface, then return the sending interface\n\t\t * (e.g., process binds socket to eth0 for Tx which is\n\t\t * redirected to loopback in the rtable/dst).\n\t\t */\n\t\tif (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)\n\t\t\tpktinfo->ipi_ifindex = inet_iif(skb);\n\n\t\tpktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);\n\t} else {\n\t\tpktinfo->ipi_ifindex = 0;\n\t\tpktinfo->ipi_spec_dst.s_addr = 0;\n\t}\n\t/* We need to keep the dst for __ip_options_echo()\n\t * We could restrict the test to opt.ts_needtime || opt.srr,\n\t * but the following is good enough as IP options are not often used.\n\t */\n\tif (unlikely(IPCB(skb)->opt.optlen))\n\t\tskb_dst_force(skb);\n\telse\n\t\tskb_dst_drop(skb);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ipv4_pktinfo_prepare", "_file_name": "net/ipv4/ip_sockglue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def get_output(command: List[str]) -> str:\n \"\"\"\n Run a command and return raw output\n\n :param str command: the command to run\n :returns: the stdout output of the command\n \"\"\"\n result = subprocess.run(command, stdout=subprocess.PIPE, check=True)\n return result.stdout.decode()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_output", "_file_name": "isort/hooks.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return((image->columns+7)/8);\n else\n return(image->columns*GetPSDPacketSize(image));\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[76, 110]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[76, 110]]}, "_func_name": "GetPSDRowSize", "_file_name": "coders/psd.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def add_post(content):\n \"\"\"Add a post to the 'database' with the current timestamp.\"\"\"\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n c.execute(\"insert into posts values('%s')\" % content)\n db.commit()\n db.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[147, 203]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[147, 203]]}, "_func_name": "add_post", "_file_name": "vagrant/forum/forumdb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _create_3par_vlun(self, volume, hostname):\n out = self._cli_run('createvlun %s auto %s' % (volume, hostname), None)\n if out and len(out) > 1:\n if \"must be in the same domain\" in out[0]:\n err = out[0].strip()\n err = err + \" \" + out[1].strip()\n raise exception.Invalid3PARDomain(err=err)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[51, 131]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[51, 131]]}, "_func_name": "_create_3par_vlun", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void opj_get_encoding_parameters(const opj_image_t *p_image,\n const opj_cp_t *p_cp,\n OPJ_UINT32 p_tileno,\n OPJ_INT32 * p_tx0,\n OPJ_INT32 * p_tx1,\n OPJ_INT32 * p_ty0,\n OPJ_INT32 * p_ty1,\n OPJ_UINT32 * p_dx_min,\n OPJ_UINT32 * p_dy_min,\n OPJ_UINT32 * p_max_prec,\n OPJ_UINT32 * p_max_res)\n{\n /* loop */\n OPJ_UINT32 compno, resno;\n /* pointers */\n const opj_tcp_t *l_tcp = 00;\n const opj_tccp_t * l_tccp = 00;\n const opj_image_comp_t * l_img_comp = 00;\n\n /* position in x and y of tile */\n OPJ_UINT32 p, q;\n\n /* preconditions */\n assert(p_cp != 00);\n assert(p_image != 00);\n assert(p_tileno < p_cp->tw * p_cp->th);\n\n /* initializations */\n l_tcp = &p_cp->tcps [p_tileno];\n l_img_comp = p_image->comps;\n l_tccp = l_tcp->tccps;\n\n /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */\n p = p_tileno % p_cp->tw;\n q = p_tileno / p_cp->tw;\n\n /* find extent of tile */\n *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),\n (OPJ_INT32)p_image->x0);\n *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),\n (OPJ_INT32)p_image->x1);\n *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),\n (OPJ_INT32)p_image->y0);\n *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),\n (OPJ_INT32)p_image->y1);\n\n /* max precision is 0 (can only grow) */\n *p_max_prec = 0;\n *p_max_res = 0;\n\n /* take the largest value for dx_min and dy_min */\n *p_dx_min = 0x7fffffff;\n *p_dy_min = 0x7fffffff;\n\n for (compno = 0; compno < p_image->numcomps; ++compno) {\n /* arithmetic variables to calculate */\n OPJ_UINT32 l_level_no;\n OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;\n OPJ_INT32 l_px0, l_py0, l_px1, py1;\n OPJ_UINT32 l_pdx, l_pdy;\n OPJ_UINT32 l_pw, l_ph;\n OPJ_UINT32 l_product;\n OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;\n\n l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);\n l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);\n l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);\n l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);\n\n if (l_tccp->numresolutions > *p_max_res) {\n *p_max_res = l_tccp->numresolutions;\n }\n\n /* use custom size for precincts */\n for (resno = 0; resno < l_tccp->numresolutions; ++resno) {\n OPJ_UINT32 l_dx, l_dy;\n\n /* precinct width and height */\n l_pdx = l_tccp->prcw[resno];\n l_pdy = l_tccp->prch[resno];\n\n l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));\n l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));\n\n /* take the minimum size for dx for each comp and resolution */\n *p_dx_min = opj_uint_min(*p_dx_min, l_dx);\n *p_dy_min = opj_uint_min(*p_dy_min, l_dy);\n\n /* various calculations of extents */\n l_level_no = l_tccp->numresolutions - 1 - resno;\n\n l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);\n l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);\n l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);\n l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);\n\n l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;\n l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;\n l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;\n\n py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;\n\n l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);\n l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);\n\n l_product = l_pw * l_ph;\n\n /* update precision */\n if (l_product > *p_max_prec) {\n *p_max_prec = l_product;\n }\n }\n ++l_img_comp;\n ++l_tccp;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-190", "source": "SVEN-before", "vuln_type": "cwe-190", "token_labels": {"evidence": [[1329, 1801]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1329, 1801]]}, "_func_name": "opj_get_encoding_parameters", "_file_name": "src/lib/openjp2/pi.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "acc_ctx_cont(OM_uint32 *minstat,\n\t gss_buffer_t buf,\n\t gss_ctx_id_t *ctx,\n\t gss_buffer_t *responseToken,\n\t gss_buffer_t *mechListMIC,\n\t OM_uint32 *negState,\n\t send_token_flag *return_token)\n{\n\tOM_uint32 ret, tmpmin;\n\tgss_OID supportedMech;\n\tspnego_gss_ctx_id_t sc;\n\tunsigned int len;\n\tunsigned char *ptr, *bufstart;\n\n\tsc = (spnego_gss_ctx_id_t)*ctx;\n\tret = GSS_S_DEFECTIVE_TOKEN;\n\t*negState = REJECT;\n\t*minstat = 0;\n\tsupportedMech = GSS_C_NO_OID;\n\t*return_token = ERROR_TOKEN_SEND;\n\t*responseToken = *mechListMIC = GSS_C_NO_BUFFER;\n\n\tptr = bufstart = buf->value;\n#define REMAIN (buf->length - (ptr - bufstart))\n\tif (REMAIN == 0 || REMAIN > INT_MAX)\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\n\t/*\n\t * Attempt to work with old Sun SPNEGO.\n\t */\n\tif (*ptr == HEADER_ID) {\n\t\tret = g_verify_token_header(gss_mech_spnego,\n\t\t\t\t\t &len, &ptr, 0, REMAIN);\n\t\tif (ret) {\n\t\t\t*minstat = ret;\n\t\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t\t}\n\t}\n\tif (*ptr != (CONTEXT | 0x01)) {\n\t\treturn GSS_S_DEFECTIVE_TOKEN;\n\t}\n\tret = get_negTokenResp(minstat, ptr, REMAIN,\n\t\t\t negState, &supportedMech,\n\t\t\t responseToken, mechListMIC);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\tif (*responseToken == GSS_C_NO_BUFFER &&\n\t *mechListMIC == GSS_C_NO_BUFFER) {\n\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tret = GSS_S_DEFECTIVE_TOKEN;\n\t\tgoto cleanup;\n\t}\n\tsc->firstpass = 0;\n\t*negState = ACCEPT_INCOMPLETE;\n\t*return_token = CONT_TOKEN_SEND;\ncleanup:\n\tif (supportedMech != GSS_C_NO_OID) {\n\t\tgeneric_gss_release_oid(&tmpmin, &supportedMech);\n\t}\n\treturn ret;\n#undef REMAIN\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "acc_ctx_cont", "_file_name": "src/lib/gssapi/spnego/spnego_mech.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def install(filename, target):\n '''Run a package's installer script against the given target directory.'''\n print(' Unpacking %s...' % filename)\n subprocess.check_call(['tar', 'xf', filename])\n basename = filename.split('.tar')[0]\n print(' Installing %s...' % basename)\n install_cmd = [os.path.join(basename, 'install.sh')]\n install_cmd += ['--prefix=' + os.path.abspath(target)]\n install_cmd += ['--disable-ldconfig']\n subprocess.check_call(install_cmd)\n print(' Cleaning %s...' % basename)\n subprocess.check_call(['rm', '-rf', basename])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "install", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def add_article_action(request: HttpRequest, default_foreward_url: str):\n forward_url: str = default_foreward_url\n if request.GET.get(\"redirect\"):\n forward_url = request.GET[\"redirect\"]\n else:\n forward_url = \"/admin\"\n if \"rid\" not in request.GET:\n return HttpResponseRedirect(\"/admin?error=Missing%20reservation%20id%20in%20request\")\n u: Profile = get_current_user(request)\n current_reservation = GroupReservation.objects.get(id=str(request.GET[\"rid\"]))\n if current_reservation.createdByUser != u and u.rights < 2:\n return HttpResponseRedirect(\"/admin?error=noyb\")\n if current_reservation.submitted == True:\n return HttpResponseRedirect(\"/admin?error=Already%20submitted\")\n # Test for multiple or single article\n if \"article_id\" in request.POST:\n # Actual adding of article\n aid: int = int(request.GET.get(\"article_id\"))\n quantity: int = int(request.POST[\"quantity\"])\n notes: str = request.POST[\"notes\"]\n ar = ArticleRequested()\n ar.AID = Article.objects.get(id=aid)\n ar.RID = current_reservation\n if \"srid\" in request.GET:\n ar.SRID = SubReservation.objects.get(id=int(request.GET[\"srid\"]))\n ar.amount = quantity\n ar.notes = notes\n ar.save()\n # Actual adding of multiple articles\n else:\n if \"group_id\" not in request.GET:\n return HttpResponseRedirect(\"/admin?error=missing%20group%20id\")\n g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET[\"group_id\"]))\n for art in Article.objects.all().filter(group=g):\n if str(\"quantity_\" + str(art.id)) not in request.POST or str(\"notes_\" + str(art.id)) not in request.POST:\n return HttpResponseRedirect(\"/admin?error=Missing%20article%20data%20in%20request\")\n amount = int(request.POST[\"quantity_\" + str(art.id)])\n if amount > 0:\n ar = ArticleRequested()\n ar.AID = art\n ar.RID = current_reservation\n ar.amount = amount\n if \"srid\" in request.GET:\n ar.SRID = SubReservation.objects.get(id=int(request.GET[\"srid\"]))\n ar.notes = str(request.POST[str(\"notes_\" + str(art.id))])\n ar.save()\n if \"srid\" in request.GET:\n response = HttpResponseRedirect(forward_url + \"?rid=\" + str(current_reservation.id) + \"&srid=\" + request.GET[\"srid\"])\n else:\n response = HttpResponseRedirect(forward_url + \"?rid=\" + str(current_reservation.id))\n return response", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[954, 997], [2195, 2269]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[954, 997], [2195, 2269]]}, "_func_name": "add_article_action", "_file_name": "c3shop/frontpage/management/reservation_actions.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)\n{\n SSL_CTX *ssl_ctx = NULL;\n SSL *ssl = NULL;\n int n, finished = 0;\n X509_VERIFY_PARAM *param;\n uint8_t verify_crls;\n\n if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))\n {\n rfbClientLog(\"Could not create new SSL context.\\n\");\n return NULL;\n }\n\n param = X509_VERIFY_PARAM_new();\n\n /* Setup verification if not anonymous */\n if (!anonTLS)\n {\n verify_crls = cred->x509Credential.x509CrlVerifyMode;\n if (cred->x509Credential.x509CACertFile)\n {\n if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))\n {\n rfbClientLog(\"Failed to load CA certificate from %s.\\n\",\n cred->x509Credential.x509CACertFile);\n goto error_free_ctx;\n }\n } else {\n rfbClientLog(\"Using default paths for certificate verification.\\n\");\n SSL_CTX_set_default_verify_paths (ssl_ctx);\n }\n\n if (cred->x509Credential.x509CACrlFile)\n {\n if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))\n {\n rfbClientLog(\"CRLs could not be loaded.\\n\");\n goto error_free_ctx;\n }\n if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;\n }\n\n if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)\n {\n if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)\n {\n rfbClientLog(\"Client certificate could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,\n SSL_FILETYPE_PEM) != 1)\n {\n rfbClientLog(\"Client private key could not be loaded.\\n\");\n goto error_free_ctx;\n }\n\n if (SSL_CTX_check_private_key(ssl_ctx) == 0) {\n rfbClientLog(\"Client certificate and private key do not match.\\n\");\n goto error_free_ctx;\n }\n }\n\n SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);\n\n if (verify_crls == rfbX509CrlVerifyClient) \n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);\n else if (verify_crls == rfbX509CrlVerifyAll)\n X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);\n\n if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))\n {\n rfbClientLog(\"Could not set server name for verification.\\n\");\n goto error_free_ctx;\n }\n SSL_CTX_set1_param(ssl_ctx, param);\n }\n\n if (!(ssl = SSL_new (ssl_ctx)))\n {\n rfbClientLog(\"Could not create a new SSL session.\\n\");\n goto error_free_ctx;\n }\n\n /* TODO: finetune this list, take into account anonTLS bool */\n SSL_set_cipher_list(ssl, \"ALL\");\n\n SSL_set_fd (ssl, sockfd);\n SSL_CTX_set_app_data (ssl_ctx, client);\n\n do\n {\n n = SSL_connect(ssl);\n\t\t\n if (n != 1) \n {\n if (wait_for_data(ssl, n, 1) != 1) \n {\n finished = 1;\n SSL_shutdown(ssl);\n\n goto error_free_ssl;\n }\n }\n } while( n != 1 && finished != 1 );\n\n X509_VERIFY_PARAM_free(param);\n return ssl;\n\nerror_free_ssl:\n SSL_free(ssl);\n\nerror_free_ctx:\n X509_VERIFY_PARAM_free(param);\n SSL_CTX_free(ssl_ctx);\n\n return NULL;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "open_ssl_connection", "_file_name": "libvncclient/tls_openssl.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def add_translationname(self, trname):\n \"\"\"Add new translation by item name for an item.\"\"\"\n if self.connection:\n for item in self.find_item_name([trname[0], '0']):\n t = (item[0], trname[1], trname[2], )\n self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (?, ?, ?)', t)\n self.connection.commit()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "add_translationname", "_file_name": "ecosldb/ecosldb.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,\n\t\t\t int class_index, int *methods, int *sym_count) {\n\tstruct r_bin_t *rbin = binfile->rbin;\n\n\tchar *class_name;\n\tint z;\n\tconst ut8 *p, *p_end;\n\n\tif (!c) {\n\t\treturn;\n\t}\n\n\tclass_name = dex_class_name (bin, c);\n\tclass_name = r_str_replace (class_name, \";\", \"\", 0); //TODO: move to func\n\n\tif (!class_name || !*class_name) {\n\t\treturn;\n\t}\n\n\tRBinClass *cls = R_NEW0 (RBinClass);\n\tif (!cls) {\n\t\treturn;\n\t}\n\tcls->name = class_name;\n\tcls->index = class_index;\n\tcls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;\n\tcls->methods = r_list_new ();\n\tif (!cls->methods) {\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tcls->fields = r_list_new ();\n\tif (!cls->fields) {\n\t\tr_list_free (cls->methods);\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tr_list_append (bin->classes_list, cls);\n\tif (dexdump) {\n\t\trbin->cb_printf (\" Class descriptor : '%s;'\\n\", class_name);\n\t\trbin->cb_printf (\n\t\t\t\" Access flags : 0x%04x (%s)\\n\", c->access_flags,\n\t\t\tcreateAccessFlagStr (c->access_flags, kAccessForClass));\n\t\trbin->cb_printf (\" Superclass : '%s'\\n\",\n\t\t\t\t dex_class_super_name (bin, c));\n\t\trbin->cb_printf (\" Interfaces -\\n\");\n\t}\n\n\tif (c->interfaces_offset > 0 &&\n\t bin->header.data_offset < c->interfaces_offset &&\n\t c->interfaces_offset <\n\t\t bin->header.data_offset + bin->header.data_size) {\n\t\tp = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);\n\t\tint types_list_size = r_read_le32 (p);\n\t\tif (types_list_size < 0 || types_list_size >= bin->header.types_size ) {\n\t\t\treturn;\n\t\t}\n\t\tfor (z = 0; z < types_list_size; z++) {\n\t\t\tint t = r_read_le16 (p + 4 + z * 2);\n\t\t\tif (t > 0 && t < bin->header.types_size ) {\n\t\t\t\tint tid = bin->types[t].descriptor_id;\n\t\t\t\tif (dexdump) {\n\t\t\t\t\trbin->cb_printf (\n\t\t\t\t\t\t\" #%d : '%s'\\n\",\n\t\t\t\t\t\tz, getstr (bin, tid));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: this is quite ugly\n\tif (!c || !c->class_data_offset) {\n\t\tif (dexdump) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" Static fields -\\n Instance fields \"\n\t\t\t\t\"-\\n Direct methods -\\n Virtual methods \"\n\t\t\t\t\"-\\n\");\n\t\t}\n\t} else {\n\t\t// TODO: move to func, def or inline\n\t\t// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]\n\t\tif (bin->header.class_offset > c->class_data_offset ||\n\t\t c->class_data_offset <\n\t\t\t bin->header.class_offset +\n\t\t\t\t bin->header.class_size * DEX_CLASS_SIZE) {\n\t\t\treturn;\n\t\t}\n\n\t\tp = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);\n\t\tp_end = p + binfile->buf->length - c->class_data_offset;\n\t\t//XXX check for NULL!!\n\t\tc->class_data = (struct dex_class_data_item_t *)malloc (\n\t\t\tsizeof (struct dex_class_data_item_t));\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Static fields -\\n\"); \n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->static_fields_size, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Instance fields -\\n\");\n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->instance_fields_size, false);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Direct methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->direct_methods_size, methods, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Virtual methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->virtual_methods_size, methods, false);\n\t}\n\n\tif (dexdump) { \n\t\tchar *source_file = getstr (bin, c->source_file);\n\t\tif (!source_file) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" source_file_idx : %d (unknown)\\n\\n\",\n\t\t\t\tc->source_file);\n\t\t} else {\n\t\t\trbin->cb_printf (\" source_file_idx : %d (%s)\\n\\n\",\n\t\t\t\t\t c->source_file, source_file);\n\t\t}\n\t}\n\t// TODO:!!!!\n\t// FIX: FREE BEFORE ALLOCATE!!!\n\t//free (class_name);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "parse_class", "_file_name": "libr/bin/p/bin_dex.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _remove_volume_set(self, vvs_name):\n # Must first clear the QoS rules before removing the volume set\n self._cli_run(['setqos', '-clear', 'vvset:%s' % (vvs_name)])\n self._cli_run(['removevvset', '-f', vvs_name])", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_remove_volume_set", "_file_name": "cinder/volume/drivers/san/hp/hp_3par_common.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool handle_client_startup(PgSocket *client, PktHdr *pkt)\n{\n\tconst char *passwd;\n\tconst uint8_t *key;\n\tbool ok;\n\n\tSBuf *sbuf = &client->sbuf;\n\n\t/* don't tolerate partial packets */\n\tif (incomplete_pkt(pkt)) {\n\t\tdisconnect_client(client, true, \"client sent partial pkt in startup phase\");\n\t\treturn false;\n\t}\n\n\tif (client->wait_for_welcome) {\n\t\tif (finish_client_login(client)) {\n\t\t\t/* the packet was already parsed */\n\t\t\tsbuf_prepare_skip(sbuf, pkt->len);\n\t\t\treturn true;\n\t\t} else\n\t\t\treturn false;\n\t}\n\n\tswitch (pkt->type) {\n\tcase PKT_SSLREQ:\n\t\tslog_noise(client, \"C: req SSL\");\n\t\tslog_noise(client, \"P: nak\");\n\n\t\t/* reject SSL attempt */\n\t\tif (!sbuf_answer(&client->sbuf, \"N\", 1)) {\n\t\t\tdisconnect_client(client, false, \"failed to nak SSL\");\n\t\t\treturn false;\n\t\t}\n\t\tbreak;\n\tcase PKT_STARTUP_V2:\n\t\tdisconnect_client(client, true, \"Old V2 protocol not supported\");\n\t\treturn false;\n\tcase PKT_STARTUP:\n\t\tif (client->pool) {\n\t\t\tdisconnect_client(client, true, \"client re-sent startup pkt\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!decide_startup_pool(client, pkt))\n\t\t\treturn false;\n\n\t\tif (client->pool->db->admin) {\n\t\t\tif (!admin_pre_login(client))\n\t\t\t\treturn false;\n\t\t}\n\n\t\tif (cf_auth_type <= AUTH_TRUST || client->own_user) {\n\t\t\tif (!finish_client_login(client))\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tif (!send_client_authreq(client)) {\n\t\t\t\tdisconnect_client(client, false, \"failed to send auth req\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 'p':\t\t/* PasswordMessage */\n\t\t/* too early */\n\t\tif (!client->auth_user) {\n\t\t\tdisconnect_client(client, true, \"client password pkt before startup packet\");\n\t\t\treturn false;\n\t\t}\n\n\t\t/* haven't requested it */\n\t\tif (cf_auth_type <= AUTH_TRUST) {\n\t\t\tdisconnect_client(client, true, \"unrequested passwd pkt\");\n\t\t\treturn false;\n\t\t}\n\n\t\tok = mbuf_get_string(&pkt->data, &passwd);\n\t\tif (ok && check_client_passwd(client, passwd)) {\n\t\t\tif (!finish_client_login(client))\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\tdisconnect_client(client, true, \"Auth failed\");\n\t\t\treturn false;\n\t\t}\n\t\tbreak;\n\tcase PKT_CANCEL:\n\t\tif (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN\n\t\t && mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))\n\t\t{\n\t\t\tmemcpy(client->cancel_key, key, BACKENDKEY_LEN);\n\t\t\taccept_cancel_request(client);\n\t\t} else\n\t\t\tdisconnect_client(client, false, \"bad cancel request\");\n\t\treturn false;\n\tdefault:\n\t\tdisconnect_client(client, false, \"bad packet\");\n\t\treturn false;\n\t}\n\tsbuf_prepare_skip(sbuf, pkt->len);\n\tclient->request_time = get_cached_time();\n\treturn true;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "handle_client_startup", "_file_name": "src/client.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "@check_document_access_permission()\ndef edit_bundle(request):\n bundle_id = request.GET.get('bundle')\n doc = None\n \n if bundle_id:\n doc = Document2.objects.get(id=bundle_id)\n bundle = Bundle(document=doc)\n else:\n bundle = Bundle()\n\n coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)])\n for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')]\n\n return render('editor/bundle_editor.mako', request, {\n 'bundle_json': bundle.json_for_html(),\n 'coordinators_json': json.dumps(coordinators, cls=JSONEncoderForHTML),\n 'doc1_id': doc.doc.get().id if doc else -1,\n 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) \n })", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "edit_bundle", "_file_name": "apps/oozie/src/oozie/views/editor2.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)\n{\n#ifndef PB_ENABLE_MALLOC\n PB_UNUSED(wire_type);\n PB_UNUSED(field);\n PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n switch (PB_HTYPE(field->type))\n {\n case PB_HTYPE_REQUIRED:\n case PB_HTYPE_OPTIONAL:\n case PB_HTYPE_ONEOF:\n if (!check_wire_type(wire_type, field))\n PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)\n {\n /* Duplicate field, have to release the old allocation first. */\n /* FIXME: Does this work correctly for oneofs? */\n pb_release_single_field(field);\n }\n \n if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)\n {\n *(pb_size_t*)field->pSize = field->tag;\n }\n\n if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||\n PB_LTYPE(field->type) == PB_LTYPE_BYTES)\n {\n /* pb_dec_string and pb_dec_bytes handle allocation themselves */\n field->pData = field->pField;\n return decode_basic_field(stream, field);\n }\n else\n {\n if (!allocate_field(stream, field->pField, field->data_size, 1))\n return false;\n \n field->pData = *(void**)field->pField;\n initialize_pointer_field(field->pData, field);\n return decode_basic_field(stream, field);\n }\n \n case PB_HTYPE_REPEATED:\n if (wire_type == PB_WT_STRING\n && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)\n {\n /* Packed array, multiple items come in at once. */\n bool status = true;\n pb_size_t *size = (pb_size_t*)field->pSize;\n size_t allocated_size = *size;\n pb_istream_t substream;\n \n if (!pb_make_string_substream(stream, &substream))\n return false;\n \n while (substream.bytes_left)\n {\n if ((size_t)*size + 1 > allocated_size)\n {\n /* Allocate more storage. This tries to guess the\n * number of remaining entries. Round the division\n * upwards. */\n allocated_size += (substream.bytes_left - 1) / field->data_size + 1;\n \n if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))\n {\n status = false;\n break;\n }\n }\n\n /* Decode the array entry */\n field->pData = *(char**)field->pField + field->data_size * (*size);\n initialize_pointer_field(field->pData, field);\n if (!decode_basic_field(&substream, field))\n {\n status = false;\n break;\n }\n \n if (*size == PB_SIZE_MAX)\n {\n#ifndef PB_NO_ERRMSG\n stream->errmsg = \"too many array entries\";\n#endif\n status = false;\n break;\n }\n \n (*size)++;\n }\n if (!pb_close_string_substream(stream, &substream))\n return false;\n \n return status;\n }\n else\n {\n /* Normal repeated field, i.e. only one item at a time. */\n pb_size_t *size = (pb_size_t*)field->pSize;\n\n if (*size == PB_SIZE_MAX)\n PB_RETURN_ERROR(stream, \"too many array entries\");\n \n if (!check_wire_type(wire_type, field))\n PB_RETURN_ERROR(stream, \"wrong wire type\");\n\n (*size)++;\n if (!allocate_field(stream, field->pField, field->data_size, *size))\n return false;\n \n field->pData = *(char**)field->pField + field->data_size * (*size - 1);\n initialize_pointer_field(field->pData, field);\n return decode_basic_field(stream, field);\n }\n\n default:\n PB_RETURN_ERROR(stream, \"invalid field type\");\n }\n#endif\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[4206, 4318], [4365, 4453]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[4206, 4318], [4365, 4453]]}, "_func_name": "decode_pointer_field", "_file_name": "pb_decode.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _checkPairing():\n if winner == loser:\n raise ValueError('Attempt to match player against self')\n\n q = '''\n SELECT COUNT(*) FROM matches\n WHERE (matches.winner_id = %s AND matches.loser_id = %s)\n OR (matches.winner_id = %s AND matches.loser_id = %s);\n '''\n cur.execute(q, (winner, loser, loser, winner))\n if cur.fetchone()[0] > 0:\n raise ValueError('Pairing %s, %s already played' % (winner, loser))", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "reportMatch._checkPairing", "_file_name": "vagrant/tournament/tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def fetch(url):\n '''Download and verify a package url.'''\n base = os.path.basename(url)\n print('Fetching %s...' % base)\n fetch_file(url + '.asc')\n fetch_file(url)\n fetch_file(url + '.sha256')\n fetch_file(url + '.asc.sha256')\n print('Verifying %s...' % base)\n # TODO: check for verification failure.\n os.system('shasum -c %s.sha256' % base)\n os.system('shasum -c %s.asc.sha256' % base)\n os.system('gpg --verify %s.asc %s' % (base, base))\n os.system('keybase verify %s.asc' % base)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[308, 492]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[308, 492]]}, "_func_name": "fetch", "_file_name": "repack_rust.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;\n\n\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}\n\n\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}\n\n\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\n\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}\n\n\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);\n\n\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;\n\n\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;\n\n\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;\n\n\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);\n\n\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);\n\n\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);\n\n\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);\n\n\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}\n\n\tmr->r_trans_private = trans_private;\n\n\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);\n\n\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;\n\n\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}\n\n\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\n\tBUG_ON(found && found != mr);\n\n\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}\n\n\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[349, 380]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[349, 380]]}, "_func_name": "__rds_rdma_map", "_file_name": "net/rds/rdma.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "def _inject_key_into_fs(key, fs, execute=None):\n \"\"\"Add the given public ssh key to root's authorized_keys.\n\n key is an ssh key string.\n fs is the path to the base of the filesystem into which to inject the key.\n \"\"\"\n sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh')\n utils.execute('mkdir', '-p', sshdir, run_as_root=True)\n utils.execute('chown', 'root', sshdir, run_as_root=True)\n utils.execute('chmod', '700', sshdir, run_as_root=True)\n\n keyfile = os.path.join('root', '.ssh', 'authorized_keys')\n\n key_data = ''.join([\n '\\n',\n '# The following ssh key was injected by Nova',\n '\\n',\n key.strip(),\n '\\n',\n ])\n\n _inject_file_into_fs(fs, keyfile, key_data, append=True)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_inject_key_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " @staticmethod\n def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:\n \"\"\" Get all projects a user has mapped on \"\"\"\n\n # This query looks scary, but we're really just creating an outer join between the query that gets the\n # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to\n # handle cases where users have only validated tasks on a project, or only mapped on a project.\n sql = '''SELECT p.id,\n p.status,\n p.default_locale,\n c.mapped,\n c.validated,\n st_asgeojson(p.centroid)\n FROM projects p,\n (SELECT coalesce(v.project_id, m.project_id) project_id,\n coalesce(v.validated, 0) validated,\n coalesce(m.mapped, 0) mapped\n FROM (SELECT t.project_id,\n count (t.validated_by) validated\n FROM tasks t\n WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n AND t.validated_by = {0}\n GROUP BY t.project_id, t.validated_by) v\n FULL OUTER JOIN\n (SELECT t.project_id,\n count(t.mapped_by) mapped\n FROM tasks t\n WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n AND t.mapped_by = {0}\n GROUP BY t.project_id, t.mapped_by) m\n ON v.project_id = m.project_id) c\n WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id)\n\n results = db.engine.execute(sql)\n\n if results.rowcount == 0:\n raise NotFound()\n\n mapped_projects_dto = UserMappedProjectsDTO()\n for row in results:\n mapped_project = MappedProject()\n mapped_project.project_id = row[0]\n mapped_project.status = ProjectStatus(row[1]).name\n mapped_project.tasks_mapped = row[3]\n mapped_project.tasks_validated = row[4]\n mapped_project.centroid = geojson.loads(row[5])\n\n project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])\n mapped_project.name = project_info.name\n\n mapped_projects_dto.mapped_projects.append(mapped_project)\n\n return mapped_projects_dto", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[1137, 1311], [1570, 1727], [1850, 1933]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1137, 1311], [1570, 1727], [1850, 1933]]}, "_func_name": "get_mapped_projects", "_file_name": "server/models/postgis/user.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _delete_vdisk(self, name, force):\n \"\"\"Deletes existing vdisks.\n\n It is very important to properly take care of mappings before deleting\n the disk:\n 1. If no mappings, then it was a vdisk, and can be deleted\n 2. If it is the source of a flashcopy mapping and copy_rate is 0, then\n it is a vdisk that has a snapshot. If the force flag is set,\n delete the mapping and the vdisk, otherwise set the mapping to\n copy and wait (this will allow users to delete vdisks that have\n snapshots if/when the upper layers allow it).\n 3. If it is the target of a mapping and copy_rate is 0, it is a\n snapshot, and we should properly stop the mapping and delete.\n 4. If it is the source/target of a mapping and copy_rate is not 0, it\n is a clone or vdisk created from a snapshot. We wait for the copy\n to complete (the mapping will be autodeleted) and then delete the\n vdisk.\n\n \"\"\"\n\n LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name)\n\n # Try to delete volume only if found on the storage\n vdisk_defined = self._is_vdisk_defined(name)\n if not vdisk_defined:\n LOG.info(_('warning: Tried to delete vdisk %s but it does not '\n 'exist.') % name)\n return\n\n self._ensure_vdisk_no_fc_mappings(name)\n\n ssh_cmd = ['svctask', 'rmvdisk', '-force', name]\n if not force:\n ssh_cmd.remove('-force')\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmvdisk\n self._assert_ssh_return(len(out.strip()) == 0,\n ('_delete_vdisk %(name)s')\n % {'name': name},\n ssh_cmd, out, err)\n LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_delete_vdisk", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {\n\tut8 op_byte = data[0];\n\tut64 offset = addr - java_get_method_start ();\n\tut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;\n\n\tif (op_byte == 0xaa) {\n\t\t// handle a table switch condition\n\t\tif (pos + 8 > len) {\n\t\t\treturn op->size;\n\t\t}\n\t\tint min_val = (ut32)(UINT (data, pos + 4)),\n\t\t\tmax_val = (ut32)(UINT (data, pos + 8));\n\n\t\tut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;\n\t\top->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);\n\t\tRAnalCaseOp *caseop = NULL;\n\t\tpos += 12;\n\t\tif (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {\n\t\t\t//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);\n\t\t\tfor (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {\n\t\t\t\t//ut32 value = (ut32)(UINT (data, pos));\n\t\t\t\tif (pos + 4 >= len) {\n\t\t\t\t\t// switch is too big cant read further\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));\n\t\t\t\tcaseop = r_anal_switch_op_add_case (op->switch_op,\n\t\t\t\t\taddr + pos, cur_case + min_val, addr + offset);\n\t\t\t\tif (caseop) {\n\t\t\t\t\tcaseop->bb_ref_to = addr+offset;\n\t\t\t\t\tcaseop->bb_ref_from = addr; // TODO figure this one out\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\teprintf (\"Invalid switch boundaries at 0x%\"PFMT64x\"\\n\", addr);\n\t\t}\n\t}\n\top->size = pos;\n\treturn op->size;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[324, 413]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[324, 413]]}, "_func_name": "java_switch_op", "_file_name": "libr/anal/p/anal_java.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)\n{\n uint32_t w, h;\n uint32_t shift;\n uint32_t leftbyte;\n uint8_t *ss;\n uint8_t *dd;\n uint8_t leftmask, rightmask;\n int early = x >= 0;\n int late;\n uint32_t bytewidth;\n uint32_t syoffset = 0;\n\n if (src == NULL)\n return 0;\n\n if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||\n (UINT32_MAX - src->height < (y > 0 ? y : -y)))\n {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"overflow in compose_image\");\n#endif\n return 0;\n }\n\n /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */\n\n /* Data is packed msb first within a byte, so with bits numbered: 01234567.\n * Second byte is: 89abcdef. So to combine into a run, we use:\n * (s[0]<<8) | s[1] == 0123456789abcdef.\n * To read from src into dst at offset 3, we need to read:\n * read: 0123456789abcdef...\n * write: 0123456798abcdef...\n * In general, to read from src and write into dst at offset x, we need to shift\n * down by (x&7) bits to allow for bit alignment. So shift = x&7.\n * So the 'central' part of our runs will see us doing:\n * *d++ op= ((s[0]<<8)|s[1])>>shift;\n * with special cases on the left and right edges of the run to mask.\n * With the left hand edge, we have to be careful not to 'underread' the start of\n * the src image; this is what the early flag is about. Similarly we have to be\n * careful not to read off the right hand edge; this is what the late flag is for.\n */\n\n /* clip */\n w = src->width;\n h = src->height;\n shift = (x & 7);\n ss = src->data - early;\n\n if (x < 0) {\n if (w < (uint32_t) -x)\n w = 0;\n else\n w += x;\n ss += (-x-1)>>3;\n x = 0;\n }\n if (y < 0) {\n if (h < (uint32_t) -y)\n h = 0;\n else\n h += y;\n syoffset = -y * src->stride;\n y = 0;\n }\n if ((uint32_t)x + w > dst->width)\n {\n if (dst->width < (uint32_t)x)\n w = 0;\n else\n w = dst->width - x;\n }\n if ((uint32_t)y + h > dst->height)\n {\n if (dst->height < (uint32_t)y)\n h = 0;\n else\n h = dst->height - y;\n }\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"compositing %dx%d at (%d, %d) after clipping\", w, h, x, y);\n#endif\n\n /* check for zero clipping region */\n if ((w <= 0) || (h <= 0)) {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"zero clipping region\");\n#endif\n return 0;\n }\n\n leftbyte = (uint32_t) x >> 3;\n dd = dst->data + y * dst->stride + leftbyte;\n bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1;\n leftmask = 255>>(x&7);\n rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7));\n if (bytewidth == 1)\n leftmask &= rightmask;\n late = (ss + bytewidth >= src->data + ((src->width+7)>>3));\n ss += syoffset;\n\n switch(op)\n {\n case JBIG2_COMPOSE_OR:\n jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_AND:\n jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_XOR:\n jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_XNOR:\n jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n case JBIG2_COMPOSE_REPLACE:\n jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);\n break;\n }\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "jbig2_image_compose", "_file_name": "jbig2_image.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static int mailimf_group_parse(const char * message, size_t length,\n\t\t\t size_t * indx,\n\t\t\t struct mailimf_group ** result)\n{\n size_t cur_token;\n char * display_name;\n struct mailimf_mailbox_list * mailbox_list;\n struct mailimf_group * group;\n int r;\n int res;\n clist * list;\n\n cur_token = * indx;\n\n mailbox_list = NULL;\n\n r = mailimf_display_name_parse(message, length, &cur_token, &display_name);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto err;\n }\n\n r = mailimf_colon_parse(message, length, &cur_token);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto free_display_name;\n }\n\n r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);\n switch (r) {\n case MAILIMF_NO_ERROR:\n break;\n case MAILIMF_ERROR_PARSE:\n r = mailimf_cfws_parse(message, length, &cur_token);\n if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {\n res = r;\n goto free_display_name;\n }\n list = clist_new();\n if (list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n goto free_display_name;\n }\n mailbox_list = mailimf_mailbox_list_new(list);\n if (mailbox_list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n clist_free(list);\n goto free_display_name;\n }\n break;\n default:\n res = r;\n goto free_display_name;\n }\n\n r = mailimf_semi_colon_parse(message, length, &cur_token);\n if (r != MAILIMF_NO_ERROR) {\n res = r;\n goto free_mailbox_list;\n }\n\n group = mailimf_group_new(display_name, mailbox_list);\n if (group == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n goto free_mailbox_list;\n }\n\n * indx = cur_token;\n * result = group;\n\n return MAILIMF_NO_ERROR;\n\n free_mailbox_list:\n if (mailbox_list != NULL) {\n mailimf_mailbox_list_free(mailbox_list);\n }\n free_display_name:\n mailimf_display_name_free(display_name);\n err:\n return res;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "mailimf_group_parse", "_file_name": "src/low-level/imf/mailimf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def extend_volume(self, volume, new_size):\n LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])\n ret = self._ensure_vdisk_no_fc_mappings(volume['name'],\n allow_snaps=False)\n if not ret:\n exception_message = (_('extend_volume: Extending a volume with '\n 'snapshots is not supported.'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n extend_amt = int(new_size) - volume['size']\n ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s'\n % {'amt': extend_amt, 'name': volume['name']})\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from expandvdisksize\n self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',\n ssh_cmd, out, err)\n LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[544, 687]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[544, 687]]}, "_func_name": "extend_volume", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info,\n Image *images,const char *filename,ExceptionInfo *exception)\n{\n#define WriteImageTag \"Write/Image\"\n\n ExceptionInfo\n *sans_exception;\n\n ImageInfo\n *write_info;\n\n MagickBooleanType\n proceed;\n\n MagickOffsetType\n progress;\n\n MagickProgressMonitor\n progress_monitor;\n\n MagickSizeType\n number_images;\n\n MagickStatusType\n status;\n\n register Image\n *p;\n\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(images != (Image *) NULL);\n assert(images->signature == MagickCoreSignature);\n if (images->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",images->filename);\n assert(exception != (ExceptionInfo *) NULL);\n write_info=CloneImageInfo(image_info);\n *write_info->magick='\\0';\n images=GetFirstImageInList(images);\n if (filename != (const char *) NULL)\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n (void) CopyMagickString(p->filename,filename,MagickPathExtent);\n (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent);\n sans_exception=AcquireExceptionInfo();\n (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images),\n sans_exception);\n sans_exception=DestroyExceptionInfo(sans_exception);\n if (*write_info->magick == '\\0')\n (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent);\n p=images;\n for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p))\n if (p->scene >= GetNextImageInList(p)->scene)\n {\n register ssize_t\n i;\n\n /*\n Generate consistent scene numbers.\n */\n i=(ssize_t) images->scene;\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n p->scene=(size_t) i++;\n break;\n }\n /*\n Write images.\n */\n status=MagickTrue;\n progress_monitor=(MagickProgressMonitor) NULL;\n progress=0;\n number_images=GetImageListLength(images);\n for (p=images; p != (Image *) NULL; p=GetNextImageInList(p))\n {\n if (number_images != 1)\n progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL,\n p->client_data);\n status&=WriteImage(write_info,p,exception);\n if (number_images != 1)\n (void) SetImageProgressMonitor(p,progress_monitor,p->client_data);\n if (write_info->adjoin != MagickFalse)\n break;\n if (number_images != 1)\n {\n proceed=SetImageProgress(p,WriteImageTag,progress++,number_images);\n if (proceed == MagickFalse)\n break;\n }\n }\n write_info=DestroyImageInfo(write_info);\n return(status != 0 ? MagickTrue : MagickFalse);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1570, 1620]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1570, 1620]]}, "_func_name": "WriteImages", "_file_name": "MagickCore/constitute.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "void ImportEPUB::ExtractContainer()\n{\n int res = 0;\n if (!cp437) {\n cp437 = new QCodePage437Codec();\n }\n#ifdef Q_OS_WIN32\n zlib_filefunc64_def ffunc;\n fill_win32_filefunc64W(&ffunc);\n unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(m_FullFilePath)).c_str(), &ffunc);\n#else\n unzFile zfile = unzOpen64(QDir::toNativeSeparators(m_FullFilePath).toUtf8().constData());\n#endif\n\n if (zfile == NULL) {\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot unzip EPUB: %1\")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));\n }\n\n res = unzGoToFirstFile(zfile);\n\n if (res == UNZ_OK) {\n do {\n // Get the name of the file in the archive.\n char file_name[MAX_PATH] = {0};\n unz_file_info64 file_info;\n unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0);\n QString qfile_name;\n QString cp437_file_name;\n qfile_name = QString::fromUtf8(file_name);\n if (!(file_info.flag & (1<<11))) {\n // General purpose bit 11 says the filename is utf-8 encoded. If not set then\n // IBM 437 encoding might be used.\n cp437_file_name = cp437->toUnicode(file_name);\n }\n\n // If there is no file name then we can't do anything with it.\n if (!qfile_name.isEmpty()) {\n // We use the dir object to create the path in the temporary directory.\n // Unfortunately, we need a dir ojbect to do this as it's not a static function.\n QDir dir(m_ExtractedFolderPath);\n // Full file path in the temporary directory.\n QString file_path = m_ExtractedFolderPath + \"/\" + qfile_name;\n QFileInfo qfile_info(file_path);\n\n // Is this entry a directory?\n if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) {\n dir.mkpath(qfile_name);\n continue;\n } else {\n dir.mkpath(qfile_info.path());\n\t\t // add it to the list of files found inside the zip\n\t\t if (cp437_file_name.isEmpty()) {\n\t\t m_ZipFilePaths << qfile_name;\n\t\t } else {\n m_ZipFilePaths << cp437_file_name;\n\t\t }\n }\n\n // Open the file entry in the archive for reading.\n if (unzOpenCurrentFile(zfile) != UNZ_OK) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // Open the file on disk to write the entry in the archive to.\n QFile entry(file_path);\n\n if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // Buffered reading and writing.\n char buff[BUFF_SIZE] = {0};\n int read = 0;\n\n while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) {\n entry.write(buff, read);\n }\n\n entry.close();\n\n // Read errors are marked by a negative read amount.\n if (read < 0) {\n unzCloseCurrentFile(zfile);\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n\n // The file was read but the CRC did not match.\n // We don't check the read file size vs the uncompressed file size\n // because if they're different there should be a CRC error.\n if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot extract file: %1\")).arg(qfile_name).toStdString()));\n }\n if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) {\n QString cp437_file_path = m_ExtractedFolderPath + \"/\" + cp437_file_name;\n QFile::copy(file_path, cp437_file_path);\n }\n }\n } while ((res = unzGoToNextFile(zfile)) == UNZ_OK);\n }\n\n if (res != UNZ_END_OF_LIST_OF_FILE) {\n unzClose(zfile);\n throw (EPUBLoadParseError(QString(QObject::tr(\"Cannot open EPUB: %1\")).arg(QDir::toNativeSeparators(m_FullFilePath)).toStdString()));\n }\n\n unzClose(zfile);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[1427, 1515]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1427, 1515]]}, "_func_name": "ImportEPUB::ExtractContainer", "_file_name": "src/Importers/ImportEPUB.cpp", "lang": "cpp", "label_confidence": "diff-derived"} {"code": "def _get_settings(view):\n return {\n 'linters': get_settings(view, 'anaconda_go_linters', []),\n 'lint_test': get_settings(\n view, 'anaconda_go_lint_test', False),\n 'exclude_regexps': get_settings(\n view, 'anaconda_go_exclude_regexps', []),\n 'max_line_length': get_settings(\n view, 'anaconda_go_max_line_length', 120),\n 'gocyclo_threshold': get_settings(\n view, 'anaconda_go_gocyclo_threshold', 10),\n 'golint_min_confidence': get_settings(\n view, 'anaconda_go_golint_min_confidence', 0.80),\n 'goconst_min_occurrences': get_settings(\n view, 'anaconda_go_goconst_min_occurrences', 3),\n 'min_const_length': get_settings(\n view, 'anaconda_go_min_const_length', 3),\n 'dupl_threshold': get_settings(\n view, 'anaconda_go_dupl_threshold', 50),\n 'path': os.path.dirname(view.file_name())\n }", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_get_settings", "_file_name": "lib/_sublime.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def user_verify(self):\n eid = self.email\n code = self.password\n if eid.strip() == '':\n return\n if code.strip() == '':\n return\n query = 'select * from usr where email like %s'\n cursor = g.conn.execute(query, (eid, ))\n for row in cursor:\n key = str(row.password)\n if key.strip() == code.strip():\n self.name = str(row.name)\n self.email = eid\n self.id = eid\n self.valid = True\n break", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "user_verify", "_file_name": "Web-app/User.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):\n # XXX see if we want to keep an external call here\n if verbose:\n zipoptions = \"-r\"\n else:\n zipoptions = \"-rq\"\n cmd = [\"zip\", zipoptions, zip_filename, base_dir]\n if logger is not None:\n logger.info(' '.join(cmd))\n if dry_run:\n return\n import subprocess\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError:\n # XXX really should distinguish between \"couldn't find\n # external 'zip' command\" and \"zip failed\".\n raise ExecError, \\\n (\"unable to create zip file '%s': \"\n \"could neither import the 'zipfile' module nor \"\n \"find a standalone zip utility\") % zip_filename", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_call_external_zip", "_file_name": "Lib/shutil.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n{\n\tstruct key *key;\n\tkey_ref_t key_ref;\n\tlong ret;\n\n\t/* find the key first */\n\tkey_ref = lookup_user_key(keyid, 0, 0);\n\tif (IS_ERR(key_ref)) {\n\t\tret = -ENOKEY;\n\t\tgoto error;\n\t}\n\n\tkey = key_ref_to_ptr(key_ref);\n\n\t/* see if we can read it directly */\n\tret = key_permission(key_ref, KEY_NEED_READ);\n\tif (ret == 0)\n\t\tgoto can_read_key;\n\tif (ret != -EACCES)\n\t\tgoto error2;\n\n\t/* we can't; see if it's searchable from this process's keyrings\n\t * - we automatically take account of the fact that it may be\n\t * dangling off an instantiation key\n\t */\n\tif (!is_key_possessed(key_ref)) {\n\t\tret = -EACCES;\n\t\tgoto error2;\n\t}\n\n\t/* the key is probably readable - now try to read it */\ncan_read_key:\n\tret = -EOPNOTSUPP;\n\tif (key->type->read) {\n\t\t/* Read the data with the semaphore held (since we might sleep)\n\t\t * to protect against the key being updated or revoked.\n\t\t */\n\t\tdown_read(&key->sem);\n\t\tret = key_validate(key);\n\t\tif (ret == 0)\n\t\t\tret = key->type->read(key, buffer, buflen);\n\t\tup_read(&key->sem);\n\t}\n\nerror2:\n\tkey_put(key);\nerror:\n\treturn ret;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[288, 326]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[288, 326]]}, "_func_name": "keyctl_read_key", "_file_name": "security/keys/keyctl.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _execute_command_and_parse_attributes(self, ssh_cmd):\n \"\"\"Execute command on the Storwize/SVC and parse attributes.\n\n Exception is raised if the information from the system\n can not be obtained.\n\n \"\"\"\n\n LOG.debug(_('enter: _execute_command_and_parse_attributes: '\n ' command %s') % str(ssh_cmd))\n\n try:\n out, err = self._run_ssh(ssh_cmd)\n except exception.ProcessExecutionError as e:\n # Didn't get details from the storage, return None\n LOG.error(_('CLI Exception output:\\n command: %(cmd)s\\n '\n 'stdout: %(out)s\\n stderr: %(err)s') %\n {'cmd': ssh_cmd,\n 'out': e.stdout,\n 'err': e.stderr})\n return None\n\n self._assert_ssh_return(len(out),\n '_execute_command_and_parse_attributes',\n ssh_cmd, out, err)\n attributes = {}\n for attrib_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attrib_name, foo, attrib_value = attrib_line.partition('!')\n if attrib_name is not None and len(attrib_name.strip()):\n attributes[attrib_name] = attrib_value\n\n LOG.debug(_('leave: _execute_command_and_parse_attributes:\\n'\n 'command: %(cmd)s\\n'\n 'attributes: %(attr)s')\n % {'cmd': str(ssh_cmd),\n 'attr': str(attributes)})\n\n return attributes", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_execute_command_and_parse_attributes", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,\n\t\t\t\t int tlen, int offset)\n{\n\t__wsum csum = skb->csum;\n\n\tif (skb->ip_summed != CHECKSUM_COMPLETE)\n\t\treturn;\n\n\tif (offset != 0) {\n\t\tint tend_off = skb_transport_offset(skb) + tlen;\n\t\tcsum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0));\n\t}\n\n\tput_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "ip_cmsg_recv_checksum", "_file_name": "net/ipv4/ip_sockglue.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int megasas_alloc_cmds(struct megasas_instance *instance)\n{\n\tint i;\n\tint j;\n\tu16 max_cmd;\n\tstruct megasas_cmd *cmd;\n\n\tmax_cmd = instance->max_mfi_cmds;\n\n\t/*\n\t * instance->cmd_list is an array of struct megasas_cmd pointers.\n\t * Allocate the dynamic array first and then allocate individual\n\t * commands.\n\t */\n\tinstance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);\n\n\tif (!instance->cmd_list) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"out of memory\\n\");\n\t\treturn -ENOMEM;\n\t}\n\n\tmemset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tinstance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),\n\t\t\t\t\t\tGFP_KERNEL);\n\n\t\tif (!instance->cmd_list[i]) {\n\n\t\t\tfor (j = 0; j < i; j++)\n\t\t\t\tkfree(instance->cmd_list[j]);\n\n\t\t\tkfree(instance->cmd_list);\n\t\t\tinstance->cmd_list = NULL;\n\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tfor (i = 0; i < max_cmd; i++) {\n\t\tcmd = instance->cmd_list[i];\n\t\tmemset(cmd, 0, sizeof(struct megasas_cmd));\n\t\tcmd->index = i;\n\t\tcmd->scmd = NULL;\n\t\tcmd->instance = instance;\n\n\t\tlist_add_tail(&cmd->list, &instance->cmd_pool);\n\t}\n\n\t/*\n\t * Create a frame pool and assign one frame to each cmd\n\t */\n\tif (megasas_create_frame_pool(instance)) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"Error creating frame DMA pool\\n\");\n\t\tmegasas_free_cmds(instance);\n\t}\n\n\treturn 0;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-476", "source": "SVEN-before", "vuln_type": "cwe-476", "token_labels": {"evidence": [[1333, 1336]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1333, 1336]]}, "_func_name": "megasas_alloc_cmds", "_file_name": "drivers/scsi/megaraid/megaraid_sas_base.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _add_chapsecret_to_host(self, host_name):\n \"\"\"Generate and store a randomly-generated CHAP secret for the host.\"\"\"\n\n chap_secret = utils.generate_password()\n ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from chhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_add_chapsecret_to_host', ssh_cmd, out, err)\n return chap_secret", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "_add_chapsecret_to_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n conn = connect()\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO players (name) VALUES ('%s')\" % (name,));\n conn.commit()\n conn.close()", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-089", "source": "SVEN-before", "vuln_type": "cwe-089", "token_labels": {"evidence": [[351, 425]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[351, 425]]}, "_func_name": "registerPlayer", "_file_name": "tournament.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def test_create_invalid_host(self):\n self.flags(lock_path=self.tempdir)\n\n #record\n self.clear_mox()\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_cpg\",\n self.fake_get_cpg)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"get_domain\",\n self.fake_get_domain)\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_host_cmd = ['showhost', '-verbose', 'fakehost']\n _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])\n\n create_host_cmd = (['createhost', '-persona', '1', '-domain',\n ('OpenStack',), 'fakehost', '123456789012345',\n '123456789054321'])\n create_host_ret = pack(CLI_CR +\n 'already used by host fakehost.foo (19)')\n _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, ''])\n\n show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), ''])\n self.mox.ReplayAll()\n\n host = self.driver._create_host(self.volume, self.connector)\n\n self.assertEquals(host['name'], 'fakehost.foo')", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "test_create_invalid_host", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void gmc_mmx(uint8_t *dst, uint8_t *src,\n int stride, int h, int ox, int oy,\n int dxx, int dxy, int dyx, int dyy,\n int shift, int r, int width, int height)\n{\n const int w = 8;\n const int ix = ox >> (16 + shift);\n const int iy = oy >> (16 + shift);\n const int oxs = ox >> 4;\n const int oys = oy >> 4;\n const int dxxs = dxx >> 4;\n const int dxys = dxy >> 4;\n const int dyxs = dyx >> 4;\n const int dyys = dyy >> 4;\n const uint16_t r4[4] = { r, r, r, r };\n const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };\n const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };\n const uint64_t shift2 = 2 * shift;\n#define MAX_STRIDE 4096U\n#define MAX_H 8U\n uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];\n int x, y;\n\n const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);\n const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);\n const int dxh = dxy * (h - 1);\n const int dyw = dyx * (w - 1);\n int need_emu = (unsigned) ix >= width - w ||\n (unsigned) iy >= height - h;\n\n if ( // non-constant fullpel offset (3% of blocks)\n ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |\n (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||\n // uses more than 16 bits of subpel mv (only at huge resolution)\n (dxx | dxy | dyx | dyy) & 15 ||\n (need_emu && (h > MAX_H || stride > MAX_STRIDE))) {\n // FIXME could still use mmx for some of the rows\n ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,\n shift, r, width, height);\n return;\n }\n\n src += ix + iy * stride;\n if (need_emu) {\n ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);\n src = edge_buf;\n }\n\n __asm__ volatile (\n \"movd %0, %%mm6 \\n\\t\"\n \"pxor %%mm7, %%mm7 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n :: \"r\" (1 << shift));\n\n for (x = 0; x < w; x += 4) {\n uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),\n oxs - dxys + dxxs * (x + 1),\n oxs - dxys + dxxs * (x + 2),\n oxs - dxys + dxxs * (x + 3) };\n uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),\n oys - dyys + dyxs * (x + 1),\n oys - dyys + dyxs * (x + 2),\n oys - dyys + dyxs * (x + 3) };\n\n for (y = 0; y < h; y++) {\n __asm__ volatile (\n \"movq %0, %%mm4 \\n\\t\"\n \"movq %1, %%mm5 \\n\\t\"\n \"paddw %2, %%mm4 \\n\\t\"\n \"paddw %3, %%mm5 \\n\\t\"\n \"movq %%mm4, %0 \\n\\t\"\n \"movq %%mm5, %1 \\n\\t\"\n \"psrlw $12, %%mm4 \\n\\t\"\n \"psrlw $12, %%mm5 \\n\\t\"\n : \"+m\" (*dx4), \"+m\" (*dy4)\n : \"m\" (*dxy4), \"m\" (*dyy4));\n\n __asm__ volatile (\n \"movq %%mm6, %%mm2 \\n\\t\"\n \"movq %%mm6, %%mm1 \\n\\t\"\n \"psubw %%mm4, %%mm2 \\n\\t\"\n \"psubw %%mm5, %%mm1 \\n\\t\"\n \"movq %%mm2, %%mm0 \\n\\t\"\n \"movq %%mm4, %%mm3 \\n\\t\"\n \"pmullw %%mm1, %%mm0 \\n\\t\" // (s - dx) * (s - dy)\n \"pmullw %%mm5, %%mm3 \\n\\t\" // dx * dy\n \"pmullw %%mm5, %%mm2 \\n\\t\" // (s - dx) * dy\n \"pmullw %%mm4, %%mm1 \\n\\t\" // dx * (s - dy)\n\n \"movd %4, %%mm5 \\n\\t\"\n \"movd %3, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm3 \\n\\t\" // src[1, 1] * dx * dy\n \"pmullw %%mm4, %%mm2 \\n\\t\" // src[0, 1] * (s - dx) * dy\n\n \"movd %2, %%mm5 \\n\\t\"\n \"movd %1, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm1 \\n\\t\" // src[1, 0] * dx * (s - dy)\n \"pmullw %%mm4, %%mm0 \\n\\t\" // src[0, 0] * (s - dx) * (s - dy)\n \"paddw %5, %%mm1 \\n\\t\"\n \"paddw %%mm3, %%mm2 \\n\\t\"\n \"paddw %%mm1, %%mm0 \\n\\t\"\n \"paddw %%mm2, %%mm0 \\n\\t\"\n\n \"psrlw %6, %%mm0 \\n\\t\"\n \"packuswb %%mm0, %%mm0 \\n\\t\"\n \"movd %%mm0, %0 \\n\\t\"\n\n : \"=m\" (dst[x + y * stride])\n : \"m\" (src[0]), \"m\" (src[1]),\n \"m\" (src[stride]), \"m\" (src[stride + 1]),\n \"m\" (*r4), \"m\" (shift2));\n src += stride;\n }\n src += 4 - h * stride;\n }\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1008, 1110]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1008, 1110]]}, "_func_name": "gmc_mmx", "_file_name": "libavcodec/x86/mpegvideodsp.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {\n\tut8 *end, *need = NULL;\n\tconst char *section_name = \"\";\n\tElf_(Shdr) *link_shdr = NULL;\n\tconst char *link_section_name = \"\";\n\tSdb *sdb_vernaux = NULL;\n\tSdb *sdb_version = NULL;\n\tSdb *sdb = NULL;\n\tint i, cnt;\n\n\tif (!bin || !bin->dynstr) {\n\t\treturn NULL;\n\t}\n\tif (shdr->sh_link > bin->ehdr.e_shnum) {\n\t\treturn NULL;\n\t}\n\tif (shdr->sh_size < 1) {\n\t\treturn NULL;\n\t}\n\tsdb = sdb_new0 ();\n\tif (!sdb) {\n\t\treturn NULL;\n\t}\n\tlink_shdr = &bin->shdr[shdr->sh_link];\n\tif (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {\n\t\tsection_name = &bin->shstrtab[shdr->sh_name];\n\t}\n\tif (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {\n\t\tlink_section_name = &bin->shstrtab[link_shdr->sh_name];\n\t}\n\tif (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) {\n\t\tbprintf (\"Warning: Cannot allocate memory for Elf_(Verneed)\\n\");\n\t\tgoto beach;\n\t}\n\tend = need + shdr->sh_size;\n\tsdb_set (sdb, \"section_name\", section_name, 0);\n\tsdb_num_set (sdb, \"num_entries\", shdr->sh_info, 0);\n\tsdb_num_set (sdb, \"addr\", shdr->sh_addr, 0);\n\tsdb_num_set (sdb, \"offset\", shdr->sh_offset, 0);\n\tsdb_num_set (sdb, \"link\", shdr->sh_link, 0);\n\tsdb_set (sdb, \"link_section_name\", link_section_name, 0);\n\n\tif (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) {\n\t\tgoto beach;\n\t}\n\tif (shdr->sh_offset + shdr->sh_size < shdr->sh_size) {\n\t\tgoto beach;\n\t}\n\ti = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size);\n\tif (i < 0)\n\t\tgoto beach;\n\t//XXX we should use DT_VERNEEDNUM instead of sh_info\n\t//TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html\n\tfor (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) {\n\t\tint j, isum;\n\t\tut8 *vstart = need + i;\n\t\tElf_(Verneed) vvn = {0};\n\t\tif (vstart + sizeof (Elf_(Verneed)) > end) {\n\t\t\tgoto beach;\n\t\t}\n\t\tElf_(Verneed) *entry = &vvn;\n\t\tchar key[32] = {0};\n\t\tsdb_version = sdb_new0 ();\n\t\tif (!sdb_version) {\n\t\t\tgoto beach;\n\t\t}\n\t\tj = 0;\n\t\tvvn.vn_version = READ16 (vstart, j)\n\t\tvvn.vn_cnt = READ16 (vstart, j)\n\t\tvvn.vn_file = READ32 (vstart, j)\n\t\tvvn.vn_aux = READ32 (vstart, j)\n\t\tvvn.vn_next = READ32 (vstart, j)\n\n\t\tsdb_num_set (sdb_version, \"vn_version\", entry->vn_version, 0);\n\t\tsdb_num_set (sdb_version, \"idx\", i, 0);\n\t\tif (entry->vn_file > bin->dynstr_size) {\n\t\t\tgoto beach;\n\t\t}\n\t\t{\n\t\t\tchar *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16);\n\t\t\tsdb_set (sdb_version, \"file_name\", s, 0);\n\t\t\tfree (s);\n\t\t}\n\t\tsdb_num_set (sdb_version, \"cnt\", entry->vn_cnt, 0);\n\t\tvstart += entry->vn_aux;\n\t\tfor (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) {\n\t\t\tint k;\n\t\t\tElf_(Vernaux) * aux = NULL;\n\t\t\tElf_(Vernaux) vaux = {0};\n\t\t\tsdb_vernaux = sdb_new0 ();\n\t\t\tif (!sdb_vernaux) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\taux = (Elf_(Vernaux)*)&vaux;\n\t\t\tk = 0;\n\t\t\tvaux.vna_hash = READ32 (vstart, k)\n\t\t\tvaux.vna_flags = READ16 (vstart, k)\n\t\t\tvaux.vna_other = READ16 (vstart, k)\n\t\t\tvaux.vna_name = READ32 (vstart, k)\n\t\t\tvaux.vna_next = READ32 (vstart, k)\n\t\t\tif (aux->vna_name > bin->dynstr_size) {\n\t\t\t\tgoto beach;\n\t\t\t}\n\t\t\tsdb_num_set (sdb_vernaux, \"idx\", isum, 0);\n\t\t\tif (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) {\n\t\t\t\tchar name [16];\n\t\t\t\tstrncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1);\n\t\t\t\tname[sizeof(name)-1] = 0;\n\t\t\t\tsdb_set (sdb_vernaux, \"name\", name, 0);\n\t\t\t}\n\t\t\tsdb_set (sdb_vernaux, \"flags\", get_ver_flags (aux->vna_flags), 0);\n\t\t\tsdb_num_set (sdb_vernaux, \"version\", aux->vna_other, 0);\n\t\t\tisum += aux->vna_next;\n\t\t\tvstart += aux->vna_next;\n\t\t\tsnprintf (key, sizeof (key), \"vernaux%d\", j);\n\t\t\tsdb_ns_set (sdb_version, key, sdb_vernaux);\n\t\t}\n\t\tif ((int)entry->vn_next < 0) {\n\t\t\tbprintf (\"Invalid vn_next\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ti += entry->vn_next;\n\t\tsnprintf (key, sizeof (key), \"version%d\", cnt );\n\t\tsdb_ns_set (sdb, key, sdb_version);\n\t\t//if entry->vn_next is 0 it iterate infinitely\n\t\tif (!entry->vn_next) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfree (need);\n\treturn sdb;\nbeach:\n\tfree (need);\n\tsdb_free (sdb_vernaux);\n\tsdb_free (sdb_version);\n\tsdb_free (sdb);\n\treturn NULL;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[2490, 2517]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[2490, 2517]]}, "_func_name": "store_versioninfo_gnu_verneed", "_file_name": "libr/bin/format/elf/elf.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def copy(self, src_data, src_path, dst_data, dst_path, job_id=None):\n credentials = ''\n\n if src_data is None: # Local\n src = src_path\n else:\n credentials += self._formatCredentials(src_data, name='src')\n src = 'src:{}'.format(src_path)\n\n if dst_data is None: # Local\n dst = dst_path\n else:\n credentials += self._formatCredentials(dst_data, name='dst')\n dst = 'dst:{}'.format(dst_path)\n\n\n command = (\n '{credentials} '\n 'rclone copy {src} {dst} '\n '--progress '\n '--stats 2s '\n ).format(\n credentials=credentials,\n src=src,\n dst=dst,\n )\n\n logging.info(sanitize(command))\n\n if job_id is None:\n job_id = self._get_next_job_id()\n else:\n if self._job_id_exists(job_id):\n raise ValueError('rclone copy job with ID {} already exists'.fromat(job_id))\n\n self._stop_events[job_id] = threading.Event()\n\n try:\n self._execute_interactive(command, job_id)\n except subprocess.CalledProcessError as e:\n raise RcloneException(sanitize(str(e)))\n\n return job_id", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[73, 98], [177, 250], [373, 446], [491, 729]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[73, 98], [177, 250], [373, 446], [491, 729]]}, "_func_name": "copy", "_file_name": "src/backend/api/utils/rclone_connection.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):\n \"\"\"Set the root password to admin_passwd\n\n admin_password is a root password\n fs is the path to the base of the filesystem into which to inject\n the key.\n\n This method modifies the instance filesystem directly,\n and does not require a guest agent running in the instance.\n\n \"\"\"\n # The approach used here is to copy the password and shadow\n # files from the instance filesystem to local files, make any\n # necessary changes, and then copy them back.\n\n admin_user = 'root'\n\n fd, tmp_passwd = tempfile.mkstemp()\n os.close(fd)\n fd, tmp_shadow = tempfile.mkstemp()\n os.close(fd)\n\n utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,\n run_as_root=True)\n utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,\n run_as_root=True)\n _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)\n utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),\n run_as_root=True)\n os.unlink(tmp_passwd)\n utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),\n run_as_root=True)\n os.unlink(tmp_shadow)", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-022", "source": "SVEN-before", "vuln_type": "cwe-022", "token_labels": {"evidence": [[689, 903], [969, 1076], [1102, 1209]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[689, 903], [969, 1076], [1102, 1209]]}, "_func_name": "_inject_admin_password_into_fs", "_file_name": "nova/virt/disk/api.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "@bot.message_handler(commands=['stats'])\ndef stats(message):\n settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\settings.db\")\n conn = settings.cursor()\n conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n name = conn.fetchone()\n settings.close()\n if name != None:\n bases.update.update_user(name[1], name[0], name[2])\n bases.problem.create_text_stats(name[1])\n img = open(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\users\\\\\" + name[1] + \".png\", \"rb\")\n bot.send_photo(message.chat.id, img)\n img.close()\n if bases.problem.create_stats_picture(name[1]):\n bot.send_message(message.chat.id, \"Sorry, you haven't solved tasks.\")\n return 0\n img = open(os.path.abspath(os.path.dirname(__file__)) + \"\\\\bases\\\\users\\\\\" + name[1] + \".png\", \"rb\")\n bot.send_photo(message.chat.id, img)\n img.close()\n else:\n bot.send_message(message.chat.id, \"You should login before getting statistic.\")", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "stats", "_file_name": "bot.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "archive_read_format_rar_read_data(struct archive_read *a, const void **buff,\n size_t *size, int64_t *offset)\n{\n struct rar *rar = (struct rar *)(a->format->data);\n int ret;\n\n if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {\n\t rar->has_encrypted_entries = 0;\n }\n\n if (rar->bytes_unconsumed > 0) {\n /* Consume as much as the decompressor actually used. */\n __archive_read_consume(a, rar->bytes_unconsumed);\n rar->bytes_unconsumed = 0;\n }\n\n *buff = NULL;\n if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {\n *size = 0;\n *offset = rar->offset;\n if (*offset < rar->unp_size)\n *offset = rar->unp_size;\n return (ARCHIVE_EOF);\n }\n\n switch (rar->compression_method)\n {\n case COMPRESS_METHOD_STORE:\n ret = read_data_stored(a, buff, size, offset);\n break;\n\n case COMPRESS_METHOD_FASTEST:\n case COMPRESS_METHOD_FAST:\n case COMPRESS_METHOD_NORMAL:\n case COMPRESS_METHOD_GOOD:\n case COMPRESS_METHOD_BEST:\n ret = read_data_compressed(a, buff, size, offset);\n if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {\n __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);\n rar->start_new_table = 1;\n }\n break;\n\n default:\n archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n \"Unsupported compression method for RAR file.\");\n ret = ARCHIVE_FATAL;\n break;\n }\n return (ret);\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "archive_read_format_rar_read_data", "_file_name": "libarchive/archive_read_support_format_rar.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def do_setup(self, ctxt):\n \"\"\"Check that we have all configuration details from the storage.\"\"\"\n\n LOG.debug(_('enter: do_setup'))\n self._context = ctxt\n\n # Validate that the pool exists\n ssh_cmd = 'svcinfo lsmdiskgrp -delim ! -nohdr'\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n search_text = '!%s!' % self.configuration.storwize_svc_volpool_name\n if search_text not in out:\n raise exception.InvalidInput(\n reason=(_('pool %s doesn\\'t exist')\n % self.configuration.storwize_svc_volpool_name))\n\n # Check if compression is supported\n self._compression_enabled = False\n try:\n ssh_cmd = 'svcinfo lslicense -delim !'\n out, err = self._run_ssh(ssh_cmd)\n license_lines = out.strip().split('\\n')\n for license_line in license_lines:\n name, foo, value = license_line.partition('!')\n if name in ('license_compression_enclosures',\n 'license_compression_capacity') and value != '0':\n self._compression_enabled = True\n break\n except exception.ProcessExecutionError:\n LOG.exception(_('Failed to get license information.'))\n\n # Get the iSCSI and FC names of the Storwize/SVC nodes\n ssh_cmd = 'svcinfo lsnode -delim !'\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n\n nodes = out.strip().split('\\n')\n self._assert_ssh_return(len(nodes),\n 'do_setup', ssh_cmd, out, err)\n header = nodes.pop(0)\n for node_line in nodes:\n try:\n node_data = self._get_hdr_dic(header, node_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('do_setup',\n ssh_cmd, out, err)\n node = {}\n try:\n node['id'] = node_data['id']\n node['name'] = node_data['name']\n node['IO_group'] = node_data['IO_group_id']\n node['iscsi_name'] = node_data['iscsi_name']\n node['WWNN'] = node_data['WWNN']\n node['status'] = node_data['status']\n node['WWPN'] = []\n node['ipv4'] = []\n node['ipv6'] = []\n node['enabled_protocols'] = []\n if node['status'] == 'online':\n self._storage_nodes[node['id']] = node\n except KeyError:\n self._handle_keyerror('lsnode', header)\n\n # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes\n self._get_iscsi_ip_addrs()\n self._get_fc_wwpns()\n\n # For each node, check what connection modes it supports. Delete any\n # nodes that do not support any types (may be partially configured).\n to_delete = []\n for k, node in self._storage_nodes.iteritems():\n if ((len(node['ipv4']) or len(node['ipv6']))\n and len(node['iscsi_name'])):\n node['enabled_protocols'].append('iSCSI')\n self._enabled_protocols.add('iSCSI')\n if len(node['WWPN']):\n node['enabled_protocols'].append('FC')\n self._enabled_protocols.add('FC')\n if not len(node['enabled_protocols']):\n to_delete.append(k)\n\n for delkey in to_delete:\n del self._storage_nodes[delkey]\n\n # Make sure we have at least one node configured\n self._driver_assert(len(self._storage_nodes),\n _('do_setup: No configured nodes'))\n\n LOG.debug(_('leave: do_setup'))", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[218, 273], [806, 857], [1463, 1507]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[218, 273], [806, 857], [1463, 1507]]}, "_func_name": "do_setup", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "filter_session_io(struct io *io, int evt, void *arg)\n{\n\tstruct filter_session *fs = arg;\n\tchar *line = NULL;\n\tssize_t len;\n\n\tlog_trace(TRACE_IO, \"filter session: %p: %s %s\", fs, io_strevent(evt),\n\t io_strio(io));\n\n\tswitch (evt) {\n\tcase IO_DATAIN:\n\tnextline:\n\t\tline = io_getline(fs->io, &len);\n\t\t/* No complete line received */\n\t\tif (line == NULL)\n\t\t\treturn;\n\n\t\tfilter_data(fs->id, line);\n\n\t\tgoto nextline;\n\t}\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "filter_session_io", "_file_name": "usr.sbin/smtpd/lka_filter.c", "lang": "c", "label_confidence": "diff-derived"} {"code": "int ares_parse_a_reply(const unsigned char *abuf, int alen,\n\t\t struct hostent **host)\n{\n unsigned int qdcount, ancount;\n int status, i, rr_type, rr_class, rr_len, naddrs;\n long int len;\n int naliases;\n const unsigned char *aptr;\n char *hostname, *rr_name, *rr_data, **aliases;\n struct in_addr *addrs;\n struct hostent *hostent;\n\n /* Set *host to NULL for all failure cases. */\n *host = NULL;\n\n /* Give up if abuf doesn't have room for a header. */\n if (alen < HFIXEDSZ)\n return ARES_EBADRESP;\n\n /* Fetch the question and answer count from the header. */\n qdcount = DNS_HEADER_QDCOUNT(abuf);\n ancount = DNS_HEADER_ANCOUNT(abuf);\n if (qdcount != 1)\n return ARES_EBADRESP;\n\n /* Expand the name from the question, and skip past the question. */\n aptr = abuf + HFIXEDSZ;\n status = ares_expand_name(aptr, abuf, alen, &hostname, &len);\n if (status != ARES_SUCCESS)\n return status;\n if (aptr + len + QFIXEDSZ > abuf + alen)\n {\n free(hostname);\n return ARES_EBADRESP;\n }\n aptr += len + QFIXEDSZ;\n\n /* Allocate addresses and aliases; ancount gives an upper bound for both. */\n addrs = malloc(ancount * sizeof(struct in_addr));\n if (!addrs)\n {\n free(hostname);\n return ARES_ENOMEM;\n }\n aliases = malloc((ancount + 1) * sizeof(char *));\n if (!aliases)\n {\n free(hostname);\n free(addrs);\n return ARES_ENOMEM;\n }\n naddrs = 0;\n naliases = 0;\n\n /* Examine each answer resource record (RR) in turn. */\n for (i = 0; i < (int)ancount; i++)\n {\n /* Decode the RR up to the data field. */\n status = ares_expand_name(aptr, abuf, alen, &rr_name, &len);\n if (status != ARES_SUCCESS)\n\tbreak;\n aptr += len;\n if (aptr + RRFIXEDSZ > abuf + alen)\n\t{\n\t free(rr_name);\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n rr_type = DNS_RR_TYPE(aptr);\n rr_class = DNS_RR_CLASS(aptr);\n rr_len = DNS_RR_LEN(aptr);\n aptr += RRFIXEDSZ;\n\n if (rr_class == C_IN && rr_type == T_A\n\t && rr_len == sizeof(struct in_addr)\n\t && strcasecmp(rr_name, hostname) == 0)\n\t{\n\t memcpy(&addrs[naddrs], aptr, sizeof(struct in_addr));\n\t naddrs++;\n\t status = ARES_SUCCESS;\n\t}\n\n if (rr_class == C_IN && rr_type == T_CNAME)\n\t{\n\t /* Record the RR name as an alias. */\n\t aliases[naliases] = rr_name;\n\t naliases++;\n\n\t /* Decode the RR data and replace the hostname with it. */\n\t status = ares_expand_name(aptr, abuf, alen, &rr_data, &len);\n\t if (status != ARES_SUCCESS)\n\t break;\n\t free(hostname);\n\t hostname = rr_data;\n\t}\n else\n\tfree(rr_name);\n\n aptr += rr_len;\n if (aptr > abuf + alen)\n\t{\n\t status = ARES_EBADRESP;\n\t break;\n\t}\n }\n\n if (status == ARES_SUCCESS && naddrs == 0)\n status = ARES_ENODATA;\n if (status == ARES_SUCCESS)\n {\n /* We got our answer. Allocate memory to build the host entry. */\n aliases[naliases] = NULL;\n hostent = malloc(sizeof(struct hostent));\n if (hostent)\n\t{\n\t hostent->h_addr_list = malloc((naddrs + 1) * sizeof(char *));\n\t if (hostent->h_addr_list)\n\t {\n\t /* Fill in the hostent and return successfully. */\n\t hostent->h_name = hostname;\n\t hostent->h_aliases = aliases;\n\t hostent->h_addrtype = AF_INET;\n\t hostent->h_length = sizeof(struct in_addr);\n\t for (i = 0; i < naddrs; i++)\n\t\thostent->h_addr_list[i] = (char *) &addrs[i];\n\t hostent->h_addr_list[naddrs] = NULL;\n\t *host = hostent;\n\t return ARES_SUCCESS;\n\t }\n\t free(hostent);\n\t}\n status = ARES_ENOMEM;\n }\n for (i = 0; i < naliases; i++)\n free(aliases[i]);\n free(aliases);\n free(addrs);\n free(hostname);\n return status;\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[1933, 1934]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1933, 1934]]}, "_func_name": "ares_parse_a_reply", "_file_name": "rutil/dns/ares/ares_parse_a_reply.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def _find_host_exhaustive(self, connector, hosts):\n for host in hosts:\n ssh_cmd = 'svcinfo lshost -delim ! %s' % host\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()),\n '_find_host_exhaustive',\n ssh_cmd, out, err)\n for attr_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attr_name, foo, attr_val = attr_line.partition('!')\n if (attr_name == 'iscsi_name' and\n 'initiator' in connector and\n attr_val == connector['initiator']):\n return host\n elif (attr_name == 'WWPN' and\n 'wwpns' in connector and\n attr_val.lower() in\n map(str.lower, map(str, connector['wwpns']))):\n return host\n return None", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[82, 140]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[82, 140]]}, "_func_name": "_find_host_exhaustive", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "validate_as_request(kdc_realm_t *kdc_active_realm,\n register krb5_kdc_req *request, krb5_db_entry client,\n krb5_db_entry server, krb5_timestamp kdc_time,\n const char **status, krb5_pa_data ***e_data)\n{\n int errcode;\n krb5_error_code ret;\n\n /*\n * If an option is set that is only allowed in TGS requests, complain.\n */\n if (request->kdc_options & AS_INVALID_OPTIONS) {\n *status = \"INVALID AS OPTIONS\";\n return KDC_ERR_BADOPTION;\n }\n\n /* The client must not be expired */\n if (client.expiration && client.expiration < kdc_time) {\n *status = \"CLIENT EXPIRED\";\n if (vague_errors)\n return(KRB_ERR_GENERIC);\n else\n return(KDC_ERR_NAME_EXP);\n }\n\n /* The client's password must not be expired, unless the server is\n a KRB5_KDC_PWCHANGE_SERVICE. */\n if (client.pw_expiration && client.pw_expiration < kdc_time &&\n !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {\n *status = \"CLIENT KEY EXPIRED\";\n if (vague_errors)\n return(KRB_ERR_GENERIC);\n else\n return(KDC_ERR_KEY_EXP);\n }\n\n /* The server must not be expired */\n if (server.expiration && server.expiration < kdc_time) {\n *status = \"SERVICE EXPIRED\";\n return(KDC_ERR_SERVICE_EXP);\n }\n\n /*\n * If the client requires password changing, then only allow the\n * pwchange service.\n */\n if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) &&\n !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {\n *status = \"REQUIRED PWCHANGE\";\n return(KDC_ERR_KEY_EXP);\n }\n\n /* Client and server must allow postdating tickets */\n if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) ||\n isflagset(request->kdc_options, KDC_OPT_POSTDATED)) &&\n (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) ||\n isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) {\n *status = \"POSTDATE NOT ALLOWED\";\n return(KDC_ERR_CANNOT_POSTDATE);\n }\n\n /*\n * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of\n * KDC_ERR_POLICY in the following case:\n *\n * - KDC_OPT_FORWARDABLE is set in KDCOptions but local\n * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the\n * client, and;\n * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but\n * preauthentication data is absent in the request.\n *\n * Hence, this check most be done after the check for preauth\n * data, and is now performed by validate_forwardable() (the\n * contents of which were previously below).\n */\n\n /* Client and server must allow proxiable tickets */\n if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) &&\n (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) ||\n isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) {\n *status = \"PROXIABLE NOT ALLOWED\";\n return(KDC_ERR_POLICY);\n }\n\n /* Check to see if client is locked out */\n if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {\n *status = \"CLIENT LOCKED OUT\";\n return(KDC_ERR_CLIENT_REVOKED);\n }\n\n /* Check to see if server is locked out */\n if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {\n *status = \"SERVICE LOCKED OUT\";\n return(KDC_ERR_S_PRINCIPAL_UNKNOWN);\n }\n\n /* Check to see if server is allowed to be a service */\n if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) {\n *status = \"SERVICE NOT ALLOWED\";\n return(KDC_ERR_MUST_USE_USER2USER);\n }\n\n if (check_anon(kdc_active_realm, client.princ, request->server) != 0) {\n *status = \"ANONYMOUS NOT ALLOWED\";\n return(KDC_ERR_POLICY);\n }\n\n /* Perform KDB module policy checks. */\n ret = krb5_db_check_policy_as(kdc_context, request, &client, &server,\n kdc_time, status, e_data);\n if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP)\n return errcode_to_protocol(ret);\n\n /* Check against local policy. */\n errcode = against_local_policy_as(request, client, server,\n kdc_time, status, e_data);\n if (errcode)\n return errcode;\n\n return 0;\n}", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "validate_as_request", "_file_name": "src/kdc/kdc_util.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def test_get_iscsi_ip(self):\n self.flags(lock_path=self.tempdir)\n\n #record driver set up\n self.clear_mox()\n _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)\n self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, \"_run_ssh\", _run_ssh)\n\n show_port_cmd = 'showport'\n _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])\n\n show_port_i_cmd = 'showport -iscsi'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),\n ''])\n\n show_port_i_cmd = 'showport -iscsiname'\n _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])\n\n #record\n show_vlun_cmd = 'showvlun -a -host fakehost'\n show_vlun_ret = 'no vluns listed\\r\\n'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(show_vlun_ret), ''])\n show_vlun_cmd = 'showvlun -a -showcols Port'\n _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])\n\n self.mox.ReplayAll()\n\n config = self.setup_configuration()\n config.iscsi_ip_address = '10.10.10.10'\n config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']\n self.setup_driver(config, set_up_fakes=False)\n\n ip = self.driver._get_iscsi_ip('fakehost')\n self.assertEqual(ip, '10.10.220.252')", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[290, 325], [397, 441], [579, 627], [724, 777], [899, 952]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[290, 325], [397, 441], [579, 627], [724, 777], [899, 952]]}, "_func_name": "test_get_iscsi_ip", "_file_name": "cinder/tests/test_hp3par.py", "lang": "python", "label_confidence": "diff-derived"} {"code": " def _map_vol_to_host(self, volume_name, host_name):\n \"\"\"Create a mapping between a volume to a host.\"\"\"\n\n LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to '\n 'host %(host_name)s')\n % {'volume_name': volume_name, 'host_name': host_name})\n\n # Check if this volume is already mapped to this host\n mapping_data = self._get_hostvdisk_mappings(host_name)\n\n mapped_flag = False\n result_lun = '-1'\n if volume_name in mapping_data:\n mapped_flag = True\n result_lun = mapping_data[volume_name]['SCSI_id']\n else:\n lun_used = [int(v['SCSI_id']) for v in mapping_data.values()]\n lun_used.sort()\n # Assume all luns are taken to this point, and then try to find\n # an unused one\n result_lun = str(len(lun_used))\n for index, n in enumerate(lun_used):\n if n > index:\n result_lun = str(index)\n break\n\n # Volume is not mapped to host, create a new LUN\n if not mapped_flag:\n ssh_cmd = ('svctask mkvdiskhostmap -host %(host_name)s -scsi '\n '%(result_lun)s %(volume_name)s' %\n {'host_name': host_name,\n 'result_lun': result_lun,\n 'volume_name': volume_name})\n out, err = self._run_ssh(ssh_cmd, check_exit_code=False)\n if err and err.startswith('CMMVC6071E'):\n if not self.configuration.storwize_svc_multihostmap_enabled:\n LOG.error(_('storwize_svc_multihostmap_enabled is set '\n 'to False, Not allow multi host mapping'))\n exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\\\n 'was not created because the VDisk is '\\\n 'already mapped to a host.\\n\"'\n raise exception.CinderException(data=exception_msg)\n ssh_cmd = ssh_cmd.replace('mkvdiskhostmap',\n 'mkvdiskhostmap -force')\n # try to map one volume to multiple hosts\n out, err = self._run_ssh(ssh_cmd)\n LOG.warn(_('volume %s mapping to multi host') % volume_name)\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n else:\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume '\n '%(volume_name)s, host %(host_name)s') %\n {'result_lun': result_lun,\n 'volume_name': volume_name,\n 'host_name': host_name})\n return result_lun", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-078", "source": "SVEN-before", "vuln_type": "cwe-078", "token_labels": {"evidence": [[1119, 1403], [2046, 2173]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[1119, 1403], [2046, 2173]]}, "_func_name": "_map_vol_to_host", "_file_name": "cinder/volume/drivers/storwize_svc.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def get_last_month(db, scene):\n sql = \"select date from matches where scene='{scene}' order by date desc limit 1;\"\n args = {'scene': scene}\n res = db.exec(sql, args)\n date = res[0][0]\n\n # If it has been more than 1 month since this last tournament,\n # go ahead and round this date up by a 1 month\n # eg, if the last tournament was 2015-01-15 (a long time ago)\n # we can assume the scene won't have more tournaments\n # So just round to 2015-02-01\n today = datetime.datetime.today().strftime('%Y-%m-%d')\n y, m, d = today.split('-')\n cy, cm, cd = date.split('-')\n if y > cy or m > cm:\n # Add 1 to the month before we return\n # eg 2018-03-01 -> 2018-04-01\n date = get_next_month(date)\n\n return date", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "get_last_month", "_file_name": "bracket_utils.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n{\n int i, j, v;\n\n if (get_bits1(gb)) {\n /* intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->intra_matrix[j] = v;\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n /* non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n if (get_bits1(gb)) {\n /* chroma_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n v = get_bits(gb, 8);\n j = s->idsp.idct_permutation[ff_zigzag_direct[i]];\n s->chroma_intra_matrix[j] = v;\n }\n }\n\n if (get_bits1(gb)) {\n /* chroma_non_intra_quantiser_matrix */\n for (i = 0; i < 64; i++) {\n get_bits(gb, 8);\n }\n }\n\n next_start_code_studio(gb);\n}", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-125", "source": "SVEN-before", "vuln_type": "cwe-125", "token_labels": {"evidence": [[0, 72]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[0, 72]]}, "_func_name": "read_quant_matrix_ext", "_file_name": "libavcodec/mpeg4videodec.c", "lang": "c", "label_confidence": "diff-derived"} {"code": " def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['comments'] = self.object.comment_set.all().order_by('-time')\n context['form'] = self.get_form()\n context['md'] = markdown(self.object.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n\n return context", "label": 1, "is_completion_vulnerable": true, "cwe": "CWE-079", "source": "SVEN-before", "vuln_type": "cwe-079", "token_labels": {"evidence": [[215, 552]], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": [[215, 552]]}, "_func_name": "get_context_data", "_file_name": "app/Index/views.py", "lang": "python", "label_confidence": "diff-derived"} {"code": "def insertUsage(user, command):\n\tc, conn = getConnection()\n\tdate = now()\n\tc.execute(\"INSERT INTO usage (date,user,command) VALUES (?,?,?)\",(date,str(user),command))\n\tconn.commit()\n\tconn.close()", "label": 0, "is_completion_vulnerable": false, "cwe": null, "source": "SVEN-after", "vuln_type": null, "token_labels": {"evidence": [], "sink": [], "source": [], "sanitizer": [], "vulnerable_line": []}, "_func_name": "insertUsage", "_file_name": "database.py", "lang": "python", "label_confidence": "diff-derived"}