The following issues were found

Modules/arraymodule.c
19 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 834 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  if (np == NULL)
        return NULL;
    if (ihigh > ilow) {
        memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
               (ihigh-ilow) * a->ob_descr->itemsize);
    }
    return (PyObject *)np;
}


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 896 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      return NULL;
    }
    if (Py_SIZE(a) > 0) {
        memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
    }
    if (Py_SIZE(b) > 0) {
        memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
               b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
    }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 899 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
    }
    if (Py_SIZE(b) > 0) {
        memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
               b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
    }
    return (PyObject *)np;
#undef b
}

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 931 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      memset(np->ob_item, a->ob_item[0], newbytes);
    } else {
        Py_ssize_t done = oldbytes;
        memcpy(np->ob_item, a->ob_item, oldbytes);
        while (done < newbytes) {
            Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
            memcpy(np->ob_item+done, np->ob_item, ncopy);
            done += ncopy;
        }

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 934 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      memcpy(np->ob_item, a->ob_item, oldbytes);
        while (done < newbytes) {
            Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
            memcpy(np->ob_item+done, np->ob_item, ncopy);
            done += ncopy;
        }
    }
    return (PyObject *)np;
}

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1047 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  if (array_resize(self, size) == -1)
        return -1;
    if (bbsize > 0) {
        memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
            b->ob_item, bbsize * b->ob_descr->itemsize);
    }

    return 0;
#undef b

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1094 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      items = p = self->ob_item;
        for (i = 1; i < n; i++) {
            p += size;
            memcpy(p, items, size);
        }
    }
    Py_INCREF(self);
    return (PyObject *)self;
}

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 1445 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

                  Py_ssize_t itemsize = self->ob_descr->itemsize;
    char *p, *q;
    /* little buffer to hold items while swapping */
    char tmp[256];      /* 8 is probably enough -- but why skimp */
    assert((size_t)itemsize <= sizeof(tmp));

    if (Py_SIZE(self) > 1) {
        for (p = self->ob_item,
             q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1456 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                          /* memory areas guaranteed disjoint, so memcpy
             * is safe (& memmove may be slower).
             */
            memcpy(tmp, p, itemsize);
            memcpy(p, q, itemsize);
            memcpy(q, tmp, itemsize);
        }
    }


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1457 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                           * is safe (& memmove may be slower).
             */
            memcpy(tmp, p, itemsize);
            memcpy(p, q, itemsize);
            memcpy(q, tmp, itemsize);
        }
    }

    Py_RETURN_NONE;

            

Reported by FlawFinder.

Tools/msi/csv_to_wxs.py
19 issues
Missing function or method docstring
Error

Line: 33 Column: 1

                  '+': '_P',
}

