The following issues were found
Lib/distutils/command/build_scripts.py
16 issues
Line: 42
Column: 9
('build_scripts', 'build_dir'),
('force', 'force'),
('executable', 'executable'))
self.scripts = self.distribution.scripts
def get_source_files(self):
return self.scripts
def run(self):
Reported by Pylint.
Line: 82
Column: 27
raise
f = None
else:
encoding, lines = tokenize.detect_encoding(f.readline)
f.seek(0)
first_line = f.readline()
if not first_line:
self.warn("%s is an empty file (skipping)" % script)
continue
Reported by Pylint.
Line: 116
Column: 25
try:
shebang.decode('utf-8')
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from utf-8".format(shebang))
# If the script is encoded to a custom encoding (use a
# #coding:xxx cookie), the shebang has to be decodable from
# the script encoding too.
Reported by Pylint.
Line: 125
Column: 25
try:
shebang.decode(encoding)
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from the script encoding ({})"
.format(shebang, encoding))
with open(outfile, "wb") as outf:
outf.write(shebang)
Reported by Pylint.
Line: 151
Column: 3
log.info("changing mode of %s from %o to %o",
file, oldmode, newmode)
os.chmod(file, newmode)
# XXX should we modify self.outfiles?
return outfiles, updated_files
class build_scripts_2to3(build_scripts, Mixin2to3):
def copy_scripts(self):
Reported by Pylint.
Line: 5
Column: 1
Implements the Distutils 'build_scripts' command."""
import os, re
from stat import ST_MODE
from distutils import sysconfig
from distutils.core import Command
from distutils.dep_util import newer
from distutils.util import convert_path, Mixin2to3
Reported by Pylint.
Line: 17
Column: 1
# check if Python is called on the first line with this expression
first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')
class build_scripts(Command):
description = "\"build\" scripts (copy and fixup #! line)"
user_options = [
('build-dir=', 'd', "directory to \"build\" (copy) to"),
Reported by Pylint.
Line: 17
Column: 1
# check if Python is called on the first line with this expression
first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')
class build_scripts(Command):
description = "\"build\" scripts (copy and fixup #! line)"
user_options = [
('build-dir=', 'd', "directory to \"build\" (copy) to"),
Reported by Pylint.
Line: 44
Column: 5
('executable', 'executable'))
self.scripts = self.distribution.scripts
def get_source_files(self):
return self.scripts
def run(self):
if not self.scripts:
return
Reported by Pylint.
Line: 53
Column: 5
self.copy_scripts()
def copy_scripts(self):
r"""Copy each script listed in 'self.scripts'; if it's marked as a
Python script in the Unix way (first line matches 'first_line_re',
ie. starts with "\#!" and contains "python"), then adjust the first
line to refer to the current Python interpreter as we copy.
"""
Reported by Pylint.
Lib/lib2to3/main.py
16 issues
Line: 14
Column: 1
import shutil
import optparse
from . import refactor
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
Reported by Pylint.
Line: 12
Column: 1
import difflib
import logging
import shutil
import optparse
from . import refactor
def diff_texts(a, b, filename):
Reported by Pylint.
Line: 17
Column: 1
from . import refactor
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
Reported by Pylint.
Line: 17
Column: 1
from . import refactor
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
Reported by Pylint.
Line: 36
Column: 5
where you do not want to replace the input files.
"""
def __init__(self, fixers, options, explicit, nobackups, show_diffs,
input_base_dir='', output_dir='', append_suffix=''):
"""
Args:
fixers: A list of fixers to import.
options: A dict with RefactoringTool configuration.
Reported by Pylint.
Line: 63
Column: 9
self._input_base_dir = input_base_dir
self._output_dir = output_dir
self._append_suffix = append_suffix
super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
def log_error(self, msg, *args, **kwargs):
self.errors.append((msg, args, kwargs))
self.logger.error(msg, *args, **kwargs)
Reported by Pylint.
Line: 65
Column: 5
self._append_suffix = append_suffix
super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
def log_error(self, msg, *args, **kwargs):
self.errors.append((msg, args, kwargs))
self.logger.error(msg, *args, **kwargs)
def write_file(self, new_text, filename, old_text, encoding):
orig_filename = filename
Reported by Pylint.
Line: 69
Column: 5
self.errors.append((msg, args, kwargs))
self.logger.error(msg, *args, **kwargs)
def write_file(self, new_text, filename, old_text, encoding):
orig_filename = filename
if self._output_dir:
if filename.startswith(self._input_base_dir):
filename = os.path.join(self._output_dir,
filename[len(self._input_base_dir):])
Reported by Pylint.
Line: 100
Column: 17
except OSError:
self.log_message("Can't rename %s to %s", filename, backup)
# Actually write the new file
write = super(StdoutRefactoringTool, self).write_file
write(new_text, filename, old_text, encoding)
if not self.nobackups:
shutil.copymode(backup, filename)
if orig_filename != filename:
# Preserve the file mode in the new output directory.
Reported by Pylint.
Line: 108
Column: 5
# Preserve the file mode in the new output directory.
shutil.copymode(orig_filename, filename)
def print_output(self, old, new, filename, equal):
if equal:
self.log_message("No changes to %s", filename)
else:
self.log_message("Refactored %s", filename)
if self.show_diffs:
Reported by Pylint.
Lib/idlelib/idle_test/test_undo.py
16 issues
Line: 129
Column: 13
text = self.text
# when number of undo operations exceeds max_undo
self.delegator.max_undo = max_undo = 10
for i in range(max_undo + 10):
text.insert('insert', 'foo')
self.assertLessEqual(len(self.delegator.undolist), max_undo)
if __name__ == '__main__':
Reported by Pylint.
Line: 5
Column: 1
# Only test UndoDelegator so far.
from idlelib.undo import UndoDelegator
import unittest
from test.support import requires
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
Reported by Pylint.
Line: 6
Column: 1
from idlelib.undo import UndoDelegator
import unittest
from test.support import requires
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
Reported by Pylint.
Line: 9
Column: 1
from test.support import requires
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
Reported by Pylint.
Line: 9
Column: 1
from test.support import requires
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
Reported by Pylint.
Line: 10
Column: 1
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
Reported by Pylint.
Line: 10
Column: 1
requires('gui')
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
Reported by Pylint.
Line: 11
Column: 1
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
@classmethod
Reported by Pylint.
Line: 14
Column: 1
from idlelib.percolator import Percolator
class UndoDelegatorTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.text = Text(cls.root)
Reported by Pylint.
Line: 39
Column: 5
self.text.delete('1.0', 'end')
self.delegator.resetcache()
def test_undo_event(self):
text = self.text
text.insert('insert', 'foobar')
text.insert('insert', 'h')
text.event_generate('<<undo>>')
Reported by Pylint.
Lib/lib2to3/pgen2/literals.py
16 issues
Line: 20
Column: 5
"\\": "\\"}
def escape(m):
all, tail = m.group(0, 1)
assert all.startswith("\\")
esc = simple_escapes.get(tail)
if esc is not None:
return esc
if tail.startswith("x"):
Reported by Pylint.
Line: 19
Column: 1
'"': '"',
"\\": "\\"}
def escape(m):
all, tail = m.group(0, 1)
assert all.startswith("\\")
esc = simple_escapes.get(tail)
if esc is not None:
return esc
Reported by Pylint.
Line: 19
Column: 1
'"': '"',
"\\": "\\"}
def escape(m):
all, tail = m.group(0, 1)
assert all.startswith("\\")
esc = simple_escapes.get(tail)
if esc is not None:
return esc
Reported by Pylint.
Line: 21
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def escape(m):
all, tail = m.group(0, 1)
assert all.startswith("\\")
esc = simple_escapes.get(tail)
if esc is not None:
return esc
if tail.startswith("x"):
hexes = tail[1:]
Reported by Bandit.
Line: 40
Column: 1
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
return chr(i)
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
Reported by Pylint.
Line: 40
Column: 1
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
return chr(i)
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
Reported by Pylint.
Line: 40
Column: 1
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
return chr(i)
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
Reported by Pylint.
Line: 41
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
return chr(i)
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
assert len(s) >= 2*len(q)
Reported by Bandit.
Line: 42
Column: 5
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
assert len(s) >= 2*len(q)
s = s[len(q):-len(q)]
Reported by Pylint.
Line: 44
Column: 9
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
assert len(s) >= 2*len(q)
s = s[len(q):-len(q)]
return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
Reported by Pylint.
Lib/distutils/tests/test_build_scripts.py
16 issues
Line: 54
Column: 36
)
return build_scripts(dist)
def write_sample_scripts(self, dir):
expected = []
expected.append("script1.py")
self.write_script(dir, "script1.py",
("#! /usr/bin/env python2.3\n"
"# bogus script w/ Python sh-bang\n"
Reported by Pylint.
Line: 73
Column: 28
"exit 0\n"))
return expected
def write_script(self, dir, name, text):
f = open(os.path.join(dir, name), "w")
try:
f.write(text)
finally:
f.close()
Reported by Pylint.
Line: 97
Column: 9
# --with-suffix=3`, python is compiled okay but the build scripts
# failed when writing the name of the executable
old = sysconfig.get_config_vars().get('VERSION')
sysconfig._config_vars['VERSION'] = 4
try:
cmd.run()
finally:
if old is not None:
sysconfig._config_vars['VERSION'] = old
Reported by Pylint.
Line: 102
Column: 17
cmd.run()
finally:
if old is not None:
sysconfig._config_vars['VERSION'] = old
built = os.listdir(target)
for name in expected:
self.assertIn(name, built)
Reported by Pylint.
Line: 14
Column: 1
from test.support import run_unittest
class BuildScriptsTestCase(support.TempdirManager,
support.LoggingSilencer,
unittest.TestCase):
def test_default_settings(self):
cmd = self.get_build_scripts_cmd("/foo/bar", [])
Reported by Pylint.
Line: 18
Column: 5
support.LoggingSilencer,
unittest.TestCase):
def test_default_settings(self):
cmd = self.get_build_scripts_cmd("/foo/bar", [])
self.assertFalse(cmd.force)
self.assertIsNone(cmd.build_dir)
cmd.finalize_options()
Reported by Pylint.
Line: 28
Column: 5
self.assertTrue(cmd.force)
self.assertEqual(cmd.build_dir, "/foo/bar")
def test_build(self):
source = self.mkdtemp()
target = self.mkdtemp()
expected = self.write_sample_scripts(source)
cmd = self.get_build_scripts_cmd(target,
Reported by Pylint.
Line: 43
Column: 5
for name in expected:
self.assertIn(name, built)
def get_build_scripts_cmd(self, target, scripts):
import sys
dist = Distribution()
dist.scripts = scripts
dist.command_obj["build"] = support.DummyCommand(
build_scripts=target,
Reported by Pylint.
Line: 43
Column: 5
for name in expected:
self.assertIn(name, built)
def get_build_scripts_cmd(self, target, scripts):
import sys
dist = Distribution()
dist.scripts = scripts
dist.command_obj["build"] = support.DummyCommand(
build_scripts=target,
Reported by Pylint.
Line: 44
Column: 9
self.assertIn(name, built)
def get_build_scripts_cmd(self, target, scripts):
import sys
dist = Distribution()
dist.scripts = scripts
dist.command_obj["build"] = support.DummyCommand(
build_scripts=target,
force=1,
Reported by Pylint.
Tools/peg_generator/pegen/testutil.py
16 issues
Line: 35
Column: 5
# Load the generated parser class.
ns: Dict[str, Any] = {}
exec(out.getvalue(), ns)
return ns["GeneratedParser"]
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
# Run a parser on a file (stream).
Reported by Pylint.
Line: 35
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
# Load the generated parser class.
ns: Dict[str, Any] = {}
exec(out.getvalue(), ns)
return ns["GeneratedParser"]
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
# Run a parser on a file (stream).
Reported by Bandit.
Line: 1
Column: 1
import importlib.util
import io
import os
import pathlib
import sys
import textwrap
import tokenize
import token
Reported by Pylint.
Line: 27
Column: 1
}
def generate_parser(grammar: Grammar) -> Type[Parser]:
# Generate a parser.
out = io.StringIO()
genr = PythonParserGenerator(grammar, out)
genr.generate("<string>")
Reported by Pylint.
Line: 34
Column: 5
genr.generate("<string>")
# Load the generated parser class.
ns: Dict[str, Any] = {}
exec(out.getvalue(), ns)
return ns["GeneratedParser"]
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
Reported by Pylint.
Line: 39
Column: 1
return ns["GeneratedParser"]
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
# Run a parser on a file (stream).
tokenizer = Tokenizer(tokenize.generate_tokens(file.readline)) # type: ignore # typeshed issue #3515
parser = parser_class(tokenizer, verbose=verbose)
result = parser.start()
if result is None:
Reported by Pylint.
Line: 41
Column: 1
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
# Run a parser on a file (stream).
tokenizer = Tokenizer(tokenize.generate_tokens(file.readline)) # type: ignore # typeshed issue #3515
parser = parser_class(tokenizer, verbose=verbose)
result = parser.start()
if result is None:
raise parser.make_syntax_error("invalid syntax")
return result
Reported by Pylint.
Line: 49
Column: 1
return result
def parse_string(
source: str, parser_class: Type[Parser], *, dedent: bool = True, verbose: bool = False
) -> Any:
# Run the parser on a string.
if dedent:
source = textwrap.dedent(source)
Reported by Pylint.
Line: 59
Column: 1
return run_parser(file, parser_class, verbose=verbose) # type: ignore # typeshed issue #3515
def make_parser(source: str) -> Type[Parser]:
# Combine parse_string() and generate_parser().
grammar = parse_string(source, GrammarParser)
return generate_parser(grammar)
Reported by Pylint.
Line: 69
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
"""Import a python module from a path"""
spec = importlib.util.spec_from_file_location(full_name, path)
assert spec is not None
mod = importlib.util.module_from_spec(spec)
# We assume this is not None and has an exec_module() method.
# See https://docs.python.org/3/reference/import.html?highlight=exec_module#loading
loader = cast(Any, spec.loader)
Reported by Bandit.
Tools/scripts/generate_opcode_h.py
16 issues
Line: 38
Column: 9
for op in ops:
bits |= 1<<op
out.write(f"static uint32_t {name}[8] = {{\n")
for i in range(8):
out.write(f" {bits & UINT32_MASK}U,\n")
bits >>= 32
assert bits == 0
out.write(f"}};\n")
Reported by Pylint.
Line: 42
Column: 15
out.write(f" {bits & UINT32_MASK}U,\n")
bits >>= 32
assert bits == 0
out.write(f"}};\n")
def main(opcode_py, outfile='Include/opcode.h'):
opcode = {}
if hasattr(tokenize, 'open'):
fp = tokenize.open(opcode_py) # Python 3.2+
Reported by Pylint.
Line: 52
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html
fp = open(opcode_py) # Python 2.7
with fp:
code = fp.read()
exec(code, opcode)
opmap = opcode['opmap']
hasjrel = opcode['hasjrel']
hasjabs = opcode['hasjabs']
used = [ False ] * 256
next_op = 1
Reported by Bandit.
Line: 52
Column: 5
fp = open(opcode_py) # Python 2.7
with fp:
code = fp.read()
exec(code, opcode)
opmap = opcode['opmap']
hasjrel = opcode['hasjrel']
hasjabs = opcode['hasjabs']
used = [ False ] * 256
next_op = 1
Reported by Pylint.
Line: 54
Column: 5
code = fp.read()
exec(code, opcode)
opmap = opcode['opmap']
hasjrel = opcode['hasjrel']
hasjabs = opcode['hasjabs']
used = [ False ] * 256
next_op = 1
for name, op in opmap.items():
used[op] = True
Reported by Pylint.
Line: 55
Column: 5
exec(code, opcode)
opmap = opcode['opmap']
hasjrel = opcode['hasjrel']
hasjabs = opcode['hasjabs']
used = [ False ] * 256
next_op = 1
for name, op in opmap.items():
used[op] = True
with open(outfile, 'w') as fobj:
Reported by Pylint.
Line: 1
Column: 1
# This script generates the opcode.h header file.
import sys
import tokenize
header = """
/* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */
#ifndef Py_OPCODE_H
#define Py_OPCODE_H
Reported by Pylint.
Line: 6
Column: 1
import sys
import tokenize
header = """
/* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */
#ifndef Py_OPCODE_H
#define Py_OPCODE_H
#ifdef __cplusplus
extern "C" {
Reported by Pylint.
Line: 18
Column: 1
/* Instruction opcodes for compiled code */
""".lstrip()
footer = """
#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT)
/* Reserve some bytecodes for internal use in the compiler.
* The value of 240 is arbitrary. */
#define IS_ARTIFICIAL(op) ((op) > 240)
Reported by Pylint.
Line: 33
Column: 1
UINT32_MASK = (1<<32)-1
def write_int_array_from_ops(name, ops, out):
bits = 0
for op in ops:
bits |= 1<<op
out.write(f"static uint32_t {name}[8] = {{\n")
for i in range(8):
Reported by Pylint.
Tools/scripts/generate_stdlib_module_names.py
15 issues
Line: 114
Column: 12
# Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
args = [TEST_EMBED, 'list_frozen']
proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
exitcode = proc.returncode
if exitcode:
cmd = ' '.join(args)
print(f"{cmd} failed with exitcode {exitcode}")
sys.exit(exitcode)
Reported by Pylint.
Line: 1
Column: 1
# This script lists the names of standard library modules
# to update Python/stdlib_mod_names.h
import os.path
import re
import subprocess
import sys
import sysconfig
Reported by Pylint.
Line: 5
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess
# to update Python/stdlib_mod_names.h
import os.path
import re
import subprocess
import sys
import sysconfig
SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
Reported by Bandit.
Line: 56
Column: 1
# Pure Python modules (Lib/*.py)
def list_python_modules(names):
for filename in os.listdir(STDLIB_PATH):
if not filename.endswith(".py"):
continue
name = filename.removesuffix(".py")
names.add(name)
Reported by Pylint.
Line: 65
Column: 1
# Packages in Lib/
def list_packages(names):
for name in os.listdir(STDLIB_PATH):
if name in IGNORE:
continue
package_path = os.path.join(STDLIB_PATH, name)
if not os.path.isdir(package_path):
Reported by Pylint.
Line: 78
Column: 1
# Extension modules built by setup.py
def list_setup_extensions(names):
cmd = [sys.executable, SETUP_PY, "-q", "build", "--list-module-names"]
output = subprocess.check_output(cmd)
output = output.decode("utf8")
extensions = output.splitlines()
names |= set(extensions)
Reported by Pylint.
Line: 80
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html
# Extension modules built by setup.py
def list_setup_extensions(names):
cmd = [sys.executable, SETUP_PY, "-q", "build", "--list-module-names"]
output = subprocess.check_output(cmd)
output = output.decode("utf8")
extensions = output.splitlines()
names |= set(extensions)
Reported by Bandit.
Line: 87
Column: 1
# Built-in and extension modules built by Modules/Setup
def list_modules_setup_extensions(names):
assign_var = re.compile("^[A-Z]+=")
with open(MODULES_SETUP, encoding="utf-8") as modules_fp:
for line in modules_fp:
# Strip comment
Reported by Pylint.
Line: 112
Column: 1
# List frozen modules of the PyImport_FrozenModules list (Python/frozen.c).
# Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
args = [TEST_EMBED, 'list_frozen']
proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
exitcode = proc.returncode
if exitcode:
cmd = ' '.join(args)
Reported by Pylint.
Line: 114
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html
# Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
args = [TEST_EMBED, 'list_frozen']
proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
exitcode = proc.returncode
if exitcode:
cmd = ' '.join(args)
print(f"{cmd} failed with exitcode {exitcode}")
sys.exit(exitcode)
Reported by Bandit.
Tools/scripts/nm2def.py
15 issues
Line: 45
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html
def symbols(lib=PYTHONLIB,types=('T','C','D')):
with os.popen(NM % lib) as pipe:
lines = pipe.readlines()
lines = [s.strip() for s in lines]
symbols = {}
for line in lines:
if len(line) == 0 or ':' in line:
Reported by Bandit.
Line: 48
Column: 5
with os.popen(NM % lib) as pipe:
lines = pipe.readlines()
lines = [s.strip() for s in lines]
symbols = {}
for line in lines:
if len(line) == 0 or ':' in line:
continue
items = line.split()
if len(items) != 3:
Reported by Pylint.
Line: 55
Column: 18
items = line.split()
if len(items) != 3:
continue
address, type, name = items
if type not in types:
continue
symbols[name] = address,type
return symbols
Reported by Pylint.
Line: 61
Column: 17
symbols[name] = address,type
return symbols
def export_list(symbols):
data = []
code = []
for name,(addr,type) in symbols.items():
if type in ('C','D'):
Reported by Pylint.
Line: 65
Column: 15
data = []
code = []
for name,(addr,type) in symbols.items():
if type in ('C','D'):
data.append('\t'+name)
else:
code.append('\t'+name)
data.sort()
Reported by Pylint.
Line: 65
Column: 20
data = []
code = []
for name,(addr,type) in symbols.items():
if type in ('C','D'):
data.append('\t'+name)
else:
code.append('\t'+name)
data.sort()
Reported by Pylint.
Line: 86
Column: 19
SPECIALS = (
)
def filter_Python(symbols,specials=SPECIALS):
for name in list(symbols.keys()):
if name[:2] == 'Py' or name[:3] == '_Py':
pass
elif name not in specials:
Reported by Pylint.
Line: 37
Column: 1
option to produce this format (since it is the original v7 Unix format).
"""
import os, sys
PYTHONLIB = 'libpython%d.%d.a' % sys.version_info[:2]
PC_PYTHONLIB = 'Python%d%d.dll' % sys.version_info[:2]
NM = 'nm -p -g %s' # For Linux, use "nm -g %s"
Reported by Pylint.
Line: 43
Column: 1
PC_PYTHONLIB = 'Python%d%d.dll' % sys.version_info[:2]
NM = 'nm -p -g %s' # For Linux, use "nm -g %s"
def symbols(lib=PYTHONLIB,types=('T','C','D')):
with os.popen(NM % lib) as pipe:
lines = pipe.readlines()
lines = [s.strip() for s in lines]
symbols = {}
Reported by Pylint.
Line: 61
Column: 1
symbols[name] = address,type
return symbols
def export_list(symbols):
data = []
code = []
for name,(addr,type) in symbols.items():
if type in ('C','D'):
Reported by Pylint.
Python/getargs.c
15 issues
Line: 258
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
vgetargs1_impl(PyObject *compat_args, PyObject *const *stack, Py_ssize_t nargs, const char *format,
va_list *p_va, int flags)
{
char msgbuf[256];
int levels[32];
const char *fname = NULL;
const char *message = NULL;
int min = -1;
int max = 0;
Reported by FlawFinder.
Line: 442
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
seterror(Py_ssize_t iarg, const char *msg, int *levels, const char *fname,
const char *message)
{
char buf[512];
int i;
char *p = buf;
if (PyErr_Occurred())
return;
Reported by FlawFinder.
Line: 1187
Column: 13
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
RETURN_ERR_OCCURRED;
}
}
memcpy(*buffer, ptr, size+1);
*psize = size;
}
else {
/* Using a 0-terminated buffer:
Reported by FlawFinder.
Line: 1222
Column: 13
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
return converterr("(cleanup problem)",
arg, msgbuf, bufsize);
}
memcpy(*buffer, ptr, size+1);
}
Py_DECREF(s);
break;
}
Reported by FlawFinder.
Line: 1577
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
vgetargskeywords(PyObject *args, PyObject *kwargs, const char *format,
char **kwlist, va_list *p_va, int flags)
{
char msgbuf[512];
int levels[32];
const char *fname, *msg, *custom_msg;
int min = INT_MAX;
int max = INT_MAX;
int i, pos, len;
Reported by FlawFinder.
Line: 2012
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
va_list *p_va, int flags)
{
PyObject *kwtuple;
char msgbuf[512];
int levels[32];
const char *format;
const char *msg;
PyObject *keyword;
int i, pos, len;
Reported by FlawFinder.
Line: 451
Column: 18
CWE codes:
126
else if (message == NULL) {
if (fname != NULL) {
PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
p += strlen(p);
}
if (iarg != 0) {
PyOS_snprintf(p, sizeof(buf) - (p - buf),
"argument %zd", iarg);
i = 0;
Reported by FlawFinder.
Line: 457
Column: 18
CWE codes:
126
PyOS_snprintf(p, sizeof(buf) - (p - buf),
"argument %zd", iarg);
i = 0;
p += strlen(p);
while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
PyOS_snprintf(p, sizeof(buf) - (p - buf),
", item %d", levels[i]-1);
p += strlen(p);
i++;
Reported by FlawFinder.
Line: 461
Column: 22
CWE codes:
126
while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
PyOS_snprintf(p, sizeof(buf) - (p - buf),
", item %d", levels[i]-1);
p += strlen(p);
i++;
}
}
else {
PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
Reported by FlawFinder.
Line: 467
Column: 18
CWE codes:
126
}
else {
PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
p += strlen(p);
}
PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
message = buf;
}
if (msg[0] == '(') {
Reported by FlawFinder.