text stringlengths 79 3.72M |
|---|
<vulnerable_code>import collections
import socket
import sys
import weakref
if hasattr(socket, 'AF_UNIX'):
self._transport = new_transport
protocol._replace_writer(self)
class StreamReader:
<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I fo... |
<vulnerable_code>
self.assertEqual(messages, [])
if __name__ == '__main__':
unittest.main()<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-106706).<fixed_code>
self.a... |
<vulnerable_code> self.converters = FakeConvertersDict()
self.legacy_converters = FakeConvertersDict()
self.language = clinic.CLanguage(None)
self.filename = None
self.destination_buffers = {}
self.block_parser = clinic.BlockParser('', self.language)
self.modules =... |
<vulnerable_code> if len(s) > 30:
return s[:26] + "..." + s[0]
return s
return "".join((
"<Block ", dsl_name, " input=", summarize(self.input), " output=", summarize(self.output), ">"))
class BlockParser:
def __repr__(self) -> str:
if self.type =... |
<vulnerable_code> self.line_number = 0
def __repr__(self) -> str:
return (
f"<Monitor {id(self)} line={self.line_number} condition={self.condition()!r}>"
)
def status(self) -> str:
return str(self.line_number).rjust(4) + ": " + self.condition()<commit_title>[PATCH 01... |
<vulnerable_code> final_argument_whitespace = True
# This text is copied to templates/dummy.html
label_text = 'CPython implementation detail:'
def run(self):
self.assert_has_content()
pnode = nodes.compound(classes=['impl-detail'])
label = sphinx_gettext(self.label_text)
... |
<vulnerable_code> ('c:type', 'uintptr_t'),
('c:type', 'va_list'),
('c:type', 'wchar_t'),
# Standard C structures
('c:struct', 'in6_addr'),
('c:struct', 'in_addr'),<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (is... |
<vulnerable_code> """
def __init__(self, func):
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError(f"{func!r} is not callable or a descriptor")
self.dispatcher = singledispatch(func)
self.func = func
def register(self, cls, method=None):
"""... |
<vulnerable_code> self.assertTrue(A.t(''))
self.assertEqual(A.t(0.0), 0.0)
def test_classmethod_register(self):
class A:
def __init__(self, arg):<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (iss... |
<vulnerable_code> if unknown:
cls = type(self)
logger = logging.getLogger(cls.__qualname__)
logger.warn(
f"Unknown platform(s) or syntax '{' '.join(sorted(unknown))}' "
f"in '.. availability:: {self.arguments[0]}', see "
f"{__fil... |
<vulnerable_code> checksum_line = ""
def __init__(self, filename: str) -> None:
pass
@abc.abstractmethod
def render(
clinic: Clinic | None,
signatures: Iterable[Module | Class | Function]
) -> str:
pass
def parse_line(self, line: str) -> None:
pa... |
<vulnerable_code> if self.verbose:
print(self.status())
if __name__ == '__main__':
for filename in sys.argv[1:]:
with open(filename) as f:
cpp = Monitor(filename, verbose=True)
print()
print(filename)
for line_number, line in enumerate(f.re... |
<vulnerable_code>
import _tkinter
tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.')))
def requires_tcl(*version):
if len(version) <= 2:
return unittest.skipUnless(tcl_version >= version,
'requires Tcl version >= ' + '.'.join(map(str, version)))
def deco(test):
@functools... |
<vulnerable_code>import tkinter
from test import support
from test.support import os_helper
from test.test_tkinter.support import AbstractTkTest, AbstractDefaultRootTest, requires_tcl
support.requires('gui')
def test_create_from_gif_data(self):
self.check_create_from_data('gif')
@requires_tcl(8, 6)
... |
<vulnerable_code> newname = f'C.{name}'
self.assertEqual(style.map(newname), {})
style.map(newname, **default)
if theme == 'alt' and name == '.' and get_tk_patchlevel() < (8, 6, 1):
default['embossed'] = [('disabled',... |
<vulnerable_code>fn_with_default_binop_expr_impl(PyObject *module, PyObject *arg)
/*[clinic end generated code: output=018672772e4092ff input=1b55c8ae68d89453]*/
/*[python input]
class Custom_converter(CConverter):
type = "str"
static PyObject *
docstr_fallback_to_converter_default_impl(PyObject *module, str a)
/*... |
<vulnerable_code> "module foo\nfoo.bar\n this: int\n *",
"module foo\nfoo.bar\n this: int\n *\nDocstring.",
)
err = "Function 'bar' specifies '*' without any parameters afterwards."
for block in dataset:
with self.subTest(block=block):
self.... |
<vulnerable_code> return ''.join(final)
def version_splitter(s: str) -> tuple[int, ...]:
"""Splits a version string into a tuple of integers.
#define {methoddef_name}
#endif /* !defined({methoddef_name}) */
""")
def __init__(self, filename: str) -> None:
super().__init__(f... |
<vulnerable_code> """
def __init__(self, func):
import weakref # see comment in singledispatch function
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError(f"{func!r} is not callable or a descriptor")
self.dispatcher = singledispatch(func)
self.fu... |
<vulnerable_code> ('c:func', 'sprintf'),
('c:func', 'stat'),
('c:func', 'system'),
('c:func', 'vsnprintf'),
# Standard C types
('c:type', 'FILE'),<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) an... |
<vulnerable_code>from test.support.os_helper import TESTFN, unlink
from textwrap import dedent
from unittest import TestCase
import collections
import contextlib
import inspect
import os.path
from clinic import DSLParser
def _expect_failure(tc, parser, code, errmsg, *, filename=None, lineno=None):
"""Helper f... |
<vulnerable_code>
return module, cls
def parse_file(
filename: str,<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-106706).<fixed_code>
return module, cls
de... |
<vulnerable_code> """
Return all known handler names as an immutable set.
"""
result = set(_handlers.keys())
return frozenset(result)
class Handler(Filterer):<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-... |
<vulnerable_code> PyObject *b = Py_None;
#if PY_VERSION_HEX >= 0x030e00C0
# error "In clinic.test.c, update parameter(s) 'b' in the clinic input of 'test_deprecate_positional_pos1_len1_optional' to be keyword-only."
#elif PY_VERSION_HEX >= 0x030e00A0
# ifdef _MSC_VER
# pragma message ("In c... |
<vulnerable_code> return '"' + s + '"'
is_legal_c_identifier = re.compile('^[A-Za-z_][A-Za-z0-9_]*$').match
def is_legal_py_identifier(s: str) -> bool:
""")
DEPRECATED_POSITIONAL_PROTOTYPE: Final[str] = r"""
#if PY_VERSION_HEX >= 0x{major:02x}{minor:02x}00C0
# error "{cpp_message}"
... |
<vulnerable_code> self.assertEqual(image['foreground'],
'-foreground {} {} #000000 yellow')
class PhotoImageTest(AbstractTkTest, unittest.TestCase):
image.configure(palette='3/4/2')
self.assertEqual(image['palette'], '3/4/2')
def test_blank(self):
image = ... |
<vulnerable_code> source.tell() - start)
if char == "=":
subpatternappend((ASSERT, (dir, p)))
else:
subpatternappend((ASSERT_NOT, (dir, p)))
continue
eli... |
<vulnerable_code> p.terminate()
p.join()
def get_debug_out(pat):
with captured_stdout() as out:<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-106706).<... |
<vulnerable_code> if source_lines is None:
return None
pat = re.compile(r'^\s*class\s*%s\b' %
getattr(obj, '__name__', '-'))
for i, line in enumerate(source_lines):
if pat.match(line):
lineno = i<commit_t... |
<vulnerable_code> except ValueError:
pass
try:
setitem(b, 0, None)
self.fail("Didn't raise TypeError")
except TypeError:
pass<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These r... |
<vulnerable_code> self.attr = 1
a = A()
self.assertEqual(_testcapi.hasattr_string(a, "attr"), True)
self.assertEqual(_testcapi.hasattr_string(a, "noattr"), False)
self.assertIsNone(sys.exception())
def testDel(self):<commit_title>[PATCH 016/395] Small fixes to code g... |
<vulnerable_code>
#define REFCHAIN(interp) &interp->object_state.refchain
/* Insert op at the front of the list of all objects. If force is true,
* op is added even if _ob_prev and _ob_next are non-NULL already. If
* force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
&_PyNotImplemented_Type
};
... |
<vulnerable_code> }
has_gil = 1;
status = pycore_interp_init(tstate);
if (_PyStatus_EXCEPTION(status)) {
goto error;<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-1... |
<vulnerable_code> _obmalloc_pools_INIT(interp->obmalloc.pools);
memcpy(&interp->obmalloc.pools.used, temp, sizeof(temp));
}
_PyEval_InitState(interp, pending_lock);
_PyGC_InitState(&interp->gc);<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>T... |
<vulnerable_code>import _testinternalcapi
def decode_stderr(err):
return err.decode('utf-8', 'replace').replace('\r', '')
with self.assertRaises(StopIteration):
next(it)
if __name__ == "__main__":
unittest.main()<commit_title>[PATCH 016/395] Small fixes to code generator (#106845... |
<vulnerable_code> def test_basic_multiple_interpreters_deleted_no_reset(self):
# without resetting; already loaded in a deleted interpreter
# At this point:
# * alive in 0 interpreters
# * module def may or may not be loaded already<commit_title>[PATCH 016/395] Small fixes to code ... |
<vulnerable_code>
@contextual
def stack_effect(self) -> StackEffect | None:
# IDENTIFIER [':' IDENTIFIER] ['if' '(' expression ')']
# | IDENTIFIER '[' expression ']'
if tkn := self.expect(lx.IDENTIFIER):
type_text = ""
if self.expect(lx.COLON):
t... |
<vulnerable_code> ), f"Push or pop above current stack level: {res}"
return res
@dataclasses.dataclass
class CopyEffect:
for peek in mgr.peeks:
out.assign(
peek.effect,
StackEffect(
peek.as_variable(),
peek.... |
<vulnerable_code> if (ptr != stack_base) {
printf(", ");
}
if (PyObject_Print(*ptr, stdout, 0) != 0) {
PyErr_Clear();
printf("<%s object at %p>",
Py_TYPE(*ptr)->tp_name, (void *)(*ptr));
}
}
printf("]\n");
fflush(stdout);
... |
<vulnerable_code> lltrace = *uop_debug - '0'; // TODO: Parse an int and all that
}
#define DPRINTF(level, ...) \
if (lltrace >= (level)) { fprintf(stderr, __VA_ARGS__); }
#else
#define DPRINTF(level, ...)
#endif<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_desc... |
<vulnerable_code>
#ifdef Py_DEBUG
#define DPRINTF(level, ...) \
if (lltrace >= (level)) { fprintf(stderr, __VA_ARGS__); }
#else
#define DPRINTF(level, ...)
#endif<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and i... |
<vulnerable_code>PyDoc_STRVAR(test_deprecate_positional_pos1_len1_optional__doc__,
"test_deprecate_positional_pos1_len1_optional($module, /, a, b=None)\n"
"--\n"
"\n");
#define TEST_DEPRECATE_POSITIONAL_POS1_LEN1_OPTIONAL_METHODDEF \
{"test_deprecate_positional_pos1_len1_optional", _PyCFunction_CAST(test_deprec... |
<vulnerable_code> f"{func.full_name}() is deprecated. Parameters {pstr} will "
f"become keyword-only parameters in Python {major}.{minor}."
)
# Format and return the code block.
code = self.DEPRECATED_POSITIONAL_PROTOTYPE.format(
condition=condition... |
<vulnerable_code>
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "pycore_runtime.h" // _PyRuntime
#include "pycore_global_objects.h" // _Py_ID()
#define CTYPES_CAPSULE_NAME_PYMEM "_ctypes pymem"
return NULL;
}
static PyObject *
POINTER(PyObject *self, PyObject *cls)... |
<vulnerable_code> PyObject *a;
PyObject *b = Py_None;
#if PY_VERSION_HEX >= 0x030e00C0
# error \
"In clinic.test.c, update parameter(s) 'b' in the clinic input of" \
static PyObject *
test_deprecate_positional_pos1_len1_optional_impl(PyObject *module,
... |
<vulnerable_code> #endif /* !defined({methoddef_name}) */
""")
DEPRECATED_POSITIONAL_PROTOTYPE: Final[str] = r"""
#if PY_VERSION_HEX >= 0x{major:02x}{minor:02x}00C0
# error \
{cpp_message}<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_descrip... |
<vulnerable_code> tc.assertEqual(cm.exception.filename, filename)
if lineno is not None:
tc.assertEqual(cm.exception.lineno, lineno)
class ClinicWholeFileTest(TestCase):
last_line.startswith("/*[clinic end generated code: output=")
)
def test_unknown_destination_command(sel... |
<vulnerable_code> # but at least make an attempt at ensuring it's a valid expression.
try:
value = eval(default)
if value is unspecified:
fail("'unspecified' is not a legal default value!")
... |
<vulnerable_code> # Handle Nans and Infs gracefully
return float(xbar), float(xbar) / float(ss)
# === Statistics for relations between two inputs ===
sxx = sumprod(x, x)
syy = sumprod(y, y)
try:
return sxy / sqrt(sxx * syy)
except ZeroDivisionError:
raise StatisticsErro... |
<vulnerable_code> "BINARY_SUBSCR_DICT",
"BINARY_SUBSCR_GETITEM",
"BINARY_SUBSCR_LIST_INT",
"BINARY_SUBSCR_TUPLE_INT",
],
"STORE_SUBSCR": [<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-10... |
<vulnerable_code> BINARY_SUBSCR_DICT,
BINARY_SUBSCR_GETITEM,
BINARY_SUBSCR_LIST_INT,
BINARY_SUBSCR_TUPLE_INT,
};
Py_DECREF(list);
}
inst(BINARY_SUBSCR_TUPLE_INT, (unused/1, tuple, sub -- res)) {
DEOPT_IF(!PyLong_CheckExact(... |
<vulnerable_code>#define SPEC_FAIL_SUBSCR_ARRAY_SLICE 10
#define SPEC_FAIL_SUBSCR_LIST_SLICE 11
#define SPEC_FAIL_SUBSCR_TUPLE_SLICE 12
#define SPEC_FAIL_SUBSCR_STRING_INT 13
#define SPEC_FAIL_SUBSCR_STRING_SLICE 14
#define SPEC_FAIL_SUBSCR_BUFFER_INT 15
#define SPEC_FAIL_SUBSCR_BUFFER_SLICE 16
static int
binary_subscr... |
<vulnerable_code> path = os.path.join(ext_path, filename)
self.assertNotIn(path, out)
def test_cli_verbose(self):
with os_helper.temp_dir() as tmp_dir:
fn = os.path.join(tmp_dir, "test.c")<commit_title>[PATCH 016/395] Small fixes to code generator (#106845... |
<vulnerable_code> help="walk --srcdir to run over all relevant files")
cmdline.add_argument("--srcdir", type=str, default=os.curdir,
help="the directory tree to walk in --make mode")
cmdline.add_argument("filename", metavar="FILE", type=str, nargs="*",
... |
<vulnerable_code>
self.docstring_append(self.function, line)
def format_docstring(self) -> str:
f = self.function
assert f is not None
new_or_init = f.kind.new_or_init
if new_or_init and not f.docstring:
# don't render a docstring at all, no signature, nothing.
... |
<vulnerable_code> emit(ANY_ALL)
else:
emit(ANY)
elif op in REPEATING_CODES:
if _simple(av[2]):
emit(REPEATING_CODES[op][2])<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in ... |
<vulnerable_code> self.assertTrue(re.fullmatch(r'(?s:(?>.*?\.).*)\Z', "a.txt")) # reproducer
self.assertTrue(re.fullmatch(r'(?s:(?=(?P<g0>.*?\.))(?P=g0).*)\Z', "a.txt"))
@unittest.skipIf(multiprocessing is None, 'test requires multiprocessing')
def test_regression_gh94675(self):
pattern ... |
<vulnerable_code>
def docstring_append(self, obj: Function | Parameter, line: str) -> None:
"""Add a rstripped line to the current docstring."""
matches = re.finditer(r'[^\x00-\x7F]', line)
if offending := ", ".join([repr(m[0]) for m in matches]):
warn("Non-ascii characters are n... |
<vulnerable_code> # Square root differential correction:
# https://www.wolframalpha.com/input/?i=Maclaurin+series+sqrt%28h**2+%2B+x%29+at+x%3D0
h = sqrt(x * y)
x = sumprod((x, h), (y, -h))
return h + x / (2.0 * h)
<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_descriptio... |
<vulnerable_code> def __call__(self, code, offset, exc):
self.events.append(("handled", type(exc)))
class ExceptionMonitoringTest(CheckEvents):
func,
recorders = self.exception_recorders)
class LineRecorder:
event_type = E.LINE<commit_title>[PATCH 016/395] Small fixes to code... |
<vulnerable_code> if (no_tools_for_event(tstate, frame, PY_MONITORING_EVENT_PY_THROW)) {
return;
}
_Py_call_instrumentation_exc0(tstate, PY_MONITORING_EVENT_PY_THROW, frame, instr);
}
void<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I fou... |
<vulnerable_code> assert(_PyErr_Occurred(tstate));
}
void
_Py_call_instrumentation_exc0(
PyThreadState *tstate, int event,
_PyInterpreterFrame *frame, _Py_CODEUNIT *instr)
{
assert(_PyErr_Occurred(tstate));
PyObject *args[3] = { NULL, NULL, NULL };
call_instrumentation_vector_protected(tstate, e... |
<vulnerable_code>}
static PyObject *
sys_trace_unwind(
_PyLegacyEventHandler *self, PyObject *const *args,
size_t nargsf, PyObject *kwnames
) {
return -1;
}
if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
(vectorcallfunc)sys_trace_func2, PyTrace_CALL,
... |
<vulnerable_code> self.expect_failure(block, err, lineno=6)
def test_directive_preserve_output(self):
err = "'preserve' only works for blocks that don't produce any output!"
block = dedent("""
/*[clinic input]
output everything buffer
follow_symlinks: ... |
<vulnerable_code> cpp = Monitor(filename, verbose=True)
print()
print(filename)
for line_number, line in enumerate(f.read().split('\n'), 1):
cpp.writeline(line)
<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These ... |
<vulnerable_code>
def checkDocstring(self, fn, expected):
self.assertTrue(hasattr(fn, "docstring"))
self.assertEqual(fn.docstring.strip(),
dedent(expected).strip())
def test_trivial(self):
parser = DSLParser(_make_clinic())
path: str
... |
<vulnerable_code> else:
return f'"argument {i}"'
CConverterClassT = TypeVar("CConverterClassT", bound=type["CConverter"])
@staticmethod
def format_docstring_parameters(params: list[Parameter]) -> str:
"""Create substitution text for {parameters}"""
text, add, output = _text... |
<vulnerable_code>/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c81ac2402d06a8b]*/
/*[clinic input]
class Test "TestObj *" "TestType"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=fc7e50384d12b83f]*/
/*[clinic input]
test_object_converter
... |
<vulnerable_code> if first_pos:
preamble = f"Passing {first_pos+1} positional arguments to "
depr_message = preamble + (
f"{func.full_name}() is deprecated. Parameter {pstr} will "
f"become a keyword-only parameter in Python {major}.{minor}."
... |
<vulnerable_code> if deop == LOAD_GLOBAL:
argval, argrepr = _get_name_info(arg//2, get_name)
if (arg & 1) and argrepr:
argrepr = "NULL + " + argrepr
elif deop == LOAD_ATTR:
argval, argrepr = _get_name_info... |
<vulnerable_code># Python 3.13a1 3555 (generate specialized opcodes metadata from bytecodes.c)
# Python 3.13a1 3556 (Convert LOAD_CLOSURE to a pseudo-op)
# Python 3.13a1 3557 (Make the conversion to boolean in jumps explicit)
# Python 3.14 will start with 3600
# Whenever MAGIC_NUMBER is changed, the r... |
<vulnerable_code>
instructions = [
('RESUME', 0,),
('PUSH_NULL', 0, 1),
('LOAD_CLOSURE', 0, 1),
('BUILD_TUPLE', 1, 1),
('LOAD_CONST', 1, 1),
('MAKE_FUNCTION', 0, 2),
('SET_FUNCTION_ATTRIBUTE', 8, 2),
('CALL', 0, 2), ... |
<vulnerable_code> loop_lbl := self.Label(),
('FOR_ITER', exit_lbl := self.Label(), 1),
('STORE_NAME', 1, 1),
('PUSH_NULL', None, 2),
('LOAD_NAME', 2, 2),
('LOAD_NAME', 1, 2),
('CALL', 1, 2),
('POP_TOP', None),<commit_title>[P... |
<vulnerable_code>dis_f = """\
%3d RESUME 0
%3d LOAD_GLOBAL 1 (NULL + print)
LOAD_FAST 0 (a)
CALL 1
POP_TOP
dis_bug708901 = """\
%3d RESUME 0
%3d LOAD_GLOBAL 1 (... |
<vulnerable_code> LOAD_GLOBAL_BUILTIN,
};
inst(LOAD_GLOBAL, (unused/1, unused/1, unused/1, unused/1 -- null if (oparg & 1), v)) {
#if ENABLE_SPECIALIZATION
_PyLoadGlobalCache *cache = (_PyLoadGlobalCache *)next_instr;
if (ADAPTIVE_COUNTER_IS_ZERO(cache->co... |
<vulnerable_code>
int is_generic = asdl_seq_LEN(type_params) > 0;
if (is_generic) {
// Used by the CALL to the type parameters function.
ADDOP(c, loc, PUSH_NULL);
}
funcflags = compiler_default_arguments(c, loc, args);
if (funcflags == -1) {
return ERROR;
Py_DECREF(... |
<vulnerable_code> break;
case KW_NAMES:
break;
case PUSH_NULL:
if (nextop == LOAD_GLOBAL && (inst[1].i_opcode & 1) == 0) {
INSTR_SET_OP0(inst, NOP);
inst[1].i_oparg |= 1;
}
brea... |
<vulnerable_code> if (!function_check_args(fget, 1, LOAD_ATTR)) {
goto fail;
}
uint32_t version = function_get_version(fget, LOAD_ATTR);
if (version == 0) {
goto fail;
if (!function_check_args(descr, 2, LOAD_ATTR)) {
... |
<vulnerable_code> items = []
for _ in range(self.ITEMS):
item = C()
item.__dict__
item.a = None
items.append(item)
return items
items = []
for _ in range(self.ITEMS):
item = C()
... |
<vulnerable_code> return make_dict_from_instance_attributes(interp, keys, values);
}
int
_PyObject_StoreInstanceAttribute(PyObject *obj, PyDictValues *values,
PyObject *name, PyObject *value)
dict = _PyDictOrValues_GetDict(*dorv_ptr);
if (dict == NULL) {
... |
<vulnerable_code> return res;
}
extern void
_PyDictKeys_DecRef(PyDictKeysObject *keys);
static void
type_dealloc_common(PyTypeObject *type)<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue... |
<vulnerable_code> op(_CHECK_MANAGED_OBJECT_HAS_VALUES, (owner -- owner)) {
assert(Py_TYPE(owner)->tp_dictoffset < 0);
assert(Py_TYPE(owner)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
PyDictOrValues dorv = *_PyObject_DictOrValuesPointer(owner);
DEOPT_IF(!_PyDictOrValues_... |
<vulnerable_code> fprintf(out, "Object materialize dict (new key): %" PRIu64 "\n", stats->dict_materialized_new_key);
fprintf(out, "Object materialize dict (too big): %" PRIu64 "\n", stats->dict_materialized_too_big);
fprintf(out, "Object materialize dict (str subclass): %" PRIu64 "\n", stats->dict_materiali... |
<vulnerable_code>// Test code object watching
#define NUM_CODE_WATCHERS 2
static int num_code_object_created_events[NUM_CODE_WATCHERS] = {0, 0};
static int num_code_object_destroyed_events[NUM_CODE_WATCHERS] = {0, 0};
long which_l = PyLong_AsLong(which_watcher);
if (which_l == 0) {
watcher_id = PyCode... |
<vulnerable_code> Array_ass_subscript,
};
PyTypeObject PyCArray_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_ctypes.Array",
0, /* tp_getattro */
0, /* tp_setattro */
&PyCData_as_buffer, /* tp_a... |
<vulnerable_code> wrapper.__name__ = getattr(user_function, '__name__')
wrapper.__qualname__ = getattr(user_function, '__qualname__')
wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
return wrapper
return decorating_function<commit_title>[PATCH 016/395] Small f... |
<vulnerable_code> for name in assigned:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
if __name__ == "__main__":
unittest.main()<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and... |
<vulnerable_code>static PyObject *
docstr_fallback_to_converter_default_impl(PyObject *module, str a)
/*[clinic end generated code: output=ae24a9c6f60ee8a6 input=0cbe6a4d24bc2274]*/
/*[clinic input]
test_deprecate_positional_pos1_len1_optional
a: object
* [from 3.14]
b: object = None
[clinic start generat... |
<vulnerable_code># Copyright 2012-2013 by Larry Hastings.
# Licensed to the PSF under a contributor agreement.
from test import support, test_tools
from test.support import os_helper
from test.support.os_helper import TESTFN, unlink
locals().update((name, getattr(ac_tester, name))
for name in d... |
<vulnerable_code>}
static PyMethodDef tester_methods[] = {
TEST_EMPTY_FUNCTION_METHODDEF
OBJECTS_CONVERTER_METHODDEF
CLONE_F2_METHODDEF
CLONE_WITH_CONV_F1_METHODDEF
CLONE_WITH_CONV_F2_METHODDEF
{NULL, NULL}
};
PyMODINIT_FUNC
PyInit__testclinic(void)
{
return PyModule_Create(&_testclinic_m... |
<vulnerable_code> assert hook not in o
if __name__ == "__main__":
from test.support import suppress_msvcrt_asserts
<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-106706).<... |
<vulnerable_code> self.fail(stderr)
if __name__ == "__main__":
unittest.main()<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in PR gh-106716 (issue gh-106706).<fixed_code>
self.fail(std... |
<vulnerable_code> PyErr_Format(PyExc_ValueError, "invalid event %d", event);
return NULL;
}
if (func == Py_None) {
func = NULL;
}<commit_title>[PATCH 016/395] Small fixes to code generator (#106845)<commit_description>These repair nits I found in PR gh-106798 (issue gh-106797) and in ... |
<vulnerable_code> && ((C)->u->u_ste->ste_type == ModuleBlock))
typedef _PyCompilerSrcLocation location;
typedef _PyCfgInstruction cfg_instr;
typedef _PyCfgBasicblock basicblock;
typedef _PyCfgBuilder cfg_builder;
#define LOCATION(LNO, END_LNO, COL, END_COL) \
((const _PyCompilerSrcLocation){(LNO), (END_LNO... |
<vulnerable_code>
typedef _PyCompilerSrcLocation location;
typedef _PyCfgJumpTargetLabel jump_target_label;
typedef _PyCfgBasicblock basicblock;
typedef _PyCfgBuilder cfg_builder;
typedef _PyCfgInstruction cfg_instr;
static const jump_target_label NO_LABEL = {-1};
#define SAME_LABEL(L1, L2) ((L1).id == (L2).id)
#defi... |
<vulnerable_code>import dis
import threading
import types
import unittest
from test.support import threading_helper
class TestLoadSuperAttrCache(unittest.TestCase):
opname = "UNPACK_SEQUENCE_LIST"
self.assert_races_do_not_crash(opname, get_items, read, write)
if __name__ == "__main__":
unittest.... |
<vulnerable_code>#include "pycore_bytesobject.h" // _PyBytes_Find()
#include "pycore_compile.h" // _PyCompile_CodeGen, _PyCompile_OptimizeCfg, _PyCompile_Assemble, _PyCompile_CleanDoc
#include "pycore_ceval.h" // _PyEval_AddPendingCall
#include "pycore_fileutils.h" // _Py_normpath
#include "pycore_frame... |
<vulnerable_code> return make_dict_from_instance_attributes(interp, keys, values);
}
// Return 1 if the dict was dematerialized, 0 otherwise.
int
_PyObject_MakeInstanceAttributesFromDict(PyObject *obj, PyDictOrValues *dorv)
{
assert(_PyObject_DictOrValuesPointer(obj) == dorv);
assert(!_PyDictOrValues_IsValu... |
<vulnerable_code> /* Offset visible to user should be the offset in bytes, as that is the
* convention for APIs involving code offsets. */
int bytes_offset = offset * (int)sizeof(_Py_CODEUNIT);
PyObject *offset_obj = PyLong_FromSsize_t(bytes_offset);
if (offset_obj == NULL) {
return -1;
... |
<vulnerable_code> # message, and future-proofs us in case we build up the function
# using ast.
seen_default = False
for f in std_fields:
# Only consider the non-kw-only fields in the __init__ call.
if f.init:
if not (f.default is MISSING and f.default_factory is MISSING):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.