def make_id(path):
    return re.sub(
        r'[^A-Za-z0-9_.]',
        lambda m: ID_CHAR_SUBS.get(m.group(0), '_'),
        str(path).rstrip('/\\'),
        flags=re.I

            

Reported by Pylint.

Too many statements (52/50)
Error

Line: 43 Column: 1

              
DIRECTORIES = set()

def main(file_source, install_target):
    with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"


            

Reported by Pylint.

Too many branches (15/12)
Error

Line: 43 Column: 1

              
DIRECTORIES = set()

def main(file_source, install_target):
    with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"


            

Reported by Pylint.

Too many local variables (19/15)
Error

Line: 43 Column: 1

              
DIRECTORIES = set()

def main(file_source, install_target):
    with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 1

              
DIRECTORIES = set()

def main(file_source, install_target):
    with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"


            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 44 Column: 48

              DIRECTORIES = set()

def main(file_source, install_target):
    with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"

    directories = defaultdict(set)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 47
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  with open(file_source, 'r', newline='') as f:
        files = list(csv.reader(f))

    assert len(files) == len(set(make_id(f[1]) for f in files)), "Duplicate file IDs exist"

    directories = defaultdict(set)
    cache_directories = defaultdict(set)
    groups = defaultdict(list)
    for source, target, group, disk_id, condition in files:

            

Reported by Bandit.

Line too long (122/100)
Error

Line: 71 Column: 1

                  for dir_parent in sorted(directories):
        lines.append('        <DirectoryRef Id="{}">'.format(dir_parent))
        for dir_name in sorted(directories[dir_parent]):
            lines.append('            <Directory Id="{}_{}" Name="{}" />'.format(dir_parent, make_id(dir_name), dir_name))
        lines.append('        </DirectoryRef>')
    for dir_parent in (make_id(d) for group in cache_directories.values() for d in group):
        lines.append('        <DirectoryRef Id="{}">'.format(dir_parent))
        lines.append('            <Directory Id="{}___pycache__" Name="__pycache__" />'.format(dir_parent))
        lines.append('        </DirectoryRef>')

            

Reported by Pylint.

Line too long (107/100)
Error

Line: 75 Column: 1

                      lines.append('        </DirectoryRef>')
    for dir_parent in (make_id(d) for group in cache_directories.values() for d in group):
        lines.append('        <DirectoryRef Id="{}">'.format(dir_parent))
        lines.append('            <Directory Id="{}___pycache__" Name="__pycache__" />'.format(dir_parent))
        lines.append('        </DirectoryRef>')
    lines.append('    </Fragment>')

    for group in sorted(groups):
        lines.extend([

            

Reported by Pylint.

Line too long (131/100)
Error

Line: 85 Column: 1

                          '        <ComponentGroup Id="{}">'.format(group),
        ])
        for source, target, disk_id, condition in groups[group]:
            lines.append('            <Component Id="{}" Directory="{}" Guid="*">'.format(make_id(target), make_id(target.parent)))
            if condition:
                lines.append('                <Condition>{}</Condition>'.format(condition))

            if disk_id:
                lines.append('                <File Id="{}" Name="{}" Source="{}" DiskId="{}" />'.format(make_id(target), target.name, source, disk_id))

            

Reported by Pylint.

Tools/peg_generator/pegen/build.py
19 issues
Unable to import 'distutils.tests.support'
Error

Line: 51 Column: 5

                  from distutils.core import Distribution, Extension
    from distutils.command.clean import clean  # type: ignore
    from distutils.command.build_ext import build_ext  # type: ignore
    from distutils.tests.support import fixup_build_ext  # type: ignore

    if verbose:
        distutils.log.set_verbosity(distutils.log.DEBUG)

    source_file_path = pathlib.Path(generated_source_path)

            

Reported by Pylint.

No name 'tests' in module 'distutils'
Error

Line: 51 Column: 5

                  from distutils.core import Distribution, Extension
    from distutils.command.clean import clean  # type: ignore
    from distutils.command.build_ext import build_ext  # type: ignore
    from distutils.tests.support import fixup_build_ext  # type: ignore

    if verbose:
        distutils.log.set_verbosity(distutils.log.DEBUG)

    source_file_path = pathlib.Path(generated_source_path)

            

Reported by Pylint.

Unused argument 'skip_actions'
Error

Line: 181 Column: 5

                  grammar: Grammar,
    grammar_file: str,
    output_file: str,
    skip_actions: bool = False,
) -> ParserGenerator:
    with open(output_file, "w") as file:
        gen: ParserGenerator = PythonParserGenerator(grammar, file)  # TODO: skip_actions
        gen.generate(grammar_file)
    return gen

            

Reported by Pylint.

TODO: skip_actions
Error

Line: 184 Column: 3

                  skip_actions: bool = False,
) -> ParserGenerator:
    with open(output_file, "w") as file:
        gen: ParserGenerator = PythonParserGenerator(grammar, file)  # TODO: skip_actions
        gen.generate(grammar_file)
    return gen


def build_c_parser_and_generator(

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pathlib
import shutil
import tokenize
import sysconfig
import tempfile
import itertools

from typing import Optional, Tuple, List, IO, Set, Dict


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

              TokenDefinitions = Tuple[Dict[int, str], Dict[str, int], Set[str]]


def get_extra_flags(compiler_flags: str, compiler_py_flags_nodist: str) -> List[str]:
    flags = sysconfig.get_config_var(compiler_flags)
    py_flags_nodist = sysconfig.get_config_var(compiler_py_flags_nodist)
    if flags is None or py_flags_nodist is None:
        return []
    return f"{flags} {py_flags_nodist}".split()

            

Reported by Pylint.

Too many local variables (18/15)
Error

Line: 31 Column: 1

                  return f"{flags} {py_flags_nodist}".split()


def compile_c_extension(
    generated_source_path: str,
    build_dir: Optional[str] = None,
    verbose: bool = False,
    keep_asserts: bool = True,
) -> str:

            

Reported by Pylint.

Import outside toplevel (distutils.log)
Error

Line: 47 Column: 5

                  If *build_dir* is provided, that path will be used as the temporary build directory
    of distutils (this is useful in case you want to use a temporary directory).
    """
    import distutils.log
    from distutils.core import Distribution, Extension
    from distutils.command.clean import clean  # type: ignore
    from distutils.command.build_ext import build_ext  # type: ignore
    from distutils.tests.support import fixup_build_ext  # type: ignore


            

Reported by Pylint.

Import outside toplevel (distutils.core.Distribution, distutils.core.Extension)
Error

Line: 48 Column: 5

                  of distutils (this is useful in case you want to use a temporary directory).
    """
    import distutils.log
    from distutils.core import Distribution, Extension
    from distutils.command.clean import clean  # type: ignore
    from distutils.command.build_ext import build_ext  # type: ignore
    from distutils.tests.support import fixup_build_ext  # type: ignore

    if verbose:

            

Reported by Pylint.

Import outside toplevel (distutils.command.clean.clean)
Error

Line: 49 Column: 5

                  """
    import distutils.log
    from distutils.core import Distribution, Extension
    from distutils.command.clean import clean  # type: ignore
    from distutils.command.build_ext import build_ext  # type: ignore
    from distutils.tests.support import fixup_build_ext  # type: ignore

    if verbose:
        distutils.log.set_verbosity(distutils.log.DEBUG)

            

Reported by Pylint.

Lib/test/test_pstats.py
19 issues
Non-iterable value SortKey is used in an iterating context
Error

Line: 66 Column: 23

                                           self.stats.sort_arg_dict_default[sortkey][-1])

    def test_sort_stats_enum(self):
        for member in SortKey:
            self.stats.sort_stats(member)
            self.assertEqual(
                    self.stats.sort_type,
                    self.stats.sort_arg_dict_default[member.value][-1])
        class CheckedSortKey(StrEnum):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest

from test import support
from io import StringIO
from pstats import SortKey
from enum import StrEnum, _test_simple_enum

import pstats
import cProfile

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 5

              class AddCallersTestCase(unittest.TestCase):
    """Tests for pstats.add_callers helper."""

    def test_combine_results(self):
        # pstats.add_callers should combine the call results of both target
        # and source by adding the call time. See issue1269.
        # new format: used by the cProfile module
        target = {"a": (1, 2, 3, 4)}
        source = {"a": (1, 2, 3, 4), "b": (5, 6, 7, 8)}

            

Reported by Pylint.

Missing class docstring
Error

Line: 29 Column: 1

                      self.assertEqual(new_callers, {'a': 2, 'b': 5})


class StatsTestCase(unittest.TestCase):
    def setUp(self):
        stats_file = support.findfile('pstats.pck')
        self.stats = pstats.Stats(stats_file)

    def test_add(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 34 Column: 5

                      stats_file = support.findfile('pstats.pck')
        self.stats = pstats.Stats(stats_file)

    def test_add(self):
        stream = StringIO()
        stats = pstats.Stats(stream=stream)
        stats.add(self.stats, self.stats)

    def test_sort_stats_int(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 5

                      stats = pstats.Stats(stream=stream)
        stats.add(self.stats, self.stats)

    def test_sort_stats_int(self):
        valid_args = {-1: 'stdname',
                      0: 'calls',
                      1: 'time',
                      2: 'cumulative'}
        for arg_int, arg_str in valid_args.items():

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 49 Column: 5

                          self.assertEqual(self.stats.sort_type,
                             self.stats.sort_arg_dict_default[arg_str][-1])

    def test_sort_stats_string(self):
        for sort_name in ['calls', 'ncalls', 'cumtime', 'cumulative',
                    'filename', 'line', 'module', 'name', 'nfl', 'pcalls',
                    'stdname', 'time', 'tottime']:
            self.stats.sort_stats(sort_name)
            self.assertEqual(self.stats.sort_type,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 57 Column: 5

                          self.assertEqual(self.stats.sort_type,
                             self.stats.sort_arg_dict_default[sort_name][-1])

    def test_sort_stats_partial(self):
        sortkey = 'filename'
        for sort_name in ['f', 'fi', 'fil', 'file', 'filen', 'filena',
                           'filenam', 'filename']:
            self.stats.sort_stats(sort_name)
            self.assertEqual(self.stats.sort_type,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 5

                          self.assertEqual(self.stats.sort_type,
                             self.stats.sort_arg_dict_default[sortkey][-1])

    def test_sort_stats_enum(self):
        for member in SortKey:
            self.stats.sort_stats(member)
            self.assertEqual(
                    self.stats.sort_type,
                    self.stats.sort_arg_dict_default[member.value][-1])

            

Reported by Pylint.

Missing class docstring
Error

Line: 71 Column: 9

                          self.assertEqual(
                    self.stats.sort_type,
                    self.stats.sort_arg_dict_default[member.value][-1])
        class CheckedSortKey(StrEnum):
            CALLS = 'calls', 'ncalls'
            CUMULATIVE = 'cumulative', 'cumtime'
            FILENAME = 'filename', 'module'
            LINE = 'line'
            NAME = 'name'

            

Reported by Pylint.

Lib/test/test_typechecks.py
19 issues
No value for argument 'sub' in unbound method call
Error

Line: 10 Column: 20

              
    def __instancecheck__(cls, inst):
        """Implement isinstance(inst, cls)."""
        return any(cls.__subclasscheck__(c)
                   for c in {type(inst), inst.__class__})

    def __subclasscheck__(cls, sub):
        """Implement issubclass(sub, cls)."""
        candidates = cls.__dict__.get("__subclass__", set()) | {cls}

            

Reported by Pylint.

Missing class docstring
Error

Line: 6 Column: 1

              import unittest


class ABC(type):

    def __instancecheck__(cls, inst):
        """Implement isinstance(inst, cls)."""
        return any(cls.__subclasscheck__(c)
                   for c in {type(inst), inst.__class__})

            

Reported by Pylint.

Missing class docstring
Error

Line: 19 Column: 1

                      return any(c in candidates for c in sub.mro())


class Integer(metaclass=ABC):
    __subclass__ = {int}


class SubInt(Integer):
    pass

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 19 Column: 1

                      return any(c in candidates for c in sub.mro())


class Integer(metaclass=ABC):
    __subclass__ = {int}


class SubInt(Integer):
    pass

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 23 Column: 1

                  __subclass__ = {int}


class SubInt(Integer):
    pass


class TypeChecksTest(unittest.TestCase):


            

Reported by Pylint.

Missing class docstring
Error

Line: 23 Column: 1

                  __subclass__ = {int}


class SubInt(Integer):
    pass


class TypeChecksTest(unittest.TestCase):


            

Reported by Pylint.

Missing class docstring
Error

Line: 27 Column: 1

                  pass


class TypeChecksTest(unittest.TestCase):

    def testIsSubclassInternal(self):
        self.assertEqual(Integer.__subclasscheck__(int), True)
        self.assertEqual(Integer.__subclasscheck__(float), False)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 5

              
class TypeChecksTest(unittest.TestCase):

    def testIsSubclassInternal(self):
        self.assertEqual(Integer.__subclasscheck__(int), True)
        self.assertEqual(Integer.__subclasscheck__(float), False)

    def testIsSubclassBuiltin(self):
        self.assertEqual(issubclass(int, Integer), True)

            

Reported by Pylint.

Method name "testIsSubclassInternal" doesn't conform to snake_case naming style
Error

Line: 29 Column: 5

              
class TypeChecksTest(unittest.TestCase):

    def testIsSubclassInternal(self):
        self.assertEqual(Integer.__subclasscheck__(int), True)
        self.assertEqual(Integer.__subclasscheck__(float), False)

    def testIsSubclassBuiltin(self):
        self.assertEqual(issubclass(int, Integer), True)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 33 Column: 5

                      self.assertEqual(Integer.__subclasscheck__(int), True)
        self.assertEqual(Integer.__subclasscheck__(float), False)

    def testIsSubclassBuiltin(self):
        self.assertEqual(issubclass(int, Integer), True)
        self.assertEqual(issubclass(int, (Integer,)), True)
        self.assertEqual(issubclass(float, Integer), False)
        self.assertEqual(issubclass(float, (Integer,)), False)


            

Reported by Pylint.

Tools/freeze/freeze.py
19 issues
Redefining built-in 'dir'
Error

Line: 257 Column: 9

                  if not win:
        # These are not directories on Windows.
        check_dirs = check_dirs + extensions
    for dir in check_dirs:
        if not os.path.exists(dir):
            usage('needed directory %s not found' % dir)
        if not os.path.isdir(dir):
            usage('%s: not a directory' % dir)
    if win:

            

Reported by Pylint.

Possibly unused variable 'ext'
Error

Line: 303 Column: 11

              
    # derive target name from script name
    base = os.path.basename(scriptfile)
    base, ext = os.path.splitext(base)
    if base:
        if base != scriptfile:
            target = base
        else:
            target = base + '.bin'

            

Reported by Pylint.

Redefining built-in 'dict'
Error

Line: 385 Column: 5

                  if debug > 0:
        mf.report()
        print()
    dict = mf.modules

    if error_if_any_missing:
        missing = mf.any_missing()
        if missing:
            sys.exit("There are some missing modules: %r" % missing)

            

Reported by Pylint.

Too many branches (92/12)
Error

Line: 111 Column: 1

              
# Main program

def main():
    # overridable context
    prefix = None                       # settable with -p option
    exec_prefix = None                  # settable with -P option
    extensions = []
    exclude = []                        # settable with -x option

            

Reported by Pylint.

Too many statements (260/50)
Error

Line: 111 Column: 1

              
# Main program

def main():
    # overridable context
    prefix = None                       # settable with -p option
    exec_prefix = None                  # settable with -P option
    extensions = []
    exclude = []                        # settable with -x option

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 111 Column: 1

              
# Main program

def main():
    # overridable context
    prefix = None                       # settable with -p option
    exec_prefix = None                  # settable with -P option
    extensions = []
    exclude = []                        # settable with -x option

            

Reported by Pylint.

Too many local variables (82/15)
Error

Line: 111 Column: 1

              
# Main program

def main():
    # overridable context
    prefix = None                       # settable with -p option
    exec_prefix = None                  # settable with -P option
    extensions = []
    exclude = []                        # settable with -x option

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 127 Column: 13

                  error_if_any_missing = 0

    # default the exclude list for each platform
    if win: exclude = exclude + [
        'dos', 'dospath', 'mac', 'macfs', 'MACFS', 'posix', ]

    fail_import = exclude[:]

    # output files

            

Reported by Pylint.

Variable name "o" doesn't conform to snake_case naming style
Error

Line: 163 Column: 9

                      usage('getopt error: ' + str(msg))

    # process option arguments
    for o, a in opts:
        if o == '-h':
            print(__doc__)
            return
        if o == '-d':
            debug = debug + 1

            

Reported by Pylint.

Variable name "a" doesn't conform to snake_case naming style
Error

Line: 163 Column: 12

                      usage('getopt error: ' + str(msg))

    # process option arguments
    for o, a in opts:
        if o == '-h':
            print(__doc__)
            return
        if o == '-d':
            debug = debug + 1

            

Reported by Pylint.

Objects/longobject.c
19 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 1991 Column: 10 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

               * Note that when converting a base B string, a char c is a legitimate
 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
 */
unsigned char _PyLong_DigitValue[256] = {
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
    37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  37, 37, 37, 37, 37, 37,
    37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 2408 Column: 21 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                                      Py_DECREF(z);
                        return NULL;
                    }
                    memcpy(tmp->ob_digit,
                           z->ob_digit,
                           sizeof(digit) * size_z);
                    Py_DECREF(z);
                    z = tmp;
                    z->ob_digit[size_z] = (digit)c;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 3242 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      return -1;
    }

    memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
    memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));

    *high = long_normalize(hi);
    *low = long_normalize(lo);
    return 0;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 3243 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  }

    memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
    memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));

    *high = long_normalize(hi);
    *low = long_normalize(lo);
    return 0;
}

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 3350 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
    assert(Py_SIZE(t1) >= 0);
    assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
    memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
           Py_SIZE(t1) * sizeof(digit));

    /* Zero-out the digits higher than the ah*bh copy. */
    i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
    if (i)

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 3366 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  }
    assert(Py_SIZE(t2) >= 0);
    assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
    memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));

    /* Zero out remaining digits. */
    i = 2*shift - Py_SIZE(t2);          /* number of uninitialized digits */
    if (i)
        memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 3506 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      const Py_ssize_t nbtouse = Py_MIN(bsize, asize);

        /* Multiply the next slice of b by a. */
        memcpy(bslice->ob_digit, b->ob_digit + nbdone,
               nbtouse * sizeof(digit));
        Py_SET_SIZE(bslice, nbtouse);
        product = k_mul(a, bslice);
        if (product == NULL)
            goto fail;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 4689 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      for (; i < size_z; ++i)
            z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
    else if (i < size_z)
        memcpy(&z->ob_digit[i], &a->ob_digit[i],
               (size_z-i)*sizeof(digit));

    /* Complement result if negative. */
    if (negz) {
        Py_SET_SIZE(z, -(Py_SIZE(z)));

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 1590 Column: 22 CWE codes: 126

              {
    PyLongObject *scratch, *a;
    PyObject *str = NULL;
    Py_ssize_t size, strlen, size_a, i, j;
    digit *pout, *pin, rem, tenpow;
    int negative;
    int d;
    enum PyUnicode_Kind kind;


            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 1664 Column: 46 CWE codes: 126

                      strlen++;
    }
    if (writer) {
        if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
            Py_DECREF(scratch);
            return -1;
        }
        kind = writer->kind;
    }

            

Reported by FlawFinder.

Lib/unittest/signals.py
19 issues
function already defined line 10
Error

Line: 20 Column: 17

                          elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")

            

Reported by Pylint.

Using the global statement
Error

Line: 50 Column: 5

              
_interrupt_handler = None
def installHandler():
    global _interrupt_handler
    if _interrupt_handler is None:
        default_handler = signal.getsignal(signal.SIGINT)
        _interrupt_handler = _InterruptHandler(default_handler)
        signal.signal(signal.SIGINT, _interrupt_handler)


            

Reported by Pylint.

Using the global statement
Error

Line: 69 Column: 5

                              signal.signal(signal.SIGINT, initial)
        return inner

    global _interrupt_handler
    if _interrupt_handler is not None:
        signal.signal(signal.SIGINT, _interrupt_handler.original_handler)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import signal
import weakref

from functools import wraps

__unittest = True


class _InterruptHandler(object):

            

Reported by Pylint.

Constant name "__unittest" doesn't conform to UPPER_CASE naming style
Error

Line: 6 Column: 1

              
from functools import wraps

__unittest = True


class _InterruptHandler(object):
    def __init__(self, default_handler):
        self.called = False

            

Reported by Pylint.

Class '_InterruptHandler' inherits from object, can be safely removed from bases in python3
Error

Line: 9 Column: 1

              __unittest = True


class _InterruptHandler(object):
    def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 9 Column: 1

              __unittest = True


class _InterruptHandler(object):
    def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 42 Column: 1

                          result.stop()

_results = weakref.WeakKeyDictionary()
def registerResult(result):
    _results[result] = 1

def removeResult(result):
    return bool(_results.pop(result, None))


            

Reported by Pylint.

Function name "registerResult" doesn't conform to snake_case naming style
Error

Line: 42 Column: 1

                          result.stop()

_results = weakref.WeakKeyDictionary()
def registerResult(result):
    _results[result] = 1

def removeResult(result):
    return bool(_results.pop(result, None))


            

Reported by Pylint.

Function name "removeResult" doesn't conform to snake_case naming style
Error

Line: 45 Column: 1

              def registerResult(result):
    _results[result] = 1

def removeResult(result):
    return bool(_results.pop(result, None))

_interrupt_handler = None
def installHandler():
    global _interrupt_handler

            

Reported by Pylint.

Lib/distutils/tests/test_core.py
19 issues
Access to a protected member _global_log of a client class
Error

Line: 55 Column: 44

                      self.old_stdout = sys.stdout
        self.cleanup_testfn()
        self.old_argv = sys.argv, sys.argv[:]
        self.addCleanup(log.set_threshold, log._global_log.threshold)

    def tearDown(self):
        sys.stdout = self.old_stdout
        self.cleanup_testfn()
        sys.argv = self.old_argv[0]

            

Reported by Pylint.

Constant name "setup_using___file__" doesn't conform to UPPER_CASE naming style
Error

Line: 15 Column: 1

              from distutils import log

# setup script that uses __file__
setup_using___file__ = """\

__file__

from distutils.core import setup
setup()

            

Reported by Pylint.

Constant name "setup_prints_cwd" doesn't conform to UPPER_CASE naming style
Error

Line: 23 Column: 1

              setup()
"""

setup_prints_cwd = """\

import os
print(os.getcwd())

from distutils.core import setup

            

Reported by Pylint.

Constant name "setup_does_nothing" doesn't conform to UPPER_CASE naming style
Error

Line: 32 Column: 1

              setup()
"""

setup_does_nothing = """\
from distutils.core import setup
setup()
"""



            

Reported by Pylint.

Constant name "setup_defines_subclass" doesn't conform to UPPER_CASE naming style
Error

Line: 38 Column: 1

              """


setup_defines_subclass = """\
from distutils.core import setup
from distutils.command.install import install as _install

class install(_install):
    sub_commands = _install.sub_commands + ['cmd']

            

Reported by Pylint.

Missing class docstring
Error

Line: 48 Column: 1

              setup(cmdclass={'install': install})
"""

class CoreTestCase(support.EnvironGuard, unittest.TestCase):

    def setUp(self):
        super(CoreTestCase, self).setUp()
        self.old_stdout = sys.stdout
        self.cleanup_testfn()

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 51 Column: 9

              class CoreTestCase(support.EnvironGuard, unittest.TestCase):

    def setUp(self):
        super(CoreTestCase, self).setUp()
        self.old_stdout = sys.stdout
        self.cleanup_testfn()
        self.old_argv = sys.argv, sys.argv[:]
        self.addCleanup(log.set_threshold, log._global_log.threshold)


            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 62 Column: 9

                      self.cleanup_testfn()
        sys.argv = self.old_argv[0]
        sys.argv[:] = self.old_argv[1]
        super(CoreTestCase, self).tearDown()

    def cleanup_testfn(self):
        path = os_helper.TESTFN
        if os.path.isfile(path):
            os.remove(path)

            

Reported by Pylint.

Method could be a function
Error

Line: 64 Column: 5

                      sys.argv[:] = self.old_argv[1]
        super(CoreTestCase, self).tearDown()

    def cleanup_testfn(self):
        path = os_helper.TESTFN
        if os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 64 Column: 5

                      sys.argv[:] = self.old_argv[1]
        super(CoreTestCase, self).tearDown()

    def cleanup_testfn(self):
        path = os_helper.TESTFN
        if os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path)

            

Reported by Pylint.

Lib/importlib/__init__.py
19 issues
Unable to import '__init__._bootstrap'
Error

Line: 62 Column: 1

              
# Public API #########################################################

from ._bootstrap import __import__


def invalidate_caches():
    """Call the invalidate_caches() method on all meta path finders stored in
    sys.meta_path (where implemented)."""

            

Reported by Pylint.

Module import itself
Error

Line: 18 Column: 5

              try:
    import _frozen_importlib as _bootstrap
except ImportError:
    from . import _bootstrap
    _bootstrap._setup(sys, _imp)
else:
    # importlib._bootstrap is the built-in import, ensure we don't create
    # a second copy of the module.
    _bootstrap.__name__ = 'importlib._bootstrap'

            

Reported by Pylint.

Access to a protected member _setup of a client class
Error

Line: 19 Column: 5

                  import _frozen_importlib as _bootstrap
except ImportError:
    from . import _bootstrap
    _bootstrap._setup(sys, _imp)
else:
    # importlib._bootstrap is the built-in import, ensure we don't create
    # a second copy of the module.
    _bootstrap.__name__ = 'importlib._bootstrap'
    _bootstrap.__package__ = 'importlib'

            

Reported by Pylint.

Module import itself
Error

Line: 36 Column: 5

              try:
    import _frozen_importlib_external as _bootstrap_external
except ImportError:
    from . import _bootstrap_external
    _bootstrap_external._set_bootstrap_module(_bootstrap)
    _bootstrap._bootstrap_external = _bootstrap_external
else:
    _bootstrap_external.__name__ = 'importlib._bootstrap_external'
    _bootstrap_external.__package__ = 'importlib'

            

Reported by Pylint.

Access to a protected member _set_bootstrap_module of a client class
Error

Line: 37 Column: 5

                  import _frozen_importlib_external as _bootstrap_external
except ImportError:
    from . import _bootstrap_external
    _bootstrap_external._set_bootstrap_module(_bootstrap)
    _bootstrap._bootstrap_external = _bootstrap_external
else:
    _bootstrap_external.__name__ = 'importlib._bootstrap_external'
    _bootstrap_external.__package__ = 'importlib'
    try:

            

Reported by Pylint.

Access to a protected member _bootstrap_external of a client class
Error

Line: 38 Column: 5

              except ImportError:
    from . import _bootstrap_external
    _bootstrap_external._set_bootstrap_module(_bootstrap)
    _bootstrap._bootstrap_external = _bootstrap_external
else:
    _bootstrap_external.__name__ = 'importlib._bootstrap_external'
    _bootstrap_external.__package__ = 'importlib'
    try:
        _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')

            

Reported by Pylint.

Access to a protected member _pack_uint32 of a client class
Error

Line: 51 Column: 16

                  sys.modules['importlib._bootstrap_external'] = _bootstrap_external

# To simplify imports in test code
_pack_uint32 = _bootstrap_external._pack_uint32
_unpack_uint32 = _bootstrap_external._unpack_uint32

# Fully bootstrapped at this point, import whatever you like, circular
# dependencies and startup overhead minimisation permitting :)


            

Reported by Pylint.

Access to a protected member _unpack_uint32 of a client class
Error

Line: 52 Column: 18

              
# To simplify imports in test code
_pack_uint32 = _bootstrap_external._pack_uint32
_unpack_uint32 = _bootstrap_external._unpack_uint32

# Fully bootstrapped at this point, import whatever you like, circular
# dependencies and startup overhead minimisation permitting :)

import warnings

            

Reported by Pylint.

Redefining built-in '__import__'
Error

Line: 62 Column: 1

              
# Public API #########################################################

from ._bootstrap import __import__


def invalidate_caches():
    """Call the invalidate_caches() method on all meta path finders stored in
    sys.meta_path (where implemented)."""

            

Reported by Pylint.

Access to a protected member _find_spec of a client class
Error

Line: 95 Column: 12

                  except AttributeError:
        raise ValueError('{}.__loader__ is not set'.format(name)) from None

    spec = _bootstrap._find_spec(name, path)
    # We won't worry about malformed specs (missing attributes).
    if spec is None:
        return None
    if spec.loader is None:
        if spec.submodule_search_locations is None:

            

Reported by Pylint